$(document).ready(function() {

    // Play slideshow
    var playSlide = setInterval(doInterval, 4000);
    function doInterval() {
        $($('#panav ul li')[0]).click(self.clickHandler);
    }

    // Pause slideshow on hover
    $('#slideshow').hover(function() {
        clearInterval(playSlide);
    },
	function() {
	    playSlide = setInterval(doInterval, 4000);
	});

    // Declare click listener
    var items = $('#panav ul li').click(clickHandler);
    var self = this;

    // Do this on click
    function clickHandler() {
        var index = items.index(this);
        var mindex = $('#panel ul li')[index];
        if (!($(mindex).hasClass('active'))) {
            showIndex(index);
            slideSide(this);
        }
    }

    // Display info on hover
    applyHover($('#panav ul li'));
    function applyHover($pHandle) {
        $pHandle.hover(function() {
            $(this).find('div').fadeIn();
        },
		function() {
		    $(this).find('div').fadeOut();
		});
    }

    // Hide thumbnail & move it to bottom of list
    function slideSide(pHandle) {
        var width = $(pHandle).outerWidth() * -1;
        $(pHandle).animate({
            'marginLeft': width
        },
		200,
		'',
		function() {
		    var clone = $(this).clone().appendTo('#panav ul').css('margin-left', '0').css('display', 'block');
		    $(this).slideUp(
				250,
				function() {
				    $(this).remove();
				    clone.remove();
				    $(this).click(clickHandler); // Reinitialize click after remove
				    applyHover($(pHandle)); 		// Reinitialize hover after remove
				    $('#panav ul').append(this);
				    $(this).css('margin-left', '0').css('display', 'block');
				}
			);
		}
	);

    }

    // Show big picture
    function showIndex(pIndex) {
        var big = $('#panel ul').children()[pIndex];
        $('#panel ul li').each(function() { $(this).removeClass('active'); });
        $(big).addClass('active').animate({
            'left': '0'
        },
		200,
		'',
		function() {
		    var slideImage = $('#panel ul li').not(this);
		    slideImage.css('left', slideImage.width());

		});
    }

    $("#panel li:last").addClass("last");


});
