$(function() {
    //Gallery in main page

    $("#thumbnail li a").click(function() {
        $("#largeImg img").hide().attr({"src": $(this).attr("href"), "title": $(this).attr("title")});
        $("#photoDescription p").html($(this).attr("title"));
        return false;
    });

    var SLIDESHOW_TIMEOUT;
    SLIDESHOW_TIMEOUT = 5000;
    var timer = null;
    var slideshowOn = false;

    var nextPic = 1;

    function getCountPic()
    {
        var $pic = $('#thumbnail li a');
        var $elements = $('#thumbnail li a');
        var elementsTotalCount = $elements.size();

        var $curPic = $elements.eq(nextPic);

        nextPic ++;
        if (nextPic >= elementsTotalCount)
        {
            nextPic = 0;
        }

        return $curPic;
    }

    function clickCountPic()
    {
        if (slideshowOn) {
            var $pic = getCountPic();
            $pic.click();
        }
    }

    function startSlideshow() {
        timer = setTimeout(nextSlide, SLIDESHOW_TIMEOUT);
        slideshowOn = true;
    }

    function stopSlideshow() {
        clearTimeout(timer);
        slideshowOn = false;
    }

    function nextSlide() {
        clickCountPic();
        if (slideshowOn) {
            setTimeout(nextSlide, SLIDESHOW_TIMEOUT);
        }
    }

    startSlideshow();
    $('#largeImg').mouseenter(stopSlideshow).mouseleave(startSlideshow);
});
