$(document).ready(function(){
	/*
	 * Rotating Ad
	*/
	var interval = 7000;
	var ad_count;
	var ad_interval;
	var old_ad = 0;
	var current_ad = 0;
	
	$( "#ads-shell" ).append( '<span class="prev btn"></span><span class="next btn"></span>' );
	$( ".prev, .next" ).fadeTo( 0, 0.3 );
	
	$( ".prev" ).click( function(i) {
		i.preventDefault();
		rotate_ad( 'prev' );
	});
	
	$( ".next" ).click( function(i) {
		i.preventDefault();
		rotate_ad( );
	});
	
	$( ".next, .prev" ).hover( 
		function() { $( this ).fadeTo( 'fast', 1 ); },
		function() { $( this ).fadeTo( 'fast', 0.3 ); 
	});
	
	// number of ads
	ad_count = $("#ads li").length;
	
	// hide all of the ads
	$("#ads li").each( function(i) { $(this).hide(); });
	
	// show first ad	
	$( "#ads li" ).eq( current_ad ).fadeIn("slow");
	
	// start rotation
	if( ad_count > 1 ) {
		
		// add navigation container
		$( "#ads-shell" ).append('<div class="ads-nav"></div>');
			
		// create navigation item for each ad
		$("#ads li").each(function(i){
			$('.ads-nav').append('<span class="nav-item">'+(i+1)+'</span>');
		});
		
		// add transparency
		$( ".nav-item" ).fadeTo( 0, 0.6 );
	
		// hover
		$( ".nav-item" ).hover( 
			function() { $( this ).fadeTo( 'fast', 1 );},
			function() { $( this ).fadeTo( 'fast', 0.6 ); 
		});
	
		ad_interval = setInterval( function() { rotate_ad(null) }, interval );
		
		// add click event handler
		$(".nav-item").each(function(i){
			$(this).css('cursor','pointer');
			$(this).click(function(){
				// rotate ad
				rotate_ad( i );
				// disable rotation on click
				clearInterval( ad_interval );
			});
		});
		
		// disable rotation on hover
		$('#ads li img').hover(
			function() { clearInterval( ad_interval ); },
			function() { ad_interval = setInterval( function() { rotate_ad(null) }, interval );
		});
	}
	
	function rotate_ad( direction ) {
		if( direction!=null ) {
			
			if( direction == 'prev' ) {
				current_ad = (old_ad - 1);
				if( current_ad == -1) current_ad = ad_count-1;
			} else {
				current_ad = direction;
			}
		
		} else {
			current_ad = (old_ad + 1) % ad_count;
		}
	
		$("#ads li").eq( old_ad ).fadeOut("slow", function() {
			$("#ads li").eq( current_ad ).fadeIn("slow");
		});
		
		old_ad = current_ad;		
	}

});