/**
 * jQuery Lightbox - Cestovatel edition
 * Version 0.1
 * @author Veros Kaplan
 *
 * LICENSE: CC BY-NC-ND
 *       (jQuery is under MIT and original jQuery LB is under CC BY-SA)
 *
 * Based on jQuery Lightbox plugin (0.4) by  Warren Krewenki
 * Based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * Originally written to make use of the Prototype framework, and Script.acalo.us, now altered to use jQuery.
 *
 **/

var Lightbox = {
	fileLoadingImage : "/images/lightbox/loading.gif",
	filePrevButton: "/images/lightbox/left_button.png",
	filePrevButtonDisabled: "/images/lightbox/left_button_disabled.png",
	fileNextButton: "/images/lightbox/right_button.png",
	fileNextButtonDisabled: "/images/lightbox/right_button_disabled.png",
	fileFirstButton: "/images/lightbox/first_button.png",
	fileLastButton: "/images/lightbox/last_button.png",
	fileCloseButton: "/images/lightbox/close_button.png",
	fileWaitAMinute: "/images/moment.gif",
	overlayOpacity : 0.90,
	borderSize : 10,
	imageArray : new Array,
	/*    guid, src/code, title, comment, height, width
	*/
	activeImage : null,
	inprogress : false,
	resizeSpeed : 350,
	collections: new Array,
	anchors: new Array,
	destroyElement: function(id){
		if(el = document.getElementById(id)){
			el.parentNode.removeChild(el);
		}
	},
	initialize: function() {	
		// attach lightbox to any links with rel 'lightbox'
		$("a").each(function(){
			if(this.rel.toLowerCase().match('lightbox')){
				$(this).click(function(){
					Lightbox.clickStart(this);
					return false;
				});
			}
		});
		
		Lightbox.destroyElement('LbOverlay'); Lightbox.destroyElement('Lightbox'); Lightbox.destroyElement("LbHeader");
		$("body").append('<div id="LbOverlay"></div>'+
			'<div id="Lightbox"><div id="LbOuterImageContainer"><div id="LbImageContainer"><img id="LbImage">'+
				'<div style="" id="hoverNav"><a href="#" id="prevLink"></a><a href="#" id="nextLink"></a></div>'+
				'<div id="LbLoading"><a href="#" id="LbLoadingLink"><img src="'+Lightbox.fileLoadingImage+'"></a></div>'+
			'</div></div>'+
			'<div id="imageDataContainer"><div id="imageData"><div id="imageDetails"><span id="LbComment"></span><div style="clear:both"></div></div></div></div></div>');
		$("body").append('<div id="LbHeader"><div class="inner"><table cellspacing="0" cellpadding="0" border="0"><tr><td width="40%" id="LbCaption"></td><td width="20%" id="LbMiddle"><a href="#" id="LbPrev"><img src="' + Lightbox.filePrevButton + '"/></a> <span id="LbNavStatus"></span> <a href="#" id="LbNext"><img src="' + Lightbox.fileNextButton +'"/></a></td><td width="40%" class="LbRight"><a href="#" id="LbFirst"><img src="'+Lightbox.fileFirstButton+'" /></a><a href="#" id="LbLast"><img src="'+Lightbox.fileLastButton+'" /></a><a href="#" id="LbNavClose"><img src="' + Lightbox.fileCloseButton +'"/></a></td></tr></table></div></div>');
		$("#LbOverlay").click(function(){ Lightbox.end(); }).hide();
		$("#LbNavClose").click(function(){ Lightbox.end(); });
		$("#Lightbox").click(function(){ Lightbox.end();}).hide();
		$("#LbLoadingLink").click(function(){ Lightbox.end(); return false;});
		$('#LbOuterImageContainer').css({width: '250px', height: '250px'});
		$("#LbHeader").hide();
		$("#prevLink").click(Lightbox.goPrev);
		$("#LbPrev").click(Lightbox.goPrev);
		$("#LbFirst").click(Lightbox.goFirst);
		$("#nextLink").click(Lightbox.goNext);
		$("#LbNext").click(Lightbox.goNext);
		$("#LbLast").click(Lightbox.goLast);
		$(window).resize(function (){
			var arrayPageSize = Lightbox.getPageSize();
			$("#LbHeader").width(arrayPageSize[2]);
			$("#LbOverlay").width(arrayPageSize[2]);
		});
		$(window).scroll(function (){
			var newTop = Lightbox.getPageScroll()[1]+5;
			$("#LbHeader").css({top: newTop});
		});
		//alert(window.location);
		var hash = window.location.hash.substr(1);
		if (hash in Lightbox.anchors) {
				Lightbox.start(hash);
		}
	},
	
	//
	//	clickStart()
	//	Display overlay and lightbox. If image is part of a set, add siblings to Lightbox.imageArray.
	//	start()
	start: function(imageHash) {
		$("select, embed, object").hide();
		// stretch overlay to fill page and fade in
		var arrayPageSize = Lightbox.getPageSize();
		$("#LbHeader").width(arrayPageSize[2]);
		$("#LbOverlay").width(arrayPageSize[2]);

		var newTop = Lightbox.getPageScroll()[1]+5;
		$("#LbHeader").css({top: newTop});
		
		$("#LbOverlay").hide().css({height: arrayPageSize[1]+'px', opacity : Lightbox.overlayOpacity}).fadeIn();
		// show navigaton header
		//
		Lightbox.imageArray = [];
		imageNum = 0;		

		collection_id = Lightbox.anchors[imageHash][0];
		imageNum = Lightbox.anchors[imageHash][1];
		$("image", Lightbox.collections[collection_id]).each(
			function(i) {
				_src = $("src",this).text();
				_title = $("title",this).text();
				_comment = $("comment",this).text();
				_uid = $(this).attr("uid");
				Lightbox.imageArray.push(
					new Array(_uid, _src, _title, _comment, undefined, undefined))			
			});

		// calculate top and left offset for the lightbox 
		var arrayPageScroll = Lightbox.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#Lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();
		
		this.changeImage(imageNum);
	},
	//
	clickStart: function(imageLink) {


		// loop through anchors, find other images in set, and add them to Lightbox.imageArray
		relname = imageLink.rel;
		relindex = relname.indexOf('|')+1;
		uid = relname.substr(relindex);
		Lightbox.start(uid);
	},
	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {	
		if(this.inprogress == false){
			this.inprogress = true;
			Lightbox.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#LbLoading').show();
			$('#LbImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();
			$('#imageDataContainer').hide();
		
			imgPreloader = new Image();
		
			// once image is preloaded, resize image container
			imgPreloader.onload=function(){
				document.getElementById('LbImage').src = Lightbox.imageArray[Lightbox.activeImage][1];
				Lightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
			}
			imgPreloader.src = Lightbox.imageArray[Lightbox.activeImage][1];
		}
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get curren width and height
		this.widthCurrent = document.getElementById('LbOuterImageContainer').offsetWidth;
		this.heightCurrent = document.getElementById('LbOuterImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (Lightbox.borderSize * 2));
		var heightNew = (imgHeight  + (Lightbox.borderSize * 2));

		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;

		$('#LbOuterImageContainer').animate({width: widthNew, height: heightNew},Lightbox.resizeSpeed,'linear',function(){
				Lightbox.showImage();

		});


		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ Lightbox.pause(250); } else { Lightbox.pause(100);} 
		}

		$('#prevLink').css({height: imgHeight+'px'});
		$('#nextLink').css({height: imgHeight+'px'});
		$('#imageDataContainer').css({width: widthNew+'px'});

		
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		$('#LbLoading').hide();
		$('#LbImage').fadeIn("fast");
		Lightbox.updateDetails();
		this.preloadNeighborImages();
		this.inprogress = false;
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
		window.location.hash =  "#"+Lightbox.imageArray[Lightbox.activeImage][0];
		$("#imageDataContainer").hide();
		$("#LbHeader").show();
		// if caption is not null
		if(Lightbox.imageArray[Lightbox.activeImage][2]){
			$('#LbCaption').html(Lightbox.imageArray[Lightbox.activeImage][2]); 
		} else {
			$('#LbCaption').empty(''); 
		}
		if(Lightbox.imageArray[Lightbox.activeImage][3]){
			$('#LbComment').html(Lightbox.imageArray[Lightbox.activeImage][3]).fadeIn();
		} else {
			$('#LbComment').empty('').hide();
		}
		
		// if image is part of set display 'Image x of x' 
		if(Lightbox.imageArray.length > 1){
			$('#LbNavStatus').html(eval(Lightbox.activeImage + 1) + " / " + Lightbox.imageArray.length);
		}

		$("#imageDataContainer").hide().slideDown("slow");
		var arrayPageSize = Lightbox.getPageSize();
		$('#LbOverlay').css({height: arrayPageSize[1]+'px'});
		Lightbox.updateNav();
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		$('#hoverNav').show();				

		// if not first image in set, display prev image button
		if(Lightbox.activeImage != 0){
			$('#prevLink').show();
			$('#LbPrev').show();
			$('#LbPrev img').attr('src', Lightbox.filePrevButton);
		} else {
			$('#LbPrev img').attr('src', Lightbox.filePrevButtonDisabled);
		}

		// if not last image in set, display next image button
		if(Lightbox.activeImage != (Lightbox.imageArray.length - 1)){
			$('#LbNext').show();
			$('#LbNext img').attr('src', Lightbox.fileNextButton);
			$('#nextLink').show();
		} else {
			$('#LbNext img').attr('src', Lightbox.fileNextButtonDisabled);
		}
		
		this.enableKeyboardNav();
	},
	goFirst: function() {
		if (Lightbox.activeImage != 0)
			Lightbox.changeImage(0);
		return false;
	},
	goLast: function() {
		if (Lightbox.activeImage != Lightbox.imageArray.length-1)
			Lightbox.changeImage(Lightbox.imageArray.length - 1);
		return false;
	},
	goNext: function() {
		if(Lightbox.activeImage < (Lightbox.imageArray.length - 1))
			Lightbox.changeImage(Lightbox.activeImage + 1); 
		return false;
	},
	goPrev: function() {
		if (Lightbox.activeImage > 0)
			Lightbox.changeImage(Lightbox.activeImage - 1); 
		return false;
	},
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
			escapeKey = 27;
		} else { // mozilla
			keycode = e.keyCode;
			escapeKey = e.DOM_VK_ESCAPE;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){	// close lightbox
			Lightbox.end();
		} else if((key == 'p') || (keycode == 37)){	// display previous image
			if(Lightbox.activeImage != 0){
				Lightbox.disableKeyboardNav();
				Lightbox.changeImage(Lightbox.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){	// display next image
			if(Lightbox.activeImage != (Lightbox.imageArray.length - 1)){
				Lightbox.disableKeyboardNav();
				Lightbox.changeImage(Lightbox.activeImage + 1);
			}
		}

	},

	preloadNeighborImages: function(){

		if((Lightbox.imageArray.length - 1) > Lightbox.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = Lightbox.imageArray[Lightbox.activeImage + 1][1];
		}
		if(Lightbox.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = Lightbox.imageArray[Lightbox.activeImage - 1][1];
		}
	
	},

	end: function() {
		this.disableKeyboardNav();
		$('#Lightbox').hide();
		$("#LbHeader").fadeOut();
		$("#LbOverlay").fadeOut();
		$("select, object, embed").show();
	},
	
	getPageSize : function(){
		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;
	},
	getPageScroll : function(){
		
		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;
	},
	pause : function(ms){
		var date = new Date();
		curDate = null;
		do{var curDate = new Date();}
		while( curDate - date < ms);
	},
	addCollection: function(collection_id, collection_url) {
		$.get(collection_url, {}, function(data) {
			Lightbox._processCollection(collection_id, data);
		});
	},
	_processCollection: function(collection_id, data) {
		Lightbox.collections[collection_id] = data;
		n = 0;
		$("image", data).each(
			function(i) {
				var uid = $(this).attr("uid");
				Lightbox.anchors[uid] = 
						new Array(collection_id,n);
				n = n + 1;
			});
	}
};

$("body").prepend('<div id="LbWaitAMinute" style="position: absolute; top: 0px; left:10px;"><img src="' + Lightbox.fileWaitAMinute +'" /></div>');
$(document).ready(function(){
	Lightbox.initialize();
	$("#LbWaitAMinute").remove();
});

