(function ($) {
  /* Add a function to jQuery to slidebox any elements */
  jQuery.fn.slidebox = function() {
    var slidebox = this;
    var originalPosition = slidebox.css('left');
    var boxAnimations = {
      open:  function() { slidebox.addClass('open'); },
      close: function() { slidebox.removeClass('open'); }
    }

	/* replacing the boxAnimations definition above */
	var boxAnimations;
	if (Modernizr.cssanimations) {
	  boxAnimations = {
	    open:  function() { slidebox.addClass('open'); },
	    close: function() { slidebox.removeClass('open'); }
	  }
	} else {
	  boxAnimations = {
	    open: function() {
	      slidebox.animate({
	        'left': '0px'
	      }, 300);
	    },
	    close: function() {
	      slidebox.stop(true).animate({
	        'left': originalPosition
	      }, 100);
	    }
	  }
	}
	
	$(window).scroll(function() {
      var distanceTop = $('#last').offset().top - $(window).height();

      if ($(window).scrollTop() > distanceTop) {
        boxAnimations.open();
      } else {
        boxAnimations.close();
      }
    });

	/* close the slide box */
	slidebox.find('.close').click(function() {
	  $(this).parent().remove();
	});
  }

  $(function() { /* onload */
    $('#slidebox').slidebox();
  });
})(jQuery);
