/*
*
* SPLI(S)T 1.1.0
* written by  Benjamin Caplan
* http://www.IAmCaplan.com
*
* Copyright (c) 2010-2011 Benjamin Caplan (http://www.IAmCaplan.com)
*
* Built for the jQuery library
* http://jquery.com
*
*/
(function($){
  $.fn.splist = function(options){

    var settings = {
      numCols: 3,
      cWidth: '',
      f: true
    };

    if(options){
      $.extend(settings, options)
    };

    var wrapper = this.parent();

    var listNumber = 1;

    this.each(function(){
      var t = $(this);
      var el = t.get(0).tagName;
      var cl = t.children('li');
      var listSize = cl.size();
      var avg=0;

      t.addClass('working');

      //CREATE LIST(S)
      var n = 1;
      while((n-1) < settings.numCols){
        var tags =  '<' + el + ' class="col" id="column' + listNumber + '-' + n + '"> <\/' + el + '>';
        $(t).before(tags);
        n++;
      };

      //SPLIT FNUNCTION
      var liSplit = Math.round(listSize/settings.numCols + 0.4999999999);
      var l = 1;
      var z = 1;
      cl.each(function(){
        $(this).addClass('liNum' + l);
        var liHeight = $(this).height();
        avg = avg + liHeight;

        if(l <= liSplit*z){
          $(this).parents().find('#column' + listNumber + '-' + z).append(this);
        }
        else{
          z++;
          $(this).parents().find('#column' + listNumber + '-' + z).append(this);
        };
        l++;
      });

      //CSS
      var col = $('.col');
      var avgLiHeight = avg/listSize;
      var newHeight = Math.round((listSize/settings.numCols) + .499999999999) * avgLiHeight;
      var newWidth = Math.round(wrapper.width()/ settings.numCols -  $(this).css('marginLeft').replace('px','') - $(this).css('margin-right').replace('px','') - .4999999999);
      //wrapper.css('height', newHeight);
      if(settings.cWidth==''){
        col.css('width', newWidth);
      }
      else{
        col.css('width', settings.cWidth);
      }
      if(settings.f==true){
        col.css('float', 'left');
        col.last().after('<div style="clear:both"/>');
      }

      //REMOVE ORIGINAL LIST...
      t.remove();

      listNumber++;
    });
  };
})(jQuery);

