﻿$(document).ready(function () {
    $('div#featuredNav a.previous').click(showPrevious);
    $('div#featuredNav a.next').click(showNext);
	$('div.video a.slideLeft').click(slideLeft);
	$('div.video a.slideRight').click(slideRight);
	
	
    var rotateArray = $('ul.rotate li');
    if (rotateArray.length == 1) return;
    var currentItem = Math.floor(Math.random() * rotateArray.length);
    var prevItem;
    var nextItem;
    var rotateTimer = setTimeout(showNext, 8000);
    var remainingMargin;

    $(rotateArray).each(function () { $(this).css('display', 'none') });
    $(rotateArray[currentItem]).css('z-index', 2).css('display', 'block');

    function startTimer() {
        rotateTimer = setTimeout(showNext, 8000);
    }

    function stopTimer() {
        clearTimeout(rotateTimer);
    }

    function showNext() {
        stopTimer();
        if (currentItem < rotateArray.length - 1) nextItem = currentItem + 1;
        else nextItem = 0;
        rotate();
        startTimer();
    }

    function showPrevious() {
        stopTimer();
        if (currentItem != 0) nextItem = currentItem - 1;
        else nextItem = rotateArray.length - 1;
        rotate();
        startTimer();
    }

    // ROTATE AND FADE THE BANNER
    function rotate() {
        $(rotateArray[nextItem]).css('z-index', 2);
        $(rotateArray[currentItem]).css('z-index', 1);
        $(rotateArray[nextItem]).fadeIn(1000);
        $(rotateArray[currentItem]).fadeOut(1500);
        currentItem = nextItem;
    }
	
	function slideRight() {
		var slideWidth = (  parseInt($('ul.slide li').css('width')) +  parseInt($('ul.slide li').css('margin-left')) + parseInt($('ul.slide li').css('margin-right')) );
		var listLength = $('ul.slide li').length * slideWidth;
		if ( parseInt( $('ul.slide').css('margin-left') ) > ((listLength*-1)+slideWidth) ) {
			$('ul.slide').animate({  marginLeft: '-='+slideWidth }, 1500 )
		}
		else {
			$('ul.slide').animate({  marginLeft: '+='+($('ul.slide li').length-1)*slideWidth }, $('ul.slide li').length*1500 );
		}
	}
	function slideLeft() {
		var slideWidth = (  parseInt($('ul.slide li').css('width')) +  parseInt($('ul.slide li').css('margin-left')) + parseInt($('ul.slide li').css('margin-right')) );
		if ( parseInt( $('ul.slide').css('margin-left') ) < 0 ) {
			$('ul.slide').animate({  marginLeft: '+='+slideWidth }, 1500 );
		}
		else {
			$('ul.slide').animate({  marginLeft: '-='+($('ul.slide li').length-1)*slideWidth }, $('ul.slide li').length*1500 );
		}
	}
});
