function extractUrl(input) {
	return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
}
 
function hitTest(offsetLeft, totalWidth, itemCount, event) {
	var pos = 0;
	var itemWidth = totalWidth/itemCount;

	perc = offsetLeft / totalWidth;
	index = perc*itemCount;
	
	if (event == 'click') {
		index = Math.floor(index);
	} else if (event == 'drag') {
		index = Math.round(index);
	}
	
	return index;
}

(function ($) {
   $.fn.liveDraggable = function (opts) {
      this.live("mouseover", function() {
         if (!$(this).data("init")) {
            $(this).data("init", true).draggable(opts);
         }
      });
   };
}(jQuery));


// TENBLACKDRESSES | start
function startBlackDressesTakeover() {
	// Slide 1
	$('.bdt-slide1').delay(1000).animate({'opacity':0},500,function(){
		startSlide2();
	});
	
}

function startSlide2()
{
	$('.bdt-slide2').delay(1000).animate({'opacity':0},500,function(){
		startSlide3();
	});
}

function startSlide3()
{
	$('.bdt-slide3').delay(1000).animate({'opacity':0},500,function(){
		switchBlackDresses(0);
	});
}

// TENBLACKDRESSES | switch names | slide-names
function switchBlackDresses(i) 
{
	if (i == 0)
	{
		//$('.bdt-slide-names').show();
		delay = 2000;
		speed = 400;
	}
	else 
	{
		
		delay = 1000 / (i*2);	
		speed = 200;
		if (i > 2)
			speed = 200 / (i/2);
		if (speed < 100)
			speed = 100;
	}
	//delay = 0;
	//speed = 400;
	if(i>0)
		$('.bdt-slide-names li:eq('+(i-1)+')').animate({'opacity':0,'margin-top':-40},speed);
	$('.bdt-slide-names li:eq('+i+')').animate({'opacity':1,'margin-top':-20},speed,function(){
		//console.log('show: ' + i);
		if (i==$('.bdt-slide-names li').length-1) {
			$('.bdt-slide-names').delay(500).animate({'opacity':0},400);
			setTimeout("endBlackDressesTakeover()",1000);//1000
		} else {
			i++;
			setTimeout("switchBlackDresses("+i+");",delay);
		}
		
	});	
}

// TENBLACKDRESSES | end
function endBlackDressesTakeover() {
	
	//console.log('end');
	$('#blackdressesTakeover').animate({'opacity':1},1000,function(){
		$(this).remove();
	});

	// Show dragbar
	$('.home-slideshow-drag .bar').delay(500).animate({'margin-top':0},300);						

	// Show logo
	$('.logo-hp').css({'opacity':1}).css({'display':'block'}).delay(500).animate({opacity:1},300);

	// Start slideshow
	homeCarousel.setSlideShow();
}

var timer;
homeCarousel = {
	type: 'both', // slideshow | draggable | both | none
	intervalTime:5000,
	slideTime: 800,
	currentSlide: 0,
	windowWidth: 0,
	slidesCount: 0,
	sliding: false,
	init: function(){
		
		// Setting globals
		this.slidesCount = $('.home-slideshow .slide').length;
		
		// On resize
		this.setWidths();
		$(window).resize( function() {
			homeCarousel.setWidths();
		});
		
		// Show
		$('.home-slideshow').show();
											
		// Preloading
		$('.home-slideshow .slide').each(function(i,v){
			bgImg = $(v).css('background-image');
			bgImg = extractUrl(bgImg);

			// Set img loads
			var imageObj = new Image();
			$(imageObj).attr("src", bgImg).load(function(response) {
				$('.home-slideshow .slide:eq('+i+') ').removeClass('loading');
				$('.home-slideshow .slide:eq('+i+') ').addClass('translateZ');
			}); 
			
			// Last image loaded! do some stuff
			if (i+1 == $('.home-slideshow .slide').length) {
			
				// Remove layer
				$('.preload-layer img').delay(1400).animate({'opacity':0},500,function(){
					
					$('.preload-layer').animate({'opacity':0},1000,function(){
						$('.preload-layer').remove();

						// TENBLACKDRESSES | start
						if (homeCarousel.type == 'slideshow' || homeCarousel.type == 'both') {
							//startBlackDressesTakeover();
							endBlackDressesTakeover();
							//homeCarousel.setSlideShow();
						}

					});		

					if(mobile())
						resetTouchScroll($('#main-content').height());
					
				})

			}
			
		})

		// Loading gif
		//$('.home-slideshow .slide').addClass('loading');
		
		// Drag!
		if (this.type == 'draggable' || this.type == 'both')
			this.setDraggable();
		
		if (this.type == 'none')
			$('.home-slideshow-drag').remove();
		
		// Enable slidebar click
		homeCarousel.setClickDragbar();

		// Keystrokes!
	   $(document).keydown(function(e) {
		  switch(e.keyCode) { 
			 case 37: // Move left
				if (homeCarousel.currentSlide == 0 && !homeCarousel.sliding) {
					
				} else if (!homeCarousel.sliding) {
					clearTimeout(timer);
					$('.home-slideshow, .bar').stop();
					homeCarousel.moveSlide(homeCarousel.currentSlide,'left');
				}
			 break;
			 case 39: // Move right
				if (homeCarousel.currentSlide != homeCarousel.slidesCount && !homeCarousel.sliding) {
					clearTimeout(timer);
					$('.home-slideshow, .bar').stop();
					homeCarousel.moveSlide(homeCarousel.currentSlide, 'right');
				} else if (!homeCarousel.sliding) {
					clearTimeout(timer);
					$('.home-slideshow, .bar').stop();
					homeCarousel.moveSlide(0,'right');
				}
			 break;
		  }
	   });


		
	},
	setWidths: function() {
		this.windowWidth = $(window).width();
				
		$('.home-slideshow').
			width( this.windowWidth * this.slidesCount );
		
		$('.home-slideshow .slide').
			width( this.windowWidth );
		
		$('.home-slideshow-drag .bar').
			width( $('.home-slideshow-drag').width() / this.slidesCount );	
		
		// Align current slide to left
		$('.home-slideshow').css({'margin-left':parseInt('-'+homeCarousel.windowWidth*homeCarousel.currentSlide)});
			
	},
	pauseSlideShow: function() {
		clearTimeout(timer);
		$('.home-slideshow').stop();
	},
	continueSlideShow: function() {
		homeCarousel.moveSlide(homeCarousel.currentSlide,'right');
	},
	setClickDragbar: function() {
		$('.home-slideshow-drag').click(function(e){
			if ($('.home-slideshow.new').length == 0 && !$(e.target).hasClass('bar') ) {
				var x = e.pageX - this.offsetLeft;

				nextSlide = hitTest (x, $('.home-slideshow-drag').width(), homeCarousel.slidesCount, 'click');
				nextSlide = nextSlide - 1;

				clearTimeout(timer);
				$('.home-slideshow, .bar').stop();

				homeCarousel.moveSlide(nextSlide, 'right');
			}
		});
	},
	setSlideShow: function() {
		timer=setTimeout('homeCarousel.moveSlide(0,"right")',homeCarousel.intervalTime);
	},
	setDraggable: function() {
		$( ".home-slideshow-drag .bar" ).liveDraggable({ 
			containment: ".home-slideshow-drag ", 
			axis: "x", 
			cursor: "move",
			start: function() {
				
				$( ".home-slideshow-drag").unbind('click');   // Disable slidebar click
				homeCarousel.pauseSlideShow();
			},
			drag: function() {
				
				pos = $( ".home-slideshow-drag .bar" ).position();
				nextSlide = hitTest (pos.left, $('.home-slideshow-drag').width(), homeCarousel.slidesCount, 'drag');
		 			
				if (homeCarousel.currentSlide != nextSlide)
					homeCarousel.dragSlide(nextSlide);
			},
			stop: function() {

				homeCarousel.setClickDragbar();	 // Enable slidebar click
				$('.bar').stop().animate({
					'left':$('.home-slideshow-drag .bar').width()*(homeCarousel.currentSlide)}, 500, 'easeOutQuint'
				);
				clearTimeout(timer);
				timer=setTimeout("homeCarousel.continueSlideShow()",homeCarousel.intervalTime);
			}
		});
	   
	},
	dragSlide: function(index) {
		homeCarousel.currentSlide = index;
		
		// Drag slide
		$('.home-slideshow').stop().animate({
			'margin-left':'-'+homeCarousel.windowWidth*index},
			homeCarousel.slideTime,
			'easeOutQuint'
		);
	},
	moveSlide: function(index, direction) {
		if ( !this.sliding ) {
			
			this.sliding = true;
			$( ".home-slideshow-drag").unbind('click'); // Disable slidebar click
			this.disableDraggable();					// Disable drag

			if(direction == 'right') {
				index++;
			} else {
				index--;
			}
			
			this.currentSlide = index;

			$('.container').html(index + ' - ' + this.slidesCount);

			// Check if end is reached
			if ( index == this.slidesCount ) {
				
				// Clone for rerun
				$('.home-slideshow').addClass('old').clone().appendTo('.home-slideshow-holder').removeClass('old').addClass('new').css('margin-left',homeCarousel.windowWidth);
				$('.home-slideshow-drag .bar').addClass('old').clone().appendTo('.home-slideshow-drag').removeClass('old').addClass('new').css('left',-200);


				// Goodbye old
				$('.home-slideshow.old').animate({
					'margin-left':'-'+homeCarousel.windowWidth*index},
					homeCarousel.slideTime,
					'easeOutQuint'
				);
				$('.bar.old').animate({
					'left':$('.home-slideshow-drag .bar').width()*index}, homeCarousel.slideTime, 'easeOutQuint'
				);

				// Hello new
				$('.home-slideshow.new').animate({
					'margin-left':0}, homeCarousel.slideTime, 'easeOutQuint', 
					function() {
						$('.home-slideshow.new').removeClass('new');
						$('.home-slideshow.old').remove();
						homeCarousel.currentSlide = 0;
						timer=setTimeout('homeCarousel.moveSlide(0,"right")',homeCarousel.intervalTime);
					}
				);
				$('.bar.new').animate({
					'left':0}, homeCarousel.slideTime, 'easeOutQuint',
					function() {
						$('.bar.new').removeClass('new');
						$('.bar.old').remove();
						homeCarousel.enableDraggable();		// Enable drag
						homeCarousel.setClickDragbar();		// Enable slidebar click
						homeCarousel.sliding = false;
					}
				);


			} else {

				// Slide
				$('.home-slideshow').animate({
					'margin-left':'-'+homeCarousel.windowWidth*index}, homeCarousel.slideTime, 'easeOutQuint', 
					function() {
						timer=setTimeout('homeCarousel.moveSlide('+index+',"right")',homeCarousel.intervalTime);
					}
				);

				$('.home-slideshow-drag .bar').animate({
					'left':$('.home-slideshow-drag .bar').width()*index}, homeCarousel.slideTime, 'easeOutQuint', 
					function() {
						homeCarousel.enableDraggable();	// Enable drag
						homeCarousel.setClickDragbar();	// Enable slidebar click
						homeCarousel.setWidths();
						homeCarousel.sliding = false;
					}
				);

			}
			
		}

	},
	disableDraggable: function() {
		$( ".bar" ).draggable( "option", "disabled", true );
	}
	,
	enableDraggable: function() {
		$( ".bar" ).draggable( "option", "disabled",  false );
	}
}


$(document).ready(function(){
	homeCarousel.init();
});

