﻿
App.gallery = function () {

	/* Private */

	/* Properties */

	var cmp = {};



	/* Defaults */

	TVI.debug = true;
    
    // Gallery initialise
    function clearThumb(oldThumb){    
        currentThumb = oldThumb;
    };

    // Change main image
    function showItem(itemToShow, gallery) {
        
        // Get new image URL
        var mainURL = gallery.find('.carousel .productThumb:eq('+ itemToShow +')').attr('href');

        // Change image
        gallery.find('.mainImageContainer IMG').attr('src', mainURL);

    }

    // Carousel
    function moveCarousel(direction, oldThumb, gallery) {

        // Stop scrolling one image before the end
        var endImage = gallery.find('.carousel .productThumb').length - 1;

        // Change thumnail according to direction. Check not start or end of carousel. 
        if((direction == 'up') && (oldThumb != '0')){
            currentThumb--;
        } else if((direction == 'down') && (oldThumb != endImage)){
            currentThumb++;    
        } else { // If image clicked
            currentThumb = oldThumb;
        }

        // Get offset of next thumb
        var position = gallery.find('.carousel .productThumb:eq('+ currentThumb +')').position();

        // Move carousel
        gallery.find('.carousel .imagesScroller').animate({'top': '-' + position.top + 'px'}, 250);

        // Change main image
        showItem(currentThumb, gallery);
    }

	/* Methods */

	var init = function () {    

        // Gallery
        $('.fancybox').fancybox({
	        padding: '0',
            'onStart':  function(){
                clearThumb(0);
            }            
        });

        
        // Arrow click
        $('.gallery .carousel .upArrow, .gallery .carousel .downArrow').live('click', function(){
            
            var gallery = $(this).parents('.gallery');

            // Get direction
            if($(this).hasClass('upArrow')){
                direction = 'up';
            } else {
                direction = 'down';
            }
            
            moveCarousel(direction, currentThumb, gallery);

            return false;
        });

        // Thumbnail click
        $('.gallery .carousel .productThumb').live('click', function(){

            var gallery = $(this).parents('.gallery');
            
            // Get new image index
            var currentThumb = $(this).index();

            moveCarousel('null', currentThumb, gallery);

            return false;
        });


	};


	/* Public */

	TVI.apply(cmp, {

		/* Properties */

		test: 'test',

		/* Methods */

		test: function () {

			/* Test function  */

		}

	});


	TVI.ready(init);


	return cmp;


} ();
