	preventSliderUpdate=false;

	var maxScroll;
	var sliderMaxValue;
	var galleryWidth;

	/**
	 * Set the width of the items holder.
	 * This is set when the window re-sizes or when an item in the holder has loaded.
	 */

	function setScrollerWidth()
	{
		galleryWidth = $("#gallery").width();
		
		$("#items").css({'width' : getScrollItemsWidth() + 50});
		$( "#items" ).draggable( "option", "containment", [ -($("#items").width() - galleryWidth), 0, 0, 0] );
		maxScroll = $("#items").width() - galleryWidth;
		
		
		
		if (!sliderMaxValue)
			sliderMaxValue = $( "#slider" ).slider( "option", "max" );
	}



	/**
	 * calculate the total width required to show all the items in the scroll area
	 */

	function getScrollItemsWidth()
	{
		var totalWidth=0;		

		$.each($("#items").children(), function(index, value) 
		{
			totalWidth += $(value).outerWidth(true);//true includes margin

		});

		return totalWidth;

	}

	

	/**
	 * Scroll the itmes holder to the specified item.
	 * @param {Object} index
	 */

	function scroll(index, center)
	{
		//calcualte the value to set the slider to for this image.

		var e = $("#items").children().eq(index);
		
		
		
		if (e[0])
		{
			var x;
			
			if (!center)
				x = e.position().left;
			else
				x = (e.position().left +  (e.width()/2)) - (galleryWidth/2);
				
			var w = maxScroll;
			var sliderValue  = Math.round( (x/w) * sliderMaxValue );			

			if (!isNaN(sliderValue))
				$('#slider').slider('value', sliderValue);
		}

	}

	
	
	function galleryMouseMoveHandler(event)
	{
		if (event.pageX < galleryWidth / 2) 
			$(this).css('cursor', "w-resize");
		
		else if (event.pageX > galleryWidth / 2) 
			$(this).css('cursor', "e-resize");
	}

	
	

	function dragHandler()
	{

		var items = $("#items");
		if (items)
		{

			var x = Math.abs(items.position().left);
			var w = maxScroll; 
		
			var sliderValue = Math.round( (x/w) * sliderMaxValue );

			//Stop the slider handlers updating the images - else we get in a funky loop
			preventSliderUpdate=true;

			//Update the slider
			$('#slider').slider('value', sliderValue);

			//Allow the slider to update again
			preventSliderUpdate=false;
		}
		
	}

	

	/**
	 * Event handler for the scroll slider, triggered when the scroll value changed
	 * @param {Object} e
	 * @param {Object} ui
	 */

	function sliderChangeHandler(e, ui)
	{
		if (preventSliderUpdate) return
		
		if(ui.handle)
		{
			preventSliderUpdate = true;
			$("#items").animate( {left: -(ui.value * (maxScroll / sliderMaxValue))}, 500, "easeInOutExpo", function(){ preventSliderUpdate=false; } );
		} 
	}



	/**
	* Event handler for the scroll slider, triggered when the user drags the handle
	 * @param {Object} e
	 * @param {Object} ui
	 */

	function sliderSlideHandler(e, ui)
	{
		if (preventSliderUpdate) return

		if(e.originalEvent.type=="mousemove")
			$("#items").css("left" , -(ui.value * (maxScroll / sliderMaxValue)) );

	}




