/*
 * Author: Renaud Guyon
 * Website: http://reno.guyon.ca
 * by Reno Guyon, 2010, for Flowstation.net
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/


var popup = {
	
	popupStatus:0,
	url: '',
	data: '',
	load: function( url, data ){

		if( this.popupStatus == 0 ){
			this.popupStatus = 1;
			this.url = url;
			this.data = data;
			this.init();
			this.center();
			
			$(document).keydown(this.handleEscape);
			
			$(".popup_close .btnClose").click(function(e){
				e.preventDefault();
				popup.close();
			});

		}

	},
	init: function(){

		$('<div></div>').appendTo(document.body).addClass('popup');
		$('<div></div>').appendTo(".popup").addClass('popup_content');
		$('<div></div>').appendTo(".popup_content").addClass('popup_close');
		$('<a></a>').appendTo(".popup_close").addClass('btnClose').attr('href', '#').attr('role', 'button').attr('unselectable','on');
		$('<img />').appendTo(".popup_close .btnClose").attr('src', '/ui/icons/close.png');
		$('<div></div>').appendTo(".popup_content").addClass('popup_titlebar');
		$('<div></div>').appendTo(".popup_content").addClass('popup_body');
		
		
		if( this.url.length > 0 ){
			$('div.popup_body').load( this.url ,this.data, function(){
				
				var popupTitle = $(".popup_body h1").text();
				$(".popup_titlebar").text( popupTitle );
				
			});
		}
		
		$("#backgroundPopup").css({"opacity": "0.7"});
		$("#backgroundPopup").fadeIn("slow");
		$("div.popup").fadeIn("slow");

	},
	center: function(){

		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var docScrollTop = $(document).scrollTop();
		var docScrollLeft = $(document).scrollLeft();
		var popupHeight = $(".popup").height();
		var popupWidth = $(".popup").width();
		//centering
		$(".popup").css({
			"position": "absolute",
			"top": 150 + docScrollTop,
			"left": windowWidth /2 - popupWidth/2 + docScrollLeft
		});
		//only need force for IE6

		$("#backgroundPopup").css({
			"height": windowHeight
		});

	},
	handleEscape: function(e){

		if (e.keyCode == 27) {
			popup.close();
		}

	},
	close: function(){

		$(document).unbind('keydown', this.handleEscape);
		
		
		if( this.popupStatus == 1 ){
			$("div.popup").fadeOut( 'slow', this.destroy );
			this.popupStatus = 0;
		}
		
	},
	destroy: function(){
		
		$("div.popup").remove();
		
	}

};