(function ($) {
  $(document).ready(function() {
    
    // Set right sidebar to same height as left sidebar
    var leftSidebar = $('#content');
    var rightSidebar = $('#sidebar_wrapper');
    
    if (parseFloat($(rightSidebar).outerHeight()) < parseFloat($(leftSidebar).outerHeight())) {
      $('#navigation').stickyBlock({
        bottomLimit: '.region-footer'
      });
      
      $(rightSidebar).css({
        height: $(leftSidebar).outerHeight() + 400
      }).find('.region-footer').css({
        position: 'absolute',
        bottom: 0
      });
    }
  });

  $.fn.stickyBlock = function( option ) {
    option = $.extend( {}, $.fn.stickyBlock.option, option );

    return this.each(function() {
      var element = $(this).children('.section');
      var elementOffset = $(element).offset();
      var elementHeight = $(element).outerHeight();
      var stickyHeight = elementOffset.top + option.additionalOffset;

      var bodyTopOffset = ($('body').hasClass('toolbar')) ? parseFloat($('body').css('padding-top').replace('px', '')): 0;

      $(this).css('height', elementHeight);

      $(window).scroll(function() {
        var windowScroll = $(window).scrollTop();
        var footerPosition = $(option.bottomLimit).offset(); // Recalc on scroll
        // console.log('windowScroll: ' + windowScroll);
        // console.log('bodyTopOffset: ' + bodyTopOffset);
        // console.log('elementHeight: ' + elementHeight);
        // console.log('stickyHeight: ' + stickyHeight);
        // console.log('elementOffset: ' + elementOffset.top);
        // console.log('option.additionalOffset: ' + option.additionalOffset);
        // console.log('(option.additionalOffset + bodyTopOffset) + px: ' + (option.additionalOffset + bodyTopOffset) + 'px');

        if ((windowScroll) > stickyHeight) {
          // The window is scrolled BELOW the point
          // where the header should stick
          
          // If the sticky element touches the footer, stop scrolling
          if ((windowScroll + bodyTopOffset + elementHeight) > footerPosition.top) {
            // set the element to position: absolute with the top being the height of the element plus the top position of the footer
            $(element).css({
              position: 'absolute',
              bottom: $(option.bottomLimit).outerHeight() + 'px',
              top: 'auto'
            });
          }
          else {
            $(element).css({
              position: 'fixed',
              top: bodyTopOffset + 'px',
              bottom: 'auto'
            });
          }
        } else {
          // The window is scrolled ABOVE the point
          // where the header should stick
          $(element).css({
            position: 'relative',
            top: 0
          });
        }
      });
    });
  };

  $.fn.stickyBlock.option = {
    additionalOffset: 0,
    bottomLimit: null
  };
})(jQuery);;

