/**
 * Modal Window
 * @version 2010-01-09
 * 
 * 
 * example 1: all classname with prefix popup open a modal
 * $(function(){
 * $.modalWindow({classPrefix : "popup"});
 * });
 **/
;
(function($) {
	var $overlay, $wrapper, $content, settings, $test;
	
	$.modalWindow = function(settings) { 
		// Default settings
		var defaultSettings = {
			type : "url",
			overlayClass : "overlay",
			overlayOpacity: 0.5,
			wrapperClass : "modalWrapper",
			contentClass : "modalContent",
			windowW: 397,
			windowH: 336
		};
		
		settings = $.extend(defaultSettings, settings);		
		$overlay = $("#" + settings.overlayClass);
		$wrapper = $("#" + settings.wrapperClass);
		$content = $("#" + settings.contentClass);
		
		prepare();
		dispatch();
		
		function dispatch() { 
			if (!settings.classPrefix) {
				alert('"classPrefix" variable is not defined in "modalWindow" plugin.');
				return;
			}
			$("[class^=" + settings.classPrefix + "]").each(function(){
				type = $(this).attr("class").replace(settings.classPrefix, "");

				if (type != "" && type.search(/^url$/) != -1) {
					settings.type = type;
				}
				 
				$(this).modalWindow(settings.type, settings);
			});
		};
	};
	
	$.fn.extend({ 
		modalWindow: function(type, settings) {
			$.modalWindow[type](this, settings);				
		}
	});	

	$.extend($.modalWindow, { 
		// url
		url : function($this, settings) {
			$this.click(function(e){
				// stop a.href
				e.preventDefault();
								
				$overlay.show();

				if ($this.attr("rel") != "") { /* dynamic width  */ 
					$wrapper.css({"width": $this.attr("rel") + "px"});
				} else {
					if ($wrapper.width() != settings.windowW) {
						$wrapper.css({"width": settings.windowW});
					}
				}				
				$wrapper.css({"height": settings.windowH});
				
				// center modal
				var winW = document.documentElement.clientWidth;
				var popupW = $wrapper.width();
				var winH = document.documentElement.clientHeight;
				var popupH = $wrapper.height();

				$wrapper.css("left", (winW - popupW)/2 + "px");				
				$wrapper.css("top", (winH - popupH)/2 + "px");
				//$content.load($this.attr("href") + "?" + Math.random()*99999);
				$content.load("/loadSite.php?url=" + $this.attr("href"));
				$wrapper.fadeIn(300);
			});
		}
	});
	
	
	function prepare() { 
		if (!$.modalWindow.ready) {
			// overlay
			$overlay.css({"opacity": "0.5"});
			//$overlay.css({"height": "1000px"});
			
			$overlay.click(function(){
				closeModal();
			});
			
			//Press Escape event!
			$(document).keypress(function(e){
				if(e.keyCode==27 && popupStatus==1){
					closeModal();
				}
			});
			
			//Press close button
			$(".closePopup").click(function(e){
				closeModal();
			});
			
		
			
			$.modalWindow.ready = true;
		}
	}
		
	function closeModal() {
		$wrapper.fadeOut("fast");
		$content.html("");
		$overlay.fadeOut("fast");
	}
	
})(jQuery);




