/*

  jQuery UI CoverFlow 2.1 App for jQueryUI 1.8.9 / core 1.5
  Copyright Addy Osmani 2010.
  
  With contributions from Paul Bakhaus, Nicolas Bonnicci
  
*/
	$(function() {

		//cache core component references
		var html = $('#demo-frame div.wrapper').html();
		var imageCaption = $('#imageCaption');
		$('#demo-frame div.wrapper').parent().append(html).end().remove();
		$sliderCtrl = $('#slider');
		$coverflowCtrl = $('#coverflow');
		$coverflowImages = $coverflowCtrl.find('img');
		$sliderVertical  = $("#slider-vertical");
		
		//app defaults
		var defaultItem  = 0;
		var listContent = "";
		
			   
		//Set the default image index.   
		setDefault(2);

		//Set the default item to display on load.
		//Correct indexing
		function setDefault($n){
			defaultItem = $n-1;  
		}

		//set the image caption
		function setCaption($t){
			imageCaption.html($t);
		}

		//Initialize CoverFlow
		$coverflowCtrl.coverflow({
			item: defaultItem,
			duration:1200,
			select: function(event, sky) 
			{
			skipTo(sky.value);
			}
		});

		//Initialize Horizontal Slider
		$sliderCtrl.slider({
			min: 0,
			max: $('#coverflow > img').length-1,
			value: defaultItem,
			slide: function(event, ui) {
				$coverflowCtrl.coverflow('select', ui.value, true);
				$('.coverflowItem').removeClass('ui-selected');
				$('.coverflowItem:eq(' + (ui.value) +')').addClass('ui-selected');
				setCaption($('.coverflowItem:eq(' + (ui.value) +')').html());
			}
		});

		var handler = function() {
			window.location = $(this).next().next().attr('href');
		};

		//Skip to an item in the CoverFlow	
		function skipTo($itemNumber) {
			$('#imageCaption').hide();
			$sliderCtrl.slider( "option", "value", $itemNumber);
			$coverflowCtrl.coverflow('select', $itemNumber, true);
			$('.coverflowItem').removeClass('ui-selected');
			$('.coverflowItem:eq(' + ($itemNumber) +')').addClass('ui-selected');
			setCaption($('.coverflowItem:eq(' + ($itemNumber) +')').html());
			$.doTimeout('caption', 650, function(state){
				$('#imageCaption').fadeIn();
			});
			$('#coverflow img').unbind('click',handler);
			$('#coverflow img:eq('+$itemNumber+')').bind('click', handler);
		}

		//Generate the text-list of items below the coverflow images.
		$coverflowImages.each(function(index, value) {
			$descr = $(this).next().html();
			$price = $(this).next().next().html();
			$link = $(this).next().next().attr('href');
			$title = $(this).attr('title');
			try{
				listContent += '<li class="ui-state-default coverflowItem" data-itemlink="' + (index) +'"><div class="cftitle"><a href="' + $link +'" title="'+ $title +'">'+ $title +'</a></div>' + $descr +'<a href="' + $link +'" title="'+ $title +'" class="price">' + $price +'</a></li>';
			}catch(e){}
		});

		//Skip all controls to the current default item
		$('#sortable').html(listContent);
		skipTo(defaultItem);

		//Assign click event for coverflow images 
		$('body').delegate('.coverflowItem','click', function(){
			skipTo($(this).data('itemlink'));
		});

	//change the main div to overflow-hidden as we can use the slider now
	$("#scroll-pane").css('overflow','hidden');

	//calculate the height that the scrollbar handle should be
	var difference = $("#sortable").height()-$("#scroll-pane").height();//eg it's 200px longer 
	var proportion = difference / $("#sortable").height();//eg 200px/500px
	var handleHeight = Math.round((1-proportion)*$("#scroll-pane").height());//set the proportional height

	//set up the slider	
	$sliderVertical.slider({
		orientation: "vertical",
		range: "max",
		min: 0,
		max: 100,
		value: 0 ,
		slide: function(event, ui) {
			var topValue = -((100-ui.value)*difference/100);
			$("#sortable").css({top:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
		}
	});

	var origSliderHeight = $sliderVertical.height();//read the original slider height
	var sliderHeight = origSliderHeight - handleHeight ;//the height through which the handle can move needs to be the original height minus the handle height
	var sliderMargin =  (origSliderHeight - sliderHeight)*0.5;//so the slider needs to have both top and bottom margins equal to half the difference
	
	var wtcoverflow = {
		yScroll: function(wrapper, scrollable) {
			var wrapper = $(wrapper), scrollable = $(scrollable);
			scrollable.hide();
			var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
			var interval = setInterval(function(){
				var images = scrollable.find('img');
				var completed = 0;
				images.each(function(){
					if (this.complete) completed++;
				});
				if (completed == images.length){
					clearInterval(interval);
					setTimeout(function(){
						loading.hide();
						wrapper.css({overflow: 'hidden'});
						scrollable.slideDown('slow', function(){
							enable();
						});
					}, 1000);	
				}
			}, 100);
			function enable(){
				var inactiveMargin = 99;
				var wrapperWidth = wrapper.width();
				var wrapperHeight = wrapper.height();
				var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
				var lastTarget;
				wrapper.mousemove(function(e){
					lastTarget = e.target;
					var wrapperOffset = wrapper.offset();
					var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
					if (top < 0){
						top = 0;
					}
					wrapper.scrollTop(top);
				});
			}
		}
	}
	wtcoverflow.yScroll('#scroll-pane', 'ul#sortable');
	
	i = defaultItem+1;
	$.doTimeout('cf-slideshow', 3500, function(state){
		if ( state == false) {
			return false;
		} else {
			if ( i == $('#coverflow > img').length ) {
				// do something finally
				skipTo(0);
				i = 1
				return true;
			}
			skipTo(i);
			i++
			return true;
		}
	});

	$('#coverflow img').live('click', function(el){
		$.doTimeout('cf-slideshow', false, function(){
			return false;
		});
	});
	
	//$('#imageCaption:last').css({'bottom':'77px'});

});
