/* This array stores the current displays on this page.
 * Each display is an array itself that stores the following data:
 * display[0] : The name of the display
 * display[1] : The interval id gotten from setInterval for the display
 * display[2] : The current progress identified by a string. p.e. "|||||"
 * display[3] : The current innerHTML of process area. The innerHTML on process
 *              area changes when a response arrives.
*/
var displays = new Array();

/* This is the time in milliseconds for all displays to update its progress bar
 */
var maxTime = 200;

/* This is the text to show when an error ...?
 */
var divText;

/* This is the array of params we always need to send to server upon get requests
 */
var params = new Array();

/* En este arreglo se guardan los elementos del formulario que han sido validados así:
 * En elementosvalidados[0]: se almacena el identificador (nombre) del elemento
 * En elementosvalidados[1]: se almacena el rotulo del elemento para identificarlo en pantalla.
 * En elementosvalidados[2]: se almacena ('si'/'no') dependiendo de si el elemento fue validado correctamente o no
 * En elementosvalidados[3]: se almacena una referencia al objeto "element" en sí mismo
*/
var elementosvalidados = new Array();

function onAnchorClick(display) {
    try {
        //Start progress on bar on display
        startProgressBar(display);
    } catch(exception) {
        //Stop progress bar
        var i;
        for(i = 0; i < displays.length; i++) {
            if(displays[i][0] == display) {
                break;
            }
        }
        clearInterval(displays[i][1]);
        throw exception;
    }
}
function doBack(display) {
}
/* Gets the given url and displays its content on display
 */
function doGet(url, display) {
    try {
        //Start progress on bar on display
        startProgressBar(display);
        
        //Expand url with standar parameters
        if(url.indexOf('/portalserver/servlet/', 0) >= 0) {
            var i;
            for(i = 0; i < params.length; i++) {
                url += '&' + params[i]
            }
        }
        
        //Get the url on process area associated with display
        getProcessDoc(display).location.replace(url);
    } catch(exception) {
        //Stop progress bar
        var i;
        for(i = 0; i < displays.length; i++) {
            if(displays[i][0] == display) {
                break;
            }
        }
        clearInterval(displays[i][1]);
        throw exception;
    }
}

/* This posts a form and gets its response on display
 *
 */
function doPost(f, display) {
    var formId, processDoc, i;

    try {
        //Is this form ok to submit?
        if(!validarFormulario(f)) {
            return false;
        }
        
        //If this form has SELECT elements, we put all the selected items in the
        //form value1|value2|value3...
        var i = 0;
        var name = '';
        var value= '';
        for(i = 0; i < f.elements.length; i++) {
            if(f.elements[i].type == 'select-multiple') {
                var e = f.elements[i];
                name = e.name;
                value = '';
                for(var j = 0; j < e.length; j++) {
                    if(e.options[j].selected) {
                        value += e.options[j].value + '|';
                    }
                }
                //setParam(name + '=' + value) ;
                e.name = 'back_' + e.name;
            }
        }
        
        //Sets the current display to receive the response and add all parameteres
        f.action += '?display=' + display;
        for(i = 0; i < params.length; i++) {
            f.action += '&' + params[i]
        }
        
        //This are the SELECT values
        if(name != '') {
            f.action += '&' + name + '=' + value;
        }

        //f.method = 'post';
        f.target = 'ptk_process' + display;
        f.submit();
        
        /*
        //Get the id of the form object 
        formId = f.getAttribute("id");
    
        //Empty process area
        processDoc = getProcessDoc(display);
        while(processDoc.body.hasChildNodes()) {
            processDoc.body.removeChild(processDoc.body.lastChild);
        }
        
        //Clone form object to process area
        //var newForm = clone(formId, display);
        //processDoc.body.appendChild(newForm);
        var newForm = new String(document.getElementById(formId).parentNode.innerHTML);
        processDoc.body.innerHTML = newForm;
        
        //Copy values from cloned form: formId
        formulario = processDoc.getElementById(formId);
        for(i = 0; i < formulario.elements.length; i++) {
            if( formulario.elements[i].type == 'button' ||
                formulario.elements[i].type == 'reset' ||
                formulario.elements[i].type == 'submit' ||
                formulario.elements[i].type == 'checkbox') {
                continue;
            }
            var elementName = formulario.elements[i].name;
            if(elementName == 'display') continue;
            formulario.elements[elementName].value = document.getElementById(formId).elements[elementName].value;
        }
    
        //Submit form
        formulario.action += '?display=' + display;
        formulario.method = 'post';
        formulario.target = 'ptk_process' + display;
        formulario.submit();
        */
        //Start progress bar. Be carefull invoking this method replaces the
        //display content so we put this at bottom.
        startProgressBar(display);
    } catch(exception) {
        //Stop progress bar
        for(i = 0; i < displays.length; i++) {
            if(displays[i][0] == display) {
                break;
            }
        }
        clearInterval(displays[i][1]);
        throw exception;
    }
}

/*
 *
 */
function setParam(param) {
    params[params.length] = param;
}
/*
 *
 */
function setResponse(display) {
    var i;
    try {
        //Stop progress bar
        for(i = 0; i < displays.length; i++) {
            if(displays[i][0] == display) {
                break;
            }
        }
        clearInterval(displays[i][1]);
        displays[i][3] = getProcessDoc(display).body.innerHTML;
        document.getElementById('ptk_display' + display).innerHTML = displays[i][3];
    } catch(exception) {
        clearInterval(displays[i][1]);
        document.getElementById('ptk_display' + display).innerText = divText;
        throw exception;
    }
}

/*
 *
 */
function startProgressBar(display) {
    var timerCounter = '|';
    var func = 'updateProgress(\'' + display + '\')';
    var processDoc = getProcessDoc(display);
    
    //Is this display already created?
    var bFound = false;
    var i;
    for(i = 0; i < displays.length; i++) {
        if(displays[i][0] == display) {
            bFound = true;
            break;
        }
    }
     
    if(!bFound) {
        //Start progress bar.on the new display
        displays[displays.length] = new Array(display, setInterval(func, maxTime), timerCounter, '');
    } else {
        //Start progress bar.
        displays[i][1] = setInterval(func, maxTime);
        displays[i][2] = timerCounter;
    }
}

/*
 *
 */
function updateProgress(display) {
    var i;
    for(i = 0; i < displays.length; i++) {
        if(displays[i][0] == display) {
            break;
        }
    }
    
    document.getElementById('ptk_display' + display).innerHTML = '<div id="ptk_progress_bar" name="ptk_progress_bar" style="width: 100%; border: 1px solid Black; padding : 1px 1px 1px 1px;">' + displays[i][2] + '</div>';
    displays[i][2] += '|';
}

/*
 *
 */
function getProcessDoc(display) {
    var ptk_processObj;
    var ptk_processDoc;
    
    //This is for IE5.5+, IE6, NS6
    ptk_processObj = document.getElementById('ptk_process' + display);

    //This is for IE5 Mac
    if(document.frames) {
        ptk_processObj = document.frames['ptk_process' + display];
    }

    if(ptk_processObj.contentDocument) {
        // For NS6
        ptk_processDoc = ptk_processObj.contentDocument;
    } else if(ptk_processObj.contentWindow) {
        // For IE5.5 and IE6
        ptk_processDoc = ptk_processObj.contentWindow.document;
    } else if(ptk_processObj.document) {
        // For IE5
        ptk_processDoc = ptk_processObj.document;
    }
    
    return ptk_processDoc;
}

/* Esta funcion hace una copia del elemento identificado por id en el documento cargado
 * en el frame ptk_display, al documento cargado en ptk_process.
 */
function clone(id, display) {
    //Crear el nodo inicial en process con el correspondiente en
    //display identificado por id
    var displayNode = document.getElementById(id);
    var processNode = getProcessDoc(display).createElement(displayNode.nodeName);
    var i = 0;
    for(i = 0; i < displayNode.attributes.length; i++) {
        processNode.setAttribute(displayNode.attributes.item(i).nodeName, displayNode.attributes.item(i).nodeValue);
    }
    
    //Adicionar un nodo para informar al servidor el display que debe usar
    //especificar cuando genere la respuesta
    var newNode;
    newNode = getProcessDoc(display).createElement("input");
    newNode.setAttribute('type', 'hidden');
    newNode.setAttribute('id', 'display');
    newNode.setAttribute('name', 'display');
    newNode.setAttribute('value', display);
    processNode.appendChild(newNode);

    //Ahora crear el subarbol de nodos hijos de displayNode
    cloneNode(processNode, displayNode, display);
    return processNode;
}

/*
 *
 */
function cloneNode(processNode, displayNode, display) {
    var children = displayNode.childNodes;
    var newNode;
    var i;
    var create;
    for(i = 0; i < children.length; i++) {
        create = false;
        var oldNode = children.item(i);
        if(oldNode.nodeType == 1) {//ELEMENT_NODE
            newNode = getProcessDoc(display).createElement(oldNode.nodeName)
            create = true;
        }

        if(create) {
            var j;
            for(j = 0; j < oldNode.attributes.length; j++) {
                newNode.setAttribute(oldNode.attributes.item(j).nodeName, oldNode.attributes.item(j).nodeValue);
            }

            cloneNode(newNode, oldNode, display);
            processNode.appendChild(newNode);
        }
    }
}

/* Funciones de validación
*/
function parseUnicode(str) {
    ret = '';
    chars = 'áéíóúÁÉÍÓÚ\'"<>&';
    var i = 0;
    var j = 0;
    while(i < str.length) {
        var found = false;
        //Mac OS
        if(str.charAt(i) == '\r' && str.charAt(i+1) != '\n') {
            ret += '&#13;&#10;';
            i++;
            continue;
        }
        //Unix
        if(str.charAt(i) == '\n' && str.charAt(i-1) != '\r') {
            ret += '&#13;&#10;';
            i++;
            continue;
        }
        //Windows
        if(str.charAt(i) == '\r' && str.charAt(i+1) == '\n') {
            ret += '&#13;&#10;';
            i += 2;
            continue;
        }
        for(j = 0; j < chars.length; j++) {
            if(str.charAt(i) == chars.charAt(j)) {
                found = true;
                break;
            }
        }
        if(found) {
            ret += '&#' + str.charCodeAt(i) + ';';
        } else {
            ret += str.charAt(i);
        }
        i++;
    }
    
    return ret;
}
function validaAlfabetico(e, rotulo) {
    var alfabe = /^[^0123456789]*$/
    var valido = 'no';
    if(alfabe.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si';
    }
    addToElementosValidados(e, rotulo, valido);
}
function validaCorreoe(e, rotulo) {
    var mail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+\s*$/
    var valido = 'no'
    if(mail.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaAlfanumerico(e, rotulo) {
	var alfanum = /^([^"<'&>])+$/
    var valido = 'no'
    if(alfanum.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaNumerico(e, rotulo) {
    var numero = /^(\s?)(\d+)(\s?)$/
    var valido = 'no'
    if(numero.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaTexto(e, rotulo) {
    var txt = /^([^"<'&>])+$/
    var valido = 'no'
    if(txt.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaSeleccion(e, rotulo) {
    var valido = 'no'
    var size = document.getElementById(e.name).getAttribute('size')
    if(e.selectedIndex != 0 && size == '') {
        valido = 'si'
    } else if(e.selectedIndex != -1 && size != '') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaUrl(e, rotulo) {
    var url = /^(http:\/|ftp:\/|gopher:\/|mailto:|news:|telnet:\/|www.)\S?[\/]*\S*\s*$/
    var valido = 'no'
    if(url.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaImagen(e, rotulo) {
    var imagen = /^\w+\.(gif|jpg)\s*$/i
    var valido = 'no'
    if(imagen.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaFecha(e, rotulo) {
    var fecha = /^(01|02|03|04|05|06|07|08|09|10|11|12)[\/](01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)[\/](\d{4})\s*$/
    var valido = 'no'
    if(fecha.test(e.value)) {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaTiempo(e, rotulo) {
    var time = /^(01|02|03|04|05|06|07|08|09|10|11|12)[\/](01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)[\/](\d{4})\s(1|01|2|02|3|03|4|04|5|05|6|06|7|07|8|08|9|09|10|11|12)[:](00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59)\s(am|pm)\s*$/
    var valido = 'no'
    if(time.test(e.value)) {
        valido = 'si'
    }
    addToElementosValidados(e, rotulo, valido)
}
function validaPassword(e, rotulo) {
    var pass = /^([^"<'&>])+$/
    var valido = 'no';
    if(pass.test(e.value) && validaCaracteresEspeciales(e) == 'si') {
        valido = 'si';
    }
    addToElementosValidados(e, rotulo, valido);
}
function validaCaracteresEspeciales(e){
//    e.value = parseUnicode(e.value);
//    return 'si';
    
    var valido = 'si'
    var caracteresE = "&'<>\"";
    var validar = e.value;
    for (i = 0;  i < validar.length;  i++){
        var str = validar.charAt(i);
        for (j = 0;  j < caracteresE.length; j++){
            if(str == caracteresE.charAt(j)){
                valido = 'no'
                break
            }
        }
        if(valido == 'no') {
            break
        }
    }
    return valido
    
}
function addToElementosValidados(elemento, rotulo, valido) {
    var i = 0
    for(i = 0; i < elementosvalidados.length; i++) {
        if(elementosvalidados[i][0] == elemento.name) {
            elementosvalidados[i][2] = valido
            return
        }
    }
    elementosvalidados[elementosvalidados.length] = new Array(elemento.name, rotulo, valido, elemento);
}

/* Validates a form
 *
 */
function validarFormulario(formulario) {
    var i = 0
    for(i = 0; i < formulario.elements.length; i++) {
        if( formulario.elements[i].type == 'button' ||
            formulario.elements[i].type == 'reset' ||
            formulario.elements[i].type == 'submit' ||
            formulario.elements[i].type == 'checkbox' ||
            formulario.elements[i].type == 'hidden') {
            continue;
        }
        
        var elemento = formulario.elements[i]
        var clase = document.getElementById(elemento.name).getAttribute('clase')
        var title = document.getElementById(elemento.name).getAttribute('title')
        if(clase == 'seleccion') {
            validaSeleccion(elemento, title)
        } else if(clase == 'alfabetico') {
            validaAlfabetico(elemento, title)
        } else if(clase == 'correoe') {
            validaCorreoe(elemento, title)
        } else if(clase == 'texto') {
            validaTexto(elemento, title)
        } else if(clase == 'numerico') {
            validaNumerico(elemento, title)
        } else if(clase == 'alfanumerico') {
            validaAlfanumerico(elemento, title)
        } else if(clase == 'imagen') {
            validaImagen(elemento, title)
        } else if(clase == 'url') {
            validaUrl(elemento, title)
        } else if(clase == 'fecha') {
            validaFecha(elemento, title)
        } else if(clase == 'tiempo') {
            validaTiempo(elemento, title)
        } else if(clase == 'password') {
            validaPassword(elemento, title)
        }
    }

    //Presentar la lista de campos requeridos que no han sido diligenciados
    
    //Indica si todos los campos fueron validados correctamente
    var todosOk = true
    
    //El primer elemento al que se le debe dar foco si la validación falla
    var focusIt
    
    //Indica si ya se tiene por lo menos un elemento no valido que debe tener el foco
    var hasFocus = false
    
    //El mensaje que ve el usuario de los campo requeridos.
    var mensaje = 'Los siguientes campos son requeridos: \n'
    
    for(var j = 0; j < elementosvalidados.length; j++) {
        var elemento = elementosvalidados[j][3]
        var requerido = document.getElementById(elemento.name).getAttribute('requerido')
        if(requerido == 'si' && elemento.value == '') {
            todosOk = false
            mensaje += elementosvalidados[j][1] + '\n'
            if(!hasFocus) {
                focusIt = elemento
                hasFocus = true
            }
        }
    }
    if(!todosOk) {
        focusIt.focus()
        alert(mensaje);
        return false
    }

    //Verificar que los campos diligenciados estén en el formato correcto
    for(var j = 0; j < elementosvalidados.length; j++) {
        var elemento = elementosvalidados[j][3]
        var requerido = document.getElementById(elemento.name).getAttribute('requerido')
        if(elemento.value != '') {
            if(elementosvalidados[j][2] == 'no') {
                alert('Revise el campo: ' + elementosvalidados[j][1] + '. Escriba el formato adecuado si es una dirección de correo o una fecha.');
                elemento.focus()
                return false;
            }
        }
    }
    
    //All Right, so we replace by Unicode
    for(i = 0; i < formulario.elements.length; i++) {
        if( formulario.elements[i].type == 'button' ||
            formulario.elements[i].type == 'reset' ||
            formulario.elements[i].type == 'submit' ||
            formulario.elements[i].type == 'checkbox' ||
            formulario.elements[i].type == 'hidden') {
            continue;
        }
        
        var elemento = formulario.elements[i]
        elemento.value = parseUnicode(elemento.value);
    }
    
    //OJO: Es necesario desplazar la ventana a su origen
    window.scrollTo(0, 0)
    
    elementosvalidados.length = 0;
    return true;
}
