/************************************************************************
* Form.js											 FECHA: 10-10-2004 *
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
* PROPOSITO : Define los objetos encargados de soportar la operacion	*
*	 general de los formularios en el Framework IBIZA.				 *
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
* AUTOR: Mauricio Mendez M.											 *
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
* id = "$Id: IBZForm.js,v 1.3 2009/01/19 16:18:56 GOYA\admingoya Exp $"
************************************************************************/

/************************************************************************
 * DESCRIPCION: 
 *	 Declara un objeto de tipo formulario encargado de 
 *	 encapsular toda la informacion que maneja un progrma estandar del 
 *	 framework IBIZA. Se encarga de hacer parse del documento XML que
 *	 contiene la estuctura y definicion de los campos que conforman el
 *	 formulario
 * PARAMETROS:
 *	 formWindow: Objeto ventana en el cual se visualiza el formulario
 *	 pageNumber: Corresponde al numero de paginas del formolario
 * RESULTADO: 
 *	 Devuelve un objeto Form vacio sobre el cual se pueden adicionar
 *	 todos los elemntos que componen el formulario.
 * PRE:
 *	 Se ha cargado completamente la pagina HTML en donde se visualiza
 *	 el contenido del formulario.
 * POST:
 * OJO: 
// ***********************************************************************/

function IBZ_Form( formWindow, companyId, applicationId, moduleId, formId, region )
{
	/********************************************************
	*				Atributos del objeto					*
	*********************************************************/

	//Variable que indica que es el primer cargue del formulario
	this.isFirstSend = new Boolean();
	this.formWindow = formWindow;

	//Variables formulario solicitado
	this.companyId = companyId;
	this.applicationId = applicationId;
	this.moduleId = moduleId;
	this.formId = formId;
	this.region = region;

	//Atributos de control del estado del formulario 
	this.processOnGoing = false;
	this.callBackFunction = null;
	this.callBackObject = null;

	/* Arreglos asociativos para el almacenamiento de los objetos del formulario */
	this.sectionArray = new Array();
	this.sectionAssocArray = new Array();
	this.tableArray = new Array();
	this.tableAssocArray = new Array();
	this.fieldArray  = new Array();
	this.fieldAssocArray  = new Array();
	this.listArray  = new Array();
	this.listAssocArray  = new Array();
	this.actionArray  = new Array();
	this.actionAssocArray  = new Array();

	//Variables encargadas de almacenar el objeto DOM de la aplicacion.
	this.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

	this.formXmlDOM = new ActiveXObject("Microsoft.XMLDOM");
	this.formXmlDOM.async = "false";

	this.formExchangeXmlDOM = new ActiveXObject("Microsoft.XMLDOM");
	this.formExchangeXmlDOM.async = "false";

	//Variables que almacenan estados del formulario
	this.controlStateVarsDoc = new ActiveXObject("Microsoft.XMLDOM");
	this.controlStateVarsDoc.async = "false";

	/********************************************************
	*		Declaracion de metodos del objeto Form		 *
	*********************************************************/

	// Metodo para iniciar la operacion del formulario
	this.Start = IBZForm_Start;

	// Metodos de definicion de la composicion del formulario
	this.BuildForm = IBZForm_BuildForm;
	this.LoadForm = IBZForm_LoadForm;

	// Metodos para el manejo del flujo de control hacia el servidor
	this.UpdateDOMFromFields = IBZForm_UpdateDOMFromFields;
	this.UpdateInterfaceFields = IBZForm_UpdateInterfaceFields;
	this.StartFieldValidation = IBZForm_StartFieldValidation;
	this.FinishFieldValidation = IBZForm_FinishFieldValidation;
	this.StartServerProcess = IBZForm_StartServerProcess;
	this.requiredFieldsEmpty = IBZForm_RequiredFieldsEmpty;

	// Metodos para la manipulacion de las variables de control
	this.SetControlStateVar = IBZForm_SetControlStateVar;

	/********************************************************
	*				Inicio proceso						 *
	*********************************************************/

	// Metodo inicio proceso solicitud datos al servidor
	this.Start();
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de iniciar la operacion del formulario, producto
*	 del cargue inicial completo del documento html. 
* PARAMETROS:
*	 None
* RESULTADO:
*	 Envia una solicitud XMLHTTPRequest al servidor con la informacion
*	 basica de identificacion del formulario y la sesion, con lo cual
*	 se puede identificar que formulario y que privilegios y opciones
*	 por defecto debera iniciar la operacion
* PRE:
*	 La pagina del formulario ha sido totalmente cargada, y se ha 
*	 ejecutado el constructor de la clase definiendo los atributos en
*	 donde se almacenaran los objetos del formulario.
* POST:
*	 Se ha enviado una solicitud XMLHTTPRequest, y se esta en espera
*	 de su correspondiente respuesta.
* OJO: 
*	 Al finalizar este metodo no necesariamente se ha obtenido la 
*	 respuesta del servidor, sino que su procesamiento es asincronico;
*	 es decir que al recibirse la respuesta se dispara un metodo para
*	 atender dicho evento.
*-------------------------------------------------------------------- */
function IBZForm_Start()
{
	var xmlContentText = new String();

	// Se construye el documento XML con la primera solicitud
	xmlContentText = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<IBZ_Form companyId=\"" + this.companyId + "\" applicationId=\"" + this.applicationId + "\" moduleId=\"" + this.moduleId + "\" formId=\"" + this.formId + "\"><IBZ_ControlStateVars><IBZ_StateVar varName=\"currentProcess\">START</IBZ_StateVar><IBZ_StateVar varName=\"formStatus\">STANDARD</IBZ_StateVar><IBZ_StateVar varName=\"region\">" + this.region + "</IBZ_StateVar></IBZ_ControlStateVars></IBZ_Form>";

	this.formXmlDOM.loadXML( xmlContentText );
	this.isFirstSend = true;

	// Se dispara el proceso de obtencion de informacion del servidor
	this.callBackFunction = this.BuildForm;
	this.StartServerProcess();
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Se encarga de enviar una solicitud XmlHttpRequest hacia el servidor
*	 solicitando un DDI actualizado despues del proceso correspondiente
*	 a la accion especificada
* PARAMETROS:
* RESULTADO:
*	 Informa si se adiciono correctamente la pagina al formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_StartServerProcess()
{

	//Se genera la solicitud XMLHTTPRequest hacia el servidor
	this.xmlHttpRequest.open( "POST", "../ddimanager.aspx", false );

	//metodo que se debera ejecutar al recibirse la respuesta del server
	this.xmlHttpRequest.onreadystatechange = this.ReturnServerProcess;

	//alert( "Antes:" + this.formXmlDOM.xml );

	//Se inicia el envio y recepcion de informacion del servidor
	//Se dispara el metodo respectivo al devolver la informacion del servidor
	this.xmlHttpRequest.send( this.formXmlDOM );

	//alert( "Despues:" + this.formExchangeXmlDOM.xml );
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Inicia el proceso de construccion del formulario
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function ReturnServerProcess()
{
	var pagina = null;
	var responseDataServer = new String();

	//Indica que el servidor termino de enviar la respuesta al cliente
	if( this.xmlHttpRequest.readyState == 4 )
	{
		//Obtener el valor devuelto por el servidor
		responseDataServer = this.xmlHttpRequest.responseText;

		//Si la respuesta del servidor es exitosa se procesa el XML de regreso de lo contrario
		//se envia el error respectivo
		if( this.xmlHttpRequest.status == 200 && responseDataServer != "404" )
		{
			//La respuesta esta completa, se actualiza el DOM y se ejecuta el callBack 
			if( responseDataServer != "" )
			{
				this.formExchangeXmlDOM.loadXML( responseDataServer );

				//alert( "Despues: " + this.formExchangeXmlDOM.xml );

				//Si es la primera vez que se inicia el proceso
				//carga el DOM con la estructura
				if( this.isFirstSend == true )
				{
					this.formXmlDOM.loadXML( responseDataServer );
					this.isFirstSend = false;
				}

				//Si es la primera vez construye el formulario
				//de lo contrario llama a funcion indicada de finalizacion de validaciones del campo
				this.callBackFunction();
			}
			else
			{
				//Permite el envio de informacion al servidor
				//aunque ocurra un error
				this.processOnGoing = false;
				alert( "El servidor no envio informacion requerida para realizar la operacion." );
			}
		}
		else
		{
			//se muestra solo si hay error
			pagina = window.open( "about:blank", "ErrorServidor" );
			pagina.document.write( responseDataServer );
		}
	}

	//limpiar
	responseDataServer = "";
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Se encarga de contruir los objetos que copnforman un formulario
*	 a partir de la definicion del formulario obtenida de un XML
*	 recibido como primer solicitud XmlHttpRequest. 
* PARAMETROS:
* RESULTADO:
*	 Informa si se adiciono correctamente la pagina al formulario
* PRE:
*	 La respuesta del servidor ya se encuentra cargada en el objeto DOM
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_BuildForm()
{
	var xmlDocument = null;

	//Obtener el ROOT del documento XML
	xmlDocument = this.formXmlDOM.documentElement;

	//Cargar los diferentes objetos a IBIZA
	this.LoadForm( xmlDocument );

	//Limpiar el objeto XML
	xmlDocument = null;
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Se encarga de contruir los objetos que copnforman un formulario
*	 a partir de la definicion del formulario obtenida de un XML
*	 recibido como primer solicitud XmlHttpRequest. 
* PARAMETROS:
* RESULTADO:
*	 Informa si se adiciono correctamente la pagina al formulario
* PRE:
*	 La respuesta del servidor ya se encuentra cargada en el objeto DOM
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_LoadForm( xmlDocument )
{
	/********************************************************
			Variables										*
	*********************************************************/

	//Recorrer el DDI
	var childCursor = new Number();
	var nodeObject = null;
	var nodeName = new String();
	var callSubElement = new Boolean();
	var currentObject = null;

	/********************************************************
	*		Inicio proceso de recorrido del XML				*
	*********************************************************/

	//Iniciar la iteracion sobre el nodo actual
	nodeObject = xmlDocument.firstChild;
	while( nodeObject != null )
	{
		//Validar solo nodos elemento
		if( nodeObject.nodeType == 1 )
		{
			nodeName = nodeObject.nodeName;

			callSubElement = false;

			//Valida los tipos de objetos que permiten ser anadidos a IBIZA
			if( nodeName == "IBZ_Section" || nodeName == "IBZ_Action" || nodeName == "IBZ_TextField"
				|| nodeName == "IBZ_ListField" || nodeName == "IBZ_LabelField" || nodeName == "IBZ_DateField"
				|| nodeName == "IBZ_TextAreaField" || nodeName == "IBZ_Table"
				|| nodeName == "IBZ_ControlStateVars" )
			{
				//validar cada tipo de elemento para llamar al objeto respectivo
				if( nodeName == "IBZ_Section" )
				{
					//Obtener el objeto de IBIZA
					new Section( this, nodeObject );

					//Valida si es recursivo o no
					callSubElement = true;
				}
				else if( nodeName == "IBZ_Action" )
				{
					new Action( this, nodeObject );
				}
				else if( nodeName == "IBZ_TextField" )
				{
					new TextField( this, nodeObject );
				}
				else if( nodeName == "IBZ_ListField" )
				{
					new ListField( this, nodeObject );
				}
				else if( nodeName == "IBZ_LabelField" )
				{
					new LabelField( this, nodeObject );
				}
				else if( nodeName == "IBZ_DateField" )
				{
					new DateField( this, nodeObject );
				}
				else if( nodeName == "IBZ_TextAreaField" )
				{
					new TextAreaField( this, nodeObject );
				}
				else if( nodeName == "IBZ_Table" )
				{
					new Table( this, nodeObject );
				}
				else if( nodeName == "IBZ_ControlStateVars" )
				{
					this.controlStateVarsDoc = nodeObject;
				}

				//valida si tiene sub elementos
				if( callSubElement == true && nodeObject.hasChildNodes() == true )
				{
					this.LoadForm( nodeObject );
				}
			}
		}

		//Iterar sobre el siguiente nodo
		nodeObject = nodeObject.nextSibling;
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Con base en las propiedades asignadas del DOM se procede a ejecutar la accion
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_LoadProperties()
{
	var atrCursor = new Number();
	var attributeObject = null;

	//Iterar sobre los atributos
	//Asignarlos a array asociativo
	for( atrCursor = 0; atrCursor < this.XMLDocument.attributes.length; atrCursor ++ )
	{
		attributeObject = this.XMLDocument.attributes( atrCursor );

		if( attributeObject.name == "clientValidationPre" || attributeObject.name == "clientValidationPost" )
		{
			this[ attributeObject.name ] = eval( attributeObject.value );
		}
		else
		{
			this[ attributeObject.name ] = attributeObject.value;
		}
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Con base en las propiedades asignadas del DOM se procede a ejecutar la accion
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_ChangeStateAll()
{
	if( this.editable != null )
	{
		if( this.editable == "no" || this.editable == "false" )
		{
			this.Disable();
		}
		else if( this.editable == "yes" || this.editable == "true" )
		{
			this.Enable();
		}
	}

	if( this.visible != null )
	{
		if( this.visible == "no" || this.visible == "false" )
		{
			this.Hide();
		}
		else if( this.visible == "yes" || this.visible == "true" )
		{
			this.Show();
		}
	}

	if( this.style != null && Trim( this.style ) != "" )
	{
		this.SetStyle();
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Con base en las propiedades asignadas del DOM se procede a ejecutar la accion
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_ChangeState( propertyName )
{
	if( propertyName == "editable" && this.editable != null )
	{
		if( this.editable == "no" || this.editable == "false" )
		{
			this.Disable();
		}
		else if( this.editable == "yes" || this.editable == "true" )
		{
			this.Enable();
		}
	}
	else if( propertyName == "visible" && this.visible != null )
	{
		if( this.visible == "no" || this.visible == "false" )
		{
			this.Hide();
		}
		else if( this.visible == "yes" || this.visible == "true" )
		{
			this.Show();
		}
	}
	else if( propertyName == "style" && this.style != null && Trim( this.style ) != "" )
	{
		this.SetStyle();
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Se encarga de efectuar el proceso de validacion de un campo
* PARAMETROS:
*	 fieldObject: Objeto que representa el campo
* RESULTADO:
*	 El campo fue validado
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_StartFieldValidation( fieldObject )
{
	var xmlDocument = null;
	var validateFunction;
	var clentValidationResult = true;
	var tableRowId = new String();
	var tableId = new String();

	//Se esta atendiendo otro evento , no se efectua la validacion del campo
	if( this.processOnGoing == true )
	{
		return true;
	}

	//Se verifica si el campo tiene un proceso de validacion previo a cualquier
	//proceso server, en cuyo caso se obtiene el metodo y se ejecuta.
	if( fieldObject.clientValidationPre != null )
	{
		clentValidationResult = fieldObject.clientValidationPre();
	}

	// La validación resultó fallida
	if( clentValidationResult == false )
	{
		return( false );
	}

	xmlDocument = this.formXmlDOM.documentElement;

	//Se actualiza el DOM a partir de la información contenida en los campos 
	this.UpdateDOMFromFields( xmlDocument );

	//Se verifica si el campo exige un proceso de validacion en el servidor, en cuyo
	//caso hace los ajustes correspondientes en el XML DOM y envia la solicitud al 
	//servidor, dejando en el mismo DOM la informacion necesaria para completar el proceso
	if(fieldObject.serverValidation )
	{
		tableRowId = null;
		tableId = null;
		//Se activan las variables de control relativas al proceso de validacion de campos 
		if( fieldObject.XMLDocument.parentNode != null && fieldObject.XMLDocument.parentNode.nodeType != 9 )
		{
			tableRowId = fieldObject.XMLDocument.parentNode.getAttribute( "tableRowId" );
			tableId = fieldObject.XMLDocument.parentNode.parentNode.getAttribute( "tableId" );
		}

		if( fieldObject.fieldCode != null )
		{
			this.SetControlStateVar( "dependantField", fieldObject.fieldCode, tableRowId, tableId );
		}
		else if( fieldObject.actionId != null )
		{
			this.SetControlStateVar( "dependantField", fieldObject.actionId, tableRowId, tableId );
		}

		//Se define la funcion call back que se debe ejecutar una vez se complete el proceso server
		this.callBackFunction = this.FinishFieldValidation;
		this.callBackObject = fieldObject;

		//Se prende el atributo de validacion para que no haga otras validaciones concurrentemente.
		this.processOnGoing = true;

		//Se dispara la ejecucion de proceso en el servidor.
		this.StartServerProcess();
	}

	return( true );
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de completar el proceso de validacion de un 
*	 campo, una vez se ha retornado el nuevo DOM del server
* PARAMETROS:
*	 none
* RESULTADO:
*	 El campo fue validado
* PRE:
*	 Se acaba de recibir un DOM del server con el resultado de la
*	 validacion en el servidor
* POST:
*	 Se ejecutaron los procesos que exigia el campo posteriores a
*	 la ejecucion del proceso server
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_FinishFieldValidation()
{
	var xmlDocument = null;
	var fieldObject;
	var validateFunction;

	xmlDocument = this.formExchangeXmlDOM.documentElement;

	/* Como primera medida se actualiza la interfaz del formulario con los nuevos valores */
	this.UpdateInterfaceFields( xmlDocument );

	fieldObject = this.callBackObject;

	//La validacion fue exitosa, o reporto una advertencia, pero puede
	//continuar el flujo normal del programa, se ejecuta la funcion Post.
	if( fieldObject.clientValidationPost != null )
	{
		// El campo validado tiene un proceso posterior al proceso servidor. Se ejecuta
		fieldObject.clientValidationPost();
	}

	this.processOnGoing = false;
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de actualizar el documento DDI a partir de los
*	 valores que tienen los campos en la interfaz
* PARAMETROS:
*	 none
* RESULTADO:
*	 Los valores en el DOM para los diferentes campos coinciden con 
*	 los valores de la interfaz
* PRE:
*	 El formulario está completamente definido
* POST:
*	 La interfaz se encuentra actualizada
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_UpdateDOMFromFields( xmlDocument, tableRowId )
{
	/********************************************************
			Variables										*
	*********************************************************/

	//Recorrer el DDI
	var childCursor = new Number();
	var nodeObject = null;
	var nodeName = new String();
	var callSubElement = new Boolean();
	var currentObject = null;

	/********************************************************
			Inicio proceso									*
	*********************************************************/

	//Iniciar la iteracion sobre el nodo actual
	nodeObject = xmlDocument.firstChild;
	while( nodeObject != null )
	{
		//Validar solo nodos elemento
		if( nodeObject.nodeType == 1 )
		{
			nodeName = nodeObject.nodeName;

			if( tableRowId == null )
			{
				tableRowId = "";
			}

			callSubElement = true;

			//Valida los tipos de objetos que permiten ser anadidos a IBIZA
			if( nodeName == "IBZ_Section" || nodeName == "IBZ_TextField"
				|| nodeName == "IBZ_ListField" || nodeName == "IBZ_LabelField" || nodeName == "IBZ_DateField"
				|| nodeName == "IBZ_TextAreaField" || nodeName == "IBZ_Table"
				|| nodeName == "IBZ_ControlStateVars" || nodeName == "IBZ_StateVar"
				|| nodeName == "IBZ_TableRow" )
			{
			
				//validar cada tipo de elemento para llamar al objeto respectivo
				if( nodeName == "IBZ_Section" )
				{
					callSubElement = true;
				}
				else if( nodeName == "IBZ_TextField" )
				{
					nodeObject.text = this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].GetValue();
					callSubElement = false;
				}
				else if( nodeName == "IBZ_ListField" )
				{
					//removeChilds( nodeObject );
					this.listAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].GetValue( nodeObject );
					callSubElement = false;
				}
				else if( nodeName == "IBZ_LabelField" )
				{
					nodeObject.text = this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].GetValue();
					callSubElement = false;
				}
				else if( nodeName == "IBZ_DateField" )
				{
					nodeObject.text = this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].GetValue();
					callSubElement = false;
				}
				else if( nodeName == "IBZ_TextAreaField" )
				{
					nodeObject.text = this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].GetValue();
					callSubElement = false;
				}
				else if( nodeName == "IBZ_Table" )
				{
					currentObject = this.tableAssocArray[ nodeObject.getAttribute( "tableId" ) ];
					nodeObject.setAttribute( "pageSize" ) = currentObject.pageSize;

					callSubElement = true;
				}
				else if( nodeName == "IBZ_TableRow" )
				{
					tableRowId = "_" + nodeObject.getAttribute( "tableRowId" );

					currentObject = this.tableAssocArray[ nodeObject.parentNode.getAttribute( "tableId" ) ];
					if( currentObject.rowArray[ Number( nodeObject.getAttribute( "tableRowId" ) ) - 1 ] != null )
					{
						callSubElement = !( currentObject.rowArray[ Number( nodeObject.getAttribute( "tableRowId" ) ) - 1 ].disabled );
					}
					else
					{
						callSubElement = false;
					}
				}

				//valida si tiene sub elementos
				if( callSubElement == true && nodeObject.hasChildNodes() == true )
				{
					this.UpdateDOMFromFields( nodeObject, tableRowId );
				}
			}
		}

		//Iterar sobre el siguiente nodo
		nodeObject = nodeObject.nextSibling;
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de anadir un IBZ_ListItem al campo IBZ_ListField
* PARAMETROS:
*	 none
* RESULTADO:
*	 Los campos contienen los valores actualizados
* PRE:
*	 Se acaba de recibir un DOM del server con el resultado del
*	 proceso ejecutado en el servidor, y se encuentra en 
* POST:
*	 La interfaz se encuentra actualizada
* OJO: 
*-------------------------------------------------------------------- */
function appendListItem( xmlNode, selected, returnValue, textValue )
{
	var newItem;

	if( ( returnValue != null && returnValue != "" ) 
		|| ( textValue != null && textValue != "" ) )
	{
		newItem = xmlNode.ownerDocument.createElement( "IBZ_ListItem" );

		newItem.setAttribute( "selected", selected.toString() );
		newItem.setAttribute( "return", returnValue );
		newItem.text = textValue;

		xmlNode.appendChild( newItem );
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de eliminar los sublementos de un nodo
* PARAMETROS:
*	 none
* RESULTADO:
*	 Los campos contienen los valores actualizados
* PRE:
*	 Se acaba de recibir un DOM del server con el resultado del
*	 proceso ejecutado en el servidor, y se encuentra en 
* POST:
*	 La interfaz se encuentra actualizada
* OJO: 
*-------------------------------------------------------------------- */
function removeChilds( xmlNode )
{
	var itemCursor;

	if( xmlNode.hasChildNodes == true )
	{
		for(itemCursor = 0; itemCursor < xmlNode.childNodes.length; itemCursor++ )
{
			xmlNode.removeChild( xmlNode.childNodes.item( itemCursor ) );

			//Valor necesario para que elimine cada item debido al recalculo de posicion al eliminar con el anterior metodo
			itemCursor--;
		}
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Metodo responsable de actualizar todos los campos de la interfaz
*	 con los valores obtenidos desde el servidor
* PARAMETROS:
*	 none
* RESULTADO:
*	 Los campos contienen los valores actualizados
* PRE:
*	 Se acaba de recibir un DOM del server con el resultado del
*	 proceso ejecutado en el servidor, y se encuentra en 
* POST:
*	 La interfaz se encuentra actualizada
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_UpdateInterfaceFields( xmlDocument, tableRowId )
{
	/********************************************************
			Variables										*
	*********************************************************/

	//Recorrer el DDI
	var childCursor = new Number();
	var nodeObject = null;
	var nodeName = new String();
	var callSubElement = new Boolean();
	var currentObject = null;

	/********************************************************
			Inicio proceso									*
	*********************************************************/

	//Iniciar la iteracion sobre el nodo actual
	nodeObject = xmlDocument.firstChild;
	while( nodeObject != null )
	{
		//Validar solo nodos elemento
		if( nodeObject.nodeType == 1 )
		{
			nodeName = nodeObject.nodeName;

			callSubElement = false;
			if( tableRowId == null )
			{
				tableRowId = "";
			}

			//Valida los tipos de objetos que permiten ser anadidos a IBIZA
			if( nodeName == "IBZ_Section" || nodeName == "IBZ_Action" || nodeName == "IBZ_TextField"
				|| nodeName == "IBZ_ListField" || nodeName == "IBZ_LabelField" || nodeName == "IBZ_DateField"
				|| nodeName == "IBZ_TextAreaField" || nodeName == "IBZ_Table" 
				|| nodeName == "IBZ_ControlStateVars" || nodeName == "IBZ_StateVar"
				|| nodeName == "IBZ_TableRow" )
			{
				//validar cada tipo de elemento para llamar al objeto respectivo
				if( nodeName == "IBZ_Section" )
				{
					//Obtener el objeto de IBIZA
					this.sectionAssocArray[ nodeObject.getAttribute( "sectionId" ) ].Update( nodeObject );

					//Valida si es recursivo o no
					callSubElement = true;
				}
				else if( nodeName == "IBZ_Action" )
				{
					this.actionAssocArray[ nodeObject.getAttribute( "actionId" ) ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_TextField" )
				{
					this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_ListField" )
				{
					this.listAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_LabelField" )
				{
					this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_DateField" )
				{
					this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_TextAreaField" )
				{
					this.fieldAssocArray[ nodeObject.getAttribute( "fieldCode" ) + tableRowId ].Update( nodeObject );
				}
				else if( nodeName == "IBZ_Table" )
				{
					currentObject = this.tableAssocArray[ nodeObject.getAttribute( "tableId" ) ];

					currentObject.Update( nodeObject );
					currentObject.FillPageSize();

					//Valida si es recursivo o no
					callSubElement = true;
				}
				else if( nodeName == "IBZ_TableRow" )
				{
					tableRowId = "_" + nodeObject.getAttribute( "tableRowId" );

					//Valida si es recursivo o no
					callSubElement = true;
				}
				else if( nodeName == "IBZ_ControlStateVars" )
				{
					//Valida si es recursivo o no
					callSubElement = true;
				}
				else if( nodeName == "IBZ_StateVar" )
				{
					currentObject = this.controlStateVarsDoc.selectSingleNode( "IBZ_StateVar[ @varName = '" + nodeObject.getAttribute("varName") + "' ]" );

					if( currentObject != null )
					{
						currentObject.text = nodeObject.text;
					}
				}

				//valida si tiene sub elementos
				if( callSubElement == true && nodeObject.hasChildNodes() == true )
				{
					this.UpdateInterfaceFields( nodeObject, tableRowId );
				}
			}
		}

		//Iterar sobre el siguiente nodo
		nodeObject = nodeObject.nextSibling;
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Con base en las propiedades asignadas del DOM se procede a ejecutar la accion
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_Update( xmlDocument )
{
	var atrCursor = new Number();
	var attributeObject = null;
	var chlCursor = new Number();
	var childObject = null;

	//Iterar sobre los atributos
	//Asignarlos a array asociativo
	for( atrCursor = 0; atrCursor < xmlDocument.attributes.length; atrCursor ++ )
	{
		attributeObject = xmlDocument.attributes( atrCursor );

		if( attributeObject.name == "clientValidationPre" || attributeObject.name == "clientValidationPost" )
		{
			this[ attributeObject.name ] = eval( attributeObject.value );
		}
		else
		{
			this[ attributeObject.name ] = attributeObject.value;
			this.XMLDocument.setAttribute( attributeObject.name, attributeObject.value );
			this.ChangeState( attributeObject.name );
		}
	}

	if( xmlDocument.hasChildNodes == true 
		&& ( this.type == "addremove" || this.action == "select" ) )
	{
		//Eliminar los valores actuales
		while(this.XMLDocument.firstChild != null)
		{
			this.XMLDocument.removeChild(this.XMLDocument.firstChild);
		}

		//Ingresar los nuevos valores
		while( (childObject = xmlDocument.firstChild) != null )
		{
			this.XMLDocument.appendChild(childObject);
		}
	}

	if( this.SetValue != null && isBlank( xmlDocument.text ) == false )
	{
		this.SetValue( xmlDocument.text );
		this.XMLDocument.text = xmlDocument.text;
	}

	if( this.UpdateItems != null )
	{
		this.UpdateItems();
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Recorre todas las variables de control del documento, hasta encontrar
*	 la variable buscada, en cuyo caso se le asigna tal valor. Si no
*	 existe, se crea la variable con el valor especificado.
* PARAMETROS:
*	 controlStateVarName: Nombre de la variable de control
*	 newValue: Nuevo valor que debe tener la variable de control
* RESULTADO:
*	 none
* PRE:
*	 El objeto XML DOM del formulario se encuentra definida, y el
*	 atributo controlStateVarsDoc contiene el sub-documento con las
*	 variables de estado.
* POST:
*	 La variable de control cuyo nombre es controlStateVarName
*	 contiene ahora el valor newValu*
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_SetControlStateVar( controlStateVarName, newValue, tableRowId, tableId )
{
	var xmlDocument;

	xmlDocument = this.controlStateVarsDoc.selectSingleNode( "./IBZ_StateVar[ @varName = '" + controlStateVarName + "' ]" );

	if( xmlDocument != null )
	{
		if( tableRowId != null )
		{
			xmlDocument.setAttribute( "tableRowId", tableRowId );
		}
		else
		{
			xmlDocument.removeAttribute( "tableRowId" );
		}

		if( tableId != null )
		{
			xmlDocument.setAttribute( "tableId", tableId );
		}

		xmlDocument.text = newValue;
	}
}

/*-----------------------------------------------------------------------
* DESCRIPCION:
*	 Con base en las propiedades asignadas del DOM se procede a ejecutar la accion
* PARAMETROS:
*	 None
* RESULTADO:
*	 Se ejecuto el proceso de construccion del formulario
* PRE:
* POST:
* OJO: 
*-------------------------------------------------------------------- */
function IBZForm_RequiredFieldsEmpty()
{
	var indexField = Number();
	var returnValue;

	returnValue = true;
	indexField = 0;
	while( indexField < this.fieldArray.length && returnValue == true )
	{
		if( ( this.fieldArray[indexField].required == "yes" || this.fieldArray[indexField].required == "true" ) 
			&& ( this.fieldArray[indexField].XMLDocument.parentNode.getAttribute("visible") == "yes" || this.fieldArray[indexField].XMLDocument.parentNode.getAttribute("visible") == "true" )
			&& this.fieldArray[indexField].IsEmpty() == true )
		{
			alert( "Por favor diligencie el campo " + this.fieldArray[indexField].name );
			returnValue = false;
		}

		indexField ++;
	}

	return( returnValue );

}

