/*
    Versión modificada para: contintaroja.cl
*/

( function($) {
    jQuery.rqsLayoutSettings = {
        speed: 100,
        duration: 250,
        margin: 10,
        min_cols: 1,
        width: 203,
        wrapper: 'body',
        offx: 0,
        offy:0
    }
    $.fn.rqsLayout = function( settings ) {
        var s = jQuery.extend(true, {}, jQuery.rqsLayoutSettings, settings);
        
        // cantidad de columnas que soporta el contenedor
        var columns = Math.max( s.min_cols, parseInt( $(s.wrapper).innerWidth() / ( s.width + s.margin ) ) );
        
        // altura parcial de cada columna
        var max_alturas = new Array();
        
        // medidas
        $(this).css('width',s.width  + 'px');
        if( s.two_cols ) $(s.two_cols).css('width', s.width*2 + s.margin + 2);
        if( s.three_cols ) $(s.three_cols).css('width', s.width*3 + s.margin*2 + 2);
        if( s.four_cols ) $(s.four_cols).css('width', s.width*4 + s.margin*3 + 2);
        if( s.five_cols ) $(s.five_cols).css('width', s.width*5 + s.margin*4 + 2);
        if( s.six_cols ) $(s.six_cols).css('width', s.width*6 + s.margin*5 + 2);
        
        // inicializacion
        for (x=0; x < columns; x++) {
            max_alturas[x] = 0;
        }
        // iteramos sobre cada elemento
        $(this).each( function( i ) {
            var pos;
            var cursor;
            var w;
            var altura = 0;
            var _left;
            var _top;
        
            w = ( Math.floor( $(this).outerWidth() / s.width ) );
            cursor = 0;
            if( w > 1 ) {
                for( var x = 0; x < columns -( w - 1); x++ ) {
                    cursor = max_alturas[x] < max_alturas[cursor] ? x : cursor;
                }
                pos = cursor;
                for( var x = 0; x < w; x++ ) {
                    altura = Math.max( altura, max_alturas[pos+x] );
                }
                for( var x = 0; x < w; x++ ){ 
                    max_alturas[pos+x] = parseInt( $(this).outerHeight() ) + s.margin + altura;
                }
                _left = pos*(s.width+s.margin) + s.offx;
                _top = altura + s.offy;
            }
            else {
                for( x = 0; x < columns; x++ ) {
                    cursor = max_alturas[x] < max_alturas[cursor] ? x : cursor;
                }
                _left = cursor * ( s.width + s.margin ) + s.offx;
                _top = max_alturas[cursor] + s.offy;
                max_alturas[cursor] += $(this).outerHeight() + s.margin;
            }
            $(this).stop().delay( s.speed * i ).animate({left: _left, top: _top }, s.duration);
        });
        var _height_ = 0;
        for (x=0; x < columns; x++) {
            _height_ = Math.max( _height_, max_alturas[x] );
        }
        _height_ = _height_ + 50;
        $(s.wrapper).height(_height_);
    };
})(jQuery);
