// rotate.js

function rotate() {

  // setup      
  var current = 0;
  var ie6 = false;
  var time = 5000;
  var viewclass = '.view-content-homepage-rotator';
  var linkprefix = 'home-link-';
  var activeclass = 'home-current';
  var linksdivclass = 'featured-links';
  var fadespeed = 'slow';
  // upper limit effectively handled by the number of nodes views returns
  var total = $(viewclass + ' li').length;

  $('#block-views-homepage_rotator').show();
  
  // add additional js specific styles
  $(viewclass).addClass('view-content-homepage-rotator-js');
  $(viewclass + ' li').addClass('js');
  
  // add div for rotator links
  $(viewclass).append('<div class="' + linksdivclass + '"></div>');

  // populate div with links for each li item
  for(i=0;i<total;i++) {
    tmphref = $(viewclass + ' li' + ':eq(' + i + ') a').attr('href');
    tmptitle = $(viewclass + ' li' + ':eq(' + i + ') a').html();
    
    $('.' + linksdivclass).append('<a href="' + tmphref + '" id="' + linkprefix + i + '" title="' + tmptitle + '" class="tooltip">' + (i+1) + '</a>');
  }
  
  tooltip();

  if($.browser.msie && $.browser.version < 7) { ie6 = true; } // boo!

  // hide all boxes then show first one and highlight first link
  for (i=0;i<total;i++) {
    $(viewclass + ' li').hide();
  }
  $(viewclass + ' li' + ':eq(' + current + ')').show();
  $('#' + linkprefix + current).addClass(activeclass);


  if(total>1) {
    // start auto rotating boxes
    headline_interval = setInterval(auto_rotate,time);
  
  
    $("a[@id^='" + linkprefix + "']").click(function() {
      linkid = $(this).attr('id');
      next = linkid.substring(linkid.length-1, linkid.length);
      if(current != next) {
        click_rotate(next);
      }
      return false;
    });

    function click_rotate(next) {
      clearInterval(headline_interval);
      rotate(current, next);
      current = next;
      // headline_interval = setInterval(auto_rotate,time); // optionally start rotating again
    }
    
  }

  function auto_rotate() {
    // go back to the start if current is the last item
    if(current<(total-1)) { next = current + 1; } else { next = 0; }
    rotate(current, next);
    // go back to the start if current is the last item
    if(current<(total-1)) { current ++; } else { current = 0; }
  }
  
  function rotate(from, to) {
  
  // fadeout (or hide in ie6) previous box then fade in new one. Un-highlight previous link and highligh new one. 
    if(ie6) {
      $(viewclass + ' li' + ':eq(' + to + ')').show();
      $(viewclass + ' li' + ':eq(' + from + ')').hide();
    } else {
      $(viewclass + ' li' + ':eq(' + to + ')').fadeIn(fadespeed);
      $(viewclass + ' li' + ':eq(' + from + ')').fadeOut(fadespeed);
    }
  
    // swap active class
    $('#' + linkprefix + next).addClass(activeclass);
    $('#' + linkprefix + current).removeClass(activeclass);
  }
      
}

$(document).ready(function() { 
rotate();
});
