$(document).ready(function() {
	lightbox();
});

var ieVersion = '';

function lightbox() {
	// LightBox thumbnail viewer style variables
	
	var thumbMaxSize = 60;	// In pixels. Sets the LightBox Thumbnails' max height/width
	var visibleThumbs = 8;	// How many thumbnails will be visible in each frame
	var sliderWidth = (ieVersion == 6 ? 694 : 680);	// In pixels. Set this to the width of the visible area of the thumbnail slider
	var lbWidth = 800;		// In pixels. Overrides the math for determining the width of the lightbox.
	
	// LightBox HTML elements
	
	var links = $('a[href$=jpg], a[href$=jpeg], a[href$=JPG], a[href$=JPEG]');
	var overlay = $(jQuery('<div id="overlay" style="display: none"></div>'));
	var lightbox = $(jQuery('<div id="lightbox" style="display: none"></div>'));
	var closeBtn = $(jQuery('<a href="#close" class="close">&times; Close</a>'));
	var target = $(jQuery('<div class="target"></div>'));
	
	// Zoom-in/out
	var zoomInOut = $(jQuery('<span style="display:none;"></span>'));
	var zoomInContents = '<img src="/include/images/zoom_in_16.gif" alt="" width="16" height="16" border="0">Click to zoom in';
	var zoomOutContents = '<img src="/include/images/zoom_out_16.gif" alt="" width="16" height="16" border="0">Click to zoom out';
	
	// Slider
	var slider = $(jQuery('<div id="GWLBSlider" />'));
	var sliderPrevNext = $(jQuery('<ul id="GWLBSliderNav"></ul>'));
	var sliderPrev = $(jQuery('<li class="prevThumb">&laquo; Previous</li>'));
	var sliderNext = $(jQuery('<li class="nextThumb">Next &raquo;</li>'));
	var sliderInner = $(jQuery('<div id="GWLBSliderInner" />'));
	var sliderMask = $(jQuery('<div id="GWLBSliderMask" />'));
	var thumbList = $(jQuery('<ul id="GWLBThumbs"></ul>'));
	
	// Slider Global variables
	var selectedThumb = null;
	var sliderCurrentView = 0;
	var clickedDir = 0;
	var slideCount = null;
	var slideIncrement = 1;
	var t = null;
	var resizeTimer = null;
	var mouseInside = false;
	var linkPos = null;
	var linkHeight = null;
	var linkWidth = null;
	var img = null;
	var imgOrigHeight = null;
	var imgOrigWidth = null;
	var browserWidth = null;
	var browserHeight = null;
	var url = null;
	var cssTop = null;
	var cssLeft = null;
	var fullSize = true;
	var enlargeButtonHeight = 0;
	var targetPadding = new Array();
	var frameNum = null;
	
	// General: Cache background images in Internet Explorer 6
	// Used to prevent flickering background-images attached to links
	if (ieVersion == 6) {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	}
		
	// Construct HTML
	$('body').append(overlay).append(lightbox);
	lightbox.append(closeBtn).append(target);
	if (links.size() > 1) {
		lightbox.append(slider);
		slider.append(sliderInner);
		sliderInner.append(sliderMask);
		sliderMask.append(thumbList);
	}
	
	lightbox.show().css({'top': Math.round((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - lightbox.outerHeight()) / 2) + 'px', 'left': Math.round(($(window).width() - lightbox.outerWidth()) / 2) + 'px', 'margin-top': 0, 'margin-left': 0}).hide();
	
	// Lightbox: Set slider to 0 opacity to hide it
	// Used as alternative to "display:none;" so the element remains in the DOM
	
	slider.css('opacity', 0);
	if (ieVersion != 8 && ieVersion != 6) lightbox.css('opacity', 0);
	
	// Lightbox: Detect if the cursor is the Lightbox
	// Used to determine if click is outside lightbox
	
	lightbox.hover(function(){ 
		mouseInside=true; 
	}, function(){ 
		mouseInside=false; 
	});
	
	// Lightbox: Handle the "Close" events
	
	// Close when ".close" button is pressed
	closeBtn.click(function(c) {
		c.preventDefault();
		LBClose();
	});
	
	// Close when click outside "#lightbox" is detected
	$('body').mouseup(function() {
		if (!mouseInside) {
			LBClose();
		}
	});
	
	// Lightbox: Perform the close event
	
	function LBClose() {
		if (lightbox.is(':visible')) {
			overlay.add(lightbox).add(closeBtn).fadeOut('normal');
			slider.css('opacity', 0);
			if (ieVersion != 8) lightbox.css('opacity', 0);
			selectedThumb.removeClass('selected');
			lightbox.css('height', 0 + 'px').css('width', 0 + 'px').css('overflow', 'hidden');
			zoomInOut.css('width', '100%').remove();
			target.contents().remove();
			target.css('height','auto').css('width','auto');
			slider.css('display','block');
		}
	}

	// Function for looping through the links, attaching the event listener, and building the thumbnail list
	links.each(
		function(index) {
			var link = $(this);
			
			// Get the dimensions of the image belonging to "link" for resizing of LightBox thumbnails
			var thisThumb = $("body a[href=" + link.attr('href') + "] img");
			var thumbSrc = thisThumb.attr('src');
			if (thisThumb.width() > thumbMaxSize || thisThumb.height() > thumbMaxSize) {			
				if (thisThumb.height() > thisThumb.width()) {
					var h = thumbMaxSize;
					var w = thumbMaxSize * (thisThumb.width() / thisThumb.height());
				} else {
					var w = thumbMaxSize;
					var h = thumbMaxSize * (thisThumb.height() / thisThumb.width());
				}
			}

			link.click(
				function(c) {
					frameNum = Math.ceil(slideCount / visibleThumbs);
					zoomInOut.css('display','none');
					target.removeClass('zoomIn');
					closeBtn.fadeOut('normal');
					target.css('height','auto').css('width','auto');
					
					// Select the clicked anchor's corresponding thumbnail from the lightbox list, select it's parent LI
					selectedThumb = $('#GWLBThumbs li a[href=' + link.attr('href') + ']').parent();
					
					if (slideCount > visibleThumbs) {
					
						// Find the index of the selected LI
						var index = selectedThumb.parent().children().index(selectedThumb);
						
						// Calculate which section of thumbs the LI is part of and slide to it is necessary
						if (index < slideCount) {
							slideIncrement = Math.floor((index) / (visibleThumbs));
							animateSlide(slideIncrement,frameNum);
						}
					}
					
					// Get the details about the clicked anchor's size and position
					// Used to set the lightbox position before open animation
					linkPos = link.children().offset();
					linkWidth = link.children().innerWidth();
					linkHeight = link.children().innerHeight();
					
					// Prevent redirect to linked image
					c.preventDefault();
					
					// Open the selected image in the lightbox
					open(link.attr('href'));
					
					// Remove selected state of last image thumbnail
					$("#GWLBThumbs li.selected").removeClass('selected');
					
					// Attach selected state to new thumbnail
					selectedThumb.addClass('selected');
				}
			);
			link.attr({'lb-position': index});
			var matching = $("#GWLBThumbs a[href=" + link.attr('href') + "]");
			if(matching.size() < 1) {
				$("a[href=" + link.attr('href') + "]:first:not(#GWLBThumbs a)").clone(true).appendTo('<li />').parent().appendTo('#GWLBThumbs');
			}
			
			slideCount = $('#GWLBSlider #GWLBSliderMask #GWLBThumbs').children().size();
			
			// Resize LightBox Thumbnails
			$("#GWLBThumbs li a[href=" + link.attr('href') + "] img").css({ 'height': h, 'width': w, 'margin-top':(65 - h)/2 });
			
			if (slideCount > visibleThumbs) {
				// Set the slider mask width to the combined width of all slides
				sliderMask.css('width', sliderWidth + 'px');
				
				// Insert the Slider Navigation into the DOM
				sliderInner.prepend(sliderPrevNext);
				sliderPrevNext.append(sliderPrev);
				sliderPrevNext.append(sliderNext);
			}
		}
	);
  
  	// Lightbox: Determine if lightbox should open or just swap the image
  	
	function open(url) {
		if (lightbox.is(':visible')) {
			target.contents().fadeOut('normal', function() {
				target.contents().remove();
				loadImage(url);
			});
		} else {
			target.children().remove();
			
			// Get current browser window dimensions
			browserWidth = $(window).width();
			browserHeight = $(window).height();
			
			// Calculate the difference between top top of the browser window and the top of the document
			var scrollTop = $(window).scrollTop();
			
			// Set the top and left position value
			cssTop = parseInt((linkHeight / 2) - (lightbox.height() / 2) - scrollTop + linkPos.top);
			cssLeft = parseInt((linkWidth / 2) - (lightbox.width() / 2) + linkPos.left);
			
			// If a generated click event, center the lightbox for zooming
			if (linkPos.top == scrollTop && linkPos.left == 0) {
				cssTop = parseInt((browserHeight / 2) - (lightbox.height() / 2));
				cssLeft = parseInt((browserWidth / 2) - (lightbox.width() / 2));
			}
			
			// Position the lightbox to zoom from the clicked anchor
			lightbox.css('top', cssTop + 'px').css('left', cssLeft + 'px');
			
			overlay.css('height', $('body').height()).css('width', $('body').width()).css('opacity', 0.8);
			overlay.add(lightbox).fadeIn('normal',function(){
				loadImage(url);
			});
		}
	}
	
	// Lightbox: Load the image
	
	function loadImage(url) {	
		if (lightbox.is('.loading')) { return; }
		lightbox.addClass('loading');
		img = new Image();
		img.onload = function() {
			target.contents().css('display', 'none');
			
			// Store the current image and browser dimensions
			// Used for dynamic resizing of the lightbox when the browser is resized
			imgOrigHeight = img.height;
			imgOrigWidth = img.width;
			
			// Resize the image
			imageResize(url);			
		}
		img.src = url;
		$(img).attr('id', 'LBMainImg');
	}
	
	// Lightbox: Resize image
	
	function imageResize(url) {
		var newHeight = img.height;
		var newWidth = img.width;
		var zoomLevel = null;
		fullSize = true;
		
		// Set the maximum image dimensions for the current broweser window size
		var maxWidth = (($(window).width() > window.innerWidth ? window.innerWidth : $(window).width()) - parseInt(lightbox.css('padding-left'),10) - parseInt(lightbox.css('padding-right'), 10) - parseInt(target.css('padding-left'), 10) - parseInt(target.css('padding-right'), 10)) - 100;
		
		var maxHeight = ((parseInt($(window).height() - slider.height()) > parseInt(window.innerHeight - slider.height()) ? parseInt(window.innerHeight - slider.height()) : parseInt($(window).height() - slider.height())) - parseInt(lightbox.css('padding-top'),10) - parseInt(lightbox.css('padding-bottom'), 10) - parseInt(target.css('padding-top'), 10) - parseInt(target.css('padding-bottom'), 10)) - 100;
		
		// Proportionally resize image to fit within useable window space
		if( imgOrigWidth > maxWidth || imgOrigHeight > maxHeight ) { // One of these is larger than the window
			var ratio = imgOrigWidth / imgOrigHeight;
			if(imgOrigHeight > imgOrigWidth) {
				if (imgOrigHeight >= maxHeight) {
					newHeight = maxHeight;
					newWidth = maxHeight * ratio;
					zoomLevel = newHeight/imgOrigHeight;
				}
			} else {
				newWidth = maxWidth;
				newHeight = maxWidth / ratio;
				zoomLevel = newWidth/imgOrigWidth;
			}
			if (newHeight >= maxHeight) {
				newHeight = maxHeight;
				newWidth = maxHeight * ratio;
				zoomLevel = newHeight/imgOrigHeight;
			}
			if (newWidth >= maxWidth) {
				newWidth = maxWidth;
				newHeight = maxWidth / ratio;
				zoomLevel = newWidth/imgOrigWidth;
			}
			// Check the zoom level to allow/disallow image zoom
			if(zoomLevel < 0.85) { fullSize = false; } // if the image is being displayed smaller than full-size
			enlargeButtonHeight = 26; // Height of the enlarge button to be added or subtraced
		}
		
		// If the current browser window dimensions are smaller than the stored window dimensions, resize the image now
		// Used to keep the image from resizing after the lightbox window resizes
		if (browserWidth > $(window).width() || browserHeight > $(window).height()) {
			img.height = newHeight;
			img.width = newWidth;
		}
		
		// Set animation parameter values
		var containerMinWidth = parseInt(newWidth + parseInt(lightbox.css('padding-left'),10) + parseInt(lightbox.css('padding-right'), 10) + parseInt(target.css('padding-left'), 10) + parseInt(target.css('padding-right'), 10));
					
		if (containerMinWidth < lbWidth) containerMinWidth = lbWidth;
		
		var height = parseInt(newHeight + slider.height() + /* click to enlarge button: */ enlargeButtonHeight + parseInt(target.css('padding-top'), 10) + parseInt(target.css('padding-bottom'), 10));
		var top = parseInt((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - newHeight - /* click to enlarge button: */ enlargeButtonHeight - slider.height() - parseInt(lightbox.css('padding-top'),10) - parseInt(lightbox.css('padding-bottom'),10) - parseInt(target.css('padding-top'), 10) - parseInt(target.css('padding-bottom'), 10)) / 2) + 'px';
		var left = parseInt(($(window).width() - containerMinWidth - parseInt(lightbox.css('padding-left'),10) - parseInt(lightbox.css('padding-right'),10)) / 2) + 'px';
		
		// Set animation parameters 
		var LBAnimParams = {'width': containerMinWidth,'height': height, 'top': top, 'left': left, opacity: 1.0 };
		
		// override the pervious animation parameters for Internet Explorer 8
		if (ieVersion == 8 || ieVersion == 6) var LBAnimParams = {'width': containerMinWidth,'height': height, 'top': top, 'left': left };
		
		lightbox.animate(LBAnimParams,'normal', function(){									
			lightbox.css('overflow', 'visible');
			
			// Resize image
			img.height = newHeight;
			img.width = newWidth;	
			
			if (fullSize === false) {
				target.removeClass('zoomOut').addClass('zoomIn');
				target.append(zoomInOut);
				zoomInOut.css('width', '100%');
				zoomInOut.contents().remove();
				zoomInOut.append(zoomInContents);
				if (ieVersion == 6) {
					zoomInOut.css('width', 'auto');	
				}
				zoomInOut.fadeIn('normal');
				
				// Zoom image on click
				target.click(function(){
					if(target.hasClass('zoomIn')) {
						// Store the target element's padding for resetting
						targetPadding['top'] = target.css('padding-top');
						targetPadding['side'] = target.css('padding-right');
						targetPadding['bottom'] = target.css('padding-bottom');
						zoomFullSize();
					}
				});
			}
			
			// Verify that the lightbox is loading an image before appending any elements to the lightbox
			// Used to prevent re-appending the current image on browser window resize
			if (lightbox.is('.loading')) {
				// insert image into the lightbox
				if($('#LBMainImg')) $(img).remove();
				target.append($(img));
				
				target.contents().fadeIn('normal', function() {
					lightbox.removeClass('loading');
				});
				
				// Decide if slider should be full-width or sized to fit the available images
				if (visibleThumbs < slideCount) {
					
					// Resize the slide container to fit all slides
					$('#GWLBThumbs').css('width',parseInt(($('#GWLBThumbs li').outerWidth(true))*slideCount) + 'px');
				} else {
					
					// Resize the slider inner-container to fit the slides
					sliderInner.css('width', parseInt($('#GWLBThumbs li').outerWidth(true)*slideCount) + 'px');
				}
				
				// Fade-in the slider
				slider.fadeTo('slow', 1.0);
				
				// reveal the close button
				closeBtn.css('display','block');
			} else {
				$(img).css('top','auto').css('left','auto').css('cursor','inherit').removeClass('ui-draggable');
				target.css('width','auto').css('height','auto');
				slider.add(closeBtn).add($(img)).fadeIn('normal');	
			}
			
			var LBMainPad = Math.round(parseInt(enlargeButtonHeight) - parseInt(target.css('padding-top')));
			if(LBMainPad < 0) LBMainPad = 0;
			$(img).css('padding-top', LBMainPad + 'px');

			// Store current browser window dimensions
			browserWidth = $(window).width();
			browserHeight = $(window).height();
		});
	}
	
	// Lightbox: Zoom in on the Main Image and make it draggable
	
	function zoomFullSize() {
		
		// Verify that the image can be zoomed
		if(fullSize === false) {
			slider.add(closeBtn).add(zoomInOut).fadeOut('fast', function() {
				
				// Set various elements' CSS
				target.css('padding', '0');
				$(img).css('padding-top','0');
				target.removeClass('zoomIn').addClass('zoomOut');
				zoomInOut.contents().remove();
				zoomInOut.css('width', '100%');
				zoomInOut.append(zoomOutContents);
				
				// Calculate the dimensions and position of the lightbox window
				var maxWidth = (($(window).width() > window.innerWidth ? window.innerWidth : $(window).width()) - parseInt(lightbox.css('padding-left'),10) - parseInt(lightbox.css('padding-right'), 10)) - 100;
				
				var maxHeight = ((parseInt($(window).height()) > parseInt(window.innerHeight) ? parseInt(window.innerHeight) : parseInt($(window).height())) - parseInt(lightbox.css('padding-top'),10) - parseInt(lightbox.css('padding-bottom'), 10) + 26) - 100;
				
				var top = parseInt((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - maxHeight - parseInt(lightbox.css('padding-top'),10) - parseInt(lightbox.css('padding-bottom'),10)) / 2) + 'px';
				
				var left = parseInt(($(window).width() - maxWidth - parseInt(lightbox.css('padding-left'),10) - parseInt(lightbox.css('padding-right'),10)) / 2) + 'px';
				
				// Animate the lightbox resize
				var LBAnimParams = {'width': maxWidth,'height': maxHeight, 'top': top, 'left': left };
				
				lightbox.animate(LBAnimParams,'normal', function() {
					
					// Match the target element's dimensions to the lightbox
					target.css('width', parseInt(lightbox.width()) - parseInt(target.css('padding-right')) - parseInt(target.css('padding-left'))).css('height', parseInt(lightbox.height()) - parseInt(target.css('padding-top')) - parseInt(target.css('padding-bottom')));
					
					// Resize the image
					img.height = imgOrigHeight;
					img.width = imgOrigWidth;
					
					// Calculate and set the image's start position (horizontal and vertical center)
					var imgLeft = parseInt(Math.round(maxWidth / 2) - Math.round(imgOrigWidth / 2));
					if(imgLeft < 0) {
						imgLeft =  imgLeft + 'px';
					} else {
						imgLeft = 'auto';
					}
					$(img).css('position','relative').css('top',parseInt(Math.round(maxHeight / 2) - Math.round(imgOrigHeight / 2)) + 'px').css('left', imgLeft);
					
					lightbox.css('overflow','visible');
					zoomInOut.css('width', lightbox.innerWidth() + 'px');
					$('.close, .zoomOut span').fadeIn('fast');
					
					// Make the Image Draggable
					
					// Set the default cursor CSS
					var cursorDrag = 'url(/include/images/grabbing.cur), pointer';
					var cursorDrop = 'url(/include/images/grab.cur), pointer';
					
					// Detext the browser in use and swap set the appropriate cursor CSS (or leave default)
					jQuery.each(jQuery.browser, function(i) {
						if($.browser.safari){
							cursorDrag = 'url(/include/images/grabbing.cur), -webkit-grabbing';
							cursorDrop = 'url(/include/images/grab.cur), -webkit-grab';
						}else if($.browser.mozilla){
							cursorDrag = '-moz-grabbing';
							cursorDrop = '-moz-grab';
						}
					});
					$(img).css('cursor',cursorDrop);
					$(img).draggable({
						'cursor':cursorDrag,
						start: function() {
							$(img).css('cursor',cursorDrag);
						},
						stop: function() {
							$(img).css('cursor',cursorDrop);
						}
					});
					
					// Set the zoomout onclick event
					$(".zoomOut span").click(function(){
						if(target.hasClass('zoomOut')) {
							$(img).draggable( 'destroy' );
							closeBtn.add(zoomInOut).add($(img)).fadeOut('normal');
							target.removeClass('zoomOut');
							target.css('padding', targetPadding['top'] + ' ' + targetPadding['side'] + ' ' + targetPadding['bottom']);
							imageResize();
						}
					});
				});
			});
		}
	}
	
	// Lightbox: Select the next set of slides and slide them into view
	
	function selectAndSlide() {		
		
		if (!clickedDir) clickedDir = $("#GWLBSliderNav li").index(this);
		
		var nextView = (sliderCurrentView - 1);
		if (clickedDir) {
			nextView = (sliderCurrentView + 1);
		}
		if (nextView <= frameNum - 1 && nextView >= 0) {
			// slide to the new panel
			animateSlide(nextView, frameNum);
		}
		clickedDir = 0;
	}
	
	// Lightbox: Perform the slide movement
	function animateSlide(n,f) {
		if (n == 0) {
			sliderPrev.removeClass('hover').css({'opacity':0.3, 'cursor':'default'});
		} else sliderPrev.css({'opacity':1.0, 'cursor':'pointer'});
		
		if (n == f - 1) {
			sliderNext.removeClass('hover').css({'opacity':0.3, 'cursor':'default'});
		} else sliderNext.css({'opacity':1.0, 'cursor':'pointer'});
		
		sliderCurrentView = n;
		$('#GWLBThumbs').animate({left:"-"+ Math.round(n*sliderWidth)+"px"});
	}
	
	// LightBox: Listen for Window resize
	$(window).bind('resize', function(){
		if (lightbox.is(':visible')) {
			
			// Pause resize to help alleviate jerky animation when resizing
			if (resizeTimer) clearTimeout(resizeTimer);
			if(target.hasClass('zoomOut')) {
				resizeTimer = setTimeout(zoomFullSize, 500);
			} else {
				resizeTimer = setTimeout(imageResize, 500);
			}
		}
	});
	
	// General: Adds "hover" class to elements
	// Used to simulate :hover in Internet Explorer
	function hoverClass() {
		if ($(this).css('opacity') < 1) return;
		$(this).toggleClass('hover');
	}
	
	$("#GWLBSliderNav .prevThumb, #GWLBSliderNav .nextThumb").click(selectAndSlide);
	$("#GWLBSliderNav .prevThumb, #GWLBSliderNav .nextThumb").hover(hoverClass,hoverClass);

}
