/* Enables image rotation functionality on the home page. */
//---------------------------------------------------------------------
// getClippingsContent - /* Enables image rotation functionality on the home page. */
// @param - group - The clippings group name.
// @param - div_id - The div id of the containing div.
//--------------------------------------------------------------------- 
jQuery.homeRotate = function (group,div_id) {
   
   var last = 0;   
   var current = 0;
   var cache = [];
   var clippings = "";
   var loaded = 0;
   var num_clippings = 0;
   var timer = "";
   // Triggered by timer. Get current clipping and call
   function changeImage() {
      last = current;
      current = (current == (clippings.length - 1)) ? 0 : (current + 1);
      jQuery(div_id).find("img:first-child").fadeOut(100, function () {
         jQuery(this).attr('src', clippings[current]['src']);
         jQuery(this).attr('alt', clippings[current]['alt']);
         jQuery(this).attr('title', clippings[current]['alt']);
      })
      .fadeIn(650, function () {
         jQuery(div_id).css('backgroundImage', 'url('+clippings[current]['src']+')') // Trick for cross-fade. Set last image as background.
      });
   }
   
   // Get the clippings using an ajax call and then set the timer
   jQuery.getJSON('includes/ajax_clippings.php?', {'clip_group' : group }, function(data) {
      var cacheImage = "";
      clippings = data;
      
      // Find the currently displayed clipping image and also preload.  Callback is to initialize timer AFTER images are pre-loaded.
      $.loadImages = function (callback) {
         num_clippings = clippings.length
         for(i = 0; i < num_clippings; i++) {
            // Find the current clipping image and set to the background image for cross fade.
            if (clippings[i]['src'] == jQuery(div_id).find("img:first-child").attr('src')) {
               current = i;
               jQuery(div_id).css('backgroundImage', 'url('+clippings[i]['src']+')') 
            }
            
            // Cache all images for faster loading.            
            cache[i] = new Image();
            cache[i].onload = function() {
               loaded++; // should never hit a race condition due to JS's non-threaded nature
               if (loaded == num_clippings) {
      			   if ($.isFunction(callback)) {
      			      callback();
                  }
               }
            };
            cache[i].src = clippings[i]['src'];  
         }
      };
      
      // Start the timer.
      $.loadImages(function() {
         // Start timer
         timer = jQuery.timer(4500, function(timer) {
            changeImage();
         });
      });               
   });
};


$(document).ready(function () {
      jQuery.homeRotate("Home Banners 960", "#home-image");
});


