/**
 * jQuery Lightbox
 * Version 0.5 - 11/29/2007
 * @author Warren Krewenki
 *
 * This package is distributed under the BSD license.
 * For full license information, see LICENSE.TXT
 *
 * 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.
 *
 *
 **/

(function($){

	$.fn.lightbox = function(options){
		// build main options
		var opts = $.extend({}, $.fn.lightbox.defaults, options);
        var isMozilla = jQuery.browser.mozilla;
        var isMSIE = jQuery.browser.msie;
        
        var boxStarted = false;
        var firstLoad = true;
        var boxLoaded = false;
        var endTriggered = false;
        
        var pageImagesLoaded = false;
        
        // Set loading width and height base on default current width and height
        widthLoading = opts.widthCurrent;
        heightLoading = opts.heightCurrent;
        
        widthLastLoaded = opts.widthDefault;
        heightLastLoaded = opts.heightDefault;

        
        loadingImg = new Image();
        loadingImg.src = opts.fileLoadingImage;
        
		return this.each(function(){
			$(this).click(function(){
			    // Added by Jobert. Fix to multiple lightbox start. Set lightbox as not started. 
    		    if (boxStarted == false) {
    		    	boxStarted = true;
	    		    // initalize the lightbox
	    		    initialize();
					start(this);
					return false;
    		    }
			});
		});
		
	    /**
	     * initalize()
	     *
	     * @return void
	     * @author Warren Krewenki
	     */
	     
	    function initialize() {

			setImageModePhrase();
			
			$('#overlay,#lightbox').remove();

		    opts.inprogress = false;
		    
		    var closeImage = '<a href="javascript://" id="bottomNavClose" title="' + opts.strings.closeTitle + '"><img src="'+opts.fileBottomNavCloseImage+'"></a>';
		    var outerImage = '<div id="outerImageContainer">'+ closeImage +'<div id="imageContainer"><!--<img id="lightboxImage" src="/images/main/stuff/lightbox/blank.gif">--><div id="hoverNav"></div><div id="loading"><p>Patience is a gift.</p><a href="javascript://" id="loadingLink"><img src="'+opts.fileLoadingImage+'"></a></div></div></div>';
		    var imageData = '<div id="imageDataContainer" class="clearfix"><div id="imageData"><div id="imageDetails"><span id="caption"></span><div id="numberDisplay"></div><div id="bottomLinks"><a href="" id="imageModeLink" onclick="switchImageMode(); return false;">'+ imageModePhrase +'</a> | <a id="showImageLink" href="" target="_blank">Show photo link</a></div></div><div id="bottomNav"></div></div></div>';
		    var string = '<div id="overlay"></div><div id="lightbox">' + outerImage + imageData + '</div>';
		    $("body").append(string);
		    

		    $("#overlay,#lightbox").click(function(){ end(); }).hide();
		    $("#loadingLink,#wait,#loading,#hoverNav,#imageDataContainer,#outerImageContainer,#lightboxImage,#imageContainer").click(function(){ return false;});
		    $('#imageModeLink,#bottomNavClose').click(function(){ end(); return false; });
		    
		    $('#showImageLink').click(function(){showImageLink(); return false;});
		    
		    $('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
		    $('#imageDataContainer').width(opts.widthCurrent);
		    
		
	    };
	    
	    function showImageLink(){
			window.open(opts.imageArray[opts.activeImage][0]);
	    }
	    
	    function getPageSize() {
		    var jqueryPageSize = new Array($(document).width(),$(document).height(), $(window).width(), $(window).height());
		    return jqueryPageSize;
	    };
	    
	    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;
		    }

		    var arrayPageScroll = new Array(xScroll,yScroll);
		    return arrayPageScroll;
	    };
	    
	    function pause(ms) {
		    var date = new Date();
		    var curDate = null;
		    do{curDate = new Date();}
		    while(curDate - date < ms);
	    };
	    
	    function start(imageLink) {
	    	endTriggered = false;
	    	
	    	$('#lightboxImage').remove();	
	        
	    	$("select, embed, object").hide();
		    var arrayPageSize = getPageSize();
		    
		    //*** $("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : opts.overlayOpacity}).fadeIn();
		    $("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px'}).addClass('overlayTransparentFix').fadeIn();
		    
		    imageNum = 0;

            opts.imageArray = [];
            // if image is NOT part of a set..
		    if(!imageLink.rel || (imageLink.rel == '')){
			    // add single image to Lightbox.imageArray
			    opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
		    } else {
		    // if image is part of a set..
			    $("a").each(function(){
			        if(this.href && (this.rel == imageLink.rel)){
			            opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
			         }
			    });
		    }
		
		    if(opts.imageArray.length > 1) {
		        for(i = 0; i < opts.imageArray.length; i++){
				    for(j = opts.imageArray.length-1; j>i; j--){
					    if(opts.imageArray[i][0] == opts.imageArray[j][0]){
						    opts.imageArray.splice(j,1);
					    }
				    }
			    }
			    while(opts.imageArray[imageNum][0] != imageLink.href) { imageNum++;}
		    }

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


			$('#imageData').hide();

		    // Show patience is a gift on start of lightbox
			if (!boxLoaded) {
				boxLoaded = true;

				$('#loading').show();
				
				// Hide close button
				$("#bottomNavClose").hide();
				
				// Set default lightbox image dimension
				var widthNew = Math.max(350, opts.widthDefault  + (opts.borderSize * 2));
				var heightNew = (opts.heightDefault + (opts.borderSize * 2));
				
				
		        $('body').onImagesLoad({ 
		            selectorCallback: function(){
		        		$('#loading').fadeOut('slow', function(){
		        			if (endTriggered) {
		        				return;
		        			}
		        			
		        			pageImagesLoaded = true;
		        			
		        			// Give loading additional time to fade
		        			pause(100);
		        			
		        			$('#imageDataContainer').animate({width:widthNew},350,'linear');
		        			$('#outerImageContainer').animate({width:widthNew},350,'linear',function(){
		        				
		        			    $('#outerImageContainer').animate({height:heightNew},350,'linear',function(){
		        			    	// Show close button
		        			    	$("#bottomNavClose").show();
		        			    	
		        			    	var lightboxImage = document.getElementById('lightboxImage');	    	
		        			    	
		        			    	if (!lightboxImage) {
		        				    	// Create lightbox image
		        			    		lightboxImage = new Image();
		        			    		lightboxImage.id = 'lightboxImage';
		        				    	$('#imageContainer').prepend(lightboxImage);
		        			    	}
		        			    	
		        			    	// Set lightbox image initial width
//		        			    	$('#lightboxImage').width(opts.widthDefault);
		        			    	$('#lightboxImage').width(widthLastLoaded);
		        			    	
		        			    	// Change image
		        			    	changeImage(imageNum);
		        					// Update details on first load
		        					updateDetails();
		        			    });
		        			});
		        			
		        		});
		        	} 
		        });
			} else {
				//alert(opts.widthCurrent + ' ' + opts.heightCurrent);
				$('#loading').hide();

				if (opts.widthCurrent == widthLoading || opts.heightCurrent == heightLoading) {
					opts.widthCurrent =  opts.widthDefault + (opts.borderSize * 2);
				    opts.heightCurrent = opts.heightDefault + (opts.borderSize * 2);
				    $('#imageDataContainer').width(opts.widthCurrent);
				    $('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
				}
				
				if (imgFirstLoad) {
			    	var lightboxImage = document.getElementById('lightboxImage');	    	
			    	
			    	if (!lightboxImage) {
				    	// Create lightbox image
			    		lightboxImage = new Image();
			    		lightboxImage.id = 'lightboxImage';
				    	$('#imageContainer').prepend(lightboxImage);
			    	}
					
			    	// Set lightbox image initial width
//**			    	$('#lightboxImage').width(opts.widthDefault).height(opts.heightDefault);
			    	$('#lightboxImage').width(opts.widthDefault);
			    	
			    	opts.resizeSpeed = 350;
				}
				// Change image	
				changeImage(imageNum);
				// Update details on first load
				updateDetails();
			}
			
	    };
	    
	    function changeImage(imageNum) {
		    //**** if(opts.inprogress == false){
			    opts.inprogress = true;
			    opts.activeImage = imageNum;	// update global var

			    if (!isMSIE && !isMozilla) {
			    	$('#lightboxImage').hide();
			    	$('#lightboxImage').attr('src', '');
			    } else if (isMozilla){
			    	$('#lightboxImage').attr('src', '');
			    }	
			    $('#lightboxImage').width(widthLastLoaded).height(heightLastLoaded);
			    $('#caption').html('&nbsp;');
			    
			    doChangeImage();
		    //*** }
	    };

	    function doChangeImage() {
	    	var lightboxImage = document.getElementById('lightboxImage');	    	
	    	
	    	// Double check that lightbox image exist;
	    	if (!lightboxImage) {
	    		lightboxImage = new Image();
	    		lightboxImage.id = 'lightboxImage';
	    		$('#imageContainer').prepend(lightboxImage);
	    	}

	    	var resized = false;
	    	
	    	lightboxImage.onload=function(){
			    // Create a new image to get the dimension of loaded image.
	    		var cacheImage = new Image();
		    	
		    	cacheImage.onload=function(){
			        var trueWidth = cacheImage.width;
			        var trueHeight = cacheImage.height; 
			       
			   		if (trueWidth == 0 || trueHeight == 0) {		   			
			   			trueWidth = opts.widthDefault;
			   			trueHeight = opts.heightDefault;
			   		}

				    if (resized == false) {
				    	resized = true;

				    	newWidth = opts.widthDefault;
				    	newHeight = opts.heightDefault;
				    	
				    	// Resize lighbox only if the image height is greater than the default height
				    	if (trueHeight > opts.heightDefault) {
				    		if (opts.heightDefault == (trueHeight - 1)) {
				    			$('#imageContainer').css('padding-bottom', '9px');	
				    		} else {
				    			newHeight = trueHeight;
				    		}	
				    	}
				   		
					    resizeImageContainer(newWidth, newHeight, trueWidth, trueHeight);
				    }	
		    	}
		    	
				cacheImage.src = opts.imageArray[opts.activeImage][0];
		    	$('#cacheImage').append(cacheImage);
		    	
		    };
	    	
		    $('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0]);
		    
		    if (isMSIE || isMozilla) {
		    	$('#lightboxImage').css('display', 'inline');
		    } else {
			    $('#lightboxImage').fadeIn("fast");
		    }
		    
	    	showImage();
	    };
	    
	    function end() {
	    	endTriggered = true;
	    	
	    	firstLoad = true;
	    	
		    // Added by Jobert. Fix to multiple lightbox start. Set lightbox as not started. 
		    boxStarted = false;
		    // Set image first load to true
		    imgFirstLoad = true;
		    
		    if (!pageImagesLoaded) {
		    	boxLoaded = false;
		    	
		    	opts.widthCurrent = widthLoading;
		    	opts.heightCurrent = heightLoading;
		    	
			    $('#imageDataContainer').width(opts.widthCurrent);
			    $('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
			    $('#lightboxImage').remove();
		    }
		    
		    disableKeyboardNav();
		    
		    $('#lightbox').hide();
		    $('#overlay').fadeOut();
		    $('select, object, embed').show();
		    
	    };
	    
	    function resizeImageContainer(imgWidth, imgHeight, trueWidth, trueHeight) {
	    	 
			opts.widthCurrent = $("#outerImageContainer").outerWidth();
			opts.heightCurrent = $("#outerImageContainer").outerHeight();
			
		   	if (opts.widthCurrent == 0 || opts.heightCurrent == 0) {
		   		opts.widthCurrent = opts.widthDefault + (opts.borderSize * 2);
		   		opts.heightCurrent = opts.heightDefault + (opts.borderSize * 2);
		   	}	
			// get new width and height
			var widthNew = Math.max(350, imgWidth  + (opts.borderSize * 2));
			var heightNew = (imgHeight  + (opts.borderSize * 2));
	
			// scalars based on change from old to new
			opts.xScale = ( widthNew / opts.widthCurrent) * 100;
			opts.yScale = ( heightNew / opts.heightCurrent) * 100;
	
			// calculate size difference between new and old image, and resize if necessary
			wDiff = opts.widthCurrent - widthNew;
			hDiff = opts.heightCurrent - heightNew;
			    
			$('#imageDataContainer').animate({'width': widthNew},opts.resizeSpeed,'linear');
			$('#outerImageContainer').animate({'width': widthNew},opts.resizeSpeed,'linear',function(){
			    $('#outerImageContainer').animate({'height': heightNew},opts.resizeSpeed,'linear',function(){
			    	//alert(widthLastLoaded + ' != ' + trueWidth + ' && ' + heightLastLoaded + ' != ' + trueHeight);
			    	if (widthLastLoaded != trueWidth && heightLastLoaded != trueHeight) {
			    		$('#lightboxImage').animate({'width' : trueWidth, 'height' : trueHeight}, 350, 'linear');
			    		//$('#lightboxImage').width(trueWidth);
			    	} else if (heightLastLoaded != trueHeight) {
			    		$('#lightboxImage').animate({height : trueHeight}, 350, 'linear');
			    		//$('#lightboxImage').height(trueHeight);
			    	}
			    	
			    	if (trueHeight < opts.heightDefault) {
			    		hDiff = opts.heightDefault - trueHeight;
			    		marginTop = Math.floor(hDiff / 2);
			    		
			    		if (firstLoad) {
			    			$('#lightboxImage').animate({'marginTop' : marginTop}, 350, 'linear');
			    		} else {
			    			$('#lightboxImage').css('margin-top', marginTop + 'px');
			    		}
			    	} else {
			    		$('#lightboxImage').css('margin-top', '0');
			    	}
			    	
			    	// Set last loaded dimension;
			    	widthLastLoaded = trueWidth;
			    	heightLastLoaded = trueHeight;
			    	
			    	// Adjust image size
			    	//$('#lightboxImage').width(trueWidth).height(trueHeight);
			    	 
//***				    showImage();
					// Set resizing speed to 0
//***					opts.resizeSpeed = 0;
			    	firstLoad = false;
			    	
			    	arrPageSize = getPageSize();
			    	$("#overlay").css({height: arrPageSize[1]+'px'});
			    	
			    });
			});

		    $('#prevLink').height(imgHeight);
		    $('#nextLink').height(imgHeight);
	    };
	    
	    function showImage() {
	    	
		    updateDetails();
		    
		    opts.inprogress = false;
	    };
	    
	    function updateDetails() {
	    	
		    $('#numberDisplay').html('');

		    if(opts.imageArray[opts.activeImage][1]){
		    	$('#caption').html(opts.imageArray[opts.activeImage][1]);
		    }

		    // if image is part of set display 'Image x of x'
		    if(opts.imageArray.length > 1){
			    var nav_html;

			    nav_html = '';
			    
                // display previous / next text links
                if ((opts.activeImage) > 0 || opts.loopImages) {
                    nav_html = '<a title="' + opts.strings.prevLinkTitle + '" href="#" id="prevLinkText">' + opts.strings.prevLinkText + "</a>" + nav_html;
                }

                if (((opts.activeImage + 1) < opts.imageArray.length) || opts.loopImages) {
                    nav_html += '<a title="' + opts.strings.nextLinkTitle + '" href="#" id="nextLinkText">' + opts.strings.nextLinkText + "</a>";
                }

			    $('#numberDisplay').html(nav_html);
			    
			    //To fix hover bug on single click but triggers multible click
			    var hoverNavHtml = '<span title="' + opts.strings.prevLinkTitle + '" id="prevLink"></span><span id="nextLink" title="' + opts.strings.nextLinkTitle + '"></span>';
			    $('#hoverNav').html(hoverNavHtml);
			    
		    }

		    updateNav();
		    
			$("#imageData").show();
		    
		    // Update show image link url
		    $('#showImageLink').attr('href', opts.imageArray[opts.activeImage][0]);
		    
		    var arrayPageSize = getPageSize();
		    $('#overlay').height(arrayPageSize[1]);
		    
	    };
	    
	    function updateNav() {
		    if(opts.imageArray.length > 1){

			    
		    	$('#prevLink,#prevLinkText').click(function(){
	            	changeImage((opts.activeImage == 0) ? (opts.imageArray.length - 1) : opts.activeImage - 1); return false;
		        });
		            
		        $('#nextLink,#nextLinkText,#nextLinkFix').click(function(){
		        	changeImage((opts.activeImage == (opts.imageArray.length - 1)) ? 0 : opts.activeImage + 1); return false;
		        });
		        
			    enableKeyboardNav();
		    }
		    
		    imgFirstLoad = false;
	    };
	    
	    function keyboardAction(e) {
            var o = e.data.opts
		    var keycode = e.keyCode;
		    var escapeKey = 27;
            
		    var key = String.fromCharCode(keycode).toLowerCase();
            
		    if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
			    end();
		    } else if((key == 'p') || (keycode == 37)){ // display previous image
		        if(o.loopImages) {
		            disableKeyboardNav();
		            changeImage((o.activeImage == 0) ? (o.imageArray.length - 1) : o.activeImage - 1);
		        } 
		        else if(o.activeImage != 0){
				    disableKeyboardNav();
				    changeImage(o.activeImage - 1);
			    }
		    } else if((key == 'n') || (keycode == 39)){ // display next image
		        if (opts.loopImages) {
		            disableKeyboardNav();
		            changeImage((o.activeImage == (o.imageArray.length - 1)) ? 0 : o.activeImage + 1);
		        }
			    else if(o.activeImage != (o.imageArray.length - 1)){
				    disableKeyboardNav();
				    changeImage(o.activeImage + 1);
			    }
		    }
	    };
	    
	    function enableKeyboardNav() {
		    $(document).bind('keydown', {opts: opts}, keyboardAction);
	    };

	    function disableKeyboardNav() {
		    $(document).unbind('keydown');
	    };
	    
	};
    
	$.fn.lightbox.defaults = {
		fileLoadingImage : '/images/main/stuff/lightbox/bar-loading.gif',
		fileBottomNavCloseImage : '/images/main/stuff/lightbox/close.png',
		overlayOpacity : 0.8,
		borderSize : 10,
		imageArray : new Array,
		activeImage : null,
		inprogress : false,
		resizeSpeed : 350,
		widthDefault: 800, 
		heightDefault: 533,
		widthCurrent: 210,
		heightCurrent: 65,	
		xScale : 1,
		yScale : 1,
		displayTitle: true,
		strings : {
			prevLinkTitle: 'previous image',
			nextLinkTitle: 'next image',
			prevLinkText:  '&laquo; Previous',
			nextLinkText:  'Next &raquo;',
			closeTitle: 'close image gallery',
			image: 'Image ',
			of: ' of '
		},
        loopImages: true
	};
	
})(jQuery);

function initLightbox()
{
	 $(".lightbox").lightbox();
}
