jQuery(document).ready(function () {
	var slideWidth = jQuery(".slide").width();
	var count = jQuery('.slider-inner').children('div').length;
	var animating = false;
	
	jQuery('.slider-inner').each(function() {
		jQuery(this).css({'width':(count*slideWidth)+'px'});
	});
	
	var startingLeft = -880;
	var slideCount = startingLeft;
	var totalWidth = 0;
	
	jQuery('#next, #prev').show();

	jQuery('.slider-inner').children('.slide').each(function() {
		jQuery(this).css({'left':(slideCount)+'px'});	
		var width = jQuery(this).width();
		slideCount += width;
		totalWidth += width;
	});
	function moveImage(x, direction, skip){
			
			if(animating) return;
			if(skip!=null) {
				clearInterval(changeimage);
				//auto = setInterval(function(){moveImage(null, direction)},4000);
			}
			if (direction == null){
				direction= 'left';	
			}
			
			jQuery('.slider-inner').children('.slide').each(function() {
			var left = jQuery(this).css('left');
			left = left.substr(0,left.length-2);
			var width = jQuery(this).width();
			animating=true;
			if (direction == 'left') {
				left-=width;
				if (left < startingLeft) {
					jQuery(this).animate({'left':(left)+'px'},800,function(){
						var left = jQuery(this).css('left');
						left = left.substr(0,left.length-2);
						jQuery(this).css('left',parseInt(left)+totalWidth+'px');
					});
				} else {
					jQuery(this).stop(true).animate({'left':(left)+'px'}, {duration:800});
	
				}	
			}
			else {
				left=parseInt(left) + parseInt(width);
				if (left > (totalWidth-2*width)) {
					jQuery(this).animate({'left':(left)+'px'},800,function(){
						var left = jQuery(this).css('left');
						left = left.substr(0,left.length-2);
						jQuery(this).css('left',startingLeft+'px');
					});
				} else {
					jQuery(this).stop(true).animate({'left':(left)+'px'}, {duration:800});
	
				}	
			}
			animating = false;
			changing = false;
		});
	}
	
	function skipImage(direction) {
		if (changing)return;
		changing=true;
		//clearInterval(auto);
		changeimage = setInterval(function(){trySkipImage(direction)},800);
		//trySkipImage(direction);
	}
	function trySkipImage(direction) {
		moveImage(null, direction,true);
	}
	
	jQuery("#next").click(function () {
		skipImage('left');						   
	});
	
	jQuery("#prev").click(function () {
		skipImage('right');						   
	});
	
	jQuery("#prev, #next").hover(function(){
		jQuery(this).stop().animate({"opacity": 1});
    }, function(){
      	jQuery(this).stop().animate({"opacity": 0.5});
    });
	
	//var auto = setInterval(moveImage,4000);
	var auto;
	var changeimage;
	var changing =false;
	
});