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

function lightbox() {
	var ie = false;
	var vers = 0;
	if(jQuery.browser.msie) {
		ie = true;
		vers = parseInt(jQuery.browser.version);
	}
	
	// LightBox thumbnail viewer style variables
	
	var thumbMaxSize = 60;	// In pixels. Sets the LightBox Thumbnails' max height/width
	var visibleThumbs = 9;	// How many thumbnails will be visible in each frame
	var sliderWidth = (ie === true && vers == 6 ? 775 : 765);	// In pixels. Set this to the width of the visible area of the thumbnail slider
	
	// LightBox HTML elements
	
	var links = $('#mainImage a[href$=jpg], #prodImage .thumbs a[href$=jpg], #LBThumbs a[href$=jpg]');
	var overlay = $('#overlay');
	var lightbox = $('#lightbox');
	var closeBtn = $('#lightbox .close');
	var target = $('#lightbox .target');
	
	// Zoom-in/out
	var zoomInOut = $(jQuery('<span style="display:none;"></span>'));
	var zoomInContents = '<img src="/store/include/images/detail/icon-zoom.gif" alt="" width="19" height="21" />Click to zoom in';
	var zoomOutContents = '<img src="/store/include/images/detail/icon-zoom-out.gif" alt="" width="19" height="21" />Click to zoom out';
	
	// Slider
	var slider = $('#LBSlider');
	var sliderPrevNext = $(jQuery('<ul id="LBSliderNav"></ul>'));
	var sliderPrev = $(jQuery('<li class="prevThumb">&laquo; Previous</li>'));
	var sliderNext = $(jQuery('<li class="nextThumb">Next &raquo;</li>'));
	var sliderInner = $('#LBSliderInner');
	var sliderMask = $('#LBSliderMask');
	var thumbList = $('#LBThumbs');
	
	// Slider Global variables
	var contentContainerHeight = '';
	var selectedThumb = null;
	var sliderCurrentView = 0;
	var clickedDir = 0;
	var slideCount = thumbList.children().size();
	var slideIncrement = 1;
	var t = null;
	var resizeTimer = null;
	var mouseInside = false;
	var linkPos = null;
	var linkpad = 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 targetPadding = new Array();
	var frameNum = null;
	var maxWidth = null;
	var maxHeight = null;
	var windowResize = false;
	var scrollTop = null;
	var mtop = 0;
	var mleft = 0;
	var zoomLevel = 0;
	
	// General: Cache background images in Internet Explorer 6
	// Used to prevent flickering background-images attached to links
	if (ie === true && vers == 6) {
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	}
	
	lightbox.show().css({'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 (ie === false) 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('.loading')) return false;
		if (lightbox.is(':visible')) {
			lightbox.removeClass('visible');
			overlay.add(lightbox).add(closeBtn).fadeOut('normal');
			$('#prodInfo').animate({'height':contentContainerHeight});
			$('#prodImage').add('#pricing').fadeIn();
			// show select menus
			if (ie === true) {
				$('#pricing select').css('display','inline');
			}
			slider.css('opacity', 0);
			if (ie === false) lightbox.css('opacity', 0);
			selectedThumb.removeClass('selected');
			lightbox.css('height', 0 + 'px').css('width', 0 + 'px').css('overflow', 'hidden');
			zoomInOut.remove();
			target.contents().remove();
			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) {
					// Prevent redirect to linked image
					c.preventDefault();
					
					if(lightbox.is('.loading')) return false;
					if(lightbox.is(':hidden')) {
						// capture the height of the content container
						contentContainerHeight = $('#prodInfo').height();
						// Set content container height so fadeout isn't jarring
						$('#prodInfo').css({'height': contentContainerHeight + 'px', 'overflow':'visible'});
						
						// Hide select menus
						if (ie === true) {
							$('#pricing select').css('display','none');
						}
						
						// Fade out product image column and pricing column for smoother transition
						$('#prodImage').add('#pricing').fadeOut();
						
						// Hide Thumbnails
						slider.css('opacity', 0);
					}
					
					frameNum = Math.ceil(slideCount / visibleThumbs);
					zoomInOut.css('display','none');
					target.removeClass('zoomIn');
					closeBtn.fadeOut('normal');
					
					// Select the clicked anchor's corresponding thumbnail from the lightbox list, select it's parent LI
					selectedThumb = $('#LBThumbs 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);
						}
					}
					
					// scroll to lightbox
					scrollPage($('#prodInfo'));
					
					// Get the details about the clicked anchor's size and position
					// Used to set the lightbox position before open animation
					linkPos = $('img:eq(0)', link).offset();
					linkpad = parseInt($('img:eq(0)', link).css('padding-top'));
					linkWidth = $('img:eq(0)', link).width();
					linkHeight = $('img:eq(0)', link).height();
					
					// Open the selected image in the lightbox
					open(link.attr('href'));
					
					// Remove selected state of last image thumbnail
					$("#LBThumbs li.selected").removeClass('selected');
					
					// Attach selected state to new thumbnail
					selectedThumb.addClass('selected');
				}
			);
			
			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.hasClass('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
			scrollTop = $(window).scrollTop();
			
			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;
		fullSize = true;
		
		// Set the maximum image dimensions for the current broweser window size
		maxWidth = parseInt($('#prodInfo').width() - 10);
				
		maxHeight = ((parseInt($(window).height() - slider.height()) > parseInt(window.innerHeight - slider.height()) ? parseInt(window.innerHeight - slider.height() - 10) : 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)) - 30;
		
		if(maxHeight > 600) maxHeight = 600;
		
		// 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
		}
		
		// 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 = $('#prodInfo').width();
		var height = null;
		
		if (lightbox.hasClass('visible') && windowResize === false) {
			height = lightbox.height();
		} else {
			height = parseInt(maxHeight + slider.height() + parseInt(target.css('padding-top'), 10) + parseInt(target.css('padding-bottom'), 10) + 10);
		}
		
		// Set animation parameters 
		var LBAnimParams = {'width': containerMinWidth,'height': height, opacity: 1.0 };
		overlay.css({'height':height,'width':containerMinWidth});
		
		// override the previous animation parameters for Internet Explorer 8
		if (ie === true) var LBAnimParams = {'width': containerMinWidth,'height': height };
		
		target.css({'height':parseInt(height - $('#LBSliderBG').height() - 3)});
		
		$('#prodInfo').add(lightbox).animate(LBAnimParams,'normal', function() {
			
			overlay.fadeIn('fast');
						
			// Resize image
			if (lightbox.hasClass('visible')) {
				img.height = newHeight;
				img.width = newWidth;
			} else {
				img.height = linkHeight;
				img.width = linkWidth;
			}
			
			if (fullSize === false) {
				target.removeClass('zoomOut').addClass('zoomIn');
				target.append(zoomInOut);
				zoomInOut.contents().remove();
				zoomInOut.append(zoomInContents);
				zoomInOut.fadeIn('normal');
			}
			
			// 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));
								
				$(img).css({
					'top': parseInt(linkPos.top - lightbox.offset().top + linkpad),
					'left': parseInt((linkPos.left - lightbox.offset().left)),
					'position':'absolute'
				});
				
				lightbox.css({'width':'100%'});
				
				if (lightbox.hasClass('visible')) {
					
					$(img).css({'width':newWidth + 'px', 'height': newHeight + 'px', 'left': parseInt(($('#prodInfo').width() / 2) - (newWidth / 2)) + 'px', 'top': parseInt(((lightbox.height() - slider.height()) / 2) - (newHeight / 2) + 2) + 'px'});
					
				} else {
					
					$(img).animate({'width':newWidth + 'px','height':newHeight + 'px','left': parseInt(($('#prodInfo').width() / 2) - (newWidth / 2)) + 'px', 'top': parseInt(((lightbox.height() - slider.height()) / 2) - (newHeight / 2) + 2) + 'px'});
					
				}
				
				target.contents().fadeIn('normal', function() {
					lightbox.removeClass('loading').addClass('visible');
				});
				
				// 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
					$('#LBThumbs').css('width',parseInt((($('#LBThumbs li').outerWidth(true))*slideCount)*1.1) + 'px');
				} else {
					
					// Resize the slider inner-container to fit the slides
					sliderInner.css('width', parseInt($('#LBThumbs li').outerWidth(true)*slideCount) + 'px');
				}
				
				closeBtn.add($('.target span')).fadeIn('slow');
				
				// reveal the close button
				closeBtn.css('display','block');
			} else {
				var params = {
					'width':newWidth + 'px',
					'height': newHeight + 'px',
					'left': parseInt(($('#prodInfo').width() / 2) - (newWidth / 2)) + 'px',
					'top': parseInt(((lightbox.height() - slider.height()) / 2) - (newHeight / 2) + 5) + 'px'
				}
				if ($(img).width() != newWidth && $(img).height() != newHeight) {
					$(img).animate(params,"normal");
				} else {
					$(img).css(params);
				}
				if (!(ie === true && vers <= 7)) {
					$(img).css({'cursor':'inherit'});
				}
			}

			// Store current browser window dimensions
			browserWidth = $(window).width();
			browserHeight = $(window).height();
			
			// Fade-in the slider
			slider.fadeTo('slow', 1.0);
		});
	}
	
	// Lightbox: Zoom in on the Main Image and make it draggable
	
	function zoomFullSize() {
		
		// Verify that the image can be zoomed
		if(fullSize === true) return;
		
		// Set various elements' CSS
		target.css('padding', '0');
		$(img).css('padding-top','0');
		target.removeClass('zoomIn').addClass('zoomOut');
		zoomInOut.contents().remove();
		zoomInOut.append(zoomOutContents);
			
		// Resize the image				
		$(img).animate({
			'height': imgOrigHeight + 'px',
			'width': imgOrigWidth + 'px',
			'top': 
				(target.height() / 2) - (
					mtop < $("#LBMainImg").offset().top || mtop > $("#LBMainImg").offset().top + $("#LBMainImg").height() ?
					(mtop < $("#LBMainImg").offset().top ? 0 : imgOrigHeight):
					(mtop - $("#LBMainImg").offset().top) / zoomLevel
				) + 'px',
			'left':
				(target.width() / 2) - (
					mleft < $("#LBMainImg").offset().left || mleft > $("#LBMainImg").offset().left + $("#LBMainImg").width() ?
					(mleft < $("#LBMainImg").offset().left ? 0 : imgOrigWidth):
					(mleft - $("#LBMainImg").offset().left) / zoomLevel
				) + 'px'
		},"normal");
		
		lightbox.css('overflow','visible');
		
		// 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(/store/include/images/detail/grabbing.cur), -webkit-grabbing';
				cursorDrop = 'url(/store/include/images/detail/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);
			}
		});
	}
	
	// Zoom image on click
	target.click(function(e){
		if(target.hasClass('zoomOut')) {
			$(img).draggable( 'destroy' );
			target.removeClass('zoomOut');
			target.css('padding', targetPadding['top'] + ' ' + targetPadding['side'] + ' ' + targetPadding['bottom']);
			$(img).removeClass('ui-draggable');
			imageResize(url);
			
		} else if(target.hasClass('zoomIn')) {
			targetPadding['top'] = target.css('padding-top');
			targetPadding['side'] = target.css('padding-right');
			targetPadding['bottom'] = target.css('padding-bottom');
			
			// Collect the mouse position
			mtop = e.pageY;
			mleft = e.pageX;
			zoomFullSize();
		}
	});
	
	// Lightbox: Select the next set of slides and slide them into view
	
	function selectAndSlide() {		
		
		if (!clickedDir) clickedDir = $("#LBSliderNav 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').addClass('inactive');
		} else sliderPrev.removeClass('inactive');
		
		if (n == f - 1) {
			sliderNext.removeClass('hover').addClass('inactive');
		} else sliderNext.removeClass('inactive');
		
		sliderCurrentView = n;
		$('#LBThumbs').animate({left:"-"+ Math.round(n*sliderWidth)+"px"});
	}
	
	// LightBox: Listen for Window resize
	$(window).bind('resize', function(){
		if (lightbox.is(':visible')) {
			if (target.hasClass('zoomIn') || target.hasClass('zoomOut')) {
				
				// Pause resize to help alleviate jerky animation when resizing
				if(resizeTimer) clearTimeout(resizeTimer);
				windowResize = true;
				resizeTimer = setTimeout(function() {
					// scroll to lightbox
					scrollPage($('#prodInfo'));
					
					// Resize Image 
					imageResize(url);
					windowResize = false;
					}, 500);
			}
		}
	});
	
	// Store Detail: Activate Lightbox on click of view all button
	$('#prodImage .viewall').click(function(c){
		c.preventDefault();
		$('#prodImage #mainImage a').click();
	});
	
	// General: scroll the page to the lightbox
	function scrollPage(scrollto) {
		var destination = $(scrollto).offset().top;
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-15}, 500 );
	}
	
	// General: Adds "hover" class to elements
	// Used to simulate :hover in Internet Explorer
	function hoverClass() {
		if ($(this).hasClass('inactive')) return;
		$(this).toggleClass('hover');
	}
	
	$("#LBSliderNav .prevThumb, #LBSliderNav .nextThumb").click(selectAndSlide);
	$("#LBSliderNav .prevThumb, #LBSliderNav .nextThumb").hover(hoverClass,hoverClass);

}
