/*
Copyright (c) 2007 Christian yates
christianyates.com
chris [at] christianyates [dot] com
Licensed under the MIT License: 
http://www.opensource.org/licenses/mit-license.php
 
Inspired by work of Ingo Schommer
http://chillu.com/2007/9/30/jquery-columnizelist-plugin
*/
(function(jQuery){
  jQuery.fn.columnizeList = function(settings){
    settings = jQuery.extend({
      cols: 4,
      constrainWidth: 0,
      width : 0
    }, settings);
    // var type=this.getNodeType();
    var container = this;
    var idcontainer = '';
    if (container.length == 0) { return; }
    var prevColNum = 10000; // Start high to avoid appending to the wrong column
    var size = jQuery('li',this).size();
    var percol = Math.ceil(size/settings.cols);
    var tag = container[0].tagName.toLowerCase();
    var classN = container[0].className;
    var tmpwidth = jQuery(container).width();
    if(settings.width != 0){

    	tmpwidth = parseInt(settings.width);
    }
    var colwidth = Math.floor( tmpwidth /settings.cols);
    var maxheight = 0;
    // Prevent stomping on existing ids with pseudo-random string
    var rand = Math.floor(Math.random().toPrecision(6)*10e6);
  
    jQuery('<ul id="container'+rand+'" class="'+classN+'"></ul>').css({width: tmpwidth + 'px'}).insertBefore(container);
    idcontainer = 'container'+rand;
    jQuery("body").data(classN, idcontainer);
    jQuery('li',this).each(function(i) {
      //var currentColNum = Math.floor(i/percol);
      //var currentColNum = 1;
      if(jQuery(this).find('h2').size()==1) { currentColNum = Math.floor(i/percol); }
      if(prevColNum != currentColNum) {
    	jQuery(".list-column-processed").css({'width':colwidth + "px"});
        if (jQuery("#col" + rand + "-" + prevColNum).height() > maxheight) { maxheight = jQuery("#col" + rand + "-" + prevColNum).height(); }
        //alert(tag);
        jQuery("#container"+rand).append('<li class="list-column-processed"><'+tag+' id="col'+rand+'-'+currentColNum+'"></'+tag+'></li>');
      }
      jQuery(this).attr("value",i+1).appendTo("#col"+rand+'-'+currentColNum);
      prevColNum = currentColNum;
    });
    jQuery("li.list-column-processed").css({
      'float':'left',
      'list-style':'none',
      'margin':0,
      'padding':0
    });
    if (settings.constrainWidth) {
      jQuery(".list-column-processed").css({'width':colwidth + "px"});
    };
    jQuery("#container"+rand).after('<div style="clear: both;"></div>');
    jQuery("#container"+rand+" "+tag).height(maxheight+10);
    // Add CSS to columns
    this.remove();      
    return this;
  };
})(jQuery);
