(function ($) {
  jQuery.fn.slidebox = function() {
    var slidebox = this;
    var originalPosition = slidebox.css('right');
    var open = false;
 
    /* GA tracking */
    var track = function(label) {
      return _gaq.push(['_trackEvent', 'Slidebox', label]);
    }
    var boxAnimations;
 
    if (Modernizr.cssanimations) {
      boxAnimations = {
        open:  function() { slidebox.addClass('open'); },
        close: function() { slidebox.removeClass('open'); },
      }
    } else {
      boxAnimations = {
        open: function() {
          slidebox.animate({
            'right': '0px'
          }, 300);
        },
        close: function() {
          slidebox.stop(true).animate({
            'right': originalPosition
          }, 100);
        }
      }
    }
 
    $(window).scroll(function() {
      var distanceTop = $('#last').offset().top - $(window).height();
 
      if ($(window).scrollTop() > distanceTop) {
        if (!open) {
          open = true;
          boxAnimations.open();
          track("Open");
        }
      } else {
        open = false;
        boxAnimations.close();
      }
    });
 
    slidebox.find('.close').click(function() {
      $(this).parent().remove();
      track("Close");
    });
    slidebox.find('.related a').click(function() {
      track("Read More");
    });
  }
 
  $(function() {
    $('#slidebox').slidebox();
  });
})(jQuery);
 
/* Google analytics code provides this variable */
var _gaq = _gaq || [];

