
(function($){
  
  $.fn.cgScroll = function(options) {
    var defaults = {
      per_row : null
    };
    var options = $.extend(defaults, options);
    
    return this.each(function() {
      var obj = $(this);
      var items = obj.find('.items');
            
      var view_pane_height = items.height();
      
      
      // wrap the list in a div and open up the ul
      items
        .wrap('<div class="cg-viewpane">')
        .css({overflow:'visible'})
        .closest('.cg-viewpane')
        .height(view_pane_height)
        .css({overflow:'hidden'})
        .find('.items').height('auto').css({position:'absolute', top:0});
      
      var max_top = Math.max(items.height() - view_pane_height, 0);
      
      // alternative of calculating height because IE7 isn't playing ball
      if (options.per_row) {
        var elm_height = parseInt(items.find('li').height()) + parseInt(items.find('li').css('marginBottom'));
        max_top = Math.max((Math.ceil(items.find('li').length / options.per_row) * elm_height) - view_pane_height, 0);
      }
      
      reset_buttons();
      
      obj.find('.next').click(function(){
        var current_top = items.css('top');
        
        var new_top = parseInt(current_top) - view_pane_height;
        if (-new_top > max_top)
          new_top = -max_top;
        
        items.animate({top:new_top}, {complete:reset_buttons});
        return false;
      });
      
      obj.find('.prev').click(function(){
        var current_top = items.css('top');
      
        var new_top = Math.min(parseInt(current_top) + view_pane_height, 0);
      
        items.animate({top:new_top}, {complete:reset_buttons});
        return false;
      });
      
      
      // update the interface to nable disable the scroll buttons
      function reset_buttons() {
        var current_top = parseInt(items.css('top'));
                
        if (current_top == 0)
          obj.find('.prev').addClass('jcarousel-prev-disabled');
        else
          obj.find('.prev').removeClass('jcarousel-prev-disabled');
      
        if (current_top == -max_top)
          obj.find('.next').addClass('jcarousel-next-disabled');
        else
          obj.find('.next').removeClass('jcarousel-next-disabled');
      }
    
    });
  }
 
})(jQuery);

