// Variables
var zoomStatus = false;
var mouseX = 0;
var mouseY = 0;
var mainW; // Width
var mainH; // Height
var mainX; // X-Coordinate
var mainY; // Y-Coordinate
var boxW; // Width
var boxH; // Height
var boxX; // X-Coordinate
var boxY; // Y-Coordinate
var boxC; // Horizontal Centre X-Coordinate
var boxV; // Vertical Centre Y-Coordinate
var fullW; // Width
var fullH; // Height
var fullImageUrl;
var prevThumbInterval;
var nextThumbInterval;

// When DOM is ready
$(function() {

    // Main image click
    $("#images a.active").click(function(e) {
        
    	// Open zoom
    	return openImageZoom(e, $(this));
    	
    });
    
    // Main image mouse out
    $("#images a.active").bind('mouseout', closeImageZoom);
    
    // Zoom image
    function openImageZoom(eventObj, imageObj)
    {
		
    	// Check zoom format
    	if ($('#panBox').length > 0) {
	    	
	        // Update mouse coordinates
	        mouseX = eventObj.pageX;
	        mouseY = eventObj.pageY;
	        
	        // Check if zoom on
	        if (zoomStatus) {
	            
	            // Close pan box
	            closePanBox();
	            
	        } else {
	            
	            // Open pan box
	            openPanBox(imageObj.attr('href'));
	            
	        }
        
    	} else {
    		
    		// Open lightbox
    		openLightBox(imageObj.attr('href'));
    		
    	}
    	
        // Disable link
        return false;
        
    }
    
    // Close image zoom
    function closeImageZoom()
    {
    	
    	// Check zoom format
    	if ($('#panBox').length > 0) {
    		
	    	// Close pan box
	    	return closePanBox();
	    	
    	} else {
    		
    		// Return
    		return false;
    		
    	}
    	
    }
    
    // Open light box
    function openLightBox(fullImageUrl)
    {
		
        // Update zoom status
        zoomStatus = true;

        // Get body dimensions
        var bodyW = $('body').width();
        var bodyH = $('body').height();
        
        // Get screen dimensions
        var screenW = $(window).width();
        var screenH = $(window).height();
        
        // Get scroll coordinates
        var scrollX = $(window).scrollLeft();
        var scrollY = $(window).scrollTop();
        
        // Create full image object
        var fullImage = new Image();
        
        // Handle full image events
        $(fullImage)
            
            // On image load
            .load(function() {
            	
                // Update full image dimensions
                fullW = this.width;
                fullH = this.height;

                // Get image coordinates
                var imgX = scrollX + Math.round((screenW - fullW) / 2);
                var imgY = scrollY + Math.round((screenH - fullH) / 2);
                
                // Make sure coordinates not less than ten
                if (imgX < 10) { imgX = 10; }
                if (imgY < 10) { imgY = 10; }
                
                // Set div options
                $('#lightBoxBg').css('position', 'absolute');
                $('#lightBoxBg').css('float', 'left');
                $('#lightBoxBg').css('left', '0px');
                $('#lightBoxBg').css('top', '0px');
                $('#lightBoxBg').css('width', bodyW + 'px');
                $('#lightBoxBg').css('height', bodyH + 'px');
                $('#lightBoxBg').css('background-color', '#EEEEEE');
                $('#lightBoxBg').css('filter', 'alpha(opacity:50)');
                $('#lightBoxBg').css('-moz-opacity', '.50');
                $('#lightBoxBg').css('opacity', '.50');
                $('#lightBoxBg').css('cursor', 'pointer');
                $('#lightBox').css('position', 'absolute');
                $('#lightBox').css('float', 'left');
                $('#lightBox').css('left', imgX + 'px');
                $('#lightBox').css('top', imgY + 'px');
                $('#lightBox').css('width', fullW + 'px');
                $('#lightBox').css('height', fullH + 'px');
                $('#lightBox').css('background-image', 'url(' + fullImageUrl + ')');
                $('#lightBox').css('cursor', 'pointer');
                
                // Show lightbox
                $('#lightBoxBg').fadeIn();
                $('#lightBox').fadeIn();
                
            })
            
            // On image error
            .error(function() {
                
                // Error loading image
                alert('Error loading image');
                
            })
            
            // Set image source
            .attr('src', fullImageUrl);
        
    }

    // Assign event handlers for lightbox divs
    $('#lightBoxBg').click(closeLightBox);
    $('#lightBox').click(closeLightBox);
    
    // Close light box
    function closeLightBox() {
        
        // Hide divs
        $('#lightBoxBg').hide();
        $('#lightBox').hide();
        
    }
    
    // Open pan box
    function openPanBox(fullImageUrl) {

        // Update zoom status
        zoomStatus = true;
        
        // Enable mouse tracking
        $().bind('mousemove', mouseMove);
        
        // Get main image dimensions and position
        mainW = $('#images a.active img').width();
        mainH = $('#images a.active img').height();
        mainX = $('#images a.active img').offset().left;
        mainY = $('#images a.active img').offset().top;
        
        // Get box dimensions and position
        boxW = mainH;
        boxH = mainH;
        boxX = mainX + mainW + 20;
        boxY = mainY;
        boxC = Math.round(boxW / 2);
        boxV = Math.round(boxH / 2);
        
        // Get loading icon position
        var loadingIconPos = (boxC - 33) + 'px ' + (boxV - 33) + 'px';
        
        // Set dimension and positions of boxes
        $('#loadingBox').css('width', boxW);
        $('#loadingBox').css('height', boxH);
        $('#loadingBox').css('left', boxX);
        $('#loadingBox').css('top', boxY);
        $('#loadingBox').css('background-position', loadingIconPos);
        $('#panBox').css('width', boxW);
        $('#panBox').css('height', boxH);
        $('#panBox').css('left', boxX);
        $('#panBox').css('top', boxY);
        $('#panBox').css('background-position', '0px 0px');
        
        // Show loading box
        $('#loadingBox').fadeIn();

        // Check if using IE6
        if ($.browser.msie && $.browser.version.substr(0,1)<7) {
            
            // Hide all selects
            $('select').hide();
            
        }
        
        // Create full image object
        var fullImage = new Image();
        
        // Handle full image events
        $(fullImage)
            
            // On image load
            .load(function() {
                
                // Update full image dimensions
                fullW = this.width;
                fullH = this.height;
                
                // Adjust zoom
                adjustPanBox();
                
                // Set zoom box background
                $('#panBox').css('background-image', 'url(' + fullImageUrl + ')');
                
                // Hide loading box
                $('#loadingBox').fadeOut();
                
                // Show zoom box
                $('#panBox').fadeIn();
                
            })
            
            // On image error
            .error(function() {
                
                // Error loading image
                alert('Error loading image');
                
            })
            
            // Set image source
            .attr('src', fullImageUrl);
        
    }

    // Track mouse for pan box
    function mouseMove(e) {
        
        // Update mouse coordinates
        mouseX = e.pageX;
        mouseY = e.pageY;
        
        // Check if full image dimensions specificed
        if (fullW > 0 && fullH > 0) {
            
            // Adjust zoom
            adjustPanBox();
            
        }
        
    }
    
    // Adjust position of image inside pan box
    function adjustPanBox() {
        
        // Get position of mouse within main image
        var mainMouseX = mouseX - mainX;
        var mainMouseY = mouseY - mainY;
        
        // Get position relevent within main image (as decimal fraction)
        var mainMousePcX = mainMouseX / mainW;
        var mainMousePcY = mainMouseY / mainH;
        
        // Workout centre/focus point of full image
        var fullCenX = Math.round(mainMousePcX * fullW);
        var fullCenY = Math.round(mainMousePcY * fullH);
        
        // Get css positions
        var cssPosX = (-fullCenX) + (boxW / 2);
        var cssPosY = (-fullCenY) + (boxH / 2);
        
        // Make sure css pos x not greater than x pos of zoom box
        if (cssPosX > 0) { cssPosX = 0; }
        
        // Make sure css pos y not greater than y pos of zoom box
        if (cssPosY > 0) { cssPosY = 0; }
        
        // Make sure css pox x not less than total x pos of zoom minus full w
        if (cssPosX < (boxW) - fullW) {
            
            // Use minimum value
            cssPosX = (boxW) - fullW;
            
        }

        // Make sure css pox y not less than total y pos of zoom minus full h
        if (cssPosY < (boxH - fullH)) {
            
            // Use minimum value
            cssPosY = (boxH - fullH);
            
        }
        
        // Update background position
        $('#panBox').css('background-position', cssPosX + 'px ' + cssPosY + 'px');
        
    }
    
    // Close pan box
    function closePanBox() {

        // Update zoom status
        zoomStatus = false;
        
        // Disable mouse tracking
        $().unbind('mousemove', mouseMove);

        // Check if using IE6
        if ($.browser.msie && $.browser.version.substr(0,1)<7) {
            
            // Show all selects
            $('select').show();
            
        }
        
        // Check if zoom box show
        if ($('#panBox').is(':visibile')) {
            
            // Hide zoom box
            $('#panBox').fadeOut();
            
        }
        
    }
    
    // Thumbnail click zoom image
    $('.thumbnailClickZoom').click(function(e) {
    	
    	// Zoom image
    	return openImageZoom(e, $(this));
    	
    });

    // Thumbnail hover zoom image
    $('.thumbnailHoverZoom').hover(function(e) {
    	
    	// Zoom image
    	return openImageZoom(e, $(this));
    	
    });
    
    // Thumbnail click change image
    $('.thumbnailClickMain').click(function(e) {
        
    	// Change main image
    	return changeMainImage($(this));
    	
    });

    // Thumbnail hover change image
    $('.thumbnailHoverMain').mouseover(function(e) {
        
    	// Change main image
    	return changeMainImage($(this));
    	
    });
    
    // Change main image
    function changeMainImage(thumbnailObj)
    {
    	
        // Update full image link
        $('#images a.active').attr('href', thumbnailObj.attr('href'));
        
        // Update main image
        $('#images a.active img').attr('src', thumbnailObj.attr('rel'));
        
        // Check thumbnails format
        if (thumbnailObj.parents('ul').attr('class') == 'slider') {
	        
	        // Get thumb list items
	        var thumbsLi = $('#thumbnails ul').find('li');
	        
	        // Start counter for number of hidden thumbs
	        var numHiddenCount = 0;
	        
	        // Loop
	        for (i = 0; i < thumbsLi.length; i++) {
	            
	            // Check if visibile
	            if (thumbsLi[i].style.fontSize == '0em') {
	                
	                // Increment counter
	                numHiddenCount = numHiddenCount + 1;
	                
	            }
	            
	        }
	        
	        // Get parent id
	        var parentId = thumbnailObj.parent().attr('id');
	        
	        // Check if first visible is thumb clicked
	        if (thumbsLi[numHiddenCount].id == parentId) {
	            
	            // Previous thumb
	            prevThumb();
	            
	        } else {
	
	            // Next thumb
	            nextThumb();
	            
	        }
	        
        }
        
        // Return false (stop link from opening)
        return false;
        
    }
    
    // Mouse over for prev thumb button
    $('#prevThumbnail').mouseover(function(e) {
        
        // Move to prev thumb
        prevThumb();
        
        // Enable interval
        prevThumbInterval = setInterval(prevThumb, 1000);
        
    });

    // Mouse click for prev thumb button
    $('#prevThumbnail').click(function(e) {
        
        // Move to prev thumb
        prevThumb();
        
    });

    // Mouse out for prev thumb button
    $('#prevThumbnail').mouseout(function(e) {
        
        // Enable interval
        clearInterval(prevThumbInterval);
        
    });

    // Mouse over for next thumb button
    $('#nextThumbnail').mouseover(function(e) {

        // Move to next thumb
        nextThumb();
        
        // Enable interval
        nextThumbInterval = setInterval(nextThumb, 1000);
        
    });

    // Mouse click for next thumb button
    $('#nextThumbnail').click(function(e) {

        // Move to next thumb
        nextThumb();
        
    });

    // Mouse out for next thumb button
    $('#nextThumbnail').mouseout(function(e) {
        
        // Enable interval
        clearInterval(nextThumbInterval);
        
    });
    
    // Move prev thumb
    function prevThumb() {
        
        // Get thumb list itesm
        var thumbsLi = $('#thumbnails ul').find('li');
        
        // Check if at least 3 thumbs
        if (thumbsLi.length > 3) {
            
            // Start counter for number of hidden thumbs
            var numHiddenCount = 0;
            
            // Loop
            for (i = 0; i < thumbsLi.length; i++) {
                
                // Check if visibile
                if (thumbsLi[i].style.fontSize == '0em') {
                    
                    // Increment counter
                    numHiddenCount = numHiddenCount + 1;
                    
                }
                
            }
    
            // Check if at least one hidden
            if (numHiddenCount > 0) {
                
                // Get last hidden image element id
                var elementId = thumbsLi[numHiddenCount - 1].id;
                
                // Unhide last hidden image
                $('#' + elementId).css('font-size', '1em');
                var thumbWidth = $('#' + elementId).width();
                var oldMarginLeftPx = $('#thumbnails ul').css('margin-left');
                oldMarginLeft = eval(oldMarginLeftPx.replace('px', ''));
                var adjustPx = oldMarginLeft + thumbWidth;
                $('#thumbnails ul').animate({marginLeft: adjustPx + 'px'});
                
            }
            
            // Check if prev button should be hidden
            if ((numHiddenCount - 1) <= 0) {
                
                // Hide
                $('#prevThumbnail').hide();
                
                // Check if timer exists
                if (prevThumbInterval) {
                    
                    // Clear interval
                    clearInterval(prevThumbInterval);
                    
                }
                
            }
            
            // Make sure next button visibile
            $('#nextThumbnail').show();
            
        }
        
    };

    // Move next thumb
    function nextThumb() {
        
        // Get thumb list itesm
        var thumbsLi = $('#thumbnails ul').find('li');
        
        // Check if at least 3 thumbs
        if (thumbsLi.length > 3) {
            
            // Start counter for number of hidden thumbs
            var numHiddenCount = 0;
            
            // Loop
            for (i = 0; i < thumbsLi.length; i++) {
                
                // Check if visibile
                if (thumbsLi[i].style.fontSize == '0em') {
                    
                    // Increment counter
                    numHiddenCount = numHiddenCount + 1;
                    
                }
                
            }
            
            // Check if at least three left
            if (numHiddenCount < (thumbsLi.length - 3)) {
                
                // Get first visibile image element id
                var elementId = thumbsLi[numHiddenCount].id;
                
                // Hide first visible image
                var thumbWidth = $('#' + elementId).width();
                var oldMarginLeftPx = $('#thumbnails ul').css('margin-left');
                oldMarginLeft = eval(oldMarginLeftPx.replace('px', ''));
                var adjustPx = oldMarginLeft - thumbWidth;
                $('#thumbnails ul').animate({marginLeft: adjustPx + 'px'});
                $('#' + elementId).css('font-size', '0em');
                
            }
            
            // Check if next button should be hidden
            if ((numHiddenCount + 1) >= (thumbsLi.length - 3)) {
                
                // Hide
                $('#nextThumbnail').hide();
    
                // Check if timer exists
                if (nextThumbInterval) {
                    
                    // Clear interval
                    clearInterval(nextThumbInterval);
                    
                }
                
            }
    
            // Make sure prev button visibile
            $('#prevThumbnail').show();
            
        }
        
    };

});
