jQuery.fn.Exists = function() {
	return ($(this).size() > 0);
}
jQuery.fn.HidePopups = function() {
	$('.popupLayer').each(function() {
		if($(this).IsVisible()) {
			$(".cover").hide();
			
			if($(this).IsIframeLayer()) {
				var lm = $("#layerMask");
				var $t = $(this);
				//$t.appendTo(lm);
			}
			$(this).ToggleVisibility("hide");
		}
	});
}

jQuery.fn.IsIframeLayer = function() {
	var $this = $(this);
	return ($this.find("iframe").length > 0) ? true : false;
}

jQuery.fn.IsVisible = function() {
	var $this = $(this);
	return ($this.css("display") == "none" || $this.css("visibility") == "hidden") ? false : true;
}

jQuery.fn.ToggleVisibility = function(mode) {
	var $this = $(this);
	switch(mode) {
		case "hide":
			if($this.IsIframeLayer()) {
				$this.css("visibility", "hidden");
			} else {
				$this.hide();
			}
			break;
		case "show":
			if($this.IsIframeLayer()) {
				$this.css("visibility", "visible");
			} else {
				$this.show();
			}
			break;			
		default:
			if($this.IsIframeLayer()) {
				$this.css("visibility", function() {
					return ($this.css("visibility") == "hidden" ? "visible" : "hidden");
				});
			} else {
				$this.toggle();	
			}
	}
}
function openLayer(el, e) {
	var $this = $("#"+el);
	toggleCover("show");
	$this.ToggleVisibility("show");
	$this.css({
		top: "0",
		left: "50%",
		marginLeft: ($this.width()/2)*(-1),
		marginTop: setPopupPosition({layer: $this})
	});
	$this.find(".popupframe:first").attr("src", el.toLowerCase() +".html");
	$.Event(e).stopPropagation();
}

function toggleCover(vis) {
	if(!$('div.cover').Exists()) {
		$("<div>").addClass("cover").appendTo("body");
	}
	if(vis == "show") {
		$(".cover").show();
		$(".cover").css({
			width: document.documentElement.clientWidth + "px",
			height: document.getElementById('layoutC').offsetHeight + "px"
		});		
	} else {
		$(".cover").hide();
	}
}

function setPopupPosition(options) {
	var defaults = {
		layer: "",
		default_marginTop: "55"
	}
	var o = $.extend(defaults, options);
	
	var layerStyle = {
		top: 0,
		left: "50%",
		marginLeft: (o.layer.width()/2)*(-1),
		marginTop: getTopPosition(o.layer, o.default_marginTop)
	}
	
	
	o.layer.css(layerStyle);
	
	function getTopPosition(el, default_marginTop) {
		var top_height = document.documentElement.scrollTop;
		if(el.height() > document.documentElement.clientHeight) {
			return default_marginTop + top_height; 
		} else {
			return (document.documentElement.clientHeight/2) - (el.height()/2) + top_height;
		}
	}
}
