var okToClose = false;
var holdNext = false;
var popTotalImages = 0;
var popCurrentImage = 0;
var clickDisabled = false;
var controlsDisabled = true;

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(document).ready(function(){
	popTotalImages = $("a[rel=lightbox]").size();
	popCurrentImage = 1;
	$("a[rel=lightbox]").click(function(){showInterface();return false;});	
});

function refreshPopControls() {	
	$("#popup").mouseenter(function() {
		if (controlsDisabled) return;
		$("#popup .controls").show();
		okToClose = false;
		$("#popup").mouseleave(function() {
			$("#popup .controls").hide();
			okToClose = true;
		});
	});
	$("#overlay").click(function(){doClose();});
	$("#popupWrapper").click(function(){
		if (okToClose) doClose();
	});
	

	if (popCurrentImage+1 > popTotalImages) {
		$("#popup .controls .nextButton").attr("class","nextButton disabled");
		$("#bigimage").click(function(){});
		$("#bigimage").css("cursor","");
	} else {
		$("#popup .controls .nextButton").attr("class","nextButton");
		$("#bigimage").css("cursor","hand").css("cursor","pointer");
		$("#bigimage").click(function() {
			//temporary hack to prevent this even from being fired twice in safari (for some reason)
			if (holdNext == false) {			
				doNextImage();
			}			
			holdNext = true;
			setTimeout("holdNext = false",1);
		});
	}
	if (popCurrentImage == 1)
		$("#popup .controls .prevButton").attr("class","prevButton disabled");
	else
		$("#popup .controls .prevButton").attr("class","prevButton");		
		
	$("#popup .description h3").html("Image "+popCurrentImage+" of " + popTotalImages);
	$("#popup .description p").html($("a:eq("+(popCurrentImage-1)+")[rel=lightbox]").attr("alt"));
}


//These three functions should be consolidated into one
function doNextImage() {
	if (clickDisabled || popCurrentImage + 1 > popTotalImages) return;
	clickDisabled = true;
	popCurrentImage+=1;	
	doImage();
}

function doPrevImage() {
	if (clickDisabled || popCurrentImage == 1) return;
	clickDisabled = true;
	popCurrentImage-=1;		
	doImage();
}

function doImage() {
	$("#popup").stop({clearQueue:true,gotoEnd:true})
	$("#popup").mouseenter(function(){});	
	$("#popup .close").fadeOut("fast");
	$("#popup .controls").fadeOut("fast");
	$("#bigimage").fadeOut("slow",function(){		
		$("#bigimage").attr("src",$("a:eq("+(popCurrentImage-1)+")[rel=lightbox]").attr("href")+'?random=' + (new Date()).getTime());
		$("#bigimage").load(function() {
			if($("#bigimage").width() < 450) mybigimagewidth = 450;
			else mybigimagewidth = $("#bigimage").width();
			
			if(parseFloat($("#popup .inner").css("width")) == mybigimagewidth) {
				$("#bigimage").fadeIn("slow", function() {				
					$("#popup .controls").fadeIn("slow", function() {
						$("#popup .close").fadeIn("slow");							
					});
					
					clickDisabled = false;
					refreshPopControls();
				});
			} else {
				$("#popup").animate({
					width: mybigimagewidth + 40 + 'px',
					height: $("#bigimage").height() + 40 + 'px'
				}, function() {			
					$("#popup .inner").css({
						width: mybigimagewidth,
						height: $("#bigimage").height() + 20 + 'px'
					});
					$("#bigimage").fadeIn("slow", function() {				
						$("#popup .controls").fadeIn("slow", function() {
							$("#popup .close").fadeIn("slow");							
						});
						
						clickDisabled = false;
						refreshPopControls();
					});
				});
			}
		});
	});
}

function doInitialImage() {	
	popCurrentImage = 1;
	controlsDisabled = true;
	clickDisabled = false;
	okToClose = false;

	$("#bigimage").attr("src",$("a:eq("+(popCurrentImage-1)+")[rel=lightbox]").attr("href")+'?random=' + (new Date()).getTime());	
	$("#popup").mouseenter(function(){});
	$("#bigimage").load(function() {
		if($("#bigimage").width() < 450) mybigimagewidth = 450;
		else mybigimagewidth = $("#bigimage").width();
		
		$("#popup").animate({
			width: mybigimagewidth + 40 + 'px',
			height: $("#bigimage").height() + 40 + 'px'
		}, function() {			
			$("#popup .inner").css({
				width: mybigimagewidth,
				height: $("#bigimage").height() + 20 + 'px'
			})					
			$("#bigimage").fadeIn("slow");
			$("#popup .controls").fadeIn("slow");
			$("#popup .close").fadeIn("slow");
			refreshPopControls();
			controlsDisabled = false;
		});
	});
}

function doClose() {
	$("#popup").fadeOut("fast",function(){
		$('#overlay').fadeOut("fast",function(){$("#popupElements").remove()});		
	});
}

/*
****
<div id="popup">
	<div class="inner">
		<a href="#" class="close" onclick="doClose();return false;"></a>
		<img src="photos/image1.jpg" id="bigimage"/>
		<div class="controls">
			<a class="prevButton" onclick="doPrevImage()">Prev</a>
			<div class="description">
				<h3>Blah 1/2</h3>
				<p>Blah blah blah</p>			
			</div>
			<a class="nextButton" onclick="doNextImage()" href="#">Next</a>
		</div>
		<div class="shadowControls">
			<a class="prevButton" onclick="doPrevImage()">Prev</a>
			<a class="nextButton" onclick="doNextImage()" href="#">Next</a>
		</div>
	</div>
</div>
*/

function showInterface() {
	// Apply the HTML markup into body tag
	$('body').append('<div id="popupElements"><div id="overlay"></div><div id="popupWrapper"><div id="popup" style="display:none"><div id="popupInner"><div class="close" onclick="doClose();return false;"></div><div class="inner"><img src="" id="bigimage"/><div class="controlsBackground"></div><div class="controls"><div class="prevButton" onclick="doPrevImage()">Prev</div><div class="description"><h3></h3><p></p></div><div class="nextButton" onclick="doNextImage()">Next</div></div><div class="shadow controls"><div class="prevButton" onclick="doPrevImage()" href="#">Prev</div><div class="description"><h3></h3><p></p></div><div class="nextButton" onclick="doNextImage()">Next</div></div></div></div></div></div></div>');	
	// Get page sizes
	var arrPageSizes = ___getPageSize();
	// Style overlay and show it
	$('#overlay').css({
		backgroundColor:	'white',
		opacity:			'0.8',
		width:				arrPageSizes[0],
		height:				arrPageSizes[1]		
	}).fadeIn("fast", function() {	
		$('#popupWrapper').css({
			top: 134+$(document).scrollTop()+'px'
		});
		$('#popup').fadeIn("fast", function() {doInitialImage()});	
	});
	// Get page scroll
	var arrPageScroll = ___getPageScroll();
	// Calculate top and left offset for the popup div object and show it
			
	// If window was resized, calculate the new overlay dimensions
	$(window).resize(function() {
		// Get page sizes
		var arrPageSizes = ___getPageSize();
		// Style overlay and show it
		$('#overlay').css({
			width:		arrPageSizes[0],
			height:		arrPageSizes[1]
		});
		
		// Get page scroll
		var arrPageScroll = ___getPageScroll();
		// Calculate top and left offset for the popup div object and show it
		
	});	
}

function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};

function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};		
		
