var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(id, showBackground) {
	//loads popup only if it is disabled
	if(popupStatus == 0) {
		if (showBackground) {
			$("#backgroundPopup").css({"opacity": "0.9"});
			$("#backgroundPopup").fadeIn("slow");
		}

		$(id).fadeIn("slow");
		popupStatus = 1;
	}
}

function disablePopup(id){
    if ($(id).hasClass('refresh'))
    {
        window.location = window.location;
    }

	if (popupStatus==1) {
		$("#backgroundPopup").fadeOut("slow");
		$(id).fadeOut("slow");
		popupStatus = 0;
	}

	$('select').css('visibility', 'visible')
}

$('.popupClose').livequery('click', function(e) { 
		e.preventDefault(); 

		var divId = $(this).parent().parent().attr('id');

		if (divId) {
			disablePopup('#'+$(this).parent().parent().attr('id')); 
		} else {
			disablePopup('#' + $(this).attr('rel'));
		}

});

//centering popup
function centerPopup(id, showBackground){

	// scrOfY = document.body.scrollTop;
	scrOfY = $(window).scrollTop();

	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $(id).height();
	var popupWidth = $(id).width();
	
	//	console.log(windowHeight/2-popupHeight/2);
	//	console.log(windowHeight/2-popupHeight/2+scrOfY);

	//centering
	$(id).css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2+scrOfY,
		// "top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6

	if (showBackground) {
		$("#backgroundPopup").css({
			"height": windowHeight
		});
	}
	
	var divArea = $(id).clone();
	$(id).remove();
	divArea.appendTo('body');
}


function initPopup(id, showBackground) {

	showBackground = typeof(showBackground) != 'undefined' ? showBackground : true;
	
	
	$('.popup').width($(id).width() + 24);
	
	$('select').css('visibility', 'hidden')
	$(id + ' select').css('visibility', 'visible')

	centerPopup(id, showBackground);
	loadPopup(id, showBackground);
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
	
	$(".popupClose").click(function(){
		disablePopup('#' + $('.popup:visible').attr('id'));
	});
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup('#' + $('.popup:visible').attr('id'));
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup('#' + $('.popup:visible').attr('id'));
		}
	});

});

