/**
 *    CUSTOM CAROUSEL FUNCTION BASED ON JCAROUSEL
 *       
 *       To show carousel:
 *       createCarousel("myFirstCarousel");
 *       
 *    To show carousel and automatically update it every interval time:
 *       createCarousel("myFirstCarousel");
 *       gTimers["myFirstCarousel"] = setInterval("reloadAndReset('myFirstCarousel')", interval*1000);
 *
 *    To Stop an automatically updating carousel:
 *       clearInterval(gTimers["myFirstCarousel"]);
 *
 *    To cause a carousel to reload:
 *       reloadAndReset("myFirstCarousel");
 */

interval = 20; // Time in seconds between reset/reload of carousels
useTestURL = false;  // Use test URLS
realURL="../zuma/get_leaderboard.php";  // The URL which will be used if usTestURL==false
gData = new Array();   // The data array
gCarousels = new Array();  // Array of carousels, indexed by string identifier
gTimers = new Array();
urlCounter=0; // Utility just used to generate bogus changing urls for test environ

/** This is in page.fbconnect.js now
* Do this stuff on document load  **/
//$(document).ready(function() { 	
	// Create the carousel
	// createCarousel("myFirstCarousel");
  	// truncate long names
	// $(".welcome_name_truncate").ellipsis();
// });

// Debugger. Uncomment if you want to see what's happening
//function debug(text) {
  // $("#notification").append(text + "<br/>");
//}

/* utility function only - for test environment to get varying JSON data
function getJsonURL(identifier) {
  if (useTestURL) {
    url= "../js/json_output_"+urlCounter %4+".js";
  } else {
    url = realURL;
  }
  urlCounter++;
  return url;
}
*/

// jcarousel calls this to add the item. Stock stuff here
/* format the data in each li */
var getItemHTML = function(d) {
  return '<div class="' +
  d.active + '"><div class="lb-rank">' +
  d.rank + '</div><div class="lb-photo"><div style="background: url(' +
  d.pic + ') top center no-repeat;"><a class="' +
  d.active + '" target="_blank" href="' +
  d.profile_url + '"><img class="product" alt=" " src="../images/spacer.gif" border="0" /></a></div></div><div class="lb-name"><div class="lb-name-truncate"><a target="_blank" href="' +
  d.profile_url + '">' +
  d.name + '</a></div><h1>' +
  d.score + '</h1></div><div class="lb-icons"><a class="smack-button" href="javascript:launchSmackTalkFeedForm(\'' +
  d.fb_id + '\', \'' +
  d.pic + '\');"><img src="../images/spacer.gif" width="50" height="45" border="0" alt="" /></a></div></div>';
};

// Callback used to capture the object rEvery subdomain on the (gs) Grid-Service MUST have it's own html folder (example: /domains/sub.mt-example.com/html/). eference to carousel
function onInitCarousel(carousel, state) {
  //debug("onInitCarousel: carousel="+carousel+ " and state="+state);
  if (state == 'init') {
    gCarousels[carousel.options.identifier] = carousel;
  }
}

// jcarousel calls this to do the load. We just grab the data (already loaded)
// from the global array gData
function itemAddCallback(carousel, first, last, data) {
  //debug("itemAddCallback: carousel="+carousel+" and first="+first+ " last="+last+ " data="+data);
  for (i = 0, j = data.length; i < j; i++) {
    carousel.add(i, getItemHTML(data[i]));
  }
  carousel.size(data.length);
}

function itemLoadCallback(carousel, state) {
  //debug("itemLoadCallback: carousel="+carousel+" and state="+state);
  if (state != 'init') {
    return;
  }
  itemAddCallback(carousel, carousel.first, carousel.last, gData[carousel.options.identifier]);
}

// Find and return the index of the first item labeled "active"
function getActiveItem(data) {
  var activeitem=-1;
  // find out what position we're currently in
  $.each(data, function(n,item) {
    if (item.active == "active") {
      activeItem=n;
      return false;
    }
    return true;
  });
  return activeItem;
}

// Called asynchronously after data is loaded. But this is the major creator of carousel
function startCarousel(whoami, data) {
  gData[whoami]=data;
  activeItem = getActiveItem(data);
  //debug("activeItem="+activeItem);
  
  $('#mycarousel').jcarousel({
    itemLoadCallback: itemLoadCallback,
    start: activeItem > 1 ? activeItem -1 : activeItem,
    scroll: 5,
    initCallback: onInitCarousel,
    identifier: whoami
  });   
  //debug("Carousel created");
}

// Load data and do asynchronous callback to the start function after data is loaded
function loadAndStart(identifier) {
 //create timestamp when function runs
  var timestamp = Number(new Date());
  
  //debug("getData: Calling getJSON");
  $.getJSON(realURL+'?'+timestamp, function(data, textStatus){
    startCarousel(identifier,data.items);
    });    
}

// Reload data and then reset the carousel
function reloadAndReset(identifier) {
 //create timestamp when function runs
  var timestamp = Number(new Date());
  
  //debug("reloadAndReset: Calling getJSON");
  $.getJSON(realURL+'?'+timestamp, function(data, textStatus){
    gData[identifier] = data.items;
    activeItem=getActiveItem(data.items);
    gCarousels[identifier].options.start = activeItem > 2 ? activeItem-1 : activeItem;
    gCarousels[identifier].reset();
    });    
}

// Create the carousel
function createCarousel(identifier) {
  //debug("CreateCarousel (" + identifier + ") " + new Date());
  loadAndStart(identifier); 
  // truncate long names
  $(".lb-name-truncate").ellipsis();
}


/*** Loading GIF for leaderboard

	jQuery(function($) {  
		$("#contentArea").load("get_leaderboard.php");  
	});  

	$().ajaxSend(function(r,s){  
		$("#loading").show();  
	});  

	$().ajaxStop(function(r,s){      	
		$("#loading").fadeOut("fast");  
	});
  
***/