/**
 * jQuery position plugin
 *
 * @author Davy De Pauw
 * 
 */

(function($) {
    $.fn.position = function(options) {
        
        return this.each(function() {

            // Extend options
            var opts = $.extend({}, $.fn.position.defaults, options);

            // Get container
            var $c = $(this);

            // Create div
            $d = $('<div></div>');

            // Copy attributes
            if($c.attr('id')) $d.attr('id', $c.attr('id'));
            if($c.attr('class')) $d.attr('class', $c.attr('class'));

            // Wrap div around container
            $d = $c.wrap($d).parent();

            // Set row width
            var $rWidth = 0;
            // Get container width
            var $cWidth = $c.width();

            // Get elements within container
            var $els = $c.children();

            // Determine row type
            opts.rType = $c[0].tagName.toLowerCase();

            // Remove parent wrapper from elements
            $els.unwrap();

            // Create constructor for new row
            var row = '<' + opts.rType + ' class="' + opts.rowClass + '"></' + opts.rType + '>';

            // Compose and attach new row
            $r = $(row).appendTo($d);

            // Iterate each element
            $els.each(function(i) {
                // Outerwidth
                $oWidth = $(this).outerWidth(true);
                // Innerwidth
                $iWidth = $(this).outerWidth(false);

                // Reset module
                $(this).removeClass(opts.lastClass);

                // Check if element with margins fits into row
                if(($rWidth + $oWidth) <= $cWidth)
                {
                    $rWidth += $oWidth;
                }
                // Check if element without margin fits into row
                else if(($rWidth + $iWidth) <= $cWidth)
                {
                    // Add class last to element
                    $(this).addClass(opts.lastClass);
                    $rWidth += $iWidth;
                }
                // Start new row
                else
                {
                    // Attach new row
                    $r = $(row).appendTo($d);
                    $rWidth = 0;
                    $rWidth += $oWidth;
                }
                // Append element to row
                $(this).appendTo($r);
            });


        });
    };

    // Set plugin defaults
    $.fn.position.defaults = {
        lastClass: 'last',
        rowClass: 'row clearfix'
    };

}) (jQuery);

