
/**
 * $Id: archivo.js 1827 2008-09-03 21:01:07Z mancai $
 */

var Archivo = (function(){
    var self = this;
    
    /**
     * Date functions.
     *
     * @author Sam Ruby 
      * http://intertwingly.net/code/venus/
     */
    
    // Parse an HTML5-liberalized version of RFC 3339 datetime values
    var parseRFC3339 = function (string) {
        var date=new Date(0);
        var match = string.match(/(\d{4})-(\d\d)-(\d\d)\s*(?:[\sT]\s*(\d\d):(\d\d)(?::(\d\d))?(\.\d*)?\s*(Z|([-+])(\d\d):(\d\d))?)?/);
        if (!match) return;
        if (match[2]) match[2]--;
        if (match[7]) match[7] = (match[7]+'000').substring(1,4);
        var field = [null,'FullYear','Month','Date','Hours','Minutes','Seconds','Milliseconds'];
        for (var i=1; i<=7; i++) if (match[i]) date['setUTC'+field[i]](match[i]);
        if (match[9]) date.setTime(date.getTime()+
            (match[9]=='-'?1:-1)*(match[10]*3600000+match[11]*60000) );
        return date;
    }
    
    
    //Returns the differences between two dates
    var dateDiff = function(a,b){
        var diff = new Date(a - b);
        var days = Math.floor( ((a-b)  % (1000 * 60 * 60 * 24 * 31)) / (1000 * 60 * 60 * 24));
        var months = Math.floor( (a-b) / (1000 * 60 * 60 * 24 * 31));
        return [months, days, diff.getUTCHours(), diff.getUTCMinutes(), diff.getUTCSeconds()];
    } 


    var friendlyDate = function(date){
        var today = new Date();
        var labels = [["mes", "meses"], ["día", "días"], ["hora", "horas"],["minuto", "minutos"], ["segundo", "segundos"]];
        var diff = dateDiff(today, date);
        var rtn = [];
        for (var i=0; i < diff.length; i++){
            if (diff[i] > 0){
                rtn.push(diff[i] + " " + ((diff[i] > 1) ? labels[i][1] : labels[i][0]))
            }
        }
        return rtn;
    }

    //Atributos privados
    var $ = jQuery;

    return {
    
        /**
         *
         *
         */
        ultimas: function (){
            $('span.archivo-ultimos-fecha').each(function(){
                var fecha = $(this).attr('data-fecha')
                var friendly = friendlyDate(parseRFC3339(fecha));
                var texto = friendly.slice(0,1)[0];
                if (texto == "1 día"){
                    texto = "Ayer";
                }else{
                    texto = "Hace " + texto;
                }
                $(this).text(texto);
            })
        },
    
        /**
         * Instrucciones para inicializar  
         *
         */
        init: function(){

            //Mostrar sólo los 15 primeros valores por sección
            $('#archivo-filtro-seccion li').slice(10).hide();
            
            //Enlace para mostrar todas las secciones
            var mostrar = $(document.createElement('span'));
            mostrar.attr('class', 'accion');
            mostrar.text('Mostrar todas'); 
            mostrar.click(function(){
                $('#archivo-filtro-seccion li').slice(10).show();
                $(this).remove()
            })
            $('#archivo-filtro-seccion').after(mostrar);
            
            
            //Texto de ayuda en el formulario
            var inputQ = $('#archivo-form-buscador-q');
            var label = $('#archivo-form-buscador label[for=archivo-form-buscador-q]');
            var frm = $('#archivo-form-buscador');


            if (inputQ && label && frm){
                //Utilizar el texto de ayuda cuando el campo de búsqueda no tenga ningún valor
                if (jQuery.trim(inputQ.val()).length == 0){
                    inputQ.val(label.text());
                }
    
                //Borrar el texto de ayuda cuando se quiera buscar algo
                inputQ.focus(function(){
                    $('#archivo-form-mensaje').hide();
                    if ($(this).val() == label.text()){
                        $(this).val('');
                    }
                });
    
                //Verificar que se esté buscando un texto
                frm.submit(function(){
                    if ((jQuery.trim(inputQ.val()).length == 0) || (inputQ.val() == label.text())){
                        $('#archivo-form-mensaje').show();
                        inputQ.val('');
                        return false;
                    }
                });
            }
        }
    }
})();

Archivo.init();