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));

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;
		homeCarousel.setSlideShow();
		$('.bar').css({
                    'left':$('.home-slideshow-drag .bar').width()*(homeCarousel.currentSlide)
					}
                );
		
        // On resize
        this.setWidths();
        $(window).resize( function() {
            homeCarousel.setWidths();
        });
        
        // 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();

                        // Set slideshow
                        if (homeCarousel.type == 'slideshow' || homeCarousel.type == 'both') {
                            homeCarousel.setSlideShow();
                        }

                    })      

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

                    // Show logo
                    $('.logo-hp').css({'opacity':0}).css({'display':'block'}).delay(500).animate({opacity:1},300);
                    
                    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();
});


