/**
 *
 * Custom Lightbox created by myself using
 * pointers from http://kilianvalkhof.com/2008/javascript/building-your-own-lightbox-part-1/
 *
 *
*/

$(document).ready(function(){
	// add a click event
	$(".lightbox").click(function(){
		var overlayLink = $(this).attr("href");
		window.startOverlay(overlayLink);
		return false;
	});
	
}); 

function startOverlay(overlayLink) {
	//add the elements to the dom
	$("body")
		.append('<div class="overlay"></div><div class="container"></div>');
	
	// set size and animate the semitransparant layer
	$(".overlay").css({'height': document.body.clientHeight + 'px', 'width' : document.body.clientWidth + 'px'});	
	$(".overlay").animate({"opacity":"0.6"}, 400, "linear");
	
	//add the lightbox image to the DOM
	$(".container").html('<img src="'+overlayLink+'" alt="" /><br />');
	$(".container").append('<a href="javascript:void(0);" id="jbclose">Close</a>');
	//position it correctly after downloading
	$(".container img").one('load', function() {
			var imgWidth = $(".container img").width();
			var imgHeight = $(".container img").height();
			
			var docEl = document.documentElement;
			var docW = window.innerWidth || self.innerWidth || (docEl&&docEl.clientWidth) || document.body.clientWidth;
			var docH = window.innerHeight || self.innerHeight || (docEl&&docEl.clientHeight) || document.body.clientHeight;
			var docH2 = window.pageYOffset || self.pageYOffset || (docEl&&docEl.scrollTop) || document.body.clientHeight;
			var containerTop =  docH2 + ( docH / 2);
			
			$(".container")
			.css({
				"top"			:	containerTop + 'px',
				"left"			:	"50%",
				"width"			:	imgWidth + 'px',
				"height"		:	imgHeight + 'px',
				"margin-top"	:	-(imgHeight / 2) + 'px',
				"margin-left"	:	-(imgWidth / 2) + 'px'
			})
			.animate({"opacity":"1"}, 400, "linear");
		
		// you need to initiate the removeoverlay function here, otherwise it will not execute.
		window.removeOverlay();
	}).each(function(){
		if(this.complete) $(this).trigger("load");
	});
	
}
function removeOverlay() {
// allow users to be able to close the lightbox
	$("#jbclose").click(function(){
		$(".container, .overlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".container, .overlay").remove();
		});
		$("body").css({"overflow-y":"auto"});
	});

	$(".overlay").click(function(){
		$(".container, .overlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".container, .overlay").remove();
		});
		$("body").css({"overflow-y":"auto"});
	});

} 