(function($) {
  
  $(initMoreLinks);
  $(initScroller);
  $(resizeScroller);
  
  var _resizeTo;
  
  $(window)
    .bind('resize.scroller', resize_handler);
      
  function resize_handler(e) {
    if (_resizeTo) {
      clearTimeout(_resizeTo);
      _resizeTo = null;
    }
    _resizeTo = setTimeout(function() {
      $(window).unbind('resize.scroller');
      _resizeTo = null;
      window.status = window.status + ' - ' + e.target;
      resizeScroller();
      $(window).bind('resize.scroller', resize_handler);
    }, 50);    
  }
      
  function initMoreLinks() {
    $('a.more')
      .bind('click', moreLinks_handleClick);
  }
  
  function initScroller() {
    $('div.cwt-scroll')
      .jScrollPane(scrollSettings);
  }
  
  function resizeScroller() {
    var $cont = $('div.jScrollPaneContainer');
    if (!$cont.length) return;
    var o1 = $cont.css({height: 'auto'}).offset();
    var o2 = $('#footer').offset();
    var nh = o2.top - o1.top - 0; /* Originalmente el último valor era 24 */
    var min = 150;
    nh = Math.max(nh, min);
    $cont.css({height: nh + 'px' }).find('div.cwt-scroll').jScrollPane(scrollSettings);
  }
  
  var scrollSettings  = {
    showArrows: true,
    animateTo: false
  };
  
  
  function moreLinks_handleClick(e) {
    var hash = this.href.split('#')[1];
    if (hash) {
      var $target = $('#' + hash);
      e.preventDefault();
      if ($target.is(':hidden')) {
        $('div.target').hide();
        $target
          .show()
          .parents('div.cwt-scroll')
            .jScrollPane(scrollSettings);
      }
      $target
        .css('background-color', '#ffc')
        .animate({backgroundColor: '#fff'}, 1000, function() {
          $(this).css('background-color', '');
        });
      var $scroller = $target.parents('div.cwt-scroll');
      if ($scroller[0] && $scroller[0].scrollTo) {
        $scroller[0].scrollTo('#' + hash, true);
      }
    }
  }
  
  
})(jQuery);
