(function(){

var colorTimer;

function installHandlers(){
  $(".footer #more-link").click(function(){
    $(this).fadeOut();
    $(".footer #more").slideDown();
    $('html, body').animate({
      scrollTop: $("body").height() 
    }, 550);
    
    return false;
  });
  
  var goHome = null;
  $("#masthead").hover(function(){
    if( goHome == null && location.pathname.length > 6)
      goHome = $("<div class='home-link'/>")
        .text("Home")
        .appendTo("body")
        .click(function(){
          location.assign("http://www.azarask.in/blog/");
        });

      
    goHome.css({
      position:"absolute",
      top: "70px",
      left: "36%",
      opacity: 1.0,
    }).show()  }, function(e){
    if(e.pageY < 200) return;
    goHome.fadeOut().dequeue();
  })
    
  $(".comment-viz")
  .click(function(){
    if( $(".commentlist:visible").length > 0 ){
      var text = $(".comment-viz h2").text();
      if( text.match(/Already/) ) return;
      $(".comment-viz h2").text( "Already " + text.replace(/V/,"v") );    
      return;
    }
    showComments();
    return false;
  })
  .hover(function(){    
    moreCommentColors();
    colorTimer = setInterval( moreCommentColors, 200 );
    },
  function (){
    clearInterval(colorTimer);
    }
  );
}

function showComments(instant){
    var text = $(".comment-viz h2").text();
    $(".comment-viz h2").text( text.replace(/View/, "Viewing") );
    baseColor = {r:0x94+40, g:0xCC, b:0x3D};

    if( instant == true ) $(".commentlist").show();
    else $(".commentlist").slideDown();
}

var baseColor = {r:0x94, g:0xCC, b:0x3D};

function moreCommentColors(){
  function randGreen(){
    return "rgb(%,%,%)"
      .replace(/%/, baseColor.r + Math.max(parseInt(Math.random()*50)-25),0)
      .replace(/%/, baseColor.g + Math.max(parseInt(Math.random()*50)-25),0)
      .replace(/%/, baseColor.b + Math.max(parseInt(Math.random()*50)-25),0);
  }

  var threshold = .2;
  if( $(".comment-count").length > 70 ) threshold = .6;
  if( $(".comment-count").length > 150 ) threshold = .9;
     
  $(".comment-count").each(function(){
    if(Math.random() > threshold) $(this).animate({backgroundColor: randGreen()}, 200);
  });
}

function handleCommentAnchorLink(){
  if( location.hash.match(/comment/) ){
    showComments(true);
    location.assign( location );
  }  
}

function stickyFooter(){
  var docHeight = $(document).height()-$(window).height();
  if( location.pathname.length >= 7 ) return;
  function makeSticky(){
    if( window.scrollY >= docHeight ) $(".footer").css({ position: "fixed", bottom: 0});
    else $(".footer").css({"position": "relative"});
  }
  setInterval( makeSticky, 100 );
}


installHandlers();
moreCommentColors();
handleCommentAnchorLink();
stickyFooter();



})();
