/**
 * Plugin loco
 *
 */

/*
Ejemplo:

$('.col').rqsLayout({
        min_cols:       3,              
        two_cols:       '.twocols',      
        three_cols:     '.threecols',    
        two_cols:       '.twocols',      
        five_cols:      '.fivecols',     
        speed:          50,              
        duration:       350,             
        width:          200,             
        margin:         20,              
        wrapper:        '#wrapper',          
        offx:           0,               
        offy:           0,               
        hidden:         true,
        complete:       function(){
            // Code
        }
});

*/

jQuery( function($) {
    jQuery.rqsLayoutSettings = {
        min_cols:       4,              // Mínimo de columnas que se muestran en el contenedor
        two_cols:       '.twocols',     // 
        three_cols:     '.threecols',   // 
        four_cols:      '.fourcols',     // 
        five_cols:      '.fivecols',    // 
        speed:          50,             // Desfase entre cada animación
        duration:       350,            // velocidad de cada animación
        width:          200,            // ancho de las columnas
        margin:         20,             // margen entre columnas
        padding:         0,             // padding que poseen las columnas
        wrapper:        'body',         // contenedor de las columnas
        offx:           0,              // Desplazamiento en el eje x desde el contenedor
        offy:           0,              // Desplazamient en el eje Y desde el contenedor
        hidden:         true            // indica si los elementos están ocultos 
    }
    $.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.margin) / ( s.width + s.margin + s.padding) ) );
        
        // altura parcial de cada columna
        var max_alturas = new Array();
        
        // medidas
        $(this).css('width',s.width  + 'px').css('padding',s.padding  + 'px');
        if( s.two_cols ) $(s.two_cols).css('width', s.width*2 + s.margin  + 2*s.padding);
        if( s.three_cols ) $(s.three_cols).css('width', s.width*3 + s.margin*2 + 4*s.padding); 
        if( s.four_cols ) $(s.four_cols).css('width', s.width*4 + s.margin*3 + 6*s.padding); 
        if( s.five_cols ) $(s.five_cols).css('width', s.width*5 + s.margin*4 + 8*s.padding);  
        if( s.six_cols ) $(s.six_cols).css('width', s.width*6 + s.margin*5 + 10*s.padding); 
        
        // inicializacion
        for (x=0; x < columns; x++) {
            max_alturas[x] = 0;
        }
        
        var cantidad = $(this).size();
        
        // iteramos sobre cada elemento
        $(this).each( function( i ) {
            var self = $(this);
            var pos;
            var cursor;
            var w;
            var altura = 0;
            var _left;
            var _top;
        
            w = ( Math.floor( $(this).outerWidth() / (s.width + s.padding * 2) ) );
            cursor = 0;
            
            if( w > 1 ) {
                // Versión cambiada
                // Se posiciona el cursor sobre la columna factible con mayor altura
                // Se asigna la máxima posición por defecto
                for( var x = 0; x < columns -( w - 1); x++ ) {
                    cursor = max_alturas[x] > max_alturas[cursor] ? x : cursor;
                }
                pos = cursor;
                for( var y = 0; y < w; y++ ) {
                    altura = Math.max( altura, max_alturas[pos+y] );
                }
                
                // Para cada posición factible
                for( var x = 0; x < columns -( w - 1); x++ ) {
                    
                    // Se obtiene la altura a la cual el objeto podría podría posicionarse
                    var _altura = 0;
                    for( var y = 0; y < w; y++ ) {
                        _altura = Math.max( _altura, max_alturas[x+y] );
                    }
                    
                    // si la posición brinda una mejor altura, se actualiza el cursor y la nueva altura
                    if( _altura < max_alturas[cursor] ) {
                        cursor = x;
                        altura = _altura;
                    }
                }
                pos = cursor;
                for( var x = 0; x < w; x++ ){ 
                    max_alturas[pos+x] = parseInt( $(this).outerHeight() ) + s.margin + altura;
                }
                _left = pos*(s.width+s.margin+2*s.padding) + s.offx;
                _top = altura + s.offy;
                
                // Original
                //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+2*s.padding) + s.offx;
                //_top = altura + s.offy;
            }
            else {
                for( x = 0; x < columns; x++ ) {
                    if( max_alturas[x] < max_alturas[cursor] ) {
                        cursor = x;
                    }
                }
                _left = ( cursor * ( s.width + s.margin + 2*s.padding ) ) + s.offx;
                _top = ( max_alturas[cursor] ) + s.offy;
                max_alturas[cursor] += $(this).outerHeight() + s.margin;
            }
            if( s.hidden ) {
                $(this).delay( s.speed * i ).animate({left: _left, top: _top }, s.duration).fadeIn(s.duration, function(){
                    // complete: function(){}
                    if( i == cantidad - 1 ) {
                        if( s.complete ) {
                            s.complete();
                        }
                        var _height_ = 0;
                        for (x=0; x < columns; x++) {
                            _height_ = Math.max( _height_, max_alturas[x] );
                        }
                        //_height_ = _height_ + 20;
                        $(s.wrapper).height(_height_);
                    }
                });
            }
            else{
                $(this).delay( s.speed * i ).animate({left: _left, top: _top }, s.duration, function(){
                    // complete: function(){}
                    if( i == cantidad - 1 ) {
                        if( s.complete ) {
                            s.complete();
                        }
                        var _height_ = 0;
                        for (x=0; x < columns; x++) {
                            _height_ = Math.max( _height_, max_alturas[x] );
                        }
                        //_height_ = _height_ + 20;
                        $(s.wrapper).height(_height_);
                    }
                })
            }
        });
    };
})(jQuery);
