var id=1;
var maxID;
var image;
var promoTitle;
var copyText;
var more_url;
var download_url;
var isAnimating;
var intervalID;  

function promoCycle(){

  var newID = id;
  newID++;
  if(id < maxID){
    $('#'+newID).click();
  }else{
    $('#1').click();
  }
  intervalID = setTimeout(promoCycle, 8000);
  
}

function buildNav(){
  var navHTML = '<ul>';
  var navOutput = '';
  var navCount = 1;

  for(i=maxID;i>=1; i--){
    
                navOutput = '<li><a id="'+i+'">'+navCount+'</a></li>';
    navHTML += navOutput;
   navCount++;
  }
  
  navHTML += '<div class="cl">&nbsp;</div>';
  $('.img-nav').append(navHTML);
}



function buildPromo(image, promoTitle, copyText, more_url, download_url, xml_id){
	
	
	  // Build HTML string and return
	  output = '';
	  output += '<li class="promoItem" id="p'+xml_id+'">';
	  output += '<div class="left"> <img src="'+image+'" alt="" /> </div>';
	  output += '<div class="info"><div class="promo-copy"><h2>'+promoTitle+'</h2>';
	  output += '<p>'+copyText+'</p></div>';
	  output += '<p class="info-links">';
	
	  if(more_url.length > 0){output += '<a href="'+more_url+'" class="blue-btn"><span>More</span></a>';}
      if(download_url.length > 0){output += '<a href="'+download_url+'" class="blue-btn download-btn"><span>Download</span></a>';}

	  output += '</p><div class="cl">&nbsp;</div>';  
	  output += '</div><div class="cl">&nbsp;</div></li>';
	  return output;
	
}

// function handlePromoXML (xml){
function handlePromoXML (){

	

	var xml_id = 1;
	var promo_html = '';	
	
	// $("promo").each(function() {
	// 		alert("in");
	// 		image = $(this).find("pic").text();
	// 	    promoTitle = $(this).find("promo_title").text();
	// 	    copyText = $(this).find("copy").text();
	// 	    more_url = $(this).find("more_url").text();
	// 	    download_url= $(this).find("download_url").text();
	// 	
	// 	    mydata = buildPromo(image, promoTitle, copyText, more_url, download_url, xml_id);
	// 	    promo_html = promo_html + mydata;
	// 	    xml_id++;
	// 	});
	// 
	// 	$("#promoContainer").html(promo_html);
	
	 
	  $("#p1").show();
	  maxID = ($("#promoContainer").children().length);
		
	  if (maxID > 1){
		intervalID = setTimeout(promoCycle, 0);
	  	buildNav();
	  	$('.img-nav li a:first').addClass('active');
	  }else if (maxID == 1){
		$('.img-nav').hide();
	  }

	  $('.img-nav a').click(function() {
		
		if(!isAnimating){
	      var $this = $(this);
	      var y = $this.attr("id");
	
	      if ( y != id ){
	        isAnimating= true;
			$('.img-nav a').removeClass('active');
		    $('a#'+y).addClass('active');
	        $("#p"+id).hide();
	        id=y;
	        $("#p"+y).show();
	 	  	isAnimating = false;
	        clearInterval(intervalID);  
		  }
	     }
	  });
}

$(document).ready(function(){ 
  	$(".promoItem").hide();
	handlePromoXML();
});
