/**
 * @author forellana
 */
(function($) {
	$.fn.popup = function(options){
		var defaults = {
			'dim': 0.7,
			'closeHandle': '',
			'show': false,
			'closeOnOutsideClick': true
		};
		
		var options = $.extend(defaults, options);
		
		return this.each(function(){
			$(this).after('<div class="popup_window_background"></div>');
			var $this = $(this);
			var bk = $(this).next('.popup_window_background');
			var popupStatus = 0;
			
			function loadPopup(){
				if (popupStatus == 0) {
					$(bk).css({
						'opacity': options.dim
					});
					$(bk).fadeIn("slow");
					$this.fadeIn("slow");
				}
				popupStatus = 1;
			}
			
			function disablePopup(){
				
				if (popupStatus == 1) {
					$(bk).fadeOut('slow');
					$this.fadeOut('slow');
					popupStatus = 0;
				}
			}
			
			function centerPopup(){
				var windowWidth = document.documentElement.clientWidth;
				var windowHeight = document.documentElement.clientHeight;
				var popupWidth = $this.width();
				var popupHeight = $this.height();
				
				$this.css({
					'position': 'fixed',
					'top': windowHeight / 2 - popupHeight / 2,
					'left': windowWidth / 2 - popupWidth / 2
				});
				
				$(bk).css({
					'height': windowHeight
				})
			}
			
			$(this).bind('center', function() {
				centerPopup();
			});
			
			function show(){
				centerPopup();
				loadPopup();
			}
			
			$(options.closeHandle).click(function(){
				disablePopup();
			});
			
			//var ignoreClick = false;
			$(bk).click(function(){
				//if (!ignoreClick) {
				if (defaults.closeOnOutsideClick) {
					disablePopup();
				}
				//}
				
				//ignoreClick = false;
			});
			
			$this.click(function() {
				//ignoreClick = true;
				//return false;
			});
			
			$(document).keypress(function(e){
				if (e.keyCode == 27 && popupStatus == 1 && defaults.closeOnOutsideClick) {
					disablePopup();
				}
			});
			
			$this.bind('close_popup', function() {
				disablePopup();
			});
			
			if (options.show) {
				show();
			}
		});
	}
})(jQuery);
