$(function() {
  var animating = false, $current = $('#heros > li:visible:first'), speed = 'slow', timeout;
  
  $('#heros > li[id!=hero-last]').click(function(event) {
    if (event.target.tagName == 'LI') {
      clearTimeout(timeout);
      window.location.href = $('a:first', this)[0].href;
    }
  });
  
  function enableImgs(parent) {
    $('img', parent).each(function() {
      var $this = $(this);
      $this.attr('src', $this.attr('data-src'));
    });
  }

  function loadImage($to, callback) {
    var toUrl = $to.css('backgroundImage'), img = new Image();
    enableImgs($to);
    
    if (toUrl.substring(0, 4) == 'url(') {
  		$(img).bind('error load onreadystatechange', function() {
        $to.removeClass('prevent-loading');
        callback();
  		});

      img.src = toUrl.substring(4, toUrl.length - 1);
    } else {
      $to.removeClass('prevent-loading');
      callback();
    }
  }

  function crossFade($to, callback) {
    $current.fadeOut(speed);
		$current = $to;
		$to.fadeIn(speed, function() {
		  animating = false;
		  if (callback) callback();
		});
  }

  function show($to, callback) {
    if (animating) return;
    
    clearTimeout(timeout);
    animating = true;
    
    if ($to.hasClass('prevent-loading')) {
      loadImage($to, function() {
        crossFade($to, callback);
      });
    } else {
      crossFade($to, callback);
    }
  };
  
  function previousImage() {
    var $previous = $current.prev();
    if ($previous.length == 0) $previous = $('#heros > li:last');
	  show($previous);
  };
  
  function nextImage(callback) {
    var $next = $current.next();
    if ($next.length == 0) $next = $('#heros > li:first');
    show($next, callback);
  };
  
  $("#next-image").click(function(event) {
    event.preventDefault();
    speed = 'fast';
    nextImage();
  });

  $("#previous-image").click(function(event) {
    event.preventDefault();
    speed = 'fast';
    previousImage();
  });

  $("#heros").hover(showAuthorCredit, hideAuthorCredit);

  function showAuthorCredit() {
    $("#heros .author-credit").fadeIn("fast", function() { $(this).show() });
  }
    
  function hideAuthorCredit() {
    $("#heros .author-credit").fadeOut("fast", function() { $(this).hide() });
  }

  function autorotate() {
    timeout = setTimeout(function() {
      if ($current.attr('id') != 'hero-last') nextImage(autorotate);
    }, 4000);
  }
  
  autorotate();
});

