﻿/* Declairation Example: 
 * var PopUp = new popUpWin(window name [String], url to load [String], data [JSON Object]); 
 * - If no div is defined on the page to hold the popup, one is created automatically using the "WindowName" paramater.
 * - carefull when using the data paramater, it has issues when trying to pass html as a value.
 * - Use PopUp.show() to open the popup and PopUp.hide() to close it (where "PopUp" is the name you ahve given to the varable which represents the popup window)
 */

function popUpWin(WindowName) {
	
	if ($("#backgroundPopup").length == 0) { 
		$(document.body).prepend("<div id=\"backgroundPopup\"></div>"); 
	}
	if ($("#"+WindowName).length == 0) { 
		$(document.body).prepend("<div id=\"" + WindowName + "\" class=\"popup\"></div>"); 
	}
	
	if (!$("#"+WindowName).hasClass("popup")) { 
		$("#"+WindowName).addClass("popup");
	}
	
	this.show = function(path, data) {
		loadPopup(WindowName, path, data);
	};

	this.hide = function() {
		disablePopup(WindowName);
	};

	$("#backgroundPopup").click(function(){
		disablePopup(WindowName);
	});
	
	$("#"+WindowName+" a.closeMe").live("click", function(){
		disablePopup(WindowName);
	});
}

function loadPopup(WindowName, path, data){
	scrollTo(0,0);
	document.body.style.overflow = 'hidden';
//	$(document.body).css({overflow: "hidden"});
	$("#backgroundPopup").css({ "opacity": "0.7" });
	$("#backgroundPopup").fadeIn("slow");
	
	if (path!=undefined) {
		loadContent(WindowName, path, data);
	} else {
		centerPopup(WindowName);
		$("#"+WindowName).fadeIn("slow");
	}
	
}

function disablePopup(WindowName){
	scrollTo(0,0);
	document.body.style.overflow = 'auto';
//	$(document.body).css({overflow: "auto"});
	$("#backgroundPopup").fadeOut("slow");
	$("#"+WindowName).fadeOut("slow");
}

function centerPopup(WindowName){
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#"+WindowName).height();
	var popupWidth = $("#"+WindowName).width();
	
	$("#"+WindowName).css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	
	$("#backgroundPopup").css({
		"width": windowWidth,
		"height": windowHeight
	});
}

function loadContent(WindowName, path, data) {
	var method = "GET";
	if (!data) {
		data={};
	} else {
		method = "POST";
	}
	
	$.ajax({
		type: method,
		url: path+"?t="+Math.random(),
		cache: false,	
		data: data,
		success: function(data){
			$("#"+WindowName).html(data);
			centerPopup(WindowName);
			$("#"+WindowName).fadeIn("slow");
		},
		error: function() {
			alert("Error loading popup window data.");
		}
	});
}