/**
 * Max length of a jcLongDescription field.
 */
var JC_LONG_DESCRIPTION_LENGTH = 3900;

	/**Constantes para el uso de la funcion displayTool*/
	var TOP_LVL = 1;
	var BOTTOM_LVL =2;

	/**
	 * Despliega el ToolTipText
	 * @param event evento que dispara la funcion.
	 * @param saMessage el mensaje de a mostrar
	 */
	function displayTool( event, saMessage){
		document.getElementById('toolTipText').innerHTML = '<table  cellspacing="0" cellpadding="0"><tr><td class="toolTip">' + saMessage + '</td></tr></table>';
		document.getElementById('toolTipText').style.visibility='visible';
		document.getElementById('toolTipText').style.top  =  event.clientY;
		document.getElementById('toolTipText').style.left =  event.clientX;
	}

	/**
	 * Despliega el ToolTipText con las coordenada X especificada.
     * @param event evento que dispara la funcion.
     * @param saMessage el mensaje de a mostrar
	 * @param iaX Coordenada X, donde debe de aparecer el mensaje.
	 */
	function displayToolX(event, saMessage, iaX ){
		document.all["toolTipText"].innerHTML = '<table  cellspacing="0" cellpadding="0"><tr><td class="toolTip">' + saMessage + '</td></tr></table>';		
		document.all["toolTipText"].style.visibility="visible";
        document.all["toolTipText"].style.top  =  event.clientY;
		document.all["toolTipText"].style.left =  iaX;
	}

	function displayToolY(event, saMessage, iaY){
		document.all["toolTipText"].innerHTML = '<table  cellspacing="0" cellpadding="0"><tr><td class="toolTip">' + saMessage + '</td></tr></table>';		
		document.all["toolTipText"].style.visibility="visible";
        document.all["toolTipText"].style.top  =  iaY;
		document.all["toolTipText"].style.left =  event.clientX;
	}

	/**
	 * Obtiene la coordenada de izquierda del Objeto enviado
	 */
	function getOffsetLeft (el) {
    	var ol = el.offsetLeft;
	    while ((el = el.offsetParent) != null)
    	    ol += el.offsetLeft;
	    return ol;
	}
	
	/*
	 * Obtiene la coordenada de arriba del Objeto enviado
	 */	
	function getOffsetTop (el) {
    	var ot = el.offsetTop;
	    while((el = el.offsetParent) != null)
	        ot += el.offsetTop;
    	return ot;
	}
	
	/*
	 * Esconde el tool tip Text
	 */	
	function hideTool(){
		document.all["toolTipText"].style.visibility="hidden";	
	}		
	
	function changeColor(){
		document.all["letter" + iLayer].style.color=my_color[iCounter];
		if(iCounter==0){
			document.all["letter" + iLayer].style.visibility="visible";
		}
		if(iCounter==12){
			document.all["letter" + iLayer].style.visibility="hidden";
			iCounter = 0;
			if(iLayer==9){
				iLayer=1
			} else {
				iLayer++;
			}
		} else {
			iCounter++;
		}
		setTimeout("changeColor()", 150);
	}
	

	function allowNumbers(){
		if (event.keyCode < 48 || event.keyCode > 57) {
			event.returnValue = false;
		}
	}
	
	function allowDecimalNumbers(numbers, decimals, mask, txtObject){
		oText = window.event.srcElement;
		if(txtObject != undefined){
			oText = txtValueOrder;
		}

		blReturnValue = true;
		if (txtObject==undefined && ((event.keyCode < 45 || event.keyCode > 57) && event.keyCode != 46)) {
			blReturnValue = false;
		}
		fieldValue = oText.value+(txtObject==undefined?String.fromCharCode(event.keyCode):"");

		if (isNaN(fieldValue)) {
			blReturnValue = false;
		}else {
			if(fieldValue.indexOf('.')!=-1){
                var newRange = document.selection.createRange();
                var allRange = event.srcElement.createTextRange();
                var dotRange = allRange.duplicate();
                dotRange.moveEnd("character",-(oText.value.length));
                dotRange.moveStart("character", oText.value.indexOf("."));
                dotRange.moveEnd("character", oText.value.indexOf("."));
                var where = newRange.compareEndPoints("StartToStart",dotRange);
                if (where > 0) {
                    fieldValue = oText.value+(txtObject==undefined?String.fromCharCode(event.keyCode):"");

                } else {
                    fieldValue = String.fromCharCode(event.keyCode) + oText.value;
                }
				dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
				if (dectext.length > decimals ||
					fieldValue.indexOf('.') != fieldValue.lastIndexOf('.')){
					blReturnValue =false;
				}
			}
			ilEnd = fieldValue.length;
			if(fieldValue.indexOf('.')!=-1){
				ilEnd = fieldValue.indexOf('.');
			}
			dectext = fieldValue.substring(0, ilEnd);
			if(dectext.length > numbers){
				blReturnValue =false;
			}
			if (parseFloat(fieldValue) > parseFloat(mask) ){
				blReturnValue = false;
			}
		}
		event.returnValue = blReturnValue;

		return blReturnValue;
	}

var validationField = null;

function allowDecimalNumbersOnPaste(numbers, decimals, srcElement) {
	var reg = eval("/^\\d{0,"+numbers+"}(\\.\\d{0,"+decimals+"})?$/");
/*
	alert(event.srcElement.value + "\n" +
		reg.test(event.srcElement.value) + "\n" +
		event.srcElement.value.match(reg));
*/
    if (srcElement == null) {
        if (event != null) {
            srcElement = event.srcElement;
        } else {
            return;
        }
    }
	if (srcElement.value != "" && !reg.test(srcElement.value)) {
		var numberTest = new NumberFormat(srcElement.value);
		numberTest.setCurrency(false);
		numberTest.setCommas(false);
		numberTest.setPlaces(decimals);
		srcElement.value = numberTest.toFormatted();
//		alert(srcElement.value);
		if (!reg.test(srcElement.value)) {
			var arrSplit = srcElement.value.split('.');
			var numbersValue = arrSplit.length > 0 && arrSplit[0] != null ? arrSplit[0] : "";
			var decimalsValue = arrSplit.length > 1 && arrSplit[1] != null ? arrSplit[1] : "";
			if (numbersValue.length > numbers) {
				numbersValue = numbersValue.substring(0, numbers);
			}
			if (decimalsValue.length > decimals) {
				decimalsValue = decimalsValue.substring(0, decimals);
			}
			srcElement.value = numbersValue + (decimalsValue.length > 0 ? "." + decimalsValue: "");
//			alert(event.srcElement.value);
		}
	}
}


    /**
     * Validate a number field have the specified number of literals and decimals.
     * (does not validate the value type)
     */
        function restrictDecimals(field, inNumbers, inDecimal){
        //alert(field.value);
        var toReturn = field.value;
        var string = field.value;
        var pointIndex = string.indexOf('.');
        //alert(pointIndex);
        //validate decimals
        //alert('toReturn.charAt(inNumbers+1):'+toReturn.charAt(inNumbers));
        if(pointIndex!=-1){
            var arr = string.split(".");
            var decimals = arr[1];
            var numberRecibed = arr[0];
            //alert('decimals:'+decimals);
            if(decimals.length > inDecimal)
            {
                decimals = decimals.substring(0, inDecimal);
                //alert('decimal subst:'+decimals);
                toReturn = numberRecibed + '.' + decimals;
            }
            if(numberRecibed.length > inNumbers){
                numberRecibed = numberRecibed.substring(0, inNumbers);
                toReturn = numberRecibed + '.' + decimals;
            }
            
        }else{
            if(toReturn.length > inNumbers && toReturn.charAt(inNumbers+1) != '.'){
                toReturn = toReturn.substring(0, inNumbers);
            }else{
                toReturn = string;  
            }
                
        }
        
        field.value = toReturn;
    }


	function formatDecimalNumber(decimals){
	    if (event.srcElement.value != "") {
            var numberTest = new NumberFormat(event.srcElement.value);
            numberTest.setCurrency(false);
            numberTest.setCommas(false);
            numberTest.setPlaces(decimals);
            event.srcElement.value = numberTest.toFormatted();
        }
	}

    function allowNumbersAndDot() {
        if (event.srcElement.value.indexOf(".") != -1 && event.keyCode == 46) {
            event.returnValue = false;
            return false;
        }
        if ((event.keyCode < 46 || event.keyCode > 57) && event.keyCode != 46) {
            event.returnValue = false;
            return false;
        }
    }


	function allowLetters(){
		allowFreeText();
	}

	function allowLettersAndNumbers(){
		allowFreeText();
	}

/*
	function allowFreeText (){
            if (
            (event.keyCode < 32 && event.keyCode != 10 && event.keyCode != 13) ||   //Control chars except LF and CR
            (event.keyCode == 39) ||    // '
            (event.keyCode == 60) ||    // <
            (event.keyCode == 62) ||    // >
            (event.keyCode > 126 && event.keyCode < 192) ||  //allows spanish and french chars
			(event.keyCode > 255)
             )
                event.returnValue = false;
	}
*/
	function allowFreeText (textarea){
	    //window.status = event.keyCode;
			if (
				(event.keyCode < 32 && event.keyCode != 10 && event.keyCode != 13) ||   //Control chars except LF and CR
				(event.keyCode > 38 && event.keyCode < 40) || /* !$ enabled, requested by user */
				(event.keyCode > 90 && event.keyCode < 94) ||
				(event.keyCode > 94 && event.keyCode < 97) ||
				(event.keyCode > 122 && event.keyCode < 127)  ||
				(event.keyCode == 161)  ||
				(event.keyCode == 168)  ||
				(event.keyCode == 176)  ||
				(event.keyCode == 180)  ||
				(event.keyCode == 191)  ||
				(event.keyCode > 255)
			)				
                event.returnValue = false;
	}
	

	function removeInvalidText(field) 
	{
       var i=0;
		for(i=0; i<field.value.length; i++)
		{
			if (
					(field.value.charCodeAt(i) < 32 && field.value.charCodeAt(i) != 10 && field.value.charCodeAt(i) != 13) ||   //Control chars except LF and CR
					(field.value.charCodeAt(i) > 38 && field.value.charCodeAt(i) < 40) ||
					(field.value.charCodeAt(i) > 90 && field.value.charCodeAt(i) < 94) ||
					(field.value.charCodeAt(i) > 94 && field.value.charCodeAt(i) < 97) ||
					(field.value.charCodeAt(i) > 122 && field.value.charCodeAt(i) < 127)  ||
					(field.value.charCodeAt(i) == 161)  ||
					(field.value.charCodeAt(i) == 168)  ||
					(field.value.charCodeAt(i) == 176)  ||
					(field.value.charCodeAt(i) == 180)  ||
					(field.value.charCodeAt(i) == 191)  ||
					(field.value.charCodeAt(i) > 255)
			)
        	{
           			field.value=field.value.replace(field.value.charAt(i--),"") ;
			}
		}
        
	}

	function allowEmail(){
            if ((event.keyCode > 32 && event.keyCode < 45) || 
                (event.keyCode == 47) ||
                (event.keyCode > 57 && event.keyCode < 64) || 						
                (event.keyCode > 90 && event.keyCode < 95) ||
                (event.keyCode == 96) ||
                (event.keyCode > 122 ) ||(event.keyCode == 13 ) ) 
                event.returnValue = false;		            
	}

	
	/**
	 * Posible caracteres extraños
	 */
/*	var INVALID_CHARACTERS = '\\*+-_\'¿?¡!#$%&=;,[]{}~´`¨\"|°<>\n';*/
	var INVALID_CHARACTERS = '';
	/**
	 * Contiene los caracteres invalidos que el usuario escribio.
	 */
	var INVALID_CHARS = '';
	/**
	 * Mensaje que se despliega cuando un campo no ha sido capturado o seleccionado.
	 */
	var REQUIRED_MESSAGE='Los siguientes campos son requeridos:\n\n';
	/**
	 * Mensaje que se despliega para informar que al menos un campo debe ser llenado.
	 */
	var OPTIONAL_MESSAGE='At least one of these must be selected:\n\n';
	/**
	 * Mensaje que se despliega para informar que se encontro un caracter invalido.
	 */
	var INVALID_CHAR_MESSAGE='The next characters are invalid:\n';
	
	function setCoreMsg( saRequiredMsg, saOptionlMsg, saInvalidCharMsg ){
		REQUIRED_MESSAGE = saRequiredMsg + "\n\n" ;
		OPTIONAL_MESSAGE = saOptionlMsg + "\n\n";
		INVALID_CHAR_MESSAGE = saInvalidCharMsg + "\n";
	}
	/**
	 * Mensaje que guarda el nombre de los campos que no fueron llenados o seleccionados.
	 */
	var REQUIRED_FIELDS_MESSAGE='';
	/**
	 * Contiene el tipo de los campos de tipo texto oculto
	 */
	var HIDDEN_TYPE = 'hidden';
	/**
	 * Contiene el tipo de los campos de tipo texto
	 */
	var TEXT_TYPE = 'text';
	/**
	 * Contiene el tipo de los campos de tipo contraseña
	 */
	var PASSWORD_TYPE = 'password';
	/**
	 * Contiene el tipo de los campos de tipo area de texto
	 */
	var TEXTAREA_TYPE = 'textarea';
	/**
	 * Contiene el tipo de los campos de tipo radio
	 */
	var RADIO_TYPE = 'radio';
	/**
	 * Contiene el tipo de los campos de tipo combo box
	 */
	var SELECT_ONE_TYPE = 'select-one';
	/**
	 * Contiene el tipo de los campos de tipo list box
	 */
	var SELECT_MULTIPLE_TYPE = 'select-multiple';
	/**
	 * Contiene el tipo de los campos de tipo check box
	 */
    var CHECK_BOX_TYPE = 'checkbox';
	/**
	 * Contiene el tipo de los campos de tipo arreglo
	 */
	var ARRAY = '-array';
	
	/**
	 * Función que busca caracteres invalidos en el objeto que recibe como parametro.
	 * 
	 * @param objaFieldObject Objeto que es un campo de tipo texto en la forma.
	 *
	 * @return <code>true</code> Si es encontrado algún caracter invalido.
	 * 			<code>false</code> Si no contiene ninguna caracter invalido.
	 */
	function containsInvalidChars(objaFieldObject){
		blReturnedValue=false;//Bandera para señalar si hay algun caracter extraño en el campo que se recibe como parametro
		for(ilCounter=0;INVALID_CHARACTERS.length>ilCounter;ilCounter++){//Recorremos nuestros caracteres
			if(objaFieldObject.value.indexOf(INVALID_CHARACTERS.charAt(ilCounter))!=-1){//Buscamos el caracter en el valor del campo
				blReturnedValue = true;//Si es encontrado marcamos la bandera como verdadera
				alert("found invalid char: " + INVALID_CHARACTERS.charAt(ilCounter));
				if(INVALID_CHARS.indexOf(INVALID_CHARACTERS.charAt(ilCounter))==-1){//Si no se ha registrado
					INVALID_CHARS+=INVALID_CHARACTERS.charAt(ilCounter)+' ';//Registramos los caracteres invalidos
				}
			}
		}
		return blReturnedValue;//Retornamos el resultado
	}
	/**
	 * Función que verifica si el campo es vacio.
	 * 
	 * @param objaFieldObject Objeto que es un campo de tipo texto en la forma.
	 *
	 * @return <code>true</code> Si el no campo esta vacio o contiene solamente espacios
	 *	, <code>false</code> Si el campo no esta vacio.
	 */
	function isEmpty(objaFieldObject){
		var blReturn = false;
		if(objaFieldObject.value != null){
			if( removeSpaces( objaFieldObject.value ) == '' ){
				blReturn = true;
			}
		}
		return blReturn;
	}
	

	
	/**
	 * Verifica que el campo no contenga caracteres invalidos y despliega una alerta en el caso que contenga
	 * 
	 * @param objaFieldObject <code>Object</code> Contiene un objeto de la forma.
	 * 
	 * @return <code>true</code> si contiene caracteres invalidos, de lo contrario <code>false</code>
	 */
	function checkField(objaElement){
		blReturn = false;
		if(containsInvalidChars(objaElement.field)){//Si el objeto contiene algún caracter invalido desplegamos una alerta
			alert(INVALID_CHAR_MESSAGE+INVALID_CHARS+objaElement.displayName);
			objaElement.field.select();//Seleccionamos el texto del campo
			objaElement.field.focus();//Colocamos el foco al campo.
			//Asignamos false para decir que hay un error
			blReturn = true;
		}else{
			INVALID_CHARS = '';//Limpiamos el contenedor de caracteres invalidos por que ya no hay errores.
		}
		return blReturn;
	}
	
	/**
	 * Función que valida el arreglo de objetos que recibe como parametro.
	 * Para los objetos de tipo Text, Password y Text Area valida que no sean vacios(por que son requeridos).
	 * Para los objetos de tipo Select y Radio button valida que este seleccionado un elemento de opción valido.
	 * 
	 * @param lstaArrayOfElements <code>Array</code> Contiene una lista de objetos de tipo Element
	 * 
	 * @return <code>true</code> Si todos los campos estan capturados y/o seleccionados.
	 * 			<code>false</code> Si falta algún campo por capturar.
	 */
	function doFieldsValidation(lstaArrayOfElements){
	
	
		blReturnFieldsValidation = true;//Bandera de retorno que señala si todos los campos estan capturados
		//Recorremos el arreglo de elementos.

		for(ilIndex=0;lstaArrayOfElements.length>ilIndex;ilIndex++){//Recorremos nuestro arreglo de objetos
		
			//Verificamos si el campo no fue capturado
			if(	doTextFieldsValidation(lstaArrayOfElements[ilIndex])	||
				doComboFieldsValidation(lstaArrayOfElements[ilIndex])	||
				doRadioFieldsValidation(lstaArrayOfElements[ilIndex]))
				{
				
				//Alamacenamos el nombre del campo que no fue capturado
				REQUIRED_FIELDS_MESSAGE+='* '+lstaArrayOfElements[ilIndex].displayName+'\n';
				//Asignamos false para decir que hay un error
				blReturnFieldsValidation = false;
			}
		
		}
		//Si no se capturaron los campos requeridos desplegamos una alerta
		if(REQUIRED_FIELDS_MESSAGE!=''){
			alert(REQUIRED_MESSAGE+REQUIRED_FIELDS_MESSAGE);
		}else{
			blReturnFieldsValidation = true;
		}
		REQUIRED_FIELDS_MESSAGE='';//Limpiamos el contenedor de los nombres de los campos no camputarod.
		return blReturnFieldsValidation;//Retornamos el resultado
	}
	/**
	 * Función que valida el arreglo de objetos que recibe como parametro, para que al menos uno este seleccionado.
	 * Para los objetos de tipo Text, Password y Text Area valida que no sean vacios(por que son requeridos).
	 * Para los objetos de tipo Select y Radio button valida que este seleccionado un elemento de opción valido.
	 * 
	 * @param lstaArrayOfElements <code>Array</code> Contiene una lista de objetos de tipo Element
	 * 
	 * @return <code>true</code> Si al menos uno de los campos fué caputurado y/o seleccionado, de lo contrario <code>false</code>
	 */
	function doFieldsValidationForAtleastOne(lstaArrayOfElements){
		blReturnFieldsValidation = true;//Bandera de retorno que señala si al menos uno de los campos en el arreglo fue seleccionado
		//Recorremos el arreglo de elementos.
		for(ilIndex=0;lstaArrayOfElements.length>ilIndex;ilIndex++){//Recorremos nuestro arreglo de objetos
			//Verificamos si al menos uno de los campos fué capturado
			if(	doTextFieldsValidation(lstaArrayOfElements[ilIndex])	||
				doComboFieldsValidation(lstaArrayOfElements[ilIndex])	||
				doRadioFieldsValidation(lstaArrayOfElements[ilIndex])){
				REQUIRED_FIELDS_MESSAGE+='* '+lstaArrayOfElements[ilIndex].displayName+'\n';
				//Asignamos false para decir que ningun campo fue capturado
				blReturnFieldsValidation = false;
			}else {
				//Asignamos true para decir que un campo fue seleccinado
				blReturnFieldsValidation = true;
				//Rompemos el ciclo por que ya encontramos un campo capturado
				break;
			}
		}
		if(!blReturnFieldsValidation){
			alert(OPTIONAL_MESSAGE+REQUIRED_FIELDS_MESSAGE);
		}
		REQUIRED_FIELDS_MESSAGE='';//Limpiamos el contenedor de los nombres de los campos no camputarod.
		return blReturnFieldsValidation;//Retornamos el resultado
	}
	/**
	 * Valida objetos de tipo Text, Password y Textare
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>true</code> Si el campo no tiene datos, de lo contrario retorna <code>false</code>
	 */
	function doValidationText(objaElement){
		blValidationTextReturn = false;
		if(isEmpty(objaElement.field)){//Si el objeto contiene algún caracter invalido desplegamos una alerta
			blValidationTextReturn = true;
		}
		
		return blValidationTextReturn;
	}
	/**
	 * Valida objetos de tipo Text, Password y Textare
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>true</code> Si el campo no tiene datos, de lo contrario retorna <code>true</code>
	 */
	function doValidationTexts(objaElement){
		blValidationTextReturn = false;
		for(ilIndx=0;objaElement.field.length>ilIndx;ilIndx++){
			if(isEmpty(objaElement.field[ilIndx])){
				blValidationTextReturn = true;
			}
		}
		return blValidationTextReturn;
	}
	/**
	 * Valida campos de tipo select-one y select-multiple. La función comprueba si de los elementos en la lista
	 * se encuentra seleccionado el segundo elemento, suponiendo que el primero elemento no es valido
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>false</code> Si el campo tiene tiene seleccionado un elemento, de lo contrario retorna <code>true</code>
	 */
	function doValidationDropDown(objaElement){
		blReturnValidationDropDown = true;
		for(ilIndx=0;objaElement.field.options.length>ilIndx;ilIndx++){
			if(objaElement.field.options[ilIndx].selected ){
					if( !isEmpty( objaElement.field.options[objaElement.field.options.selectedIndex] ) ){
							blReturnValidationDropDown = false;
							break;
					}
			}
		}
		return blReturnValidationDropDown;
	}
	

	/**
	 * Valida campos de tipo select-one y select-multiple. La función comprueba si de los elementos en la lista
	 * se encuentra seleccionado el segundo elemento, suponiendo que el primero elemento no es valido
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>true</code> Si el campo tiene tiene seleccionado un elemento, de lo contrario retorna <code>false</code>
	 */
	function doValidationDropDowns(objaElement){
		blReturnValidationDropDown = false;
		for(ilCounter=0;objaElement.field.length>ilCounter;ilCounter++){
			for(ilIndx=1;objaElement.field[ilCounter].options.length>ilIndx;ilIndx++){
				if(!objaElement.field[ilCounter].options[ilIndx].selected){
					blReturnValidationDropDown = true;
					break;
				}
			}
		}
		return blReturnValidationDropDown;
	}
	/**
	 * Validación de radio buttons. La función valida que se encuentre seleccionado al menos un radio
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>true</code> Si el campo tiene tiene seleccionado un elemento, de lo contrario retorna <code>false</code>
	 */
	function doValidationRadios(objaElement){
		blReturnValidationRadio = true;
		for(ilIndx=0;objaElement.field.length>ilIndx;ilIndx++){
			if(objaElement.field[ilIndx].checked){
				blReturnValidationRadio=false;
				break;
			}
		}
		return blReturnValidationRadio;
	}
	/**
	 * Validación de radio button. La función valida que se encuentre seleccionado el radio
	 * 
	 * @param objaElement <code>Element</code> Contiene el campo a validar
	 * 
	 * @return <code>true</code> Si el campo tiene tiene seleccionado un elemento, de lo contrario retorna <code>false</code>
	 */
	function doValidationRadio(objaElement){
		blValidationRadio = false;
		if(!objaElement.field.checked){
			blValidationRadio = true;
		}
		return blValidationRadio;
	}
	/*
	 * Función que crea un objeto para contener un elemento para validación.
	 * 
	 * @param objaFieldObject <code>Object</code> Contiene un objeto de la forma.
	 * @param saDisplayName <code>String</code> Contiene el nombre para el despliegue del campo.
	 */
	function Element(objaFieldObject, saDisplayName){
		//Contiene el objeto que es un campo en la forma
		this.field=objaFieldObject;
		//Contiene el nombre del campo que tiene que desplegar al usuario
		this.displayName=saDisplayName;
		//Contiene el tipo de objeto que se tiene como atributo
		this.fieldType=getFieldType(this.field);
	}
	/**
	 * Retorna el tipo de objeto al que pertenece el parametro
	 *
	 * @param objaField Objeto de la forma de HTML, debe ser un objeto valido de tipo
	 * 		text, password, textarea, radio, select-one, select-multiple, o un arreglo 
	 * 		de estos.
	 */
	function getFieldType(objaField){
//	    alert("field to validate: " + objaField);
		slReturnType = objaField.type;
		
		//Si no tiene tipo es por que es un arreglo de objetos
		if(	slReturnType==null){
			if(	objaField[0].type==TEXT_TYPE){
				slReturnType = TEXT_TYPE+ARRAY;
			} else 
			if(	objaField[0].type==PASSWORD_TYPE){
				slReturnType = PASSWORD_TYPE+ARRAY;
			} else 
			if(	objaField[0].type==TEXTAREA_TYPE){
				slReturnType = TEXTAREA_TYPE+ARRAY;
			} else 
			if(	objaField[0].type==RADIO_TYPE){
				slReturnType = RADIO_TYPE+ARRAY;
			}else 
			if(	objaField[0].type==SELECT_ONE_TYPE){
				slReturnType = SELECT_ONE_TYPE+ARRAY;
			} else 
			if(	objaField[0].type==SELECT_MULTIPLE_TYPE){
				slReturnType = SELECT_MULTIPLE_TYPE+ARRAY;
			}else if( objaField[0].type==CHECK_BOX_TYPE ){
                            slReturnType = CHECK_BOX_TYPE+ARRAY;
                        }else if( objaField[0].type==HIDDEN_TYPE ){
                            slReturnType = HIDDEN_TYPE+ARRAY;
                        }

		}
		return slReturnType;
	}
	/**
	 * Valida la entrada requerida de texto.
	 *
	 * @param objaElement El elemento que contiene el campo a validar.
	 *
	 * @return <code>false</code> si el campo fue capturado, de lo contrario <code>true</code>
	 */
	function doTextFieldsValidation(objaElement){
		blReturnFieldsValidation = false;
		
		if( objaElement.fieldType==HIDDEN_TYPE ||	
		    objaElement.fieldType==TEXT_TYPE ||
			objaElement.fieldType==PASSWORD_TYPE ||
			objaElement.fieldType==TEXTAREA_TYPE){
				//Validamos que el campo no este vacio
				if(doValidationText(objaElement)){
					//Asignamos true para decir que hay un error
					blReturnFieldsValidation = true;
				}
		} else 
		if( objaElement.fieldType==HIDDEN_TYPE+ARRAY ||
			objaElement.fieldType==TEXT_TYPE+ARRAY || 
			objaElement.fieldType==PASSWORD_TYPE+ARRAY ||
			objaElement.fieldType==TEXTAREA_TYPE+ARRAY){
			//Validamos que el campo no este vacio
			if(doValidationTexts(objaElement)){
				//Asignamos true para decir que hay un error
				blReturnFieldsValidation = true;
			}
		}
		return blReturnFieldsValidation;
	}
	/**
	 * Valida la entrada requerida de combos.
	 *
	 * @param objaElement El elemento que contiene el campo a validar.
	 *
	 * @return <code>false</code> si el campo fue capturado, de lo contrario <code>true</code>
	 */
	function doComboFieldsValidation(objaElement){
	 
		blReturnFieldsValidation = false;
		
		if(	objaElement.fieldType==SELECT_ONE_TYPE ||
			objaElement.fieldType==SELECT_MULTIPLE_TYPE){
			//Validamos que este seleccionada una opción de la lista, que no sea el primer elemento
			if(doValidationDropDown(objaElement)){
				//Asignamos true para decir que hay un error
				blReturnFieldsValidation = true;
			}
		} else 
		if (	objaElement.fieldType==SELECT_ONE_TYPE+ARRAY ||
				objaElement.fieldType==SELECT_MULTIPLE_TYPE+ARRAY){
			if(doValidationDropDowns(objaElement)){
				//Asignamos true para decir que hay un error
				blReturnFieldsValidation = true;
			}
		}
		
		return blReturnFieldsValidation;
	}
	/**
	 * Valida la entrada requerida de radios.
	 *
	 * @param objaElement El elemento que contiene el campo a validar.
	 *
	 * @return <code>false</code> si el campo fue capturado, de lo contrario <code>true</code>
	 */
	function doRadioFieldsValidation(objaElement){
		blReturnFieldsValidation = false;
		//Verificamos si el campo es solamente un radio.
		if(objaElement.fieldType==RADIO_TYPE){
			if(doValidationRadio(objaElement)){
				//Asignamos true para decir que hay un error
				blReturnFieldsValidation = true;
			}
		} else 
		//Verificamos si el campo pertenece a el grupo de objetos de radio o checkbox
		if(objaElement.fieldType==RADIO_TYPE+ARRAY){
			//Validamos que al menos un radio este seleccionado
			if(doValidationRadios(objaElement)){
				//Asignamos true para decir que hay un error
				blReturnFieldsValidation = true;
			}
		}
		return blReturnFieldsValidation;
	}	
	
	/**
	 * Función que valida la longitud Maxima de un campo TEXTAREA.
	 *
	 * @param objaFieldObject Objeto que es un campo de tipo TEXTAREA.
	 * @param iaMaxlength     Lomgitud Maxima.
	 * @return <code>true</code> Si el contenido es menor a la longitud, <code>false</code> Si el campo excede la longitud.
	 */
	function validateMaxLength(objaFieldObject,iaMaxLength){
            if (objaFieldObject.value.length >= iaMaxLength){
                event.returnValue = false;
            }
	}
	/**
	 * Función que convierte a Mayuscula el Contenido de Campo Texto.
	 *
	 * @return  El contenido en Mayusculas.
	 */
	function toUpperCase(){

	}
	/**
	 * Función que valida la longitud Maxima de un campo TEXTAREA.
         * No permite capturar mas caracteres.
	 *
	 * @param objaFieldObject Objeto que es un campo de tipo TEXTAREA.
	 * @param iaMaxlength     Lomgitud Maxima.
	 */
	function isLengthMaxComments(objaFieldObject,iaMaxLength){
            var slTexT = '';
            if (objaFieldObject.value.length >= iaMaxLength){
                slTexT = objaFieldObject.value;
                slTexT = slTexT.substring(0,iaMaxLength);
                objaFieldObject.value = slTexT;
                event.returnValue = false;
            }
        }

	function isLengthMax(objaFieldObject,iaMaxLength){
            var slTexT = '';
            if (objaFieldObject.value.length >= iaMaxLength){
                slTexT = objaFieldObject.value;
                slTexT = slTexT.substring(0,iaMaxLength);
                objaFieldObject.value = slTexT;
                return true;
            } else {
                return false;
            }
        }

	function formatCurrency(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
			num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') +  num + '.' + cents);
		//return (((sign)?'':'-') + '$' + num + '.' + cents);
}

        function checkDecimals(fieldName, fieldValue) {
                decallowed = 2;  // how many decimals are allowed?
                if (isNaN(fieldValue)) {
                        alert("Numero Invalido");
                        fieldName.select();
                        fieldName.focus();
                }else {
                        if (fieldValue.indexOf('.') == -1) fieldValue += ".";
                                dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
                                if (dectext.length > decallowed ){					
                                        alert("Numero Invalido");
                                        fieldName.select();
                                        fieldName.focus();
                              }	
                              if (parseFloat(fieldValue) > parseFloat("999999.00") ){
                                    alert("Máximo valor aceptado 999999");
//                                    fieldName.value=formatCurrency(fieldName.value);
                                    fieldName.select();
                                    fieldName.focus();
                              }
                   }
                }
	/**
	 * Función que habilita todos los Objectos de una Forma
	 *
	 */
        function enabledElements(theForm){
            for (var i = 0; i < theForm.elements.length; i++) {
              theForm.elements[i].disabled = false;
            }
        }

	/**
	 * Función que desahabilita todos los Objectos de una Forma
	 *
	 */
        function disabledElements(theForm){
            for (var i = 0; i < theForm.elements.length; i++) {
              theForm.elements[i].disabled = true;
            }
        }

        /**
        * Funciones para Piezas Por Surtir, Devueltas y Cotizaciones   
        */

        /**
        *  Funciones para llenar Dinamicamente el combo cuando tiene un estatus
        *  de Rechazo o Rectificacion.
        *  -Funcion para Eliminar las opciones al Combo
        */
        function clearOption(saComboBox){
                var numItems = eval('document.frmMain.' + saComboBox + '.length;'); 
                for (i=numItems-1; i>=0; i--){
                        eval('document.frmMain.' + saComboBox + '.options[i]=null;');
                }                
        }
        /**
        *	Funcion para Agregar Opciones al Combo
        */	
        function addItems(saComboBox,objStatusEdit){
            clearOption(saComboBox);
            var ilArraySize = 0;
            ilArraySize = eval( objStatusEdit + '.length');
            for(ilCount = 0;ilCount < ilArraySize; ilCount++){
                 eval('document.frmMain.' + saComboBox + '.options[document.frmMain.' + saComboBox + 
                  '.length] = new Option(' + objStatusEdit + '[' + ilCount + '].scDescription,' + 
                    objStatusEdit + '[' + ilCount + '].scId);');
            }
        }
		
        /**
        * Funcion que obtiene el numero de ComboBox que existen 
        */			
        function getComboListLength( objaComboBox ){
            var ilLength;
            if( objaComboBox == null ){
                return 0;
            }
            if( getFieldType( objaComboBox ) ==  SELECT_ONE_TYPE ){
                ilLength = 0;
            }else if( getFieldType( objaComboBox )  ==   ( SELECT_ONE_TYPE + ARRAY )  ){
                ilLength = objaComboBox.length;
            }
            return ilLength;
        }
	/**
	  * Remueve todos los espacios contenidos en la cadena.
          */
	    function removeSpaces( string ) {
    	    var temp = "";
        	string = '' + string;
	        splitstring = string.split(" ");
    	    for(i = 0; i < splitstring.length; i++)
        	    temp += splitstring[i];
	        return temp;
	    }
    /**
     * Sets values to translation and language fields
     */
	function setTranslations(objaLenguage, objaTranslation ){
		objlLanguage = document.forms[0].language;
		objlTranslation = document.forms[0].translation;
		for(ilCounter=0;objaLenguage.length>ilCounter;ilCounter++){
			objlLanguage.value += objaLenguage[ilCounter].value;
			if( objaTranslation[ilCounter].value=='' ){
				objaTranslation[ilCounter].value=' ';
			}
			
			objlTranslation.value += objaTranslation[ilCounter].value;
			if(objaLenguage.length>ilCounter+1){
				objlLanguage.value += ",";
				objlTranslation.value += ",";
			}
		}
	}
	
	/**Validation for Values*/
	function validateValue(aText){
		blValidationTextReturn = true;
		if(isEmpty(aText) || containsInvalidChars(aText)){
			blValidationTextReturn = false;
		}		
		return blValidationTextReturn;
	}
	/**Validates if one option of the combo is selected*/
	function validateCombo(cmbField){
		index = cmbField.selectedIndex;
		blIsValid = true;
		if(index==0){
			blIsValid = false;
		}
		return blIsValid;
	}
	
	function selectAll( objaField ){
		if( objaField != null && getFieldType(objaField) == SELECT_MULTIPLE_TYPE  ){
			for( var ilElement = 0; ilElement < objaField.options.length; ilElement++ ){
				objaField.options[ilElement].selected=true;
			}
		}
	}
	
	function invertSelection( objaField ){
		if( objaField != null && getFieldType(objaField) == SELECT_MULTIPLE_TYPE ){
			for( var ilElement = 0; ilElement < objaField.options.length; ilElement++ ){
				if( objaField.options[ilElement].selected ){
					objaField.options[ilElement].selected=false;
				}else{
					objaField.options[ilElement].selected=true;
				}
			}
		}
	}


	function changeStyle(id, newClass) {
  		identity = document.getElementById(id);
		identity.className = newClass;
	 }

	function getIntRowId(idStr){
		return parseInt(idStr.substring(0,idStr.indexOf('_')));	
	}

	function getStrRowId(idStr){
		return idStr.substring(idStr.indexOf('_'));	
	}
	
	function getMonthlyValueRowId(idStr, offSet){
		var yearId = getIntRowId(idStr) + offSet;
		var divId = yearId + getStrRowId(idStr);
		return divId;	
	}
	
	function showBefore(idStr) {		
	    var beforeDiv = document.getElementById(getMonthlyValueRowId(idStr, -1));
	    if (beforeDiv != null) {
	        showYear(getMonthlyValueRowId(idStr, -1));
	        rightArrowId = getArrowId(idStr, 'R', -1);
	        leftArrowId = getArrowId(idStr, 'L', -1);
			var year = idStr.substring(0,4);
	 		var part = idStr.substring(4, idStr.length);
	 		year = year - 2;
	 		var idPrevRow = year + part;
	        if(previousRowsWithData(idPrevRow)){
	        	changeStyle( leftArrowId, 'ci7LabelRed' );
	        } else {
	        	changeStyle( leftArrowId, 'ci7Label' );
	        }
	        if(nextRowsWithData(idPrevRow)){
	        	changeStyle( rightArrowId, 'ci7LabelRed' );
	        } else {
	        	changeStyle( rightArrowId, 'ci7Label' );
	        }
	    }
	}
			
	function showAfter(idStr) {		
	    if (document.getElementById(getMonthlyValueRowId(idStr, 2)) != null) {
	        showYear(getMonthlyValueRowId(idStr, 1));
	        leftArrowId = getArrowId(idStr, 'L', 1);
	        rightArrowId = getArrowId(idStr, 'R', 1);
	        if(previousRowsWithData(idStr)){
	        	changeStyle( leftArrowId, 'ci7LabelRed' );
	        } else {
	        	changeStyle( leftArrowId, 'ci7Label' );
	        }
	        if(nextRowsWithData(idStr)){
	        	changeStyle( rightArrowId, 'ci7LabelRed' );
	        } else {
	        	changeStyle( rightArrowId, 'ci7Label' );
	        }
	    }
	}
 
 	function previousRowsWithData(idStr){
 		var hasData = false;
 		var newId;
 		var year = idStr.substring(0,4);
 		var part = idStr.substring(4, idStr.length);
 		for(var i=0; i < 5; i++){
	 		newId = year + part;
 			if(rowWithData(newId)){
				hasData = true;
 				break;
 			}
 			year = parseInt(year) - 1;
 		}
 		return hasData;
 	}
 	
 	function nextRowsWithData(idStr){
 		var hasData = false;
 		var newId;
 		var year = idStr.substring(0,4);
 		var part = idStr.substring(4, idStr.length);
 		year = parseInt(year) + 3;
 		for(var i=0; i < 5; i++){
	 		newId = year + part;
 			if(rowWithData(newId)){
				hasData = true;
 				break;
 			}
			year = parseInt(year) + 1; 			
 		}
 		return hasData;
 	}
 
 	function getArrowId(idStr, type, y){
 		var arrowId;
 		var year = idStr.substring(0,4);
        var part = idStr.substring(4, idStr.length);
        year = parseInt(year) + y;
        arrowId = year + part + type;
        return arrowId;
 	}
 
	function rowWithData(idStr){
		var hasData = false;
		for(i=1; i < 13; i++){
			var field = document.getElementById(idStr + '_' + i);
			if( field != null && field.value != null && field.value != '' ){
				hasData = true;
				break;
			}
		}
		return hasData;	
	}

	function showYear(idStr) {
	    var currentRow = document.getElementById(getMonthlyValueRowId(idStr, 0));
	    var beforeRow = document.getElementById(getMonthlyValueRowId(idStr, -1));
	    var afterRow = document.getElementById(getMonthlyValueRowId(idStr, 1));
	    var afterTwoRow = document.getElementById(getMonthlyValueRowId(idStr, 2));
	
	    if (beforeRow != null) {
	        beforeRow.style.display = 'none';
	    }
	    if (afterTwoRow != null) {
	        afterTwoRow.style.display = "none";
	    }
	
	    if (currentRow != null) {
	        currentRow.style.display = 'inline';
   	        currentRow.cells[0].style.visibility = "visible";
	        currentRow.cells[1].style.visibility = "visible";
	        currentRow.cells[3].style.visibility = "visible";
	    }
	    if (afterRow != null) {
	        afterRow.style.display = 'inline';
	        afterRow.cells[0].style.visibility = "hidden";	        
	        afterRow.cells[1].style.visibility = "hidden";
	        afterRow.cells[3].style.visibility = "hidden";
	    }
	    
	
	}

	function changeTDElementsStyle(oTable, newStyle){
		var oParent = oTable.firstChild;
        var oElement = oParent.firstChild;	     
	     // Navigate down the document tree until you find the first TD element.
		while (oElement.tagName != "TD"){
			oParent = oElement;
			oElement = oElement.firstChild;
		}
		while (oParent != null){
		  while (oElement != null) {
		  	oElement.className = newStyle;
		    oElement = oElement.nextSibling;
		  }		
		  oParent = oParent.nextSibling;		
		  if (oParent != null) {
		    oElement = oParent.firstChild;
		  }
		}	
	}	

	function changeTDStyleSelective(oTable, oldStyle, newStyle){
		var oParent = oTable.firstChild;
        var oElement = oParent.firstChild;	     
	     // Navigate down the document tree until you find the first TD element.
		while (oElement.tagName != "TD"){
			oParent = oElement;
			oElement = oElement.firstChild;
		}
		while (oParent != null){
		  while (oElement != null) {
		  	if (oElement.className == oldStyle){
  				oElement.className = newStyle;
		  	}		  
		    oElement = oElement.nextSibling;
		  }		
		  oParent = oParent.nextSibling;		
		  if (oParent != null) {
		    oElement = oParent.firstChild;
		  }
		}	
	}	

	function changeElementsStyleSelective(oElements, oldStyle, newStyle){
		for(i=0; i<oElements.length; i++) {
			if (oElements[i].className == oldStyle){
	 		    oElements[i].className = newStyle;
			}
	    }
	}	

	function applyStyleReadOnly(form) {
	     for (i = 0; i < form.elements.length; i++) {
	     	if (form.elements[i].readOnly == true ||
	     	    form.elements[i].disabled == true){
	     		form.elements[i].className = "ci7TextInputRO";
	     	}
	     }
	}	
	
	/**
	 * Calls to a browser button (input type file)
	 * opens the box to attach a file
	 *
	 * @param browser string contains the location (form.element) where file button is
	 */
	function attachFile(browser){
		eval(browser+".click()");
	}
	
	/**
	 * Displays the attachment file location in a div.
	 *
	 * @param attachment element id of the div where the location of the file is goin to be displayed
	 * @param browser string contains the location (form.element) where file button is
	 */
	function displayAttachment(attachment, browser, nameSize){
		//eval("document.getElementById('"+attachment+"').attachmentFile="+browser+".value");
		//eval("document.getElementById('"+attachment+"').innerText="+browser+".value.length>"+nameSize+"?"+browser+".value.substring(0,"+nameSize+")+'...':"+browser+".value;");
	}
	/**
	 * Returns the Inner HTML value of the div
	 * 
	 * @param divId the div id value
	 */
	function getDivContent(divId){
		return document.getElementById(divId).attachmentFile;
	}

    function trim(str){
        s = str.replace(/^(\s)*/, '');
        s = s.replace(/(\s)*$/, '');
        return s;
    }

    function validate_email(field,alerttxt){
        with (field){
            apos=value.indexOf("@")
            dotpos=value.lastIndexOf(".")
            if (apos<1||dotpos-apos<2){
                alert(alerttxt);
                return false
            } else {
                return true
            }
        }
    }
