/*
 * jQuery MoreOrLess Plugin
 *
 * Purpose:
 *
 *  Insert links to show/hide items in a list
 *
 * Example:
 *
 *  $(function() {
*
 *    $('#some_links').moreorless({ 
 *      'max'      : 3, 
 *      'moreText' : 'Please sir, may i have some more?', 
 *      'lessText' : 'Not so much!' 
 *    });
*
 *  });
 *
 * Todo:
 *
 *  Infer child type and eliminate "tag" option 
 *  so as to handle arbitrarily complex and nested items (eg tables)
 *
 */
(function( $ ){
  $.fn.moreorless = function( options ) {
    var o = {
      'max'           : 5,
      'tag'           : 'li',
      'moreText'      : 'more',
      'lessText'      : 'less',
      'moreClass'     : 'more',
      'lessClass'     : 'less',
      'showMoreClass' : 'showMore',
      'showLessClass' : 'showLess'
    };
    return this.each( function() {
      var container = $( this );
      if ( options ) { 
        $.extend( o, options );
      }
      if ( container.children().length > o.max ) {
        container.children().each( function( index, element ) {
          if ( index >= o.max ) {
            $( element ).addClass( o.moreClass );
          }
        });
        var moreLink = '<'+o.tag+' class="'+o.lessClass+' '+o.showMoreClass+'"><a href="#">'+ o.moreText+'</a></'+o.tag+'>';
        var lessLink = '<'+o.tag+' class="'+o.moreClass+' '+o.showLessClass+'"><a href="#">'+ o.lessText+'</a></'+o.tag+'>';
        container.find( o.tag+':nth-child('+o.max+')' ).after( moreLink );
        container.append( lessLink );
        container.find( '.'+o.moreClass ).each( function() {
          $( this ).hide();
        });
        container.find( '.'+o.showMoreClass+' a' ).click( function() {
          container.find( '.'+o.lessClass ).slideUp();
          container.find( '.'+o.moreClass ).slideDown();
        });
        container.find( '.'+o.showLessClass+' a' ).click( function() {
          container.find( '.'+o.moreClass ).slideUp();
          container.find( '.'+o.lessClass ).slideDown();
        });
      }
    });
  };
})(jQuery);

