$(document).ready(function(){
	
	$(".lightbox").click(function(){
		overlayLink = $(this).attr("href");
		overlayTitle = $(this).attr("title");
		window.startOverlay(overlayLink, overlayTitle);
		return false;
	});
});


function startOverlay(overlayLink,overlayTitle) {
	$("body")
		.append('<div class="overlay"></div><div class="boxContainer"></div>')

	$(".overlay").animate({"opacity":"0.6"}, 400, "linear");

	$(".boxContainer").html('<a href="#"><h2 class="closeBox">Close</h2></a><img src="'+overlayLink+'" alt="'+overlayTitle+'" />');
	

	var newImg = new Image();
	newImg.src = overlayLink;
	var newheight = newImg.height;
	var newwidth = newImg.width;
	
	var screenWidth = document.body.clientWidth;
	var screenHeight = document.documentElement.clientHeight;
	var alerter = 'Width: '+screenWidth+'\n Height:'+screenHeight+'\nimgw: '+newwidth+'\n imgh: '+newheight;
	
	if(newwidth > screenWidth){
		var windowWidth = screenWidth - 100;
		var overFlow = "scroll";
	}
	else
	{
		var windowWidth = newwidth;
		var overFlow = "hidden";
	}
	
	if(newheight > screenHeight){
		var windowHeight = screenHeight - 100;
		var overFlow = "scroll";
	}
	else
	{
		var windowHeight = newheight;
		var overflow = "hidden";
	}
	

if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }



	
	$(".boxContainer img").load(function() {
		var imgWidth = $(".boxContainer img").width();
		var imgHeight = $(".boxContainer img").height();
		var imgLeft = (screenWidth/2)-(windowWidth/2)-10;
		$(".boxContainer")
			.css({
				"top":        	scrOfY+50+"px",
				"left":       	imgLeft,	
				"text-align": 	"center",
				"margin":		"0px auto",			
				"width":      	windowWidth,
				"overflow": 	overFlow,
				"height":     	windowHeight	
			})
			.animate({"opacity":"1"}, 400, "linear");

		window.removeOverlay();
	});
}
function removeOverlay() {
	
	$(".closeBox").click(function(){
		$(".boxContainer, .overlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".boxContainer, .overlay").remove();	
		});
	});

	$(".overlay").click(function(){
		$(".boxContainer, .overlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".boxContainer, .overlay").remove();	
		});
	});
}
