/**
 * @author Tom
 */
var sizefactor = 0.4;
var speedfactor = 0.3;

var width = 0;
var speed = 10;
var direction = 0;
var prevDirection = 0;
var margin = 0;
var rightImgWidth = 0;
var scroll = true;
var endL = false;
var endR = false;

$(document).ready(function(){
	
	loadImages();
	followMouse();
	direction = -1;
	scrolling();
	
});

function scrolling(){
			
	if(margin<(-4*rightImgWidth) && direction == -1){
		elem = $('#slider .image').first();
		cW = elem.width();
		$('#slider').append('<div class=\"image\">'+elem.html()+'</div>');
		elem.remove();
		margin = margin+cW;
		$("#slider").animate({
			marginLeft: margin
		}, {
			duration: 0,
			easing: 'linear'
		});
	}
			
	if(margin>=(-1*rightImgWidth) && direction == 1){
		elem = $('#slider .image').last();
		cW = elem.width();
		$('#slider').prepend('<div class=\"image\">'+elem.html()+'</div>');
		margin = margin-cW;
		$("#slider").animate({
			marginLeft: margin
		}, {
			duration: 0,
			easing: 'linear'
		});
		elem.remove();
	}
	
	margin = (speed * speedfactor * direction) + margin;
	
	prevDirection = direction;
	
	$("#slider").animate({
		marginLeft: margin
	}, {
		duration: 200,
		easing: 'linear',
		complete: function(){
			scrolling();
		}
	});
	
	$("#thumbslider").animate({
		marginLeft: margin/7
	}, {
		duration: 200,
		easing: 'linear'
	});
			
}

function loadImages(){
		
	$("#slider img").each(function(){
		
		$(this).attr('src',$(this).attr('id'));
		width += $(this).width();
		rightImgWidth = $(this).width();
		
	});
	
	
	toCenter();
	
	$("#slider").css('width',width);

}

function toCenter(){
	
	c = width / -2;
	margin = c;
	$('#slider').css('margin-left',c);
					
}

function followMouse(){
	
	$('#window').mousemove(function(e){
        
		var windowWidth = $(this).width();
		
		var x = e.pageX - this.offsetLeft;
		
		// check which side to scroll to
		if(x >= (windowWidth - (sizefactor*windowWidth))){
			
			// go right
			speed = (sizefactor * windowWidth) - (windowWidth -  x);
			direction = +1;
			
		}else if(x <= (0 + (sizefactor*windowWidth))){
			
			//go left
			speed = (sizefactor * windowWidth) - x;
			direction = -1;
			
		}else if( (x < (windowWidth - (sizefactor*windowWidth)))
			&&
			(x > (0 + (sizefactor*windowWidth)))
			){
				direction = 0;
			}
		
		if(scroll==false){
			scroll = true;
			scrolling();
		}
				
    });

	
}

