/**
 * Automate carousel by given timeout
 * This should be run after carousel generated
 */
var automateCarousel = function (timeout) {
    timeout = timeout || 5000; //5 seconds by default

    var lastIndex = 0,
        thumbs = $("#thumbs"),
        active = true,
        itemCount = $("#photos li").length,
        moveCount = 0,
        minItem = 6,
        loopAfter = (100 - itemCount) % 10;

    $("#details").hover(function() {
        active = false;
    }, function() {
        active = true;
    });
    
    var slide = function () { 
        if (!active) {
            return false;
        }

        var allItems =  thumbs.find("ul li");

	
        //move page
        if (loopAfter == 0 && moveCount == 0) {
            moveCount ++;
        }
        else {
            if (lastIndex == loopAfter) { 
                moveCount ++;
                thumbs.find(".next").trigger("click");
            }
        }
    
	var highlightedItem;
    
	if (itemCount > minItem) {
	  highlightedItem = allItems.find('a.highlight').eq(0).parent();
	  lastIndex = allItems.index(highlightedItem);
	  highlightedItem.next().find("a").trigger("click");
	}
	else {
	    
	   highlightedItem = allItems.find('a.highlight').eq(0).parent();
	   lastIndex = allItems.index(highlightedItem);
	   lastIndex = (lastIndex + 1) % itemCount;
	   allItems.eq(lastIndex).find("a").trigger("click");
	   
	}
               
    };   
    
    setInterval( slide, timeout);
};
