/*jslint white: true, browser: true, undef: true, nomen: true, eqeqeq: true,
plusplus: true, bitwise: true, newcap: true, immed: true, maxlen: 80 */
/*global jQuery, $*/

// This is a jQuery plugin that limits the number of visible child elements
// of a container and provieds a UI for showing the hidden ones.
(function($) {

    // Plugin definition
    $.fn.childlimit = function(options) {

    // Build main options
    var opts = $.extend({},$.fn.childlimit.defaults, options);

    // Process each element
    return $(this).each(function() {

        var obj = $(this);

        // Use the meta plugin to build element specific options
        obj.o = $.meta ? $.extend({}, opts, obj.data()) : opts;

        var nthChild = obj.find(':nth-child(' + obj.o.numVisible + ')');
        var extraElements = nthChild.nextAll();
        if (extraElements.length > 0) {
            var lastElement = obj.children(':last');
            extraElements.wrapAll('<div/>')
            var container = extraElements.parent();
            container.hide();
            var show = $(obj.o.showUI);
            container.after(show);

            show.bind('click', function (e) {
              show.hide('slow');
              container.slideDown('slow');
              e.preventDefault();
            });
        }
    });
  };
  
  // Plugin defaults
  $.fn.childlimit.defaults = {
      numVisible: 10,
      showUI: '<p>Show All</p>'
  };
  
}(jQuery));
