function render(data){
  document.title = "Helper Robots - " + data.comic.name;
  $(".removed").html(data.comic.name + " " + data.comic.caption);

  var spinner_url = "http://images.helper-robots.com/images/ajax-loader.gif";
  var prefetcher = new Image();
  prefetcher.src = spinner_url;

  if( data.comic.src != $("img.comic").attr("src")){
    //$("img.comic").css("visibility", "hidden");
    $("img.comic").attr("src", spinner_url);
  }

  setTimeout(function(){
    $("img.comic").attr("src", data.comic.src);
  }, 0);

  $("img.comic").attr("title", data.comic.note);
  $("img.comic").load(function(){
    $("img.comic").css("visibility", "visible");
  });
  $(".explanation").html(data.comic.explanation);
  $(".explanation").attr("class", jQuery.trim(data.comic.explanation) == "" ? "explanation hidden" : "explanation" );

  jQuery.each(["previous","next","first","last"], function(index,dir){
    $(".arrow." + dir + " img").attr("class", data[dir] ? "" : "hidden" );
    $(".arrow." + dir).attr("href", data[dir]);

    if(data.prefetch && data.prefetch[dir]){
      var prefetcher = new Image();
      prefetcher.src = data.prefetch[dir].src;
    }
  });
}

function renderAndReplace(data){
  render(data);
  window.history.replaceState(data, document.title, data.comic.link);
}

function renderAndPush(data){
  render(data);
  window.history.pushState(data, document.title, data.comic.link);
}


function setupPop(){
  if(typeof window.history == "undefined" || typeof window.history.pushState == "undefined" ){
    return; // not HTML5y enough
  }
  if(document.location.toString().substr(-1) == "/" && typeof originalJson == "undefined"){
    return; // oops, I don't know the canonical name of the front page.
  }
  $(".arrow").bind("click", arrowClick);

  window.onpopstate = function(event){
    if(event.state){
      render(event.state);
    } else {
      if(originalJson){
        render(originalJson);
      } else {
        setTimeout(function(){
          jQuery.ajax({
            url: document.location + '.json',
            dataType: "json",
            success: renderAndReplace
          });
        },0);
      }
    }
  }
}

function arrowClick(){
  var direction = $(this).attr("class").substr(6); // strip off "arrow "
  doArrow(direction);
  return false;
}

function doArrow(direction){
  var url = $(".arrow."+direction).attr("href") + ".json";

  jQuery.ajax({
    url: url,
    dataType: "json",
    success: renderAndPush
  });
}

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


