(function($) {
	
	$.fn.popupDialog = function(options, title, url) {

		if (typeof options == "string") {
			this.each(function() {
				executeAction.call(this, options, title, url);
			});
			return this;
		}
		
		var config = $.extend({}, $.fn.popupDialog.defaults, options);

		this.each(function() {
			var $this = $(this);
			var opts = $.meta ? $.extend({}, config, $this.data()) : $.extend({}, config);
			// Save the individual object's options for later
			this.opts = opts;
			$this.find(".popupClose").click(function(){
				$this.popupDialog("close");
			});
		});
		
		return this;
	};

	function executeAction(action, title, url) {
		var $this = $(this);
		switch (action) {
			case "open":
				$("#flashContent").hide();
				$this.find(".popupTitle").html(title);
				resizePopup.call(this);
				$this.show();
				$this.find(".popupContent").attr("src", url);
				break;
			case "close":
				$this.hide();
				$("#flashContent").show();
				break;
		}
	};

	function resizePopup() {
		var $this = $(this);
		var wH = $(window).height();
		var wW = $(window).width();
		
		$this.height(wH);
		$this.width(wW);
		var popup = $this.find(".popupFrame");
		
		var vMargin = this.opts.vMargin;
		var hMargin = this.opts.hMargin;
		var popupWidth = parseInt(wW - hMargin);
		var popupHeight = parseInt(wH - vMargin);
		popup.css({
		  	"width": popupWidth + "px",
		  	"height": popupHeight + "px",
		  	"top": parseInt(vMargin / 2) + "px",
		  	"left": parseInt(hMargin / 2) + "px"
		});
		var contentHeight = popupHeight - popup.find(".popupTitleBar").height();
		
		popup.find(".popupContent").css({
		  	"width": popupWidth + "px",
		  	"height": contentHeight + "px"
		});
	}

	$.fn.popupDialog.defaults = {
		vMargin : 120,
		hMargin : 400
	};
	
})(jQuery);


$(document).ready(function(){
	$("#modalPopup").popupDialog();
	$(".popupClick").click(function(event){
		var $this = $(this);
		var title = $this.attr("popupTitle");
		var url = $this.attr("href");
		$("#modalPopup").popupDialog("open", title, url);
		event.stopImmediatePropagation();
		return false;
	})
});

