//Initial stuff
var galleryCurrent=0, galleryCount, galleryTime = 6000, galleryTimeout,animation;

$(function() {
	$(window).load( function() {
	if (gal=document.getElementById('gallery')) {
			for (i=0; i<gal.getElementsByTagName("li").length; i++) {
				var item = gal.getElementsByTagName("li")[i];
				$(item).css("left",i*1024+"px");
			}
			galleryCount = i;
		
			galleryTimout=setTimeout(galleryNext,galleryTime);
		}
		$("#gallery li").fadeIn(400);
	})
});

function galleryPrev () {
	if (galleryCurrent==0) {
		galleryCurrent=galleryCount-1;
	}
	else {
		galleryCurrent--;
	}
	
	galleryMove();
}

function galleryNext () {
	if (galleryCurrent==galleryCount-1) {
		galleryCurrent=0;
	}
	else {
		galleryCurrent++;
	}

	galleryMove();
}
function galleryMove() {
	for (i=0; i<gal.getElementsByTagName("li").length; i++) {
		var item = gal.getElementsByTagName("li")[i];
		
		if (i!=galleryCurrent && i!=galleryCurrent-1 && galleryCurrent!=0) {
			$(item).hide()
		}
		else {
			$(item).show()
		}
	}
	
	manual_animate(1000,(galleryCurrent)*1024);
	
	/*$('#slider').animate({marginLeft:-(galleryCurrent)*1024},800,'jswing',function(){
		clearTimeout(galleryTimeout);
		galleryTimeout=setTimeout(galleryNext,galleryTime);
	});*/
}

function manual_animate(_time,_toX) {
	var _fromTime = (new Date()).getTime()
	var _toTime =_fromTime+_time;
	var gal=$('#gallery')
	var fromX=gal.scrollLeft();
	var dist=_toX-fromX;
	
	function _move() {
		var _stepTime=(new Date()).getTime()-_fromTime
		var _stepFactor=_stepTime/_time;
		
		//Linear easing
		//gal.scrollLeft(fromX+dist*_stepFactor);

		//Explonential easing
		gal.scrollLeft(dist * ( -Math.pow( 2, -10 * _stepFactor) + 1 ) + fromX);

		if (_stepFactor>1) {
			gal.scrollLeft(fromX+dist);
			clearInterval(animation);
			clearTimeout(galleryTimeout);
			galleryTimeout=setTimeout(galleryNext,galleryTime);
		}
	}
	
	animation=setInterval(_move,8);
}

