var ua = navigator.userAgent; clickEvent = (ua.match(/iPad/i)) ? "touchstart" : "click";
if(clickEvent == "click") clickEvent = (ua.match(/iPhone/i)) ? "touchstart" : "click";

var resizeTimer;
var carouselSet;
var sliderActive = true; 
var sliderStarted = false;
var sliderAutoPlayTimer;
var resetVideoTimer;
var currentSlide = 0;
var wasVideoPlaying = false;
var fallbackImageTag = '<img src="http://cdn.jackjones.com/staysafe/assets/media/5632/slide_1.jpg" alt="Image1" />';
var savedVideoTag = "";

(function($) {
  $.fn.outerHTML = function() 
  {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

$(document).ready(function()
{
	savedVideoTag = $("#slide0 video").outerHTML();
});

function supportsVideo()
{
    return !!document.createElement('video').canPlayType;
}

function playVideo(id)
{
	setVideoCTA(false);
	
	$("#front-video").css("display", "block");
    $(id).get(0).play();
    if (sliderAutoPlayTimer) clearTimeout(sliderAutoPlayTimer);
}

function pauseVideo(id)
{
	//removeVideo("#front-video");
	//$("#front-video").css("display", "none");
    $(id).get(0).pause();
}

function removeVideo(id)
{
	$("#front-video").css("display", "none");
	//if($("#temp-video").length != 0)
		//$("#temp-video").replaceWith(savedVideoTag);
    $(id).replaceWith("<div id='temp-video'/>");
}

function isVideoPlaying(id) {
	if($("#temp-video").length != 0)
		return false;
	
    return (!$(id).get(0).paused && !$(id).get(0).ended);
} 

function resizeWindowEnd() {
    sliderActive = true;
}

function fullscreenFitSlider(callback) {
    var windowRatio = $(window).width() / $(window).height();
    var flipRatio = 3 / 2;
    //var flipRatio = $("#slider").height() / $("#slider").width();
    var sliderPosition;
    
    if(windowRatio >= flipRatio) {
        $('#slider>li, #slider img, #front-video-cta-bg').css({
            'width':$(window).width(),
            'height':'auto'
        });

        sliderPosition = [($(window).height() - $('#slider img').height())/2,0];
    } else {
        $('#slider>li').css({
            'width':$(window).width(),
            'height':$(window).height()
        });
        $('#slider img').css({
            'height':$(window).height(),
            'width':'auto'
        });
        $('#front-video-cta-bg').css({
            'height':$(window).height(),
            'width':'auto'
        });
        sliderPosition = [0,0];
    }
    
    var fontSize = $(window).width()/1200+'em';
    $('#slider').css('fontSize',fontSize);
    $('#slider').css('top',sliderPosition[0]);
    
    if(typeof callback !== 'undefined') callback();
}

function pauseAndResetVideo()
{
    removeVideo("#front-video");
    setVideoCTA(false);

    if (resetVideoTimer) clearTimeout(resetVideoTimer);
}

$.fn.porsSlider = function(callback) {
    var o = $(this[0]);
    var slides = o.children('li');
    var slideCount = slides.length;
    var sliderAutoPlayDelay = 5000;
    var sliderFadeTime = 1000;
    slides.hide();
    slides.css('position','absolute');
    
    var goToPrev = function() {
        if(!o.is(':animated')) {
            if (currentSlide == 0 && supportsVideo())
            {
                if (isVideoPlaying("#front-video"))
                {
                    wasVideoPlaying = true;
                }
                
                resetVideoTimer = setTimeout(pauseAndResetVideo, sliderFadeTime, true);
            }
            
            if(currentSlide === 0) {
                currentSlide = slideCount-1;
            } else {
                currentSlide--;
            }
            
            o.addClass('speed');
            
            slides.filter(':visible').fadeOut(sliderFadeTime);
            
            
            slides.eq(currentSlide).fadeIn(sliderFadeTime,function(){
                o.removeClass('speed');
            });

            if (sliderAutoPlayTimer) clearTimeout(sliderAutoPlayTimer);
            if (currentSlide != 0) sliderAutoPlayTimer = setInterval(goToNext, sliderAutoPlayDelay);
            
            if (wasVideoPlaying && currentSlide == 0)
            {
                //playVideo("#front-video");
                wasVideoPlaying = false;
            }
            
            if (currentSlide == 0)
            {
                $("#temp-video").replaceWith(savedVideoTag);
                setVideoHandling();
            }
        }
    };
    
    var goToNext = function() {
        if(!o.is(':animated') && sliderActive) {
            if (currentSlide == 0 && supportsVideo())
            {
                if (isVideoPlaying("#front-video"))
                {
                    wasVideoPlaying = true;
                }
                
                resetVideoTimer = setTimeout(pauseAndResetVideo, sliderFadeTime, true);
            }
            
            currentSlide++;
            
            o.addClass('speed');
            
            if(currentSlide === slideCount) currentSlide = 0;
            
            
            slides.filter(':visible').fadeOut(sliderFadeTime);
            
                
            slides.eq(currentSlide).fadeIn(sliderFadeTime,function(){
                o.removeClass('speed');
            });

            if (sliderAutoPlayTimer) clearTimeout(sliderAutoPlayTimer);
            if (currentSlide != 0) sliderAutoPlayTimer = setInterval(goToNext, sliderAutoPlayDelay);
            
            if (wasVideoPlaying && currentSlide == 0)
            {
                //Enable for autoplay of video when user returns to video slide
                //playVideo("#front-video");
                wasVideoPlaying = false;
            }
            
            if (currentSlide == 0)
            {
                $("#temp-video").replaceWith(savedVideoTag);
                setVideoHandling();
            }
        }
    };
       
    o.siblings('.sliderNext').bind(clickEvent, goToNext);
    o.siblings('.sliderPrev').bind(clickEvent, goToPrev);
    
    //Disabled because we want video to stay on the video slide
    //sliderAutoPlayTimer = setInterval(goToNext,sliderAutoPlayDelay);
    
    if(typeof callback !== 'undefined') callback();
};

var hasSet = false;
function setVideoHandling()
{
    if (!supportsVideo())
        return;

    if(!this.hasSet)
	{
    	$("#slide0").bind(clickEvent, function(){
       		if (!isVideoPlaying("#front-video"))
           		playVideo("#front-video");
       		else
           		pauseVideo("#front-video");
    	});

		this.hasSet = true;
	}
			
	$("#front-video").bind("ended", function () {
       	setVideoCTA(true);
    });
	$("#front-video").bind("pause", function () {
 		$(this).css("display", "none");
    });
}

function initPorsSlider() {
    if(!sliderStarted) {
        sliderStarted = true;
        fullscreenFitSlider(function(){
            $('#slider').porsSlider(function(){
                $('#slider li').first().fadeIn(1500);
                $('#slider').fadeTo(1500,1,function(){
                    $('#content').css('backgroundImage','none'); 
                });
            });
        });
    }
}

function setVideoCTA(showCTA)
{
    if (showCTA)
    {
		removeVideo("#front-video");
        $("#front-video-cta").fadeTo(500, 1);
		resizeControls();
    }
    else
    {
		if($("#temp-video").length != 0)
			$("#temp-video").replaceWith(savedVideoTag);
		
        $("#front-video-cta").fadeTo(500, 0, function(){
            $(this).hide(0);
        });
    }
}

function replayVideo()
{
    setVideoCTA(false);
    playVideo("#front-video");
}

function resizeControls()
{
	var center = {x: $(window).width() * .5, y: $(window).height() * .5};
	
	var totalHeight = $("#front-video-replay-area").height() + $("#front-video-shop-area").height() + 10;
	
	var ypos = Math.abs(parseInt($("#slider").css("top"))) + center.y - (totalHeight * .5);
	$("#front-video-replay-area").css("top", ypos);
	$("#front-video-replay-area").css("left", center.x - $("#front-video-replay-area").width() * .5);
	
	ypos = parseInt($("#front-video-replay-area").css("top")) + $("#front-video-replay-area").height() + 10;
	$("#front-video-shop-area").css("top", ypos);
	$("#front-video-shop-area").css("left", center.x - $("#front-video-shop-area").width() * .5);
}

$(document).ready(function(){
    /* Give browser 1 sec to load images in fullscreen slider. (if loaded faster slider fades in) */
    
    $('#slider').fadeTo(0,0.01);
    $('#slider li img:first').load(function(){
        initPorsSlider();
    });
    setTimeout(initPorsSlider,1000);

    /* Bind to window resize event and fit fullscreen slider to new size */
    $(window).bind('resize',function(){
        sliderActive = false;
        $('#slider, #slider>li:first').stop().fadeTo(0,1);
        fullscreenFitSlider();
        if (resizeTimer) clearTimeout(resizeTimer); 
        resizeTimer = setTimeout(resizeWindowEnd, 500);

		resizeControls();
    });
    
    if (!supportsVideo())
    {
        $("#slide0").empty().append(fallbackImageTag);
    }
    else
    {
        $("#front-video-cta").hide(0.01);
        $("#front-video-shop-area").bind(clickEvent, function(e)
        {
            location.href = "http://shop.bestseller.com/jack-jones";
        });
    
        $("#front-video-replay-area").bind(clickEvent, function(e)
        {
            //replayVideo();
        });
    
        setVideoHandling();
    }

	resizeControls();
});
