var delayFor = 5000; //number of miliseconds to wait until the ad rotates
var imgIndex = 1; //index of image to get info from
var heartBeat;

$(document).ready(function(){
  var adIndex = $("#divRWC_Rotate_Ads_Images div").size();
  
  //preload images and create ad indicators
  $("#divRWC_Rotate_Ads_Images div").each(function(){
    //preload image
    $('<img/>')[0].src = $(this).attr("rel");
    
    //create ad indicator
    $("#divRWC_Rotate_Ads").append($("<span id='spAd_" + adIndex + "'>" + adIndex + "</span>"));
    adIndex += -1;
  });
  
  //setup click and hover events
  //onclick="javascript:ViewHomepageAd(this);
  $("#divRWC_Rotate_Ads span").click(function(){
    ViewHomepageAd(this);
  }).hover(function(){
    ViewHomepageAd(this);
  });
  
  
  
  RotateHomepageAd(true);
  //myInterval = window.setInterval("RotateHomepageAd()", delayFor);
});

function RotateHomepageAd(bSetTimeout){
  var fadeDuration = 2000;
  var url = $("#divRWC_Rotate_Ads_Images div:nth-child(" + imgIndex + ")").attr("href");
  var src = $("#divRWC_Rotate_Ads_Images div:nth-child(" + imgIndex + ")").attr("rel");
  var alt = $("#divRWC_Rotate_Ads_Images div:nth-child(" + imgIndex + ")").attr("alt");
  
  if($("#divRWC_Rotate_Ads img").size() > 0){
    $("#divRWC_Rotate_Ads img").stop().animate({opacity: 0}, fadeDuration, function(){
      $("#divRWC_Rotate_Ads a").attr("href",url).children("img").attr("src",src).attr("alt",alt);
      $("#divRWC_Rotate_Ads img").animate({opacity: 1}, fadeDuration);  
      $("#divRWC_Rotate_Ads span").css("font-weight","normal");
      $("#divRWC_Rotate_Ads span[id='spAd_" + imgIndex + "']").css("font-weight","bold");

      if(bSetTimeout){
        if(imgIndex < $("#divRWC_Rotate_Ads_Images div").size()){
          imgIndex += 1;
        }
        else{
          imgIndex = 1;
        }
      }
    });
  }
  else{
    $("#divRWC_Rotate_Ads").prepend($("<a href='" + url + "'><img border='0' src='" + src + "' alt='" + alt + "' /></a><br />")).children("span[id='spAd_" + imgIndex + "']").css("font-weight","bold");

    imgIndex += 1;
  } 
 
  if(bSetTimeout){
    heartBeat = setTimeout("RotateHomepageAd(true)",delayFor);
  } 
}

function ViewHomepageAd(adIndicator){
  clearTimeout(heartBeat);
  
  var adID = parseInt($(adIndicator).html());
  
  if(imgIndex != adID){
    imgIndex = adID;
    RotateHomepageAd(false);
  }
}
