/*
 * --------------------------------------------------------------------
 * Simple Scroller
 * by Siddharth S, www.ssiddharth.com, hello@ssiddharth.com
 * Version: 1.0, 05.10.2009 	
 * --------------------------------------------------------------------
 */

$(window).load(function(){

	var lpd = false;	//looped flag
	var mb = 10;		//margineBottom
	var index = 1;
	var images = $("#gallery img");
	var thumbs = $("#thumbs img");
	var imgHeight = $(thumbs).attr("height")+mb;
	var waitTime = 5000;
	$(thumbs).slice(0,thumbs.length).clone().appendTo("#thumbs");
	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}
	
	
	$("#next").click(clicked);
	show(index);
	var timerID = setInterval(sift, waitTime);
	
	function sift()
	{
		if (index<(thumbs.length)){index++; }
		else {index=1;}
		show (index);
	}
	
	function clicked()
	{
		sift();
		clearInterval(timerID);
		timerID = setInterval(sift, waitTime);
		
	}
	
	function show(num)
	{
		var pos = ((num-1)%thumbs.length);
		$(images).fadeOut(500);
		$(".image-"+(pos)).stop().fadeIn(500);
		var scrollPos = (num)*imgHeight;
		if(((num)>=thumbs.length))lpd=true;	//looped flag set
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 1000, "swing", onComplete(num));
//		console.log("show():img.image-"+(num)+"\t"+"["+pos+"]\t"+scrollPos+"\t"+imgHeight+"\t"+lpd);
	}
	
	function onComplete(n){
		if(n==1)
		{
			if(lpd){
//			console.log("onComplete():n="+n+"\t"+(n*imgHeight));
				$("#thumbs").stop().animate({scrollTop: ((n-1)*imgHeight)}, 0);
				lpd = false;//looped flag clear
			}
		}
	}
});

