// preload images for ie6
if (window.ie6) {
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(e) { }
  var img_set = [];
  for(var i=0; i<8; i++) {
   var newimg = new Image();
   newimg.src = '/images/rot-header/'+i+'.jpg';
   img_set.push( newimg );
  }
}

var SetforLife = {
  
  testimonials_selector : $('.home .testimonial'),
  billboard_links_selector : $('.headcount'),
  
  init : function() {
    SetforLife.loop_testimonials();
    SetforLife.loop_billboards();
  },
  
  loop_testimonials : function() {
    
    if(SetforLife.testimonials_selector.length > 0) {
      SetforLife.testimonials_selector.hide();
      var i = 0;
      SetforLife.next_testimonial(i);
    }
  },
  
  next_testimonial : function(i) {
    var t = SetforLife.testimonials_selector;
    t.each(function(i){
      var element = $(this);
      setTimeout(function(){
        element.siblings().fadeOut('fast', function(){
          $(this).hide();
          element.fadeIn(2000, function(){ $(this).show(); });
        });
        
      },i*10000);
    });
  },
  
  random_order : function() {
    return (Math.round(Math.random())-0.5);
  },
  
  billboard_links_randomized : function() {
    return $('.headcount').sort( SetforLife.random_order );
  },
  
  loop_billboards : function() {
    var banner_links = $('.headcount');
    
    if( banner_links.length > 0 ) {
      var counter = 0;
    	var auto_animations = true;
    	
    	// get shuffled set
    	var shuffled = SetforLife.billboard_links_randomized();
    	$(shuffled).click(function() {
        
        var current_target = $(this).text();
        var scheduled_target = $(shuffled[counter]).text();
        
        if( auto_animations && (scheduled_target != current_target) ) { // indicates user interaction
          auto_animations = false;
        } else {
          counter = (counter==6) ? 0 : counter + 1;
        }
        // alert('next is ' + $(shuffled[counter]).text());
        
        // make this anchor active
        banner_links.removeClass('active-over');
        $(this).addClass('active-over');
        
        $('#header-swap').fadeOut('slow',function() {
          $(this).removeClass();
          $(this).addClass('img-'+current_target.replace(/^\s+|\s+$/g,""));
          
          $(this).fadeIn('slow',function(){
            if(auto_animations) {
              var next = $(shuffled[counter]);
              // if(next.length == 0) next = $('.headcount:first');
              next.animate( {backgroundPosition:'100'}, 8000, 'linear', function() {
                if(auto_animations) $(this).click();
              });
            }
          });
        });
        return false;
    	}); // end click
    	
    	// simulate click on random panel
    	$(shuffled[0]).click();
    }
  }
  
}

jQuery(document).ready(function() { SetforLife.init(); } );