﻿// JScript File

//la funcion intenta conseguir el id row del panel contenedor del control
//si no se encuentra el idRow se devuelve "0".
var gHayErrorValidacionZona0 = false;
var gHayErrorValidacionZonaLista = false;
var ZonaValidada = 0;
var ArrayGridsCapitulo = new Array;

//obtiene el panel ampliado del control pasado por parametro
function cnk_obtenerDivAmpliaControl(controlAmpliado, NumeroAmp) {
    var NombreControl = "";
    if ((typeof (controlAmpliado.id) == "undefined"))
        NombreControl = controlAmpliado.ID
    else
        NombreControl = controlAmpliado.id;

    while (NombreControl.indexOf("$") > -1) {
        NombreControl = NombreControl.replace("$", "_");
    }
    //    while(controlAmpliado.id.indexOf("$")>-1){
    //        controlAmpliado = controlAmpliado.id.replace("$","_");
    //     }    
    //    var partesControl=controlAmpliado.id.split("_");
    var partesControl = NombreControl.split("_");
    var NumAmpEncontrados = 0;
    var NomDivAmplia = "";
    var Candidato = null;
    for (var i = 0; i < partesControl.length; i++) {
        NomDivAmplia += partesControl[i] + "_";
        var controlAmp = document.getElementById(NomDivAmplia + "PNL_AMPL");
        if (controlAmp != null) {
            NumAmpEncontrados += 1;
            if (NumAmpEncontrados == NumeroAmp) {
                Candidato = controlAmp;
                break;
            }
        }
    }
    return Candidato;
}
function cnk_getRowId(idControl) {
    if (idControl == null) return;
    var panel = document.getElementById(idControl);
    if (panel.tagName != "DIV") {
        var NumeroAmp = panel.id.substring(panel.id.length - 1);
        var panel = cnk_obtenerDivAmpliaControl(panel, NumeroAmp)
    }
    var controlIdRow = cnk_obtenerControlRowId(idControl, panel);
    var candidatoIdRow = "0";
    if (controlIdRow != null)
        candidatoIdRow = controlIdRow.innerHTML;
    //     //cambiar los & en _
    //     while(idControl.indexOf("$")>-1){
    //        idControl = idControl.replace("$","_");
    //     }
    //      
    //     var parentControlNames = idControl.split("_");
    //     var baseNombreControl = "";
    //     
    //     var candidatoIdRow ="0";
    //     for (var i=0; i < parentControlNames.length;i++){
    //        baseNombreControl += parentControlNames[i] + "_";
    //        var controlIdRow = document.getElementById(baseNombreControl+ "rowId");
    //        if (controlIdRow != null)
    //        {
    //            //En firefox innerText no existe cambiar a innerHTML 
    //            candidatoIdRow = controlIdRow.innerHTML;
    //         }
    //     }
    return candidatoIdRow;
}

function cnk_setRowId(panel, idRow) {
    if (panel == null || idRow == null) return;
    var controlIdRow = cnk_obtenerControlRowId(panel.id, panel);

    if (controlIdRow == null) return;
    else controlIdRow.innerHTML = idRow;

}

function cnk_obtenerControlRowId(idControl, panel) {
    var candidatoControlIdRow = null;


    if (panel == null) {
        //cambiar los & en _
        while (idControl.indexOf("$") > -1) {
            idControl = idControl.replace("$", "_");
        }

        var parentControlNames = idControl.split("_");
        var baseNombreControl = "";


        for (var i = 0; i < parentControlNames.length; i++) {
            baseNombreControl += parentControlNames[i] + "_";
            var controlIdRow = document.getElementById(baseNombreControl + "rowId");
            if (controlIdRow != null) {
                candidatoControlIdRow = controlIdRow;
            }

        }

    }
    else //buscar el idrow dentro del  panel
    {
        var controles = panel.getElementsByTagName("span");
        //buscar el idRow que sea el numero minimo de padres hasta el id row
        var minNumParents = 100;
        for (var j = 0; j < controles.length; j++) {
            if (controles[j].id.length > 0 && controles[j].id.indexOf("rowId") > 0) {

                var controlPadre = controles[j].parentNode;
                var numPadres = 1;

                //buscar el idRow que sea el numero minimo de padres hasta el id row
                while (controlPadre != null && controlPadre.id != panel.id) {
                    controlPadre = controlPadre.parentNode;
                    if (controlPadre.id == panel.id && numPadres < minNumParents) {
                        minNumParents = numPadres;
                        candidatoControlIdRow = controles[j];

                    }

                    numPadres++;
                }
            }
        }
    }

    return candidatoControlIdRow;
}

function cnk_ExploradorFireFox() {
    lRet = false;
    if (navigator.userAgent.toLowerCase().indexOf("mozilla") >= 0) {
        if (navigator.userAgent.toLowerCase().indexOf("firefox") >= 0)
            lRet = true;
    }
    return lRet;
}

//obtiene del panel los campos de ampliacion
function cnk_getCamposAmplia(idAmplia, nivelAmp) {

    var panelAmplia = cnk_obtenerElemento(idAmplia);

    if (typeof (panelAmplia) == "undefined" || typeof (nivelAmp) == "undefined") return "";

    var controlCamposAmplia = cnk_obtenerControlAcabaConEnPanel(panelAmplia, nivelAmp + "xxzCamposAmplia");
    if (controlCamposAmplia == null) return "";

    //return controlCamposAmplia.innerText;
    return controlCamposAmplia.innerHTML;
}

//obtiene el panel capitulo padre de un control, pasando su id
function cnk_obtenerPanelPadre(control) {

    if (control == null) return null;
    //si se esta pasando el id, encontrar el control. En otro caso, ya se esta pasando el control

    if (control.id == null) {

        control = cnk_obtenerElemento(control);

    }



    if (control == null) return null;



    var controlPadre = control.parentNode;

    var panelPadre = null;

    while (controlPadre != null) {


        if (controlPadre.id.lastIndexOf("ppadre") == controlPadre.id.length - 6) {

            panelPadre = controlPadre;

            break;

        }

        controlPadre = controlPadre.parentNode;

    }



    return panelPadre;



}

//La funcion un control que esta al lado del control que se pasa con idControl.
//se busca el panel padre, y se revisa todos los elementos hasta que se encuentra
//el control.
function cnk_obtenerControlHermano(idControl, lsCampo, lsZona, lsAmp) {
    //busca el control padre del control 'hermano' que se pasa como un parametro
    var loPanelPadre = cnk_obtenerPanelPadre(idControl);
    return cnk_obtenerControlEnPanel(loPanelPadre, lsCampo, lsZona, lsAmp);

}

function cnk_obtenerControlEnPanel(panelPadre, lsCampo, lsZona, lsAmp) {
    var lsControlIdEnd = lsCampo + "_" + lsZona + "_" + lsAmp;
    //para 
    var tablaControl = cnk_obtenerTablaControl(lsControlIdEnd);
    if (tablaControl != null) panelPadre = tablaControl

    return cnk_obtenerControlAcabaConEnPanel(panelPadre, lsControlIdEnd);

}

function cnk_obtenerControlAcabaConEnPanel(panelPadre, psControlIdEnd, tipoTag) {
    var controlHermano = null;
    var controles;

    psControlIdEnd = psControlIdEnd.toUpperCase();
    //si no se enc        
    if (panelPadre == null) {
        loPadre = document;
    }
    else {
        loPadre = panelPadre;
    }


    if (tipoTag != null) {
        controles = loPadre.getElementsByTagName(tipoTag);
    }
    else {
        if (cnk_ExploradorFireFox())
            controles = cnk_AllFireFox(loPadre);
        else
            controles = loPadre.all;
    }


    //busca en los controles hijos un control con id que acaba como lsCampo_lsZona_lsAmp
    for (var i = 0; i < controles.length; i++) {
        if (controles[i].id.length > 0 &&
            controles[i].id.toUpperCase().indexOf(psControlIdEnd) == (controles[i].id.length - psControlIdEnd.length)
            || (controles[i].id.length > 0 &&
            controles[i].id.toUpperCase().indexOf(psControlIdEnd) == (controles[i].id.length - psControlIdEnd.length) - 7)) {
            //intenta verificar si el control es de infragistics
            try {


                //intentar encontrar el control de numerico
                controlHermano = igedit_getById(controles[i].id);

                if (controlHermano != null) break;

                //intentar encontrar el control fecha
                if (controles[i].id.indexOf("_hidden") == controles[i].id.length - 7) {
                    controlHermano = igdrp_getComboById(controles[i].id.substring(0, controles[i].id.length - 7));
                }

                if (controlHermano != null) break;

                //devlover el metodo normal
                controlHermano = controles[i];
                break;
            }
            catch (e) {
                // no hacer nada.
            }
        }
    }


    return controlHermano;
}
function cnk_AllFireFox(pControl, Ret) {

    if (typeof (Ret) == "object")
        var lRet = Ret;
    else
        var lRet = new Array();

    lRet.push(pControl);
    var i = 0;
    for (i = 0; i < pControl.childNodes.length; i++) {
        if (typeof (pControl.childNodes[i].id) != "undefined") {
            if (pControl.childNodes[i].childNodes.length > 0) {
                if (pControl.childNodes[i].tagName == "TABLE") {
                    var fila = 0;
                    for (fila = 0; fila < pControl.childNodes[i].rows.length; fila++) {
                        var celda = 0;
                        for (celda = 0; celda < pControl.childNodes[i].rows[fila].cells.length; celda++) {
                            lRet = cnk_AllFireFox(pControl.childNodes[i].rows[fila].cells[celda], lRet);
                        }
                    }
                }
                else
                    lRet = cnk_AllFireFox(pControl.childNodes[i], lRet);
            }
            else
                lRet.push(pControl.childNodes[i]);
        }
    }
    return lRet
}
function cnk_obtenerTablaControl(lsControlIdEnd) {
    var tablas = getElementsByName_iefix("TABLE", lsControlIdEnd.toUpperCase());
    var tabla = null;
    if (tablas.length == 1) {
        tabla = tablas[0];
    }

    return tabla;
}

//obtener el elemento por su atribute NAME. el getElementsByName nativo de JavaScript no funciona. 
function getElementsByName_iefix(tag, name) {

    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for (i = 0, iarr = 0; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if (att == name) {
            arr[iarr] = elem[i];
            iarr++;
        }
    }
    return arr;
}

function cnk_configurar_visibilidad(divAmplia, visible) {
    if (divAmplia == null) return false;

    var visiblityStyle = visible ? "" : "hidden";
    if (divAmplia.style.visibility != visiblityStyle) {
        divAmplia.style.visibility = visiblityStyle;
    }
    return true;
}

function cnk_BloquearControl(control, SoloLectura) {
    if (SoloLectura == "True") {
        if (control.setValue != null) {
            control.Element.readOnly = true;
            control.Element.className = "SOLOLECTURA";
        }
        else {
            control.readOnly = true;
            control.className = "SOLOLECTURA";
        }
    }
}
function cnk_Bloquear_Panel(panel, bloqueo, nivelamp) {
    if (nivelamp == 0)
        var panelamp = mPanelAmplia1;
    else
        var panelamp = mPanelAmplia2;

    if (bloqueo)
        CrearMarcoOcultar(panelamp, nivelamp);
    else {
        if (panel != null) {
            EliminarMarcoOcultar(panel.Marco);
            panel.Marco = null;
            EliminarMarcoOcultar(panel.pantalla);
            panel.pantalla = null;
            if (nivelamp == 0) {
                if (typeof (igtab_getTabById) == 'function') {
                    var otab = igtab_getTabById(cnk_EliminarPartesDeNombre(panel.id, 2) + "tabCapitulos")
                    if (otab)
                        otab.element.setAttribute("Ampliado", 0);
                }
            }
        }
    }

    cnk_Bloquear_Panel_Botones(panel, nivelamp, bloqueo);
}

function cnk_Bloquear_Panel_Botones(panel, nivelamp, bloqueo) {

    if (nivelamp == 0) {
        if (panel != null) {
            var lista = panel.id.split("_");
            var nom = ""
            for (i = 0; i < lista.length - 2; i++) {
                nom = nom + lista[i] + "_";
            }
        }
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnAceptar2", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnCancelar2", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnAplicar2", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnAceptar", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnCancelar", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "btnAplicar", bloqueo);
    }
    else {
        if (panel != null) {
            var lista = panel.id.split("_");
            var nom = ""
            for (i = 0; i < lista.length - 2; i++) {
                nom = nom + lista[i] + "_";
            }
        }
        cnk_Bloquear_Panel_Botones_Objeto(nom, "BTN_ACEPTAR", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "ETQ_ACEPTAR", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "ETQ_CANCELAR", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "BTN_CANCELAR", bloqueo);
        cnk_Bloquear_Panel_Botones_Objeto(nom, "IMG_MOVER", bloqueo);


    }

}

function cnk_Bloquear_Panel_Botones_Objeto(control, objeto, bloqueo) {
    var obj = null;
    //obj=igtbl_getElementById(control+objeto);
    obj = document.getElementById(control + objeto);
    if (obj) {
        obj.disabled = bloqueo;
        obj.setAttribute("Ampliado", bloqueo ? 1 : 0);
    }
}

function cnk_ObtenerDivAmpliado(panel, Idpadre) {
    var ret = null;
    var c = panel.getElementsByTagName("DIV");
    for (i = 0; i < c.length; i++) {
        if (c[i].id.indexOf('PNL_AMPL') > 0) {
            if (cnk_EliminarPartesDeNombre(Idpadre, 2) == cnk_EliminarPartesDeNombre(c[i].id, 2))
                ret = c[i];
        }
    }
    return ret;
}

function cnk_EliminarPartesDeNombre(Nombre, partes) {
    var Retorno = null;
    while (Nombre.indexOf("$") > -1) {
        Nombre = Nombre.replace("$", "_");
    }

    var parentControlNames = Nombre.split("_");
    var baseNombreControl = "";
    for (var i = 0; i < parentControlNames.length - partes; i++) {
        baseNombreControl += parentControlNames[i] + "_";
    }

    return baseNombreControl;
}


function cnk_configurar_disabled(divAmplia, disabled) {
    if (divAmplia == null) return false;


    return true;
}

//obtiene un elemento por su id, bien directamente o con la funcion getElementById
function cnk_obtenerElemento(idElemento) {
    return document.all ? document.all[idElemento] : document.getElementById(idElemento);
}


//obtiene el ampliable que es un amliable del controlTrigger que es un div hijo del panel contenedor de conroltrigger
function cnk_obtenerPanelAmpliaHijo(controlTrigger, idAmpliaEnd) {
    if (controlTrigger == null || idAmpliaEnd == null) return null;

    var panelPadre = cnk_obtenerPanelPadre(controlTrigger);
    if (panelPadre == null) return;

    return cnk_obtenerControlAcabaConEnPanel(panelPadre, idAmpliaEnd, "div");

}

function cnk_obtenerNombreContenedor(idControl) {
    var Retorno = null;
    while (idControl.indexOf("$") > -1) {
        idControl = idControl.replace("$", "_");
    }

    var parentControlNames = idControl.split("_");
    var baseNombreControl = "";

    for (var i = 0; i < parentControlNames.length - 4; i++) {
        baseNombreControl += parentControlNames[i] + "_";
    }

    return baseNombreControl;
}

//obtiene el control contenedor, pasando su id
function cnk_obtenerNombreControlPadre(idControl) {
    //cambiar los $ en _
    var Retorno = null;
    while (idControl.indexOf("$") > -1) {
        idControl = idControl.replace("$", "_");
    }

    var parentControlNames = idControl.split("_");
    var baseNombreControl = "";

    for (var i = 0; i < parentControlNames.length; i++) {
        baseNombreControl += parentControlNames[i] + "_";
        var panelPadre = document.getElementById(baseNombreControl + "ppadre");
        if (panelPadre != null) {
            Retorno = panelPadre;
        }
    }
    return Retorno;
}

//La funcion un control que esta al lado del control que se pasa con idControl.
//se busca el panel padre, y se revisa todos los elementos hasta que se encuentra
//el control.
function cnk_obtenerControlHermano(idControl, lsCampo, lsZona, lsAmp) {
    //busca el control padre del control 'hermano' que se pasa como un parametro
    var loPanelPadre = cnk_obtenerPanelPadre(idControl);
    var loPadre = null;
    var lsIdLast = lsCampo + "_" + lsZona + "_" + lsAmp;
    //var idPanelPadre = loPanelPadre.id;
    var controlHermano = null;

    //si no se enc        
    if (loPanelPadre == null) {
        loPadre = document;
    }
    else {
        loPadre = loPanelPadre;
    }

    //   JMC 20070809: He creado la función BuscaRecursivo y he comentado
    // este trozo porque se trataba de un bucle que pasa por todos los controles
    // que hay en la página. Cuando la página contiene una zona de lista con más
    // de 300 registros, el número de controles supera los 10.000 y se tira mucho
    // tiempo, dejando la página bloqueada. 
    // La función recursiva en lugar de recorrer todos los controles, va buscando
    // dentro de los hijos. Si detecta un hijo que pertenece a una zona de lista
    // que no es la que estamos buscando, no entra. De esta manera se ahorra tener
    // que recorrer controles de forma innecesaria.

    var cCandidato;
    cCandidato = BuscaRecursivo(loPadre, lsCampo, lsZona, lsAmp);

    return cCandidato;



    //    //busca en los controles hijos un control con id que acaba como lsCampo_lsZona_lsAmp
    //    for (var i=0;i<loPadre.all.length;i++)
    //    {
    //        if (loPadre.all[i].id.length >0 && 
    //            loPadre.all[i].id.toUpperCase().indexOf(lsIdLast.toUpperCase())>0 )
    //        {
    //            //intenta verificar si el control es de infragistics
    //            try{
    //        
    //        
    //            //intentar encontrar el control de numerico
    //            controlHermano = igedit_getById(loPadre.all[i].id);
    //            
    //            if (controlHermano != null) break;
    //            
    //            //intentar encontrar el control fecha
    //            if (loPadre.all[i].id.indexOf("_hidden") == loPadre.all[i].id.length-7)
    //            {
    //                controlHermano = igdrp_getComboById(loPadre.all[i].id.substring(0,loPadre.all[i].id.length-7)); 
    //            }
    //            
    //            if (controlHermano != null) break;
    //            
    //            //devlover el metodo normal
    //            controlHermano = loPadre.all[i];
    //            break;
    //            }
    //            catch (e){
    //                // no hacer nada.
    //            }
    //        }
    //    }        
    //        
    //    return controlHermano;
}

// ------------------------------------------------------------------
// BuscaRecursivo
// ------------------------------------------------------------------
// He creado la función BuscaRecursivo porque en la función 
// cnk_obtenerControlHermano se hacía un bucle que pasa por todos los controles
// que hay en la página. Cuando la página contiene una zona de lista con más
// de 300 registros, el número de controles supera los 10.000 y se tira mucho
// tiempo, dejando la página bloqueada. 
// La función recursiva en lugar de recorrer todos los controles, va buscando
// dentro de los hijos. Si detecta un hijo que pertenece a una zona de lista
// que no es la que estamos buscando, no entra. De esta manera se ahorra tener
// que recorrer controles de forma innecesaria.
// ------------------------------------------------------------------
//  J. Moraté - 20070809
// ------------------------------------------------------------------
function BuscaRecursivo(control, sCampo, iZona, iAmp) {

    // Identificador del control que buscamos
    var cntrId;
    cntrId = sCampo + '_' + iZona + '_' + iAmp;

    // Si el control no es nulo y tiene hijos en los que iterar
    // if (control != null && control.children.length > 0)                                                       //M 20080115
    if (control != null && typeof (control.children) != "undefined" && control.children.length > 0) {
        var hermano;                                                                                              //A 20070925
        hermano = null;

        // Recorrer los hijos de este control
        for (var h = 0; h < control.children.length; h++) {
            // Si el hijo es el control que buscamos...
            if (control.children[h].id.length > 0 && control.children[h].id.toUpperCase().indexOf(cntrId.toUpperCase()) > 0) {

                //intenta verificar si el control es de infragistics
                try {
                    //var hermano;

                    //intentar encontrar el control de numerico
                    hermano = igedit_getById(control.children[h].id);

                    if (hermano != null) return hermano;

                    //intentar encontrar el control fecha
                    if (control.children[h].id.indexOf("_hidden") == control.children[h].id.length - 7) {
                        hermano = igdrp_getComboById(control.children[h].id.substring(0, control.children[h].id.length - 7));
                    }

                    if (hermano != null) return hermano;

                    //devolver el metodo normal
                    if (control.children[h].type == "undefined" || control.children[h].type != "hidden") {
                        hermano = control.children[h];
                        return hermano;
                    }
                } catch (e) {
                    // no hacer nada.
                }

            } else {
                // Si no es el control que buscamos, tendremos que iterar de forma recursiva
                // entre sus hijos.

                // Si el control no tiene identificador y tiene hijos, iteramos.
                if (control.children[h].children.length > 0 && control.children[h].id.length == 0) {
                    //BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);                                          //M 20070925
                    hermano = BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);
                } else {
                    // Si el control tiene identificador, vemos si podemos ahorrarnos esta
                    // iteración mirando si las zonas de lista coinciden
                    if (control.children[h].id.length > 0) {
                        // Si el control que busco es de zona 0 y el control hijo
                        // pertenece a una zona de lista, es seguro que no está dentro de
                        // esta rama, así que evito recorrer estos controles
                        if (iZona == 0 && control.children[h].id.indexOf('xZONAx') < 0) {
                            //BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);
                            hermano = BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);
                        }

                        // Si el control que busco es de zona de lista, sólo se encontrará
                        // en aquellos hijos cuyo número de zona coincida, evitando recorrer
                        // el resto de zonas de lista innecesariamente.
                        if (iZona > 0 && control.children[h].id.indexOf('xZONAx') > 0 && control.children[h].id.indexOf('xZONAx' + iZona) > 0) {
                            //BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);
                            hermano = BuscaRecursivo(control.children[h], sCampo, iZona, iAmp);
                        }
                    }
                }
                if (hermano != null) return hermano;                                                                    //A 20070925
            }

        } //for
    }
} //BuscaRecursivo

function obtenerColumnasOrigenDepend(gridName) {
    return obtenerCampoInfoGrid(gridName, "CampoDepend");
}

function obtenerCampoOrigenAmplia(panel) {
    var i = 0;
    varc = panel.getElementsByTagName("INPUT");
    for (i = 0; i < varc.length; i++) {
        if (varc[i].id != "") {
            if (cnk_ObtenerTipoEditor(varc[i].id) == "ZONA") {
                var lgrid = igtbl_getElementById(varc[i].id)
                return obtenerCampoInfoGrid(lgrid.id, "CampoOrigenAmplia");
            }
        }
    }
    return "";
}
//obtener si este grid es readonly en el cliente (en caso las amplaciones van por AJAX, los grids siempre son 
//editables, y en caso que en M00 la zona no es editable, hay que evitarlo por el cliente.
//retorna true si es readonly
function obtenerReadOnlyGrid(gridName) {
    return (obtenerCampoInfoGrid(gridName, "ReadOnly") == "1");

}

//sirve para encontrar un campo que da informacion sobre el grid, como CampoDepend o ReadOnlyZona
function obtenerControlInfoGrid(gridName, campoInfo) {

    var lGrid = igtbl_getGridById(gridName);
    var lsCampoInfo = "";

    if (lGrid != null) {
        var idGrid = lGrid.UniqueID;
        var arrayIdGrid;
        var lsNombreControlCampoInfo = "";


        while (idGrid.indexOf("$") > -1) {
            idGrid = idGrid.replace("$", "_");
        }


        arrayIdGrid = idGrid.split("_");
        var lIdxZONA = arrayIdGrid.length - 3;

        for (var i = 0; i < arrayIdGrid.length; i++) {
            if (i == lIdxZONA)
                lsNombreControlCampoInfo += campoInfo;

            lsNombreControlCampoInfo += arrayIdGrid[i];
            if (i + 1 != arrayIdGrid.length)
                lsNombreControlCampoInfo += "_";
        }
        var lControlCampoInfo = document.getElementById(lsNombreControlCampoInfo);

    }
    return lControlCampoInfo;
}

//sirve para encontrar un campo que da informacion sobre el grid, como CampoDepend o ReadOnlyZona
function obtenerCampoInfoGrid(gridName, campoInfo) {
    //buscar el control que tiene la informacion de campo de infornacion del grid como los campos dependencia

    //transformar el id de grid de una forma como "ctl00xContentPlaceHolder1xpanelcapxctl00xZONA1x0x0" a
    // "ctl00_ContentPlaceHolder1_panelcap_ctl00_ZONA1_0_0"
    var lGrid = igtbl_getGridById(gridName);
    var lsCampoInfo = "";

    if (lGrid != null) {
        var idGrid = lGrid.UniqueID;
        var arrayIdGrid;
        var lsNombreControlCampoInfo = "";

        //cambiar los $ en _
        while (idGrid.indexOf("$") > -1) {
            idGrid = idGrid.replace("$", "_");
        }

        //intentar conseguir un control de la informacion de los campos depend
        //que se llama algo como ctl00_ContentPlaceHolder1_panelcap_ctl00_CampoDependZONA1_0_0
        arrayIdGrid = idGrid.split("_");
        var lIdxZONA = arrayIdGrid.length - 3;

        for (var i = 0; i < arrayIdGrid.length; i++) {
            if (i == lIdxZONA) lsNombreControlCampoInfo += campoInfo;

            lsNombreControlCampoInfo += arrayIdGrid[i];

            if (i + 1 != arrayIdGrid.length) lsNombreControlCampoInfo += "_";
        }


        //ya que se ha obtenido el id del control con la informacion de los campos depend
        //se puede intentar conseguirlo
        var lControlCampoInfo = document.getElementById(lsNombreControlCampoInfo);
        if (lControlCampoInfo != null) {
            //lsCampoInfo = lControlCampoInfo.innerText;
            if (lControlCampoInfo.tagName == "SELECT")
                lsCampoInfo = lControlCampoInfo.value;
            else
                lsCampoInfo = lControlCampoInfo.innerText;
        }

    }
    return lsCampoInfo;
}

//function obtenerColumnasOrigenDepend(gridName)
//{
//   //buscar el control que tiene la informacion de los campos dependencia
//   
//   //transformar el id de grid de una forma como "ctl00xContentPlaceHolder1xpanelcapxctl00xZONA1x0x0" a
//   // "ctl00_ContentPlaceHolder1_panelcap_ctl00_ZONA1_0_0"
//   var lGrid = igtbl_getGridById(gridName);
//   var lArrayCampoDepend = null;
//   
//   if (lGrid != null)
//   {
//      var idGrid = lGrid.UniqueID;
//      var arrayIdGrid;
//      var lsNombreControlCampoDepend = "";
//      
//      //cambiar los $ en _
//     while(idGrid.indexOf("$")>-1){
//        idGrid = idGrid.replace("$","_");
//     }
//     
//     //intentar conseguir un control de la informacion de los campos depend
//     //que se llama algo como ctl00_ContentPlaceHolder1_panelcap_ctl00_CampoDependZONA1_0_0
//     arrayIdGrid = idGrid.split("_");
//     var lIdxZONA = arrayIdGrid.length - 3;
//     
//     for (var i=0;i<arrayIdGrid.length;i++)
//     {
//        if (i==lIdxZONA) lsNombreControlCampoDepend += "CampoDepend";
//        
//        lsNombreControlCampoDepend += arrayIdGrid[i];
//        
//        if (i+1 != arrayIdGrid.length) lsNombreControlCampoDepend += "_";
//     }
//     
//     
//     //ya que se ha obtenido el id del control con la informacion de los campos depend
//     //se puede intentar conseguirlo
//     var lControlCampoDepend = document.getElementById(lsNombreControlCampoDepend);
//     if (lControlCampoDepend != null)
//     {
//        lArrayCampoDepend = lControlCampoDepend.innerHTML.split(";");
//        
//     }    
//      
//   }
//   return lArrayCampoDepend;
//}

function obtenerFechaDeString(lsFecha) {
    var fecha = null;
    if (lsFecha.length >= 12) {
        try {
            var valueDate = new Date();
            var month = lsFecha.substr(3, 2);
            month = month - 1;
            valueDate.setFullYear(lsFecha.substr(6, 4), month, lsFecha.substr(0, 2));
            fecha = valueDate;
        }
        catch (e) {

        }
    }
    return fecha;

}
// J.Moraté: 20060815
// Estas funciones sirven para el control del movimiento de los ampliables

//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2001 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

// Determine browser and version.

function Browser() {

    var ua, s, i;

    this.isIE = false;
    this.isNS = false;
    this.isFirefox = false;
    this.version = null;

    ua = navigator.userAgent;

    s = "MSIE";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isIE = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    s = "Netscape6/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    s = "Firefox";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isFirefox = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    // Treat any other "Gecko" browser as NS 6.1.
    s = "Gecko";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = 6.1;
        return;

    }


}

var browser = new Browser();

// Global object to hold drag information.
var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

    var el;
    var x, y;

    //alert('Paso del Brandivino! ' + id);
    // If an element id was given, find it. Otherwise use the element being
    // clicked on.

    if (id)
        dragObj.elNode = document.getElementById(id);
    else {
        try {
            if (browser.isIE) {
                var nodoObj;
                nodoObj = window.event.srcElement;

                if (nodoObj.id.indexOf('IMG_MOVER') < 0)
                    return;

                //si existe el atributo ampliado verificar que no este ampliado 1 ampliado 0 no ampliado 
                if (typeof (nodoObj.attributes["Ampliado"]) != "undefined")
                    if (nodoObj.attributes["Ampliado"].nodeValue == 1) return;

                while (nodoObj != null && nodoObj.id.indexOf('PNL_AMPL') < 0) {
                    nodoObj = nodoObj.parentElement;
                }
                //if (nodoObj.id.indexOf('PNL_AMPL') >= 0)
                //  nodoObj = nodoObj.parentElement;
                dragObj.elNode = nodoObj;

            }
            if (browser.isNS || browser.isFirefox) {
                var nodoObj;
                nodoObj = event.target
                if (nodoObj.id.indexOf('IMG_MOVER') < 0)
                    return;

                //si existe el atributo ampliado verificar que no este ampliado 1 ampliado 0 no ampliado 
                if (typeof (nodoObj.attributes["Ampliado"]) != "undefined")
                    if (nodoObj.attributes["Ampliado"].nodeValue == 1) return;

                while (nodoObj != null && nodoObj.id.indexOf('PNL_AMPL') < 0) {
                    nodoObj = nodoObj.parentNode;
                }
                dragObj.elNode = nodoObj;

            }
        }
        catch (ex) {
            return;
        }


        // If this is a text node, use its parent element.

        if (dragObj.elNode.nodeType == 3)
            dragObj.elNode = dragObj.elNode.parentNode;
    }

    // Get cursor position with respect to the page.
    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
    }
    if (browser.isNS || browser.isFirefox) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Save starting positions of cursor and element.
    dragObj.cursorStartX = x;
    dragObj.cursorStartY = y;
    dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
    dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);
    dragObj.PosicionClickY = event.offsetY;
    dragObj.PosicionClickX = event.offsetX;
    dragObj.AnchoControl = dragObj.elNode.offsetWidth;
    dragObj.AltoControl = dragObj.elNode.offsetHeight;

    if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
    if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0;

    // Update element's z-index.

    //dragObj.elNode.style.zIndex = ++dragObj.zIndex;

    // Capture mousemove and mouseup events on the page.


    if (browser.isIE) {
        document.attachEvent("onmousemove", dragGo);
        document.attachEvent("onmouseup", dragStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    if (browser.isNS) {
        document.addEventListener("mousemove", dragGo, true);
        document.addEventListener("mouseup", dragStop, true);
        event.preventDefault();

    }
    if (browser.isFirefox) {
        document.addEventListener("mousemove", dragGo, true);
        document.addEventListener("mouseup", dragStop, true);
        event.preventDefault();
    }

}

function dragGo(event) {

    var x, y;

    // Get cursor position with respect to the page.

    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
    }
    if (browser.isNS || browser.isFirefox) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Move drag element by the same amount the cursor has moved.

    //controlamos que no desaparezca por arriba (menu)
    var TablaCabecera = document.getElementById("tituloCabecera");
    if (TablaCabecera) {
        if ((TablaCabecera.offsetTop + TablaCabecera.offsetHeight) > y)
            y = (TablaCabecera.offsetTop + TablaCabecera.offsetHeight) + dragObj.PosicionClickY;
    }

    //controlamos que no desaparezca por abajo
    //    if (y+20>getDocumentHeight()) 
    //        y=getDocumentHeight()-20; 
    if (y + dragObj.AltoControl > getDocumentHeight())
        y = getDocumentHeight() - dragObj.AltoControl;

    //controlamos que no desaparezca por la izquierda
    if ((x - 20) < 0)//if ( (x- dragObj.AnchoControl)<0)
        x = 20; //x=dragObj.AnchoControl-dragObj.PosicionClickX;

    //controlamos que no desaparezca por la derecha
    if ((x + 16 + dragObj.PosicionClickX) > getDocumentWidth())
        x = getDocumentWidth() - dragObj.PosicionClickX - 16;

    dragObj.elNode.style.top = (dragObj.elStartTop + y - dragObj.cursorStartY) + "px";
    dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";


    if (browser.isIE) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    if (browser.isNS) {
        event.preventDefault();
    }

    if (browser.isFirefox) {
        event.preventDefault();
        // event.preventBubble();
    }
}

function dragStop(event) {

    // Stop capturing mousemove and mouseup events.

    if (browser.isIE) {
        document.detachEvent("onmousemove", dragGo);
        document.detachEvent("onmouseup", dragStop);
    }
    if (browser.isNS) {
        document.removeEventListener("mousemove", dragGo, true);
        document.removeEventListener("mouseup", dragStop, true);
    }
    if (browser.isFirefox) {
        document.removeEventListener("mousemove", dragGo, true);
        document.removeEventListener("mouseup", dragStop, true);
    }

    //informa al servidor la nueva posicion de ampliable
    informaPosicionAmliable();
}

//informa al servidor la nueva posicion de ampliable
function informaPosicionAmliable() {
    var urlpost;
    var currentTime = new Date();

    if (dragObj == null || dragObj.elNode == null) return;

    //_BSQ_ es el ampliable de busqueda
    if (dragObj.elNode.id.indexOf("_BSQ_") < 0) {
        urlpost = "Ajax/Capitulo/CapituloCambios.aspx?Accion=PosicionAmpliable&x=" +
                      parseInt(dragObj.elNode.style.left, 10) +
                      "&y=" + parseInt(dragObj.elNode.style.top, 10) +
                      "&IDPanelAmp=" + dragObj.elNode.id + "&signatura=" + currentTime;
        var loader = new net.ContentLoader(urlpost, null);
    }
}


function UpdateGridRecordChange() {
    if (_updatedRecordChange) return;
    _updatedRecordChange = true;

    igtbl_Grid.prototype._recordChangeEX = igtbl_Grid.prototype._recordChange;
    igtbl_Grid.prototype._recordChange = function(type, obj, value) {
        if (type != "ChangedCells" && type != "AddedRows" && type != "DeletedRows") {
            this._recordChangeEX(type, obj, value);
        }
    }
}



function GetSize(file) {
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var f = fso.getFile(file);
    return fso.getFile(file).size;
}

function checkFileSize(ctrl) {

    var fileupload = obtenerControlDeNombre(ctrl);
    //check if file size is > 10 MB

    if (GetSize(fileupload.value) > 10485760)//10 MB=10485760 B
    {

        alert('Sorry file size > 10MB');

        fileupload.form.reset();
        //file grater than 10MB then reset form

    }
}

//    function fMostrarDetalles() {
//    
//    var oDiv;
//    oDiv = document.getElementById('panelDetalles');
//    oDiv.style.visibility = 'visible' ;
//        
//    }

function PaginaConValidadores() {
    if (typeof (Page_ClientValidate) != 'function')
        return false
    else
        return true
}
function ExistenErroresPagina() {
    if (!PaginaConValidadores())
        return false;
    else {
        if (!Page_IsValid)
            return true;
        else
            return false;
    }
}

function ComboFechaCambiado(oCalendar, newValue, oEvent) {
    reportaCambios(oCalendar);
    Page_ClientValidate();
}

function EditFechaCambiado(oEdit, oldValue, oEvent) {
    reportaCambios(oEdit);
}

var gEventoValidar
function AjaxValidatorIsValid(val, args) {
    var valor = ValidatorGetValue(val.controltovalidate);
    var currentTime = new Date();
    var ValidarCampo = false;
    var lzona = val.attributes["zona"];
    var lcampo = val.attributes["campo"];
    var ltipovalidacion = val.attributes["validacion"];
    var ldato = val.attributes["dato"];


    ValidarCampo = false;
    ZonaValidada = lzona.value;
    if (ltipovalidacion.value == "C") {
        if (!gPulsoAceptar)
            ValidarCampo = true;
        else
            ValidarCampo = false;
    }
    else if (ltipovalidacion.value == "A") {
        if (gPulsoAceptar)
            ValidarCampo = true;
    }
    else
        ValidarCampo = true;


    gEventoValidar = args;
    if (ValidarCampo) {
        if (ldato.value == "F") {
            lFecha = valor.split("-");
            if (lFecha.length > 1)
                valor = lFecha[2] + "/" + lFecha[1] + "/" + lFecha[0];
            else
                valor = lFecha[0];
        }
        var lValores = "&Zona=" + ZonaValidada + "&Campo=" + lcampo.value + "&Valor=" + valor + "&IDControl=" + val.id
        if (ZonaValidada == 0)
            lValores = lValores + "&IdRow=0";
        else {
            lFila = 0;
            try {
                var gridname = val.attributes["grid"];
                if (typeof (gridname) == "undefined") {

                    lFila = cnk_getRowId(val.id);
                }
                else {

                    var NombrePadre = cnk_obtenerNombreContenedor(val.id);
                    gGrid = igtbl_getGridById(NombrePadre + gridname.value);

                    if (gGrid) {
                        if (gGrid.oActiveCell) {
                            var oFila = gGrid.oActiveCell.getRow();
                            if (oFila) {
                                lFila = oFila.getCellFromKey("NUMSECUENCIA").getValue();
                                oElemEditor = gGrid._editorCurrent;
                                oCeldaEditor = igtbl_getElementById(oElemEditor.getAttribute("currentCell"));
                            }
                        }
                    }
                }
            }
            catch (ex) {
            }
            lValores = lValores + "&IdRow=" + lFila;
        }


        var urlpost = "Ajax/Capitulo/CapituloCambios.aspx?Accion=ValidarCampo" + lValores + "&signature=" + currentTime;
        //      if (ZonaValidada==0)
        //         var loader = new net.ContentLoader(urlpost,AjaxValidatorResultado);
        //      else
        var loader = new net.ContentLoader(urlpost, AjaxValidatorResultado, null, null, null, null, false);
    }
    return true
}

function AjaxValidatorResultado() {

    if (this.req != null) {
        var xmlDoc = this.req.responseXML;
        var lValidacion = xmlDoc.getElementsByTagName("validacion");
        if (lValidacion != null) {
            if (cnk_ExploradorFireFox()) {
                var Control = cnk_obtenerElemento(lValidacion[0].childNodes[4].textContent);
                var Correcto = lValidacion[0].childNodes[1].textContent;
                var Propuesto = lValidacion[0].childNodes[2].textContent;
                var Mensaje = lValidacion[0].childNodes[3].textContent;
            }
            else {
                var Control = cnk_obtenerElemento(lValidacion[0].childNodes[4].text);
                var Correcto = lValidacion[0].childNodes[1].text;
                var Propuesto = lValidacion[0].childNodes[2].text;
                var Mensaje = lValidacion[0].childNodes[3].text;
            }
            var ltipovalidacion = Control.attributes["validacion"]
            if (Correcto == "0") {
                if (ltipovalidacion.value == "C") {
                    if (ZonaValidada == 0) {
                        gHayErrorValidacionZona0 = true;
                    }
                    else
                        gHayErrorValidacionZonaLista = true;
                }
                Control.title = Mensaje;
                gEventoValidar.IsValid = false;
                Control.isvalid = false;
                ValidatorUpdateDisplay(Control);
            }
            else {
                if (ltipovalidacion.value == "C") {
                    if (ZonaValidada == 0) {
                        gHayErrorValidacionZona0 = false;
                    }
                    else
                        gHayErrorValidacionZonaLista = false;
                }
                Control.isvalid = true;
                ValidatorUpdateDisplay(Control);
            }
            if (Propuesto != "") {
                controlValidado = document.getElementById(Control.controltovalidate)
                if (controlValidado.value != Propuesto) {
                    controlValidado.value = Propuesto;
                }

            }
            gGrid = null;
            oElemEditor = null;
            oCeldaEditor = null;
        }

    }

}

//Nos devuelve el tipo de editor que tenemos asignado a una columna
function cnk_ObtenerTipoEditor(nombreID) {

    while (nombreID.indexOf("$") > -1) {
        nombreID = nombreID.replace("$", "_");
    }

    var parentControlNames = nombreID.split("_");
    //retornamos el 4 valor que es donde ponemos el tipo de editor.
    //igtxtctl00_ContentPlaceHolder1_panelcap_1_MES_ctl17_ctl00_WNE_2_1_DIA2

    if (parentControlNames[parentControlNames.length - 3] == "ZONA")
        return parentControlNames[parentControlNames.length - 3];
    else if (parentControlNames[parentControlNames.length - 3] == "BTNAMPL")
        return parentControlNames[parentControlNames.length - 3];
    else if (parentControlNames[parentControlNames.length - 2].toUpperCase() == "DRPPNL")
        return parentControlNames[parentControlNames.length - 6];
    else
        return parentControlNames[parentControlNames.length - 4];

}


function obtenerStringDeDateTime(lDateTime) {
    return lDateTime.getMonth() + 1 + "/" + lDateTime.getDate() + "/" +
             lDateTime.getFullYear() + " " + lDateTime.getHours() + ":" +
             lDateTime.getMinutes() + ":" + lDateTime.getSeconds();
}

function obtenerStringDeDate(lDateTime) {
    return lDateTime.getDate() + "/" + (lDateTime.getMonth() + 1) + "/" +
             lDateTime.getFullYear();
    //    return  lDateTime.getMonth()+1 + "/" + lDateTime.getDate() + "/" + 
    //             lDateTime.getYear();

}

function EditFechaCambiado(oEdit, newText, oEvent) {
    //var o=cnk_obtenerElemento(oEdit.Element.id);
    reportaCambios(oEdit);
}
//Hace visible la capa que muestra la capa de cargando.
function mostrar_cargando() {
    var obj = cnk_obtenerElemento("waitDiv");
    obj.style.visibility = 'visible';

    obj = cnk_obtenerElemento("lockDiv");
    if (obj != null) {
        obj.style.visibility = 'visible';
    }
}

function CrearDIV(panelPadre) {
    if (document.createElement) {
        var d = document.createElement("DIV");
        d.style.position = "absolute";
        d.style.display = "block";
        d.style.visibility = "hidden";
        NuevoElementoDiv(panelPadre, d);
        return d;
    }
}

function CrearIFrame(panelPadre) {
    if (document.createElement) {
        var i = document.createElement("IFRAME");
        i.style.position = "absolute";
        i.style.display = "block";
        i.style.visibility = "hidden";
        i.style.background = "none";
        NuevoElementoDiv(panelPadre, i);
        return i;
    }
}

function CrearTexto() {
    if (document.createElement) {
        var i = document.createElement("input");
        i.type = "text";
        i.style.visibility = "visible";
        return i;
    }
}

function CrearImagen() {
    if (document.createElement) {
        var i = document.createElement("img");
        i.style.visibility = "visible";
        return i;
    }
}
function CrearTextoFiltro(odiv, pColumna, pID, pIDCombo) {
    odiv.Filtro = CrearDIV(odiv);
    odiv.Filtro.style.visibility = "visible";
    odiv.Filtro.style.display = "block";
    //odiv.Filtro.style.backgroundColor = "#cccccc";
    odiv.Filtro.id = pID;
    odiv.Filtro.className = "PopUpPantalla";
    odiv.Filtro.style.top = "0px";  //event.clientY ;
    odiv.Filtro.style.left = pColumna.Element.offsetLeft; //event.clientX ;
    odiv.Filtro.style.width = pColumna.Element.offsetWidth;
    odiv.Filtro.style.height = "20px";
    odiv.Filtro.style.zIndex = 0;
    odiv.Filtro.setAttribute("ControlTexto", "TEXTOFILTRO_" + pColumna.Key);

    var tbl = odiv.Filtro.appendChild(document.createElement("table"));
    var tb = tbl.appendChild(document.createElement("tbody"));
    var tr = tb.appendChild(document.createElement("tr"));
    var td = tr.appendChild(document.createElement("td"));

    var lPartes = pID.split("_");
    var lZona = lPartes[5];
    var lAmp = lPartes[6];
    var lNomFiltro = cnk_EliminarPartesDeNombre(pID, 6);
    var lImagenFiltro = cnk_obtenerElemento(lNomFiltro + "IMGFILTRO_" + lZona + "_" + lAmp);

    var oTexto = CrearTexto();
    oTexto.style.top = "0px";
    oTexto.style.width = pColumna.Element.offsetWidth - 20;
    oTexto.className = "TextBoxFiltro";
    oTexto.id = "TEXTOFILTRO_" + pColumna.Key;
    oTexto.setAttribute("ColumnaFiltro", pColumna.Key);
    oTexto.setAttribute("DivFiltro", odiv.Filtro.id);
    oTexto.setAttribute("ComboFiltro", pIDCombo);
    oTexto.setAttribute("CargadoIntro", 0);
    if (lImagenFiltro) {
        var oImagen = CrearImagen();
        oImagen.src = lImagenFiltro.src;
        oImagen.setAttribute("ObjetoFiltro", oTexto.id);
        td.appendChild(oImagen);
        td.appendChild(oTexto);
    }
    else
        td.appendChild(oTexto);

    if (lImagenFiltro)
        oImagen.onclick = function() { AplicarFiltroCombo(this) };
    else
        oTexto.onchange = function() { CambioFiltro(this) };

    //oTexto.onkeypress=function(){ KeyPressFiltro(this)}; 
    oTexto.onkeypress = KeyPressFiltro;
    oTexto.focus();


    oTexto = null;
}

function AplicarFiltroCombo(oImg) {
    var lNomTexto = oImg.attributes["ObjetoFiltro"].nodeValue;
    var oTexto = cnk_obtenerElemento(lNomTexto);
    oTexto.setAttribute("CargarCombo", 0);
    //event.returnValue=false;
    CambioFiltro(oTexto);
    return false
}

//function KeyPressFiltro(oTexto,e)
function KeyPressFiltro(evt) {
    e = evt;
    var oTexto = null;
    if (!e) {
        e = window.event;
        oTexto = e.srcElement;
    }
    else
        oTexto = e.currentTarget;

    //if(window.event) // IE
    if (e.keyCode) // IE
    {
        keynum = e.keyCode
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }

    switch (keynum) {
        case 13:
            //event.returnValue=false;
            oTexto.setAttribute("CargarCombo", 0);
            CambioFiltro(oTexto);
            return false
            break;
        case 27:
            //event.returnValue=false;

            var oCombbo = oTexto.attributes["ComboFiltro"].nodeValue;
            if (!oWC)
                oWC = igcmbo_getComboById(oCombbo);

            oTexto.setAttribute("CargarCombo", 0);
            EliminarFiltroCombo(oWC.getGrid());
            return false
            break;
        default:
            oTexto.setAttribute("CargarCombo", 0);
    }
}

function CambioFiltro(oTexto) {
    if (oTexto.attributes["CargarCombo"].nodeValue == 0) {
        if (typeof (oTexto.attributes["ColumnaFiltro"]) != "undefined") {
            var lColumna = oTexto.attributes["ColumnaFiltro"].nodeValue;
            var lValor = oTexto.value;
            var oCombbo = oTexto.attributes["ComboFiltro"].nodeValue
            if (!oWC)
                oWC = igcmbo_getComboById(oCombbo);
            WC_BeforeDropDownEx(oWC.ClientUniqueId, lValor);

        }
    }
}

function EliminarFiltroCombo(pGrid) {
    var lNom = cnk_EliminarPartesDeNombre(pGrid.UniqueID, 2);
    var lNomCampo = lNom.substring(lNom.lastIndexOf("_", lNom.length - 2) + 1, lNom.length - 1);
    var comboPartes = pGrid.ClientID.split("_");
    var numZona = comboPartes[comboPartes.length - 5];
    var nivelAmpPanel = comboPartes[comboPartes.length - 4];
    var imgSinFiltro = cnk_obtenerElemento(lNomCampo + "_" + numZona + "_" + nivelAmpPanel + "_img_sinfilter");
    //var imgSinFiltro=cnk_obtenerElemento(lNomCampo+"_img_sinfilter");

    var lDivFiltro = pGrid.Element.getAttribute("FiltroDiv");
    if (lDivFiltro != "CODIGO")
        EliminarMarcoOcultar(cnk_obtenerElemento(lDivFiltro));

    pGrid.Element.setAttribute("Filtro", 0);
    pGrid.Element.removeAttribute("FiltroDiv");

    oWC = igcmbo_getComboById(lNom.substring(0, lNom.length - 1));
    oWC.Element.setAttribute("CampoFiltro", "");
    oWC.Element.setAttribute("ValorFiltro", "");
    oWC.Element.setAttribute("campo", "");
    //oWC=null;
    if (imgSinFiltro)
        imgSinFiltro.style.display = 'none';
}

function NuevoElementoDiv(panelPadre, elemento) {
    if (panelPadre && panelPadre.appendChild)
        panelPadre.appendChild(elemento);
}

function BuscarBody() {
    if (document.body) {
        return document.body;
    }
    if (document.getElementsByTagName) {
        var bodies = document.getElementsByTagName("BODY");
        if (bodies != null && bodies.length > 0) {
            return bodies[0];
        }
    }
    return null;
}

function EstaDefinido(o) {
    return (typeof (o) != "undefined");
}

function getDocumentHeight() {
    var body = BuscarBody();
    var innerHeight = (EstaDefinido(self.innerHeight) && !isNaN(self.innerHeight)) ? self.innerHeight : 0;
    if (document.documentElement && (!document.compatMode || document.compatMode == "CSS1Compat")) {
        var topMargin = 0;
        var bottomMargin = 0;
        return Math.max(body.offsetHeight + topMargin + bottomMargin, document.documentElement.clientHeight, document.documentElement.scrollHeight, innerHeight);
    }
    return Math.max(body.scrollHeight, body.clientHeight, innerHeight);
}

function getDocumentWidth() {
    var body = BuscarBody();
    var innerWidth = (EstaDefinido(self.innerWidth) && !isNaN(self.innerWidth)) ? self.innerWidth : 0;
    if (document.documentElement && (!document.compatMode || document.compatMode == "CSS1Compat")) {
        var topMargin = 0;
        var bottomMargin = 0;
        return Math.max(body.offsetWidth + topMargin + bottomMargin, document.documentElement.clientWidth, document.documentElement.scrollWidth, innerWidth);
    }
    return Math.max(body.scrollWidth, body.clientWidth, innerWidth);
}

function CrearMarcoOcultar(panelAmp, nivelamp) {
    var odiv = cnk_obtenerPanelPadre(panelAmp);

    //miramos si existe el control tab
    if (typeof (igtab_getTabById) == 'function') {
        var otab = igtab_getTabById(cnk_EliminarPartesDeNombre(odiv.id, 2) + "tabCapitulos")
        if (otab)
            otab.element.setAttribute("Ampliado", 1);
    }
    var alto = 0;
    if (nivelamp == 0) {
        alto = getDocumentHeight() - odiv.offsetTop + "px";

    }
    else {
        if (cnk_ExploradorFireFox()) {
            var odivAmp = cnk_ObtenerDivAmpliado(mPanelAmplia0, odiv.id);
            alto = odivAmp.style.height;
        }
        else
            alto = odiv.style.height;
    }
    odiv.pantalla = CrearDIV(odiv);
    odiv.pantalla.style.top = "0px";
    odiv.pantalla.style.left = "0px";
    odiv.pantalla.style.backgroundColor = "#cccccc";
    odiv.pantalla.className = "PopUpPantalla";

    odiv.pantalla.style['-moz-opacity'] = 0.4;
    odiv.pantalla.style['-khtml-opacity'] = 0.4;
    odiv.pantalla.style.opacity = 0.4;
    if (EstaDefinido(odiv.pantalla.style.filter)) {
        odiv.pantalla.style.filter = "alpha(opacity=" + 0.4 * 100 + ")";
    }

    odiv.pantalla.style.width = odiv.style.width;
    odiv.pantalla.style.height = alto;
    odiv.pantalla.style.display = 'block';
    odiv.pantalla.style.visibility = 'visible';

    odiv.Marco = CrearIFrame(odiv);
    odiv.Marco.style.top = "0px";
    odiv.Marco.style.left = "0px";
    odiv.Marco.className = "PopUpIFrame";
    odiv.Marco.style['-moz-opacity'] = 0;
    odiv.Marco.style['-khtml-opacity'] = 0;
    odiv.Marco.style.opacity = 0;
    if (EstaDefinido(odiv.Marco.style.filter)) {
        odiv.Marco.style.filter = "alpha(opacity=" + 0 * 100 + ")";
    }

    odiv.Marco.style.display = 'block';
    odiv.Marco.style.visibility = 'visible';
    odiv.Marco.style.width = odiv.style.width;
    odiv.Marco.style.height = alto;

    var IndiceAmpliacion = panelAmp.style.zIndex;
    odiv.Marco.style.zIndex = IndiceAmpliacion - 2;
    odiv.pantalla.style.zIndex = IndiceAmpliacion - 1;
}


function EliminarMarcoOcultar(o) {
    if (o != null && o.parentNode && o.parentNode.removeChild) {
        for (var i in o) {
            if (typeof (o[i]) == "function") {
                o[i] = null;
            }
        }
        o.parentNode.removeChild(o);
        return true;
    }
    return false;
}

function obtenerStringESPDeDate(lDateTime) {
    return lDateTime.getDate() + "/" + (lDateTime.getMonth() + 1) + "/" +
             lDateTime.getFullYear();
}

function cnk_EliminarCaracterTexto(pUnicode, pCadena) {
    //como era de esperar esto no funciona
    //var oCadena=pCadena.replace(/String.fromCharCode(pUnicode)/g ,"");

    oCadena = pCadena;
    while (oCadena.indexOf(String.fromCharCode(pUnicode)) > -1) {
        oCadena = oCadena.replace(String.fromCharCode(pUnicode), "");
    }
    return oCadena;
}

function cnk_ObtenerMarcoFlotante() {
    var oMarco = document.getElementById('MarcoRemotingScript');
    if (oMarco == null) {
        var oMarco = cnk_CrearMarcoFlotante();
        setTimeout("cnk_ObtenerMarcoFlotante()", 10);
        return oMarco;
    }
    return oMarco
}

function cnk_CrearMarcoFlotante() {
    var oIFrameElement = document.createElement("iframe");
    oIFrameElement.style.display = "none";
    oIFrameElement.name = "MarcoOculto";
    oIFrameElement.id = "MarcoRemotingScript";
    document.body.appendChild(oIFrameElement);

    return oIFrameElement;
}

function cnk_ExisteEstilo(pEstilo) {
    var lbExiste = false;
    if (!(oStyleSheet = document.styleSheets))
        oStyleSheet = document.getElementsByTagName('style');

    for (var iStl = 0; iStl < oStyleSheet.length; iStl++) {
        if (oStyleSheet[iStl].cssText == pEstilo) {
            lbExiste = true;
        }
    }

    return lbExiste;
}

function cnk_EliminarObjeto(Idcontrol, identificador) {
    var obj = document.getElementById(Idcontrol + identificador);
    if (obj)
        obj.parentElement.removeChild(obj);
}

function String2HEX(s) {
    var hex = '';
    var h;
    s = s + '';

    for (i = 0; i < s.length; i++) {
        h = s.charCodeAt(i).toString(16).toUpperCase();
        if (h.length == 1) {
            h = '000' + h;
        }
        if (h.length == 2) {
            h = '00' + h;
        }
        if (h.length == 3) {
            h = '0' + h;
        }
        hex = hex + h;
    }
    return hex;

}

var opacity;
// ------------------------------------------------------------------
//  IniciarAccionAJAX
// ------------------------------------------------------------------
//  Localiza la etiqueta donde se va a escribir el mensaje que se le
//  pase. 
// ------------------------------------------------------------------
//  J. Moraté - 20070718
// ------------------------------------------------------------------
function IniciarAccionAJAX(mensaje) {
    var etiqueta;
    var div;

    // Localizar el DIV
    div = document.getElementById('divAccionAJAX');
    etiqueta = div.childNodes[0];
    if (div != null && etiqueta != null) {
        // Ponerlo como visible y establecer el mensaje
        div.style.visibility = 'visible';
        etiqueta.innerHTML = mensaje;
        opacity = 10;
    }

}

function FinalizarAccionAJAX() {
    var div;

    // Localizar el DIV
    div = document.getElementById('divAccionAJAX');
    if (div != null) {

        if (opacity > 0) {
            // Se desvanece en 1 segundo.
            opacity -= 1;
            setOpacity(div, opacity);
            setTimeout("FinalizarAccionAJAX()", 60);
        } else {
            // Ponerlo como no visible 
            div.style.visibility = 'hidden';
        }
    }
}

function setOpacity(obj, value) {
    if (obj != null) {
        obj.style.opacity = value / 10;
        obj.style.filter = 'alpha(opacity=' + value * 10 + ')';
    }
}


function cnk_DesactivarPaneles(idPanel, nivelamp, idRowAmp) {
    var divs = document.getElementsByTagName("DIV");
    var i = 0;
    var total = divs.length;
    for (i = 0; i < total; i++) {
        if (divs[i].id.indexOf(idPanel) > 0) {
            var divAmplia = divs[i];
            DesactivarAmpliacion(divAmplia, nivelamp, idRowAmp, idPanel);
        }
    }
}

function DesactivarAmpliacion(divpanel, nivelamp, idRowAmp, idPanel) {

    var controlPadre = divpanel.parentNode;
    var panelPadre = null;
    var divAmplia = null;
    var j = 0;
    var opanels = null;

    while (controlPadre != null) {
        if (typeof (controlPadre.id) != "undefined") {
            if (controlPadre.id.lastIndexOf("ppadre") == controlPadre.id.length - 6) {

                var opanels = controlPadre.getElementsByTagName("DIV");
                divAmplia = null;
                for (j = 0; j < opanels.length; j++) {
                    if (opanels[j].id.indexOf(idPanel) > 0) {
                        var divAmplia = opanels[j];
                        break;
                    }
                }
                if (divAmplia != null) {
                    configAntesLanzarAmpliable(nivelamp - 1, controlPadre, divAmplia);
                    configurarVisibilidadPaneles();
                    //DesactivarPaneles(controlPadre,nivelamp-1);
                    cnk_setRowId(divAmplia, idRowAmp);
                    cnk_setRowAmp(divAmplia, idRowAmp);
                    // ActualizarOrigenAmp( divAmplia.getElementsByTagName("DIV"),idRowAmp,nivelamp);

                }
                break;
            }

        }
        controlPadre = controlPadre.parentNode;
    }
}

function cnk_setRowAmp(panel, idRow) {
    if (panel == null || idRow == null) return;
    var controlIdRow = cnk_ObtenerControlRowAmp(panel.id, panel);

    if (controlIdRow == null) return;
    else controlIdRow.value = idRow;

}
function cnk_ObtenerControlRowAmp(idControl, panel) {

    var candidatoControlIdRow = null;

    if (panel == null) {
        //cambiar los & en _
        while (idControl.indexOf("$") > -1) {
            idControl = idControl.replace("$", "_");
        }

        var parentControlNames = idControl.split("_");
        var baseNombreControl = "";


        for (var i = 0; i < parentControlNames.length; i++) {
            baseNombreControl += parentControlNames[i] + "_";
            var controlIdRow = document.getElementById(baseNombreControl + "OrigenAmpZONA_");
            if (controlIdRow != null) {
                candidatoControlIdRow = controlIdRow;
            }

        }

    }
    else //buscar el idrow dentro del  panel
    {
        var controles = panel.getElementsByTagName("input");
        //buscar el idRow que sea el numero minimo de padres hasta el id row
        var minNumParents = 100;
        for (var j = 0; j < controles.length; j++) {
            if (controles[j].id.length > 0 && controles[j].id.indexOf("OrigenAmpZONA") > 0) {

                var controlPadre = controles[j].parentNode;
                var numPadres = 1;

                //buscar el idRow que sea el numero minimo de padres hasta el id row
                while (controlPadre != null && controlPadre.id != panel.id) {
                    controlPadre = controlPadre.parentNode;
                    if (controlPadre.id == panel.id && numPadres < minNumParents) {
                        minNumParents = numPadres;
                        candidatoControlIdRow = controles[j];

                    }

                    numPadres++;
                }
            }
        }
    }

    return candidatoControlIdRow;
}


function GridsModificados(grid, pendiente) {
    this.nombreGrid = grid;
    this.PendienteValidar = pendiente;
    this.FilaValidar = 0;
    this.IdxFila = 0;
    this.contieneValidators = false;
}

// ------------------------------------------------------------------
// getNombreDiaSemana
// ------------------------------------------------------------------
//  Retorna el nombre del día de la semana en función de una fecha y
//  de un formato que se le pase. Necesita variables definidas en el
//  diccionario. 
//  formato 1 = nombre del día de un solo caracter (L)
//          3 = nombre del día de tres caracteres (lun)
//          0 = nombre completo (lunes)
// ------------------------------------------------------------------
function getNombreDiaSemana(fecha, formato) {
    var nombre = '';

    if (fecha != null) {
        var dia = fecha.getDay();
        if (formato == null || formato == 0) {
            nombre = gvDiasSemana[dia];
        }
        if (formato == 1) {
            nombre = gvDiasSemana1[dia];
        }
        if (formato == 3) {
            nombre = gvDiasSemana3[dia];
        }
    }

    return nombre;
}

// ------------------------------------------------------------------
//  getNombreMes
// ------------------------------------------------------------------
//  Obtiene el nombre del mes en función del objeto fecha que se le 
//  pase. Necesita variables definidas en el diccionario.
//  formato 1 = nombre del mes de un solo caracter (E)
//          3 = nombre del mes de 3 caracteres (ene)
//          0 = nombre completo (enero)
// ------------------------------------------------------------------
function getNombreMes(fecha, formato) {
    var nombre = '';

    if (fecha != null) {
        var mes = fecha.getMonth();

        if (formato == null || formato == 0) {
            nombre = gvMeses[mes];
        }
        if (formato == 1) {
            nombre = gvMeses1[mes];
        }
        if (formato == 3) {
            nombre = gvMeses3[mes];
        }
    }

    return nombre;

}

function RefrescarControlPadreUpload(frameAdjunto, controlID, id) {
    var nombrecontenedor = cnk_obtenerNombreContenedor(controlID);
    var controlLink = ObtenerLinkUpload(nombrecontenedor, id);
    var controlReferencia = frameAdjunto.contentWindow.document.getElementById('Upload_ControlPadre');
    controlReferencia.value = controlLink.id;
}

function AdjuntarFicheroAjax(control, id, tieneValor) {

    var ControlPadre = cnk_obtenerPanelPadre(control.id);
    var NombreIframe = ControlPadre.id.substring(0, ControlPadre.id.indexOf("ppadre"));
    var frameAdjunto = null

    frameAdjunto = ObtenerFrameUpload(control.ownerDocument, NombreIframe);
    if (tieneValor == 1) {
        if (frameAdjunto != null) {
            RefrescarControlPadreUpload(frameAdjunto, control.id, id);
            var divAdjunto = frameAdjunto.contentWindow.document.getElementById('divRemoteScriptAdjunto');
            if (divAdjunto != null) {
                var FicheroAnterior = frameAdjunto.contentWindow.document.getElementById('Upload_FicheroAnterior');
                FicheroAnterior.value = "";
                var nombrecontenedor = cnk_obtenerNombreContenedor(control.id);
                var controlLink = ObtenerLinkUpload(nombrecontenedor, id);
                if (controlLink.href != "")
                    FicheroAnterior.value = controlLink.innerHTML;

                var partesCampo = control.id.split("_");
                var NombreControl = partesCampo[partesCampo.length - 3] + "_" + partesCampo[partesCampo.length - 2] + "_" + partesCampo[partesCampo.length - 1];
                var file = ObtenerControlUpload(NombreControl, frameAdjunto, divAdjunto);
                var controlReferencia = frameAdjunto.contentWindow.document.getElementById('Upload_Control');
                controlReferencia.value = id;
                file.click();
            }
        }
    }
    else {
        if (frameAdjunto != null) {
            RefrescarControlPadreUpload(frameAdjunto, control.id, id)
            var divAdjunto = frameAdjunto.contentWindow.document.getElementById('divRemoteScriptAdjunto');
            if (divAdjunto != null) {
                var nombrecontenedor = cnk_obtenerNombreContenedor(control.id);
                var controlLink = ObtenerLinkUpload(nombrecontenedor, id);
                if (controlLink.href != "")
                    EliminarFichero(frameAdjunto, id, controlLink)
            }
        }
    }
}

function EliminarFichero(frameAdjunto, id, controlLink) {
    var controlReferencia = frameAdjunto.contentWindow.document.getElementById('Upload_Control');
    controlReferencia.value = id;

    var fichero = frameAdjunto.contentWindow.document.getElementById('Upload_Fichero');
    fichero.value = controlLink.innerHTML;

    var eliminar = frameAdjunto.contentWindow.document.getElementById('Upload_Eliminar');

    var row = controlLink.parentElement.parentElement;
    MostrarMensajeUpload(gsEliminarFicheroUpload, row);

    eliminar.click();
}

function ObtenerFrameUpload(pDiv, pNombre) {
    var iframe = pDiv.getElementById(pNombre + "iFrameAdjunto");
    return iframe
}

function ObtenerControlUpload(nombre, frame, pDiv) {
    var control = null
    control = frame.contentWindow.document.getElementById("OBJ_" + nombre);
    if (control == null) {
        control = frame.contentWindow.document.createElement("input");
        control.setAttribute("type", "file");
        control.setAttribute("name", "OBJ_" + nombre);
        control.setAttribute("id", "OBJ_" + nombre);
        control.setAttribute("iframe", frame.id);
        control.onchange = UploadSeleccion;
        pDiv.appendChild(control);
    }
    return control
}

function MostrarMensajeUpload(Mensaje, fila) {
    var cell = document.createElement("td");
    cell.style.backgroundColor = "red";
    cell.style.color = "white";
    //cell.style.borderWidth="1px";
    //cell.style.borderColor="black"
    var cellText = document.createTextNode(Mensaje);
    cell.appendChild(cellText);
    fila.appendChild(cell);
}

function ObtenerLinkUpload(nombrecontenedor, idControl) {
    var partesCampo = idControl.split("_");
    partesCampo[partesCampo.length - 4] = "LNK";
    Nombrecontrol = "";
    for (i = 0; i < partesCampo.length; i++) {
        Nombrecontrol = Nombrecontrol + partesCampo[i]
        if (i != partesCampo.length - 1)
            Nombrecontrol = Nombrecontrol + "_"
    }
    var controlLink = document.getElementById(nombrecontenedor + Nombrecontrol);
    return controlLink
}

function UploadSeleccion() {

    var FicheroActual = this.document.getElementById('Upload_Fichero');
    var idx = this.value.lastIndexOf("\\");
    if (idx < 0)
        idx = this.value.lastIndexOf("/");

    FicheroActual.value = this.value.substring(idx + 1, this.value.length);

    var frameName = this.getAttribute("iframe");
    var iframeAdjunto = document.getElementById(frameName);
    var envio = iframeAdjunto.contentWindow.document.getElementById('Upload_Envio');

    var controlReferencia = iframeAdjunto.contentWindow.document.getElementById('Upload_ControlPadre');
    var FicheroActual = document.getElementById(controlReferencia.value);

    var IdFila = iframeAdjunto.contentWindow.document.getElementById('Upload_IdFila');
    var idRow = cnk_obtenerControlRowId(FicheroActual.id)
    IdFila.value = idRow.innerHTML;

    var row = FicheroActual.parentElement.parentElement;
    MostrarMensajeUpload(gsSubirFicheroUpload, row);

    envio.click();
}

function NotificarProcesoUpload(estado, fichero, mensaje, controlID, UrlLink) {

    var FicheroActual = document.getElementById(controlID);
    switch (estado) {
        case "1": //Insertar
        case "2": //Eliminar
            FicheroActual.innerHTML = fichero;
            if (estado == "1") {
                FicheroActual.href = UrlLink;
                reportaCambios(FicheroActual, 1);
            }
            else {
                FicheroActual.removeAttribute("href");
                reportaCambios(FicheroActual, 0);
            }
            break
        case "3":
            MostrarMensaje(mensaje, true)
            break
    }
    var row = FicheroActual.parentElement.parentElement;
    row.deleteCell(3);
}

function desbloqueo(check, elementos) {
    var i = 0
    var elem;

    if (elementos != '') {
        for (i = 0; i <= elementos.split(";").length - 2; i++) {
            elem = cnk_obtenerElemento('ctl00_ContentPlaceHolder1_panelcap_' + elementos.split(";")[i] + '');

            if (check.checked == true) {
                //habilitamos botones
                elem.disabled = false;
                elem.parentNode.disabled = false;
                elem.parentNode.style.color = 'red';
            }
            else {
                //deshabilitamos botones 
                elem.disabled = true;
                elem.parentNode.disabled = true;
                elem.parentNode.style.color = '#cccccc';
            }
        }
    }
}




