var $j = jQuery.noConflict();   //Gives jQuery a namespace of $j so it doesn't conflict w/ other libraries
var cNum = 1;                   //The current carousel feature number
var timer = null;
var cLimit = null;
var countdown = 12;
var countdownTimer = null;
var rotator_cycles = 1; //Start at 1 for the max_cycles value to make sense
var rotator_max_cycles = 3;
var animating = false;

var COUNTDOWN_TIME = 12;
var current_timer  = 0;

//Fade is now broken because we've committed to "slide"
var carousel_mode = 'slide';

function goRight(){
	stopTimerAdvanceFeatureSection();
	hideFeatureSectionsExcept( cNum + 1 );
}

function goLeft(){
	stopTimerAdvanceFeatureSection();
	hideFeatureSectionsExcept( cNum - 1, true );
}

function advanceToNextCarouselSection() {
	var next = cNum + 1;
	
	if( next > cLimit ){
		rotator_cycles++;
		next = 1;
	}
	
    hideFeatureSectionsExcept(next);
}

function hideFeatureSectionsExcept(num, reverse ) {
	//Prevent events while in transition. Prevent "going" to the page we are already at.
	if( animating || num == cNum ){
		return;
	}else{
		animating = true;
	}
	
	//Going off the right
	if( num > cLimit ){
		num = 1;
	}
	
	//Going off the left
	if( num < 1 ){
		num = cLimit;
	}
	
	//Make it reverse on the indicator clicks if we're going "backwards"
	if( !reverse && num < cNum && num != 1 ){
		reverse = true;
	}
	
	countdown = 12;
	
	if( carousel_mode == 'fade' ){
    	$j('div.Features:visible').fadeOut();
    	$j('div.Features#f'+num).fadeIn();
	}else if( carousel_mode == 'slide' ){

		$j( 'div#FeatureWrap' ).css( 'overflow', 'hidden' );

		var title_out;
		var title_in;

		var cur_title = $j( 'div.Features#f' + ( cNum ) + ' > .title > h1' ).html();
		var new_title = $j( 'div.Features#f' + ( num  ) + ' > .title > h1' ).html();

		//console.log( cur_title );

		if( $j( '#title_proxy_1 > h1' ).html() == cur_title  ){
			title_out = '#title_proxy_1';
			title_in  = '#title_proxy_2';
		}else{
			title_out = '#title_proxy_2';
			title_in  = '#title_proxy_1';
		}

		$j( title_out ).html( '<h1>' + cur_title + '</h1>' );
		$j( title_in  ).html( '<h1>' + new_title + '</h1>' );
		
		$j( title_out ).css( 'display', 'block' );
		$j( title_out ).css( 'opacity', '1' );
		$j( title_out ).css( 'padding-left', '19px' );
		$j( title_out ).css( 'margin-top', '0px' );
		
		$j( title_in ).css( 'opacity', '0' );
		$j( title_in ).css( 'padding-left', '19px' );
		$j( title_in ).css( 'margin-top', '0px' );
		$j( title_in ).css( 'display', 'block' );		

		
		var this_cnum = cNum; //We have to capture the current value because by the time we get to doing the hide it will have changed.
						      //Lexical scope FTW/L
		if( reverse ){
			$j( 'div.Features#f' + this_cnum + ' > .title' ).css( 'opacity', '0' );
			$j( 'div.Features#f' + this_cnum ).animate( { left: '940px' },  1000, 'swing', function(){ $j( 'div.Features#f' + this_cnum ).hide(); } );
		}else{
			$j( 'div.Features#f' + this_cnum + ' > .title' ).css( 'opacity', '0' );
			$j( 'div.Features#f' + this_cnum ).animate( { left: '-940px' }, 1000, 'swing', function(){ $j( 'div.Features#f' + this_cnum ).hide(); } );
		}
		
		setTimeout( function(){ $j( title_out ).animate( { opacity: '0' }, 500, 'linear', function(){ $j( title_in  ).animate( { opacity: '1' }, 500 ); } ) }, 0 );
		
		if( reverse ){
			$j( 'div.Features#f' + num ).css( 'left', '-940px' );
			$j( 'div.Features#f' + num + ' > .title' ).css( 'opacity', '0' );
		}else{
			$j( 'div.Features#f' + num ).css( 'left', '940px' );
			$j( 'div.Features#f' + num + ' > .title' ).css( 'opacity', '0' );
		}
		$j( 'div.Features#f' + num ).show();
		
		//console.log( 'Sliding ' + num + ' in' );
		$j( 'div.Features#f' + ( num ) + ' > .title > h1' ).css( 'opacity', '0' );
		setTimeout( function(){ $j( 'div.Features#f' + num ).animate({ left: '0px' }, 1000, 'swing' ); }, 0 );
		setTimeout( function(){ $j( 'div.Features#f' + num + ' > .title' ).animate( { opacity: '1' },  500, 'swing' ); }, 500 );
		
		//Update the current page indicator
		$j( '#pager > .active' ).removeClass( 'active' );
		$j( '#pager_' + num ).addClass( 'active' );
	
		//We'll be done transitioning in 1.1s
		setTimeout( function(){ animating = false; }, 1100 );
	}
	
    cNum = num; //sync it up
}

function updateTimer() {
	if( current_timer >= COUNTDOWN_TIME ){
		advanceToNextCarouselSection();
		resetTimer();
		return;
	}
	
	if( rotator_cycles > rotator_max_cycles ){
		stopTimerAdvanceFeatureSection();
		$j( '#countdown' ).css( 'visibility', 'hidden' );
	}else{
		current_timer++;
		$j( '#countdown_progress' ).css( 'width', Math.floor( 23 * ( current_timer / COUNTDOWN_TIME ) ) + 'px' );
	}
	
}

function resetTimer(){
	current_timer = 0;
	updateTimer();
}

function setTimerToAdvanceFeatureSection() {
    countdownTimer = setInterval(updateTimer, 1000); //Call decrementCountdown() every 1 second
}

function stopTimerAdvanceFeatureSection() {
    clearInterval(countdownTimer);      //Stop the countdown timer
}

$j(document).ready(function(){
    //Set the contents of all countdown displays
	$j( '#countdown'     ).css( 'width',  '23px' );
	$j( '#countdown'     ).css( 'height', '4px' );
	$j( '#countdown'     ).css( 'margin-top', '5px' );
	$j( '#countdown'     ).css( 'font-size', '1px' );
	
	$j( '#countdown_box' ).css( 'width', '23px' );
	$j( '#countdown_box' ).css( 'background-color', '#A7A7A7' );
	$j( '#countdown_box'     ).css( 'font-size', '1px' );
	$j( '#countdown_box'     ).css( 'height', '4px' );
	
	$j( '#countdown_progress').css( 'float', 'left' );
	$j( '#countdown_progress').css( 'width', '0px' );
	$j( '#countdown_progress' ).css( 'background-color', '#404040' );
	$j( '#countdown_progress'     ).css( 'font-size', '1px' );
	$j( '#countdown_progress'     ).css( 'height', '4px' );
	
    
    //Dynamically determine how many carousel sections are present. This does not (yet?) dynamically determine the number of dots in the pager.
    cLimit = $j('div.Features').length;

	function makeClosure(x) { 
	    return function(){ 
	    	return hideFeatureSectionsExcept( x ); 
		} 
	} 
	

	if( carousel_mode == 'slide' ){
		$j( 'div.Features' ).css( 'position', 'absolute' );
		$j( 'div.Features' ).css( 'top', '0px' );
		$j( 'div.Features' ).css( 'left', '940px' );
		//$j( 'div.Features' ).css( 'clear', 'none' );
		//$j( 'div.Features' ).css( 'z-index', '10' );
		$j( 'div.Features' ).hide();
		
		$j( 'div.Features#f1' ).css( 'left', '0px' );
		$j( 'div.Features#f1' ).show();
		
		//$j( '#FeatureWrap' ).css( 'overflow', 'hidden' );
		
		//Setup the pager dynamically
		var code = '';
		for( var x = 1; x <= cLimit; x++ ){
			code += '<a class="pager_indicator" href="" id="pager_' + x + '"></a>';
		}
		$j( '#pager' ).html( code );
		$j( '#pager_1' ).addClass( 'active' );
		
		for( var x = 1; x <= cLimit; x++ ){
			$j( '#pager_' + x ).bind( 'click', makeClosure( x ) );
		}
		
		
		//Setup first title
		
		$j( '.Features > .title' ).css( 'visibility', 'hidden' );
		$j( '#title_holder' ).css( 'opacity', '1' ).css( 'display', 'block' );
		//$j( 'div.Features' ).css( 'padding-top', '31px' );
		var cur_title = $j( 'div.Features#f1 > .title > h1' ).html();
		$j( '#title_proxy_1' ).html( '<h1>' + cur_title + '</h1>' );
		$j( '#title_proxy_1' ).css( 'opacity', '1' ).css( 'display', 'block' ).css( 'padding-left', '19px' );
		$j( 'div.Features#f' + ( 1 ) + ' > .title > h1' ).css( 'opacity', '0' );
	}
	
    setTimerToAdvanceFeatureSection();

    $j('div.Features').hover(function(){
        stopTimerAdvanceFeatureSection();
    },function(){
        setTimerToAdvanceFeatureSection();
    });

    //Add click listeners to the right and left spinners
    $j('a.spin-right').click(function(){
		goRight();
        return false;
    });
    $j('a.spin-left').click(function(){
		goLeft();
        return false;
    });
    
    //Add animations on hover to the feature items in feature section #3
    $j('div.FeaturedProducts ul.FeaturesList li.FeatureItem').hover(function(){
	
			var self = this;
			
			//setTimeout( function(){ 
				$j( 'div#FeatureWrap' ).css( 'overflow', 'visible' );
				$j(self).animate({"height":"100%"}, 'fast');   //Mouse over, grow taller to show bottom of box
			//}, 500 );
    }, function(){
		var self = this;
		if( !WE_ARE_IE6 ){
			$j(this).animate({"height":"127px"}, 'fast');   //Mouse out, shorten to hide bottom of box
		}else{
			$j(this).animate({"height":"136px"}, 'fast');   //Mouse out, shorten to hide bottom of box
		}
    });
    
    //Listen for clicks to the pager anchors and switch sections appropriately
    $j('#pager a').click(function(){
        var count = 1;
        var currentAnchor = $j(this);
        while (currentAnchor.prev().length) {
            count++;
            currentAnchor = currentAnchor.prev();
        }
		stopTimerAdvanceFeatureSection();
        hideFeatureSectionsExcept(count);
        return false;
    });
    
    $j('ul#res-nav li').hover(function(){
        //Over, remove 'active' from all other sibs, add to this
        $j(this).siblings().removeClass('active');
        $j(this).addClass('active');
    },function(){});

	// Misc styles fix through JS
	
	$j('div.blog-entry:last').addClass('last'); // Adds a "last" class to the blog entries to remove border

});
