$(document).ready(function (){
	
	$("#navi a, #muut_linkit a, #nuoli_kirjaudu, .kirjaudu_sisaan").popUpMaster();
	
	// SULJE POPUP
	// ruksista
	$(".btn_sulje").click(function (){
		$(this).parents(".popup").fadeOut("fast", function (){
			$("#popup_bg").fadeOut("fast");
			$(this).css({"marginTop": "", "marginLeft": "", "width": ""});
			$(".popcontent").empty().css({"height": ""});
		});
		return false;
	});
	
	// klikkaamalla taustaa
	$("#bg_close").click(function (){
		$(this).next(".popup").fadeOut("fast", function (){
			$("#popup_bg").fadeOut("fast");
			$(this).css({"marginTop": "", "marginLeft": "", "width": ""});
			$(".popcontent").empty().css({"height": ""});
		});
		return false;
	});
	
	// esc napista
	$(document).keyup(function(e) {
  		if (e.keyCode == 27) { 			// esc
			$(".popup").fadeOut("fast", function (){
				$("#popup_bg").fadeOut("fast");
				$(this).css({"marginTop": "", "marginLeft": "", "width": ""});
				$(".popcontent").empty().css({"height": ""});
			});
		}   
	});
	
	
});




// POPUP AUKEAA SCRIPTI

(function( $ ){
	$.fn.popUpMaster = function() {
		
		this.click(function (){
			
				var $this = $(this);
			
				var urli = $(this).attr("href");
				var popId = ".popup";
	
			$(popId + " .popcontent").load(urli, function (){
					var ikkuna = $(window).height();
	
				$("#popup_bg").css("height", ikkuna).fadeIn("fast", function (){
					
					var maxHeight = ikkuna - 200;
					
					if ( $(popId).height() > maxHeight ){
							var korkeus = ikkuna - 300 + "px";
						$(popId + " .popcontent").css("height", korkeus);
					}
					
					var popWidth = $(popId).width() + 40;
					var popLeftMargin = "-" + popWidth / 2 + "px";
					var popHeight = $(popId).height();
					var popTopMargin = "-" + popHeight / 2 + "px";
					
					$(popId).css({"marginTop": popTopMargin, "marginLeft": popLeftMargin, "width": popWidth}).fadeIn("fast");
					
				});
			});
			
			return false;
		});
	};
})( jQuery );
