//
// create closure
//
(function($) {
  //
  // plugin definition
  //
  $.fn.popup = function(options) {
	init();
	// build main options before element iteration
	var opts = $.extend({}, $.fn.popup.defaults, options);
	var check = $("#pop_overlay").css("display");
	var popup_html = "";
	// iterate and reformat each matched element
	this.each(function() {
	  $this = $(this);
	  // build element specific options
	  var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
	  // update element styles
	  switch(o.mode){
		  case 'HTML':
		  	popup_html = popup_html + $this.html() + o.seperator;
			break;
		  case 'Image':
		  	popup_html = popup_html + '<img src="' + $this.attr('href') + '" />' + o.seperator;
			$("#pop_inner").attr("class", "image");
			break;
	  }
	  $("#pop_inner").css("width", o.width + "px");
	  var marginwidth = ((o.width + 20)/2)*-1
	  $("#pop_inner").css("marginLeft", marginwidth + "px");
	});
    if(check=='none')
    {
		$("#pop_inner").html(popup_html + "<a href='#' class='close'>" + opts.close + "</a>")
		$("#pop_inner .close").click(function () {
													  $("#pop_overlay").css("display", "none");
													  $("#pop_container").css("display", "none");
													  $("#pop_inner").css("display", "none");
												 });
      $("#pop_overlay").css("display", "block");
      $("#pop_container").css("display", "block");
      $("#pop_inner").css("display", "block");
      $("#pop_container").css("top",($("html").scrollTop() + 100) + "px");
    }
    else
    {
      $("#pop_overlay").css("display", "none");
      $("#pop_container").css("display", "none");
      $("#pop_inner").css("display", "none");
    }     
  };
  //
  // private function for debugging
  //
  var initialized = false;
  function init() {
  	if (initialized == false){
		var div_overlay = document.createElement('div');
		var div_id = 'pop_overlay';
		div_overlay.setAttribute('id',div_id);
		document.body.appendChild(div_overlay);
		
		var div_container = document.createElement('div');
		div_id = 'pop_container';
		div_container.setAttribute('id',div_id);
		document.body.appendChild(div_container);
		
		var div_inner = document.createElement('div');
		div_id = 'pop_inner';
		div_inner.setAttribute('id',div_id);
		document.getElementById('pop_container').appendChild(div_inner);
		
		document.getElementById('pop_overlay').style.display='none';
		document.getElementById('pop_container').style.display='none';
		initialized = true;
	}
  };
  //
  // plugin defaults
  //
  $.fn.popup.defaults = {
	seperator: '<br/>',
	close: 'Close',
	mode: 'HTML',
	width: 500
  };
//
// end of closure
//
})(jQuery);
