﻿//----------------------------------------------------------------------------------
//DESNEA.Util
//Desarrollos NEA | www.desarrollosnea.com
//----------------------------------------------------------------------------------

function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;

    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined")
            root[nsParts[i]] = new Object();

        root = root[nsParts[i]];
    }
}


registerNS("DESNEA.Util");





//----------------------------------------------------------------------------------
//Relleno
//----------------------------------------------------------------------------------
var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;
function Relleno(cadena, longitud, relleno, direccion) {

    if (typeof (longitud) == "undefined") { var longitud = 0; }
    if (typeof (relleno) == "undefined") { var relleno = ' '; }
    if (typeof (direccion) == "undefined") { var direccion = STR_PAD_RIGHT; }

    if (longitud + 1 >= cadena.length) {

        switch (direccion) {

            case STR_PAD_LEFT:
                cadena = Array(longitud + 1 - cadena.length).join(relleno) + cadena;
                break;

            case STR_PAD_BOTH:
                var right = Math.ceil((padlen = longitud - cadena.length) / 2);
                var left = padlen - right;
                cadena = Array(left + 1).join(relleno) + cadena + Array(right + 1).join(relleno);
                break;

            default:
                cadena = cadena + Array(longitud + 1 - cadena.length).join(relleno);
                break;

        } // switch

    }

    return cadena;

}


//----------------------------------------------------------------------------------
//String.Format
//----------------------------------------------------------------------------------
String.format = function (texto) {
    //Verificar si existen dos argumentos en la lista de argumentos
    if (arguments.length <= 1) {
        //Si no hay 2 o mas argumentos en la lista entonces no hay nada por reemplazar
        //solo retornar el textoo original
        return texto;
    }
    //Posicionarse en el segundo argumento
    var argCantidad = arguments.length - 2;
    for (var arg = 0; arg <= argCantidad; arg++) {
        //iterar a traves de los ficha para reemplazar en el textoo original los marcadores (en orden)
        texto = texto.replace(new RegExp("\\{" + arg + "\\}", "gi"), arguments[arg + 1]);
    }
    return texto;
};


//----------------------------------------------------------------------------------
//Trim
//----------------------------------------------------------------------------------
DESNEA.Util.trim = function (cadena) {
    return trim(cadena);
}
trim = function (cadena) {
    for (i = 0; i < cadena.length; ) {
        if (cadena.charAt(i) == " ")
            cadena = cadena.substring(i + 1, cadena.length);
        else
            break;
    }

    for (i = cadena.length - 1; i >= 0; i = cadena.length - 1) {
        if (cadena.charAt(i) == " ")
            cadena = cadena.substring(0, i);
        else
            break;
    }

    return cadena;
}


//----------------------------------------------------------------------------------
//Remover Acentos
//----------------------------------------------------------------------------------
DESNEA.Util.removerAcentos = function (cadena) {
    return removerAcentos(cadena)
}
removerAcentos = function (s) {
    var r = s.toLowerCase();
    r = r.replace(new RegExp("\\s", 'g'), "-");
    r = r.replace(new RegExp("[àáâãäå]", 'g'), "a");
    r = r.replace(new RegExp("æ", 'g'), "ae");
    r = r.replace(new RegExp("ç", 'g'), "c");
    r = r.replace(new RegExp("[èéêë]", 'g'), "e");
    r = r.replace(new RegExp("[ìíîï]", 'g'), "i");
    r = r.replace(new RegExp("ñ", 'g'), "n");
    r = r.replace(new RegExp("[òóôõö]", 'g'), "o");
    r = r.replace(new RegExp("œ", 'g'), "oe");
    r = r.replace(new RegExp("[ùúûü]", 'g'), "u");
    r = r.replace(new RegExp("[ýÿ]", 'g'), "y");
    //r = r.replace(new RegExp("\\W", 'g'), "");
    return r;
};



//----------------------------------------------------------------------------------
//Historial, ir para atras
//----------------------------------------------------------------------------------
function Atras(paginas) {
    history.go(paginas);
}




//Ir a nueva pagina
//---------------------------------------------------------------
function IrA(paginaUrl) {
    window.location = paginaUrl;
}



//------------------------------------------------------------------------
//ABRIR VENTANA
//Abre una ventana popup. Con las caracteristicas pasadas como parametro
//y la centra a la pantalla segun sea el navegador (depende como
//se obtiene el tamaño de la pantalla)
//------------------------------------------------------------------------
function AbrirVentana(direccion, nombre, width, height, resize, scroll) {
    var dialogWin = new Object();
    dialogWin.width = width;
    dialogWin.height = height;
    if (navigator.appName == "Netscape") {
        dialogWin.left = window.screenX + ((window.outerWidth - dialogWin.width) / 2);
        dialogWin.top = window.screenY + ((window.outerHeight - dialogWin.height) / 2);
        var attr = 'screenX=' + dialogWin.left + ',screenY=' + dialogWin.top + ',resizable=' + resize + ',width=' + dialogWin.width + ',height=' + dialogWin.height + ',scrollbars=' + scroll + ',menubar=no,location=no,toolbar=no,status=no,directories=no';
    } else if (document.all) {
        dialogWin.left = (screen.width - dialogWin.width) / 2;
        dialogWin.top = (screen.height - dialogWin.height) / 2;
        var attr = 'left=' + dialogWin.left + ',top=' + dialogWin.top + ',resizable=' + resize + ',width=' + dialogWin.width + ',height=' + dialogWin.height + ',scrollbars=' + scroll + ',menubar=no,location=no,toolbar=no,status=no,directories=no';
    }
    var ventana = window.open(direccion, nombre, attr);
    ventana.focus();
}


//------------------------------------------------------------------------
//ABRIR VENTANA MODAL
//------------------------------------------------------------------------
function AbrirVentanaModal(direccion, nombre, width, height, resize, scroll) {

    //Abriendo ventana
    window.showModalDialog(direccion, nombre, 'chrome,dialog,modal,close=no,toolbar=no,location=no,directories=no,statusbar=no,menubar=no,scrollbars=' + scroll + ',resizable=' + resize + ',copyhistory=no,width=' + width + ',height=' + height + '\'');

}


//------------------------------------------------------------------------
//INICIALIZAR TABS
//------------------------------------------------------------------------
function inicializarTabs() {

    // Cuando el enlace sea clickeado
    $("a.tab").click(function () {
    
        // Apaga el Activo
        $(".activo").removeClass("activo");

        // Cambia Activo  
        $(this).addClass("activo");

        // Despliega, escondiendo
        $(".contenidoTab").hide('slow');

        // Muestra el contenido, obteniendo del atributo title del enlace (p.e. contenido_1), y muestra con show el contenido
        var muestra = $(this).attr("title");
        $("#" + muestra).show('slow');

    });

}



//------------------------------------------------------------------------
//ITEM: Reemplazar texto
//Parametros:
//  orig: 
//  que: 
//  por: 
//------------------------------------------------------------------------
function StringReplace(orig, que, por) {
    pos = orig.indexOf(que);
    while (pos > -1) {
        orig = orig.substring(0, pos) + por + orig.substring(pos + que.length, orig.length);
        pos = orig.indexOf(que);
    }
    return orig;
}




/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}





/*
*--------------------------------------------------------------------------------------------------------------------------------------------
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*--------------------------------------------------------------------------------------------------------------------------------------------
*/

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

/*
*--------------------------------------------------------------------------------------------------------------------------------------------
* // FIN -  Date Format 1.2.3
*--------------------------------------------------------------------------------------------------------------------------------------------
*/
