(function($){

 /******
  F'n
  ***/
  
  var hero_timer, heroshots,
      all_heroshots,
      hero_n = 0;
  var heroshot = function(o){
    var m = (hero_n + 1 == heroshots.size()) ? 0 : hero_n + 1,
        nu = heroshots.eq(m),
        old = all_heroshots.filter('.visible');
    old.css('z-index', '20').removeClass('visible');
    nu.hide().addClass('visible').css('z-index', '40').fadeIn(728, function(){
      old.css('z-index', '10');
    });
    hero_n = m;
  };
  
  var loaded_heroshots = 1;
  var init_heroshots = function(){
    // Randomize heros, admittedly nasty
    $( $.makeArray( $('#home-heroshots li').remove() )
      .sort(function(a,b){ return (Math.random() - 0.5); })
    ).appendTo('#home-heroshots');
      
    // var fashion = all_heroshots.filter('.fashion-hero');
    // fashion.eq(Math.round( Math.random() * (fashion.size()-1) )).remove().prependTo('#home-heroshots');
    // var no5 = $('.hero-no-5').remove().prependTo('#home-heroshots');
    var no5 = $('#home-heroshots li a[href$=nh1.jpg]').parent().remove().prependTo('#home-heroshots');
    all_heroshots = $('#home-heroshots li');
    
    // var start = Math.round( Math.random() * (all_heroshots.size()-1) );
    var start = 0;
    init_heroshot(all_heroshots.eq(start), function(){
      all_heroshots.eq(start).addClass('visible').css('z-index', 40)
      all_heroshots.not(start).each(function(i,tem){
        init_heroshot($(tem), heroshot_loaded);
      });
    });
  };
  
  var init_heroshot = function(li, cbk){
    var url = li.find('a.home-hero-url').remove().attr('href');
    $('<img />').attr({src: url+($.browser.msie ? '?' + (new Date()).getTime().toString() : '')}).appendTo(li).load(cbk);
  };
  
  var heroshot_loaded = function(){
    loaded_heroshots++;
    if(loaded_heroshots == all_heroshots.size())
      set_hero_set('fashion');
  };
  
  var set_hero_set = window.set_hero_set = function(name) {
    switch(name){
    case 'fashion':
      heroshots = all_heroshots.filter('.fashion-hero');
      break;
    case 'form':
      heroshots = all_heroshots.filter('.form-hero');
      break;
    case 'both':
      heroshots = all_heroshots;
      break;
    }
    var old = hero_n;
    hero_n = Math.round(Math.random() * (heroshots.size() - 1));
    if(typeof hero_timer != 'undefined') heroshot();
    clearTimeout(hero_timer);
    hero_timer = setInterval(heroshot, 6280);
  };
  
 /******
  DOM Ready
  ***/
  $(function(){
    if($('#home').size()){
      init_heroshots();
      $('#form-hit').hover(function(){ set_hero_set('form'); });
      $('#fashion-hit').hover(function(){ set_hero_set('fashion'); });
    }
  }); 
})(jQuery);

