/**
 * Rotates an ad system
 *
 * Assumes the following structure somewhere on page:
 	<div class='ad_container'>
  		<!-- Visible slots -->
 		<div class='ad_slot'>
 			<!-- ad content -->
 		</div>
 		<div class='ad_slot'>
 			<!-- ad content -->
 		</div>	
 			...
 			... 
 		<!-- Hidden slots -->
 		<div class='ad_slot' style='display: none;'>
 			<!-- ad content -->
 		</div>	
 			...
 			...
    </div>
 *
 */
 
 
 var ROTATION_DURATION = 15000; 	//Time between ad rotations (in milliseconds)
 var VISIBLE_SLOTS = 4;			   //Change to how many visible slots there are
 
 
 /*
  * Initiates rotary system, but only if there's enough
  */
  $(document).ready(function() {
 	//Start when document is ready, but only if there's more than VISIBLE_SLOTS ads
 	if ( $("div.ad_container .ad_slot").length > VISIBLE_SLOTS )	
		setTimeout("rotate();",ROTATION_DURATION);

 });
  
 
  /*
   *  Ad counter system
   */
  var counter = 1; 			//current counter (don't edit)
  
  	//Get current value
  function getCounter() { return counter; }
  	//Increment & Cycle counter
  function incCounter() { 
  	counter++;
  	if ( counter > VISIBLE_SLOTS ) 
  		counter = 1;
  }
  
  
  /*
  *   Rotate one ad slot with random hidden slot
  */
  function rotate() {
  	//select the next ad to swap out
  	$("div.ad_container #ad_slot_" + getCounter()).fadeOut(500,function() {
  		var c = getCounter();
   		
  		//Select another random hidden one
  		var restLen = $("div.ad_container .ad_slot").length - VISIBLE_SLOTS;
  		var newIndex = Number(VISIBLE_SLOTS+1+Math.floor(Math.random()*restLen));
  		
  		//Grab new content from hidden slot
    	var html = $("div.ad_container #ad_slot_" + newIndex).html();
  		
  		//Swap in present ad into new index
  		$("div.ad_container #ad_slot_" + newIndex).css('display','none');
  		$("div.ad_container #ad_slot_" + newIndex).html(
  			$("div.ad_container #ad_slot_" + c).html()
  		);
    		
  		//Swap in new ad data into slot
  		$("div.ad_container #ad_slot_" + c).html(html);
  		
  		//FAde it in
   		//$(this).fadeIn(500);
   		$("div.ad_container #ad_slot_" + getCounter()).fadeIn(500);
   		
   		//Increment the counter
     	incCounter(); 
   	});
   	
   	//Rotate again soon...
   	setTimeout("rotate();",ROTATION_DURATION);
  }
  
 