// JavaScript Document

(function ($) {
	var ie6 = $.browser.msie && parseInt($.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object";
	
	$.modal = function (data,w,h) {
		return $.modal.impl.init(data,w,h);
	};
	
	$.modal.close = function () {
		$.modal.impl.close();
	};
	
	$.modal.setSize = function (w,h) {
		$.modal.impl.setSize(w,h);	
	}
	
	$.fn.modal = function (w,h) {
		return $.modal.impl.init(this, w,h);
	};
	
	$.modal.impl = {
		
		init: function(data,w,h) {
			$("body").append('<div id="mask"></div><div id="modal"></div><a href="#" id="modalclose">X</a>');
			
			$('#mask,#modal,#modalclose').fadeIn();
			this.setSize(w,h);
			this.mask();
			this.fill(data,w,h);
			this.bindEvents();
		},
		
		fill: function(data,w,h) {
			if (data.indexOf("?")>=0) {
				$.get(data+"&scripted=true",function(htmlreturn) {
						$("#modal").html(htmlreturn);
				});	
			} else {
				$.get(data+"?scripted=true",function(htmlreturn) {
						$("#modal").html(htmlreturn);
				});
			}
		},
		
		close: function() {
			$("#mask, #modal, #modalclose").remove();
		},
		
		setSize: function(w,h) {
			$("#modal").width(w).height(h);
			$("#modal").css({
				"margin-top" : -h/2,
				"margin-left" : -w/2
			});

                $("#modalclose").css("right", $("#modal").position().left-parseInt($("#modal").css("width").replace("px",""))/2-20);
                $("#modalclose").css("top", $("#modal").position().top-parseInt($("#modal").css("height").replace("px",""))/2);

		},
		
		mask:function()
		{
				$("#mask").height($(document).height());
				$("#mask").width($(document).width());

                $("#modalclose").css("right", $("#modal").position().left-parseInt($("#modal").css("width").replace("px",""))/2-20);
                $("#modalclose").css("top", $("#modal").position().top-parseInt($("#modal").css("height").replace("px",""))/2);
		},

		bindEvents: function() {
			$("#modalclose").click(function() {
            	$.modal.impl.close();
			});
			
			$(window).resize(function() {
				$.modal.impl.mask();
			});
			
		}
	};


})(jQuery);
