﻿// JScript File

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function ConvertDecToBin(pLngNumero) {

    /*
    Descripcion     :	Convierte un numero decimal a su correspondiente binario
    Parametros      :	pLngNumero --> Numero a convertir	
    Pagina          :	javascript:LlenaTablaPropiedades()
    Activa          :	Button.onclick
    Regresa         :	True / False
    Comentarios     :
    */

    var currnum = 128;

    try {
        if (pLngNumero >= currnum) {
            num2 = "1";
            pLngNumero = pLngNumero - currnum;
            currnum = currnum / 2;
        }
        else {
            num2 = "0";
            currnum = currnum / 2;
        }
        for (p = 1; p <= 7; p++) {
            if (pLngNumero >= currnum) {
                num2 = num2 + "1";
                pLngNumero = pLngNumero - currnum;
                currnum = currnum / 2;
            }
            else {
                num2 = num2 + "0";
                currnum = currnum / 2;
            }
        }
        return num2;
    }
    catch (err) {
        strErr = "Error al construir los datos .\n\n"
        strErr += "ConvertDecToBin() : " + err.description + "\n\n"
        strErr += "Click OK to continue.\n\n"
        alert(strErr)
    }

}


function InStr2(n, s1, s2) {
    // Devuelve la posición de la primera ocurrencia de s2 en s1
    // Si se especifica n, se empezará a comprobar desde esa posición
    // Sino se especifica, los dos parámetros serán las cadenas

    var numargs = InStr2.arguments.length;

    if (numargs < 3)
        return n.indexOf(s1) + 1;
    else
        return s1.indexOf(s2, n) + 1;

}




function sortSelect(select, compareFunction) {
    /*
    Decripción:  Ordena de menor a mayor un listbox
    Parametros:  select          --> Objeto que se va a ordenar
    compareFunction --> 
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Junio 2007
    */
    if (!compareFunction)
        compareFunction = compareText;

    var options = new Array(select.options.length);
    for (var i = 0; i < options.length; i++)
        options[i] =
      new Option(
        select.options[i].text,
        select.options[i].value,
        select.options[i].defaultSelected,
        select.options[i].selected
      );
    options.sort(compareFunction);
    select.options.length = 0;
    for (var i = 0; i < options.length; i++)
        select.options[i] = options[i];
}

function compareText(option1, option2) {
    /*
    Decripción:  Compara datos y regresa dato menor 
    Parametros:  option1 --> Valor uno para comparar
    option2 --> Valor dos para comparar
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Junio 2007
    */

    return option1.text < option2.text ? -1 :
    option1.text > option2.text ? 1 : 0;
}

function MM_preloadImages() { //v3.0
    /*
    Decripción:  Carga las imagenes por defecto
    Parametros:  
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Octubre 2005
    */
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}

function swapimg(pidimg, pnimg) {
    /*
    Decripción:  Cambia todas las imagenes
    Parametros:  
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Octubre 2005
    */
    MM_swapImgRestore(pidimg, '', pnimg, 1);
    MM_swapImage(pidimg, '', pnimg, 1);
}

function swapimgdos(pidimg, pnimg) {
    /*
    Decripción:  Cambia todas las imagenes
    Parametros:  
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Octubre 2005
    */
    // MM_swapImgRestore();
    MM_swapImage(pidimg, '', pnimg, 1);
}

function MM_swapImage() { //v3.0
    /*
    Decripción:  Cambia la imagen que se esta mostrando
    Parametros:  
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Octubre 2005
    */
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function MM_swapImgRestore() { //v3.0
    /*
    Decripción:  Carga lasimagenes que estan por defecto
    Parametros:  
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Octubre 2005
    */
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_ValidaForma() { //v4.0
    /*
    Decripción:  Valida una Forma
    Parametros:  
    ** ARGUMENTOS **
    1.- n	--> Objeto a buscar
    2.- ''	--> 
    3.- (R = Requerido, NisEmail = Email, NisNum = Numero) 
    Regresa:    True, False
    Programo: 
    Fecha: Mayo 2005
    */
    var i, p, q, nm, test, num, min, max, errors = '', args = MM_ValidaForma.arguments;
    for (i = 0; i < (args.length - 2); i += 3) {
        test = args[i + 2]; val = MM_findObj(args[i]);
        if (val) {
            nm = val.name; if ((val = val.value) != "") {
                if (test.indexOf('isEmail') != -1) {
                    p = val.indexOf('@');
                    if (p < 1 || p == (val.length - 1)) errors += '- ' + nm + ' debe ser una direccion de e-mail\n';
                } else if (test != 'R') {
                    num = parseFloat(val);
                    if (isNaN(val)) errors += '- ' + nm + ' debe ser un Numero.\n';
                    if (test.indexOf('inRange') != -1) {
                        p = test.indexOf(':');
                        min = test.substring(8, p); max = test.substring(p + 1);
                        if (num < min || max < num) errors += '- ' + nm + ' debe ser un numero Entre ' + min + ' y ' + max + '.\n';
                    } 
                } 
            } else if (test.charAt(0) == 'R') errors += '- ' + nm + ' es un dato Requerido.\n';
        }
    } if (errors) alert('The following error(s) occurred:\n' + errors);
    document.MM_returnValue = (errors == '');
}

function MM_showHideLayers() { //v6.0
    /*
    Decripción:  Muestra o esconde un Layer
    Parametros:  Argumento1 --> Nombre del Layer
    Argumento2 --> Opción
    Ejecuta:     Acción 
    Programo: Eduardo Olvera
    Fecha: Mayo 2005
    */
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) if ((obj = MM_findObj(args[i])) != null) {
        v = args[i + 2];
        if (obj.style) { obj = obj.style; v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v; }
        obj.visibility = v;
    }
}

function MM_findObj(n, d) { //v4.01
    /*
    Decripción:  busca un objeto dentro de la página
    Parametros:  n --> Objeto a buscar
    d --> Nombre de la página	
    Regresa:     Asignación del objeto 
    Programo: Eduardo Olvera
    Fecha: febrero 2006
    */
    var p, i, x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_findObjt(n, d) {
    //v4.0
    // $ en el objeto es de otro FRAME (parent.parent)
    // ? es de otra Ventana (parent)
    var p, i, x;
    if (!d)
        d = window.opener.document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if ((p = n.indexOf("$")) > 0) {
        d = parent.parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all)
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
        x = MM_findObj(n, d.layers[i].document);
    if (!x && document.getElementById)
        x = document.getElementById(n);
    return x;
}

function NewWindow(mypage, myname, w, h, scroll, pos) {
    if (pos == "random") { LeftPosition = (screen.width) ? Math.floor(Math.random() * (screen.width - w)) : 100; TopPosition = (screen.height) ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100; }
    if (pos == "center") { LeftPosition = (screen.width) ? (screen.width - w) / 2 : 100; TopPosition = (screen.height) ? (screen.height - h) / 2 : 100; }
    else if ((pos != "center" && pos != "random") || pos == null) { LeftPosition = 0; TopPosition = 20 }
    settings = 'width=' + w + ',height=' + h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=' + scroll + ',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
    win = window.open(mypage, myname, settings);
    //win=window.open(mypage,myname);
}



function ocultalayer(pobjlayer) {
    /*
    Decripción:  oculta layers que vienen en el parametro pobjlayer
    Parametros:  
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var separador = ',';
    var array_datos = pobjlayer.split(separador);
    var intcont;
    for (intcont = 0; array_datos.length > intcont; intcont++) {
        MM_showHideLayers(array_datos[intcont], '', 'hide');
    }
}

function muestralayer(pobjlayer) {
    /*
    Decripción:  oculta layers que vienen en el parametro pobjlayer
    Parametros:  
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var separador = ',';
    var array_datos = pobjlayer.split(separador);
    var intcont;
    for (intcont = 0; array_datos.length > intcont; intcont++) {
        MM_showHideLayers(array_datos[intcont], '', 'show');
    }
}

function keypressallonum(pobjtxt, pevent) {
    /*
    Decripción:  permite la entrada a numeros flotantes
    Parametros:  pobjtxt ---> objeto de texto que en el que se validan los datos
    pevent  ---> evento
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var objtxt = MM_findObj(pobjtxt);
    var objtxtcambios = MM_findObj('txtcambios');
    var txtactual = objtxt.value;
    if (pevent < 48 || pevent > 57) {
        if (pevent != 46) {
            event.keyCode = 0;
            return;
        } else {

        }
    } else {

    }
}
function keypressallonument(pobjtxt, pevent) {
    /*
    Decripción:  permite la entrada a numeros enteros
    Parametros:  pobjtxt ---> objeto de texto que en el que se validan los datos
    pevent  ---> evento
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var objtxt = MM_findObj(pobjtxt);
    var objtxtcambios = MM_findObj('txtcambios');
    var txtactual = objtxt.value;
    if (pevent < 48 || pevent > 57) {
        event.keyCode = 0;
        return;
    }
}

function keypressalloabcd(pobjtxt, pevent) {
    /*
    Decripción:  permite la entrada a a letras minusculas
    Parametros:  pobjtxt ---> objeto de texto que en el que se validan los datos
    pevent  ---> evento
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var objtxt = MM_findObj(pobjtxt);
    var objtxtcambios = MM_findObj('txtcambios');
    var txtactual = objtxt.value;
    if (pevent < 97 || pevent > 122) {
        event.keyCode = 0;
        return;
    }
}

function keypressevitatag(pobjtxt, pevent) {
    /*
    Decripción:  evita meter mayor que y menor que
    Parametros:  pobjtxt ---> objeto de texto que en el que se validan los datos
    pevent  ---> evento
    Programo: Eduardo Olvera
    Fecha: Mayo 2006
    */
    var objtxt = MM_findObj(pobjtxt);
    var objtxtcambios = MM_findObj('txtcambios');
    var txtactual = objtxt.value;
    if (pevent == 60 || pevent == 62) {
        event.keyCode = 0;
        return;
    }
}


function preparagrabar(pstrforma, pobjtxtgrabar, pstrseparador, pstrcauseval) {
    /*
    Descripción:  Barre una forma para y genera una cadena para Grabar, Editar.
    Parametros:   pstrforma      ----> nombre de la forma que debe barrer.
    pobjtxtgrabar  ----> nombre del objeto en el que va a poner la cadena para grabar
    pstrseparador  ----> caracter que se utilizará como separador en la cadena.
    pstrcauseval   ----> en balco para validar 
              
    Otros:        objx   ----> objetos que se omiten
    obl    ----> campos obligatorios
    obx    ----> campos no obligatorios
    Programó: Eduardo Olvera
    Fecha:    23 noviembre de 2006                             
    */
    var objforma = MM_findObj(pstrforma);
    var objtxtgrabar = MM_findObj(pobjtxtgrabar);
    var objnombre = '';
    var intformelems = objforma.elements.length;
    var objtype = '';
    var strdatograbar = '';
    var strdatograbtmp = '';
    var strbuscabotones = '';
    var strobligatorio = '';
    var strcampo = '';
    for (i = 0; i < intformelems; i++) {//inicia for elementos
        objtype = objforma.elements[i].type;
        objnombre = objforma.elements[i].name;
        strbuscabotones = objnombre.indexOf('objx'); //objeto a omitir
        strobligatorio = objnombre.indexOf('obl'); //objeto obligatorio
        if (objtype == 'checkbox') {
            if (objforma.elements[objnombre].checked) {
                strdatograbtmp = '1';
            } else {
                strdatograbtmp = '0';
            }
        } else {
            strdatograbtmp = objforma.elements[objnombre].value.replace(/^\s*|\s*$/g, "");
        }
        if (objnombre != '__VIEWSTATE' && objnombre != 'txtpage' && strbuscabotones != 0 && objnombre != '__EVENTTARGET' && objnombre != '__EVENTARGUMENT' && objnombre != '__EVENTVALIDATION' && objnombre != '__LASTFOCUS') {
            strcampo = objnombre.replace(/obl/, '');
            strcampo = strcampo.replace(/obx/, '');
            if (UCase(strcampo) == 'PLAN') {
                strcampo = '[PLAN]';
            }
            switch (objtype) {
                case 'text':
                    if (strobligatorio == 0) {
                        if (strdatograbtmp == "") {
                            if (pstrcauseval != '0') {
                                alert("Todos los campos son obligatorios");
                                return false;
                            }
                        } else {
                            strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                        }
                    } else {
                        strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                    }
                    break;
                case 'textarea':
                    if (strobligatorio == 0) {
                        if (strdatograbtmp == "") {
                            if (pstrcauseval != '0') {
                                alert("Todos los campos son obligatorios");
                                return false;
                            }
                        } else {
                            strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                        }
                    } else {
                        strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                    }
                    break;
                case 'select-one':
                    if (strobligatorio == 0) {
                        if (strdatograbtmp == "") {
                            if (pstrcauseval != '0') {
                                alert("Todos los campos son obligatorios");
                                return false;
                            }
                        } else {
                            strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                        }
                    } else {
                        strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                    }
                    break;
                case 'checkbox':
                    if (strobligatorio == 0) {
                        if (strdatograbtmp == "") {
                            if (pstrcauseval != '0') {
                                alert("Todos los campos son obligatorios");
                                return false;
                            }
                        } else {
                            strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                        }
                    } else {
                        strdatograbar += strdatograbtmp + pstrseparador + strcampo + pstrseparador;
                    }
                    break;
                case 'radio':
                    break;
                default:
                    alert(objtype + " Este objeto no esta definido verifique pues no se grabara");
                    alert(objnombre);
                    break;
            } //termina switch
        } // termina if descarta elementos para almacenar
    } //termina for elementos
    if (strdatograbar.text != "") {
        objtxtgrabar.value = strdatograbar;
    } else {
        return false;
    }
}

/*function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);
}*/

function ocultartabla(tabla, Var1) {
    //tabla --> nombre tabla
    // vari --> true muestra -- false oculta
    tabla = document.getElementById(tabla);
    //var img = document.getElementById("img_button");
    //alert(tabla);
    //if (tabla.style.display == "none") {
    if (Var1 == "False") {
        tabla.style.display = "block";
        //img.src = "dir/cerrar.gif";
    } else {
        tabla.style.display = "none";
        //img.src = "dir/abrir.gif";
    }
}

function ocultarsubtablas() {
    var tablasubbene = document.getElementById('subbeneficios');
    var tablasubdirectorio = document.getElementById('subdirectorio');
    var tablasubmensaje = document.getElementById('submensaje');
    var tablasubcatalogos = document.getElementById('subcatalogos');
    var tablasubimgapiassa = document.getElementById('subimgapiassa');
    var tablasubcobranza = document.getElementById('subcobranza');

    tablasubbene.style.display = "none";
    tablasubdirectorio.style.display = "none";
    tablasubmensaje.style.display = "none";
    tablasubcatalogos.style.display = "none";
    tablasubimgapiassa.style.display = "none";
    tablasubcobranza.style.display = "none";

}
function ocultaadmin() {
    var tablasubbene = document.getElementById('Administracion');
    //var tablasubdirectorio =document.getElementById('subdirectorio');
    tablasubbene.style.display = "none";
    //tablasubdirectorio.style.display = "none";
}


//funciones left y rigth
function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}
function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}
function LCase(s) {
    // Devuelve la cadena convertida en minúsculas
    return s.toLowerCase();
}
function UCase(s) {
    //Devuelve la cadena en minusculas
    return s.toUpperCase();
}
function TRim(s) {
    //elimina espacios al principio y al final
    return s.replace(/^\s*|\s*$/g, '');
}

function replaceChars(entry, cmpactual, remplazapor) {
    out = cmpactual; // replace this
    add = remplazapor; // with this
    temp = "" + entry; // temporary holder
    while (temp.indexOf(out) > -1) {
        pos = temp.indexOf(out);
        temp = "" + (temp.substring(0, pos) + add +
      temp.substring((pos + out.length), temp.length));
    }
    return temp;
}

function setfocus(pobjfield) {
    //pobjfield   --> objeto endonde pone el foco
    //Pone el foco en un objeto
    pobjfield.focus()
}

/*function InStr(n, s1, s2){
// Devuelve la posición de la primera ocurrencia de s2 en s1
// Si se especifica n, se empezará a comprobar desde esa posición
// Sino se especifica, los dos parámetros serán las cadenas
var numargs = InStr.arguments.length;
if(numargs<3){
return n.indexOf(s1)+1;
}else{
return s1.indexOf(s2, n)+1;
}	
}*/
function InStr(STRING, SUBSTRING, COMPARE, START) {
    if (START) {
        STRING = STRING.substring(START, STRING.length);
    }
    if (CBool(COMPARE) || COMPARE == undefined) {
        STRING = STRING.toLowerCase();
        SUBSTRING = SUBSTRING.toLowerCase();
    }
    if (STRING.indexOf(SUBSTRING) > -1) {
        return STRING.indexOf(SUBSTRING)
    } else {
        return 0;

    }
}

function CBool(VALUE) {
    VALUE = new String(VALUE);
    VALUE = VALUE.toLowerCase();
    if (VALUE == "1" || VALUE == "-1" || VALUE == "true" || VALUE == "yes") {
        return true;
    }
    else {
        return false;
    }
}



function isFolder(sFolderPath) {
    /*
    verifica si existe un directorio
    */
    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
    return objFSO.FolderExists(sFolderPath);
}

function isFile(sFolderPath) {
    /*
    verifica si existe un directorio
    */
    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
    return objFSO.FileExists(sFolderPath);
}


function validarEmail(valor) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) {
        return true; //si es correo
    } else {
        return false; //no es correo
    }
}
