$(function(){
	$('body').addClass('js');
	$slider = $('#slider');
	$handle = $('#handle');
	$gallery = $('#gallery');
	$li = $gallery.find('li');

//	Calculate and set width of sliding ul

	gWidth = 0;
	for (i=0; i<$li.length; i++){
		gWidth += $li.eq(i).outerWidth();
	}
	$gallery.find('ul').width(gWidth);

//	Store slider and gallery scrollwidth

	gvars = {
		scrollWidth : gWidth - $slider.width()
	};
	svars = {
		scrollWidth : $slider.width() - $handle.width()
	};

//	Store animation stop points

	w = 0;
	stops = Array();
	scrollable = gWidth - $slider.outerWidth();
	for(i=0; i<$li.length; i++){
		if (w > scrollable){
			stops[i-10] = scrollable;
			break;
		}
		stops[i] = w;
		w += $li.eq(i).outerWidth();
	}

//	Animate Gallery disabled on mouse over slider and re-enables on mouseout

	animateGallery();

	$($slider, $handle).mouseover(function(){
		clearInterval(sInt);
	});

	$($slider, $handle).mouseout(animateGallery);

//	Initialize slider handle

	$handle.click(disableClick).draggable({
		axis : 'x',
		drag : slideHandle,
		containment : 'parent'
	});

//	Click support for slider

	$slider.click(function(e){
		var hPos = e.pageX - $('#Container').attr('offsetLeft');
		if (hPos <= $handle.width()){
			hPos = 0;
		}
		else if(hPos > svars.scrollWidth){
			hPos = svars.scrollWidth;
		}
		else {
			hPos = hPos - $handle.width()/2;
		}
		gPos = galleryPosition(hPos);
		animate(gPos);
	});

});

//	Function to Animate Gallery and Slider

function animate(gPos){
	var hPos = handlePosition(gPos);
	$gallery.animate({
		scrollLeft : gPos
	}, 400);
	$handle.animate({
		left : hPos
	}, 400);
}

//	Gallery Slider animation Loop

function animateGallery(){
	currentPosition = $gallery.attr('scrollLeft');
	for (i=0; i<stops.length; i++){
		if (currentPosition == stops[i]){
			count = i;
			break;
		}
		else if (currentPosition < stops[i]){
			count = i - 1;
			break;
		}
		else {
			count = i;
		}
	}
	sInt = setInterval(function(){
		count++;
		if (count == stops.length){
			count = 0;
		}
		animate(stops[count]);
	}, 10000);
}

//	Disable click on handle

disableClick = function(){
	return false;
}

//	Slide handle and Gallery on dragging the handle

slideHandle = function(){
	var hPos = $handle.attr('offsetLeft');
	$gallery.attr('scrollLeft', galleryPosition(hPos));
}

//	Calculate handle position for given state of gallery

function handlePosition(gPos){
	return Math.round(svars.scrollWidth * gPos / gvars.scrollWidth);
}

//	Calculate gallery position for given state of handle

function galleryPosition(hPos){
	return Math.round(gvars.scrollWidth *hPos / svars.scrollWidth);
}