function popup_hide(){
	$(current_popup).fadeOut(300);
	$(current_popup).removeClass('popup-window-active');
	$('#popup-mask').fadeTo(300, 0, function() {$(this).remove();});
}

var current_popup_settings = {};
var current_popup = false;

(function( $ ){
	$.fn.popup = function( options ) {  
		var settings = {
			// 'auto' : true,
			'type' : 'popup', // modal | popup
			'overlay' :  true, // true | false - ar rodyti fono perdengima?
			'timeout' : false // false | int (seconds) - laikas sekundemis, po kurio uzsidarys popup'as
		};
		return this.each(function() {
			// If options exist, lets merge them
			// with our default settings
			if ( options ) {
				$.extend( settings, options );
			}
			current_popup_settings = settings;
			current_popup = this;
			$(this).appendTo('body');
			if (settings['overlay'] || settings['type']=='modal') {
				$('body').append('<div id="popup-mask"></div>');
				$('#popup-mask').css({'width':$(window).width(),'height':$(document).height()});
				$('#popup-mask').fadeTo(0, 0);
				if (settings['overlay']) {
					$('#popup-mask').fadeTo(500, 0.5);
				}
			}

			//Get the window height and width
			var winH = $(window).height();
			var winW = $(window).width();

			$(this).addClass('popup-window-active');
			$(this).fadeTo(0,0);
			
			//Set the popup window to center
			$(this).css('top',  winH/2-$(this).height()/2+$(document).scrollTop());
			$(this).css('left', winW/2-$(this).width()/2);

			$(this).fadeTo(500, 1, function(){
				// Chrome fix
				$(this).css('left', winW/2-$(this).width()/2);
			});

			// jeigu turinys islenda uz ribu
			if (settings['overlay'] || settings['type']=='modal') {
				$('#popup-mask').css({'width':$(window).width(),'height':$(document).height()});
			}
			
			if (settings['timeout']) {
				setTimeout("popup_hide();",settings['timeout']);
			}
			
			if (settings['overlay'] && settings['type']=='popup') {
				$('#popup-mask').click(function(e){
					e.preventDefault();
					popup_hide();
				});
			}
			$('div.popup-window .popup-close').live('click', function(e){
				e.preventDefault();
				popup_hide();
			});
			
		});
	};
})( jQuery );

$(document).keyup(function(e) {
	if(e.keyCode == 27) {
		if (current_popup_settings['type']=='popup') {
			popup_hide();
		}
	}  
});
