<!--
/*

    Derechos Reservados © 2007 Ernesto Spiro Peimbert Andreakis

    @archivo  cFormulario.js

    @autor    Ernesto Spiro Peimbert Andreakis

    @fecha    abril 23 2007

    @correo   spiro79@gmail.com

    @comentarios
        Clase Javascript para facilitar la implementación de candados a campos de formularios.

    INFORMACION GENERAL:

        Alonso de la Veracruz 25
        Cd. Satélite, México
        Mexico, C.P. 53100
        Cel: 0445531935844

    LICENCIA:
        Copyright ©
        This program is free software; you can redistribute it and/or
        modify it under the terms of the GNU General Public License
        as published by the Free Software Foundation; either version 2
        of the License, or (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program; if not, write to the Free Software
        Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

*/

/*
clase cFormulario
@prop        tipos_validos lista de tipos de objetos validos para la clase
@prop        alias arreglo asociativo con aliases para los tipos de objetos validos

@method      existe
@method      obtenTipoCampo
@method      tipoCampoValido
@method      registra
@method      valorCampo
@method      previeneVacio
@method      noVacio
@method      reiniciaValor
@method      desactiva
@method      activa
@method      desactivaDependiente
*/
function cFormulario () {
    //Tipos de campos válidos para la clase
    this.tipos_validos = new Array('button',
                                   'checkbox',
                                   'file',
                                   'hidden',
                                   'password',
                                   'radio',
                                   'reset',
                                   'submit',
                                   'text',
                                   'select-one',
                                   'select-multiple',
                                   'textarea');

    /*Alias para cada uno de los tipos validos.
      Deberá existir uno para cada tipo de campo valido.*/
    this.alias = new Array();
    this.alias["button"] = "boton";
    this.alias["checkbox"] = "checkbox";
    this.alias["file"] = "campo de archivo";
    this.alias["password"] = "campo de contrasena";
    this.alias["radio"] = "campo de seleccion(radios)";
    this.alias["reset"] = "boton reset";
    this.alias["submit"] = "boton de envio";
    this.alias["text"] = "campo de texto";
    this.alias["select-one"] = "combo";
    this.alias["select-multiple"] = "combo";
    this.alias["textarea"] = "area de texto";

    /*
        @fn       cFormulario.existe = function (obj,tipo,especial)
        @param    obj nombre u objeto que se quiere validar
        @param    tipo tipo de parametro que se esta proporcionando: 'string' u 'object' son los unicos aceptables
        @param    especial unicamente contiene el id del objeto, para los alerts.
        @return   boolean
        @brief    valida si el objeto existe
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.existe = function (obj,tipo,especial) {
        var regresa = true;
        if ( obj == null ) {
            switch(tipo) {
                case 'string':
                    alert('El objeto con id = ' + especial + ' no existe.\nVerificar que exista en la pagina.');
                break;
                case 'object':
                    alert('El objeto proporcionado como parametro no existe.\nVerificar que exista en la pagina.');
                break;
                default:
                    alert('Parametro no valido.\nSe esperana \'string\' u \'object\'');
                break;
            }
            regresa = false;
        }
        return regresa;
    }

    /*
        @fn       cFormulario.obtenTipoCampo = function (obj)
        @param    obj objeto
        @return   string
        @brief    determina el tipo de un objeto
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.obtenTipoCampo = function (obj) {
        var tipo = obj.type;
        return tipo;
    }

    /*
        @fn       cFormulario.tipoCampoValido = function (obj)
        @param    obj objeto
        @return   boolean
        @brief    determina si el objeto es valido para utilizarse con la clase
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.tipoCampoValido = function (obj) {
        var regresa = false;
        var i;
        var cuantos = this.tipos_validos.length;
        var tipo = this.obtenTipoCampo(obj);
        for ( i = 0; i < cuantos; i++ ) {
            if ( tipo == this.tipos_validos[i] ) {
                regresa = true;
                break;
            }
        }
        if ( !regresa ) {
            alert('El campo \'' + obj.id + '\' no es valido para obtener su valor.\nVerifique.');
            regresa = false;
        }
        return regresa;
    }

    /*
        @fn       cFormulario.registra = function (obj)
        @param    obj objeto
        @return   boolean
        @brief    metodo inicial - valida y prepara el objeto
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.registra = function(obj) {
        var tipo = typeof(obj);
        var el_objeto;
        var regresa = true;
        switch ( tipo ) {
            case 'string':
                el_objeto = document.getElementById(obj);
                regresa = el_objeto;
                break;
            case 'object':
                el_objeto = obj;
                regresa = el_objeto;
                break;
            default:
                alert('Parametro NO valido.\nSe esperaba string u object.');
                regresa = false;
                break;
        }
        if ( !this.existe(el_objeto,tipo,obj) && regresa != false) {
            regresa = false;
        }
        return regresa;
    }

    /*
        @fn       cFormulario.valorCampo = function (obj)
        @param    obj objeto o id de objeto
        @return   string - valor del elemento
        @brief    obtiene el valor de cualquiercampo de formulario
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.valorCampo = function (objeto) {
        obj = this.registra(objeto);
        var regresa = "";
        if ( obj != false ) {
            if ( this.tipoCampoValido(obj) ) {
                var tipo = this.obtenTipoCampo(obj);
                switch(tipo) {
                    case 'text':
                    case 'textarea':
                    case 'button':
                    case 'submit':
                    case 'password':
                    case 'hidden':
                    case 'reset':
                    case 'file':
                        /*if ( tipo == 'file' ) {
                            alert('El valor de un ' + this.alias[tipo] + ' solo contiene la cadena de texto de la ruta al archivo.');
                        }*/
                        regresa = obj.value;
                    break;
                    case 'radio':
                        var nombre = obj.name;
                        var arreglo_valores = document.getElementsByName(nombre);
                        var cantidad = arreglo_valores.length;
                        var i;
                        for ( i = 0; i < cantidad; i++ ) {
                            if ( arreglo_valores[i].checked ) {
                                regresa = arreglo_valores[i].value;
                                break;
                            }
                        }
                    break;
                    case 'checkbox':
                        if ( obj.checked ) {
                            if ( obj.value ) {
                                regresa = obj.value;
                            }
                            else {
                                regresa = '1';
                            }
                        }
                        else {
                            regresa = '';
                        }
                    break;
                    case 'select-one':
                        if ( obj.options.length > 0 ) {
                            if ( obj.selectedIndex > -1 ) {
                                regresa = obj.options[obj.selectedIndex].value;
                            }
                        }
                    break;
                    case 'select-multiple':
                        if ( obj.options.length > 0 ) {
                            if ( obj.selectedIndex > -1 ) {
                                var arr_valores = new Array();
                                var arr_indices = new Array();
                                while ( obj.selectedIndex > -1 ) {
                                    arr_valores.push(obj.options[obj.selectedIndex].value);
                                    arr_indices.push(obj.selectedIndex);
                                    obj.options[obj.selectedIndex].selected = false;
                                }
                                while ( arr_indices.length > 0 ) {
                                    obj.options[arr_indices.pop()].selected = true;
                                }
                                regresa = arr_valores.toString();
                            }
                        }
                    break;
                }
            }
        }
        return regresa;
    }

    /*
        @fn       cFormulario.previeneVacio = function (obj)
        @param    obj objeto o id de objeto
        @return   -
        @brief    avisa si un objeto que no debe ir vacio se encuentra vacio
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.previeneVacio = function (obj) {
        var el_objeto = this.registra(obj);
        if ( el_objeto != false ) {
            var primera_parte = "";
            var ultima_parte = "";
            var tipo_campo = this.obtenTipoCampo(el_objeto);
            var evento = 'blur';
            //alert('para el objeto:'+el_objeto.id+' el tipo es:'+tipo_campo);
            if ( tipo_campo == 'select-one' || tipo_campo == 'select-multiple' ) {
                evento = 'change';
            }
            if ( el_objeto.attachEvent ) {
                primera_parte = "el_objeto.attachEvent( 'on" + evento + "',";
                ultima_parte = ");";
            }
            else {
                primera_parte = "el_objeto.addEventListener( '" + evento + "',";
                ultima_parte = ",false );";
            }
            var la_funcion = "";
            la_funcion += primera_parte;
            la_funcion += "function () {";
            la_funcion += "    var objeto_" + el_objeto.id + " = new cFormulario;";
            la_funcion += "    var valor = objeto_" + el_objeto.id + ".valorCampo(document.getElementById('" + el_objeto.id + "'));";
            la_funcion += "    if ( valor == '' ) {";
            la_funcion += "        alert('AVISO: El " + this.alias[this.obtenTipoCampo(el_objeto)] + " no puede ir vacio.');";
            la_funcion += "        document.getElementById('" + el_objeto.id + "').style.backgroundColor = 'red';";
            la_funcion += "    }";
            la_funcion += "    else {";
            la_funcion += "        document.getElementById('" + el_objeto.id + "').style.backgroundColor = null;";
            la_funcion += "    }";
            la_funcion += "}";
            la_funcion += ultima_parte;
            eval(la_funcion);
        }
    }

    /*
        @fn       cFormulario.noVacio = function (obj)
        @param    obj objeto o id de objeto
        @return   -
        @brief    implementa el metodo previeneVacio en cualquier objeto de formulario
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.noVacio = function (obj) {
        var el_objeto = this.registra(obj);
        if ( el_objeto != false ) {
            var tipo = this.obtenTipoCampo(el_objeto);
            switch ( tipo ) {
                case 'radio':
                    var arreglo_elementos = document.getElementsByName(el_objeto.name);
                    var cuantos = arreglo_elementos.length;
                    var i;
                    for ( i = 0; i < cuantos; i++ ) {
                        this.previeneVacio(arreglo_elementos[i]);
                    }
                break;
                default:
                    this.previeneVacio(el_objeto);
                break;
            }
        }
    }

    /*
        @fn       cFormulario.reiniciaValor = function (objeto)
        @param    objeto objeto o id de objeto
        @return   boolean
        @brief    reinicia el valor de un objeto poniendolo a cero
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.reiniciaValor = function (objeto) {
        obj = this.registra(objeto);
        if ( obj != false ) {
            if ( this.tipoCampoValido(obj) ) {
                var tipo = this.obtenTipoCampo(obj);
                switch(tipo) {
                    case 'text':
                    case 'textarea':
                    case 'button':
                    case 'submit':
                    case 'password':
                    case 'hidden':
                    case 'reset':
                    case 'file':
                        obj.value = "";
                    break;
                    case 'radio':
                        var nombre = obj.name;
                        var arreglo_valores = document.getElementsByName(nombre);
                        var cantidad = arreglo_valores.length;
                        var i;
                        for ( i = 0; i < cantidad; i++ ) {
                            if ( arreglo_valores[i].checked ) {
                                arreglo_valores[i].checked = false;
                                break;
                            }
                        }
                    break;
                    case 'checkbox':
                        if ( obj.checked ) {
                            obj.checked = false
                        }
                    break;
                    case 'select-one':
                    case 'select-multiple':
                        if ( obj.options.length > 0 ) {
                            if ( obj.selectedIndex > -1 ) {
                                obj.selectedIndex = -1;
                            }
                        }
                    break;
                }
            }
        }
    }

    /*
        @fn       cFormulario.desactiva = function (obj)
        @param    obj objeto o id de objeto
        @return   -
        @brief    desactiva un objeto reinicializando su valor
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.desactiva = function (obj) {
        var el_objeto = this.registra(obj);
        if ( el_objeto != false ) {
            var tipo = this.obtenTipoCampo(el_objeto);
            switch ( tipo ) {
                case 'radio':
                    var arreglo_elementos = document.getElementsByName(el_objeto.name);
                    var cuantos = arreglo_elementos.length;
                    var i;
                    for ( i = 0; i < cuantos; i++ ) {
                        arreglo_elementos[i].disabled = true;
                    }
                break;
                default:
                    el_objeto.disabled = true;
                break;
            }
            this.reiniciaValor(el_objeto);
        }
    }

    /*
        @fn       cFormulario.activa = function (obj)
        @param    obj objeto o id de objeto
        @return   -
        @brief    activa un objeto de formulario
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.activa = function (obj) {
        var el_objeto = this.registra(obj);
        if ( el_objeto != false ) {
            var tipo = this.obtenTipoCampo(el_objeto);
            switch ( tipo ) {
                case 'radio':
                    var arreglo_elementos = document.getElementsByName(el_objeto.name);
                    var cuantos = arreglo_elementos.length;
                    var i;
                    for ( i = 0; i < cuantos; i++ ) {
                        arreglo_elementos[i].disabled = false;
                    }
                break;
                default:
                    el_objeto.disabled = false;
                break;
            }
        }
    }

    /*
        @fn       cFormulario.desactivaDependiente = function (objeto_independiente, valores, objeto_dependiente)
        @param    obj_independiente objeto o id de objeto
        @param    valores lista de valores donde el objeto_dependiente se desactiva
        @param    obj_dependiente objeto o id de objeto
        @return   -
        @brief    desactiva un objeto dependiendo de los valores que tenga el objeto_independiente
        @author   Ernesto Spiro Peimbert Andreakis
        @date     22 abril 2007
    */
    this.desactivaDependiente = function (objeto_independiente, valores, objeto_dependiente) {
        var el_objeto1 = this.registra(objeto_independiente);
        if ( el_objeto1 != false ) {
            var el_objeto2 = this.registra(objeto_dependiente);
            if ( el_objeto2 != false ) {
                var primera_parte = "";
                var ultima_parte = "";
                var tipo_campo = this.obtenTipoCampo(el_objeto1);
                var evento = 'blur';
                //alert('para el objeto:'+el_objeto1.id+' el tipo es:'+tipo_campo);
                if ( tipo_campo == 'select-one' || tipo_campo == 'select-multiple' ) {
                    evento = 'change';
                }
                if ( el_objeto1.attachEvent ) {
                    primera_parte = "el_objeto1.attachEvent( 'on" + evento + "',";
                    ultima_parte = ");";
                }
                else {
                    primera_parte = "el_objeto1.addEventListener( '" + evento + "',";
                    ultima_parte = ",false );";
                }
                var la_funcion = "";
                la_funcion += primera_parte;
                la_funcion += "function () {";
                la_funcion += "    var valores = '" + valores + "';";
                la_funcion += "    var arr_valores = valores.split(',');";
                la_funcion += "    var cuantos = arr_valores.length;";
                la_funcion += "    var bandera = false;";
                la_funcion += "    var bandera_arreglo_valores = false;";
                la_funcion += "    var oObj_" + el_objeto1.id + " = new cFormulario;";
                la_funcion += "    var valor = oObj_" + el_objeto1.id + ".valorCampo('" + el_objeto1.id + "');";
                la_funcion += "    var i;";
                la_funcion += "    if ( oObj_" + el_objeto1.id + ".obtenTipoCampo(document.getElementById('" + el_objeto1.id + "')) == 'select-multiple' ) {";
                la_funcion += "        bandera_arreglo_valores = true;";
                la_funcion += "    }";
                la_funcion += "    if ( bandera_arreglo_valores ) {";
                la_funcion += "        valor = valor.split(',');"
                la_funcion += "    }";
                la_funcion += "    if ( !bandera_arreglo_valores ) {";
                la_funcion += "        for ( i = 0; i < cuantos; i++ ) {";
                la_funcion += "            if ( arr_valores[i] == valor ) {";
                la_funcion += "                bandera = true;";
                la_funcion += "                break;";
                la_funcion += "            }";
                la_funcion += "        }";
                la_funcion += "    }";
                la_funcion += "    else {";
                la_funcion += "        var j;";
                la_funcion += "        for ( i = 0; i < cuantos; i++ ) {";
                la_funcion += "            for ( j = 0; j < valor.length; j++ ) {";
                la_funcion += "                if ( arr_valores[i] == valor[j] ) {";
                la_funcion += "                    bandera = true;";
                la_funcion += "                    break;";
                la_funcion += "                }";
                la_funcion += "            }";
                la_funcion += "            if ( bandera ) {";
                la_funcion += "                break;";
                la_funcion += "            }";
                la_funcion += "        }";
                la_funcion += "    }";
                la_funcion += "    if ( bandera ) {";
                la_funcion += "        oObj_" + el_objeto1.id + ".desactiva( '" + el_objeto2.id + "');";
                la_funcion += "    }";
                la_funcion += "    else {";
                la_funcion += "        oObj_" + el_objeto1.id + ".activa( '" + el_objeto2.id + "');";
                la_funcion += "    }";
                la_funcion += "}";
                la_funcion += ultima_parte;
                eval(la_funcion);
            }
        }
    }
}
-->
