﻿//var ajax_url_prefix = 'http://localhost/www';

function get_proxy_http()
{
	//frame
	var frame = document.getElementById('proxy');		
	
	if (!frame)
		return null;
	
	var frame_document;
	if (typeof(frame.contentDocument) != "undefined")
	{
		var frame_document = frame.contentDocument;
		var frame_window = frame.contentWindow;
	}
	else
	{
		var frame_document = frame.document;
		var frame_window = frame.contentWindow;
	}
	//
	
	if (!frame_document)
		return null;
	
	var HXR = frame_window.getXMLHttpRequest();
	
	return HXR;
}

function process_ajax_url(this_url)
{
	var ajax_url = '';

	var ajax_static_url = '';
	
	if (window.ajax_url_prefix && false) 
	{			
		ajax_url = window.ajax_url_prefix;    //alert('exists');		
	
		ajax_url.replace(/^\s+|\s+$/g, '') ;  //trim
		
		var last_char = ajax_url.charAt(ajax_url.length-1);		
	
		if (last_char != "\/" && last_char != "\\" )
			ajax_url = ajax_url + '\/';				
	}
	else {	/*alert('does´t exists');*/  }	
	
	if (window.ajax_static_url_prefix && false) 
	{			
		ajax_static_url = window.ajax_static_url_prefix;    //alert('exists');		
	
		ajax_static_url.replace(/^\s+|\s+$/g, '') ;  //trim
		
		var last_char = ajax_static_url.charAt(ajax_static_url.length-1);		
	
		if (last_char != "\/" && last_char != "\\" )
			ajax_static_url = ajax_static_url + '\/';				
	}
	else {	/*alert('does´t exists');*/  }
	
	this_url = this_url.replace('#','');
	
	if (ajax_static_url == document.URL)
	{
		ajax_url = ajax_static_url + "proxy/proxy.php?proxy_url=" + ajax_url + this_url;;
	}
	else
	{	
		ajax_url = ajax_url + this_url;
	}
	
	//alert(/*this.url*/ajax_url);
	
	return ajax_url;
}

function process_submit_url(this_url)
{
	var ajax_url = '';
	
	if (window.ajax_url_prefix && false) 
	{			
		ajax_url = window.ajax_url_prefix;    //alert('exists');		
		
		ajax_url.replace(/^\s+|\s+$/g, '') ;  //trim
		
		var last_char = ajax_url.charAt(ajax_url.length-1);
		
		if (last_char != "/" && last_char != "\\" )
			ajax_url = ajax_url + '/';				
	}
	else {	/*alert('does´t exists');*/  }
	
	this_url = this_url.replace('#','');
	
	ajax_url = ajax_url + this_url;
	
	//alert(/*this.url*/ajax_url);
	
	return ajax_url;
}

/************************************* 050-ajax.js *********************************************

/* ***********************************************
 *	Implementación de AJAX
 *	Inmedia Web Builder Engine.
 *	Comunicación asícrona con el servidor para enviar
 *	una petición y procesar una url.
 * ***********************************************
 */

/*
 * Clase que realiza las funciones de ajax comunicación
 * asíncrona.
 */
function WBE_AjaxClass()
{

	this.parameters = new Array();
	this.httpReq;
	this.url = "NO_OUTPUT.wbe";
	this.xml_resource = "XML_DOCUMENT.wbe";
	//this.url = window.document.location.toString();
	this.params;
	this.async = false;	// Indica si se utilizará una comunicación asíncrona
	this.skip_edit_mode = false;	// Indica si se realizará la operación evitando el entorno de edición
	this.hasErrors = (!this.httpReq || this.httpReq.status != 200);
	this.timeout = 0;

	this.waitResponseHandler = function() {};

	/* Inizializa Ajax para nuevas llamadas */
	this.clear = function () {
		this.parameters = new Array();
	}

	/* Añade un nuevo parámetro para enviar.
	   Sólo lo añade si llega un parámetro */
	this.addEventPostParameter = function(sName, sValue) {
		if (sName!=null && sValue!=null) {
		
			sValue += "";
			if (sValue.indexOf('&') > 0) {
				a_sValue = sValue.split('&');
				sValue = a_sValue[0];
				var sAuxName = a_sValue[1].substring(0, a_sValue[1].indexOf('='));
				var sAuxValue = a_sValue[1].substring(a_sValue[1].indexOf('=')+1);
				this.addPostParameter(sAuxName, sAuxValue);
			}
			
			this.parameters[this.parameters.length] = sName + "=" + encodeURIComponent(sValue);
		}
	}	

	/* Añade un nuevo parámetro para enviar.
	   Sólo lo añade si llega un parámetro */
	this.addPostParameter = function(sName, sValue) {
		if (sName!=null && sValue!=null) {
			this.parameters[this.parameters.length] = sName + "=" + encodeURIComponent(sValue);
		}
	}	

    /* Añade un parametro para comprobar que el idioma no ha cambiado mientras estamos editando */
    this.addLngParameter = function() {

        var oLngId = document.getElementsByName('wbe_context_lng_id')[0];
        if (oLngId != null) {
            // comprueba si ya esta añadido
            var bAddParam = true;
            for (var i = 0; i < this.parameters.length; i++) {
                if (this.parameters[i].indexOf('wbe_context_lng_id=') > -1) {
                    bAddParam = false;
                    break;
                }
            }

            if (bAddParam) this.addPostParameter('wbe_context_lng_id', oLngId.value);
        }

    }
	
	/* Devuelve el valor de un nodo del XML que se le pasa */
	this.getXMLNodeValue = function (oXMLNode, sTagName) {
		var value = oXMLNode.getElementsByTagName(sTagName);
		return (value!=null && value.length>0 && value[0].firstChild!=null)
			? value[0].firstChild.nodeValue
			: '';
	}
	
	// Esta función envía una petición AJAX al servidor a la
	// Url que se le pasa enviando un POST con la cadena de parámetros.
	this.call = function ()  {

		this.httpReq = get_proxy_http();
		
		if (this.httpReq == null)
			if (window.XMLHttpRequest) { // Mozilla, Safari,...
				this.httpReq = new XMLHttpRequest();
				if (this.async)
					this.httpReq.onreadystatechange = this.waitResponseHandler;
			} else if (window.ActiveXObject) { // IE
				try {
					this.httpReq = new ActiveXObject("Msxml2.XMLHTTP");
					if (this.async)
						this.httpReq.onload = this.waitResponseHandler;
				} catch (e) {
					try {
					this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
					if (this.async)
						this.httpReq.onreadystatechange = this.waitResponseHandler;
					} catch (e) {}
				}
			}

		if (!this.httpReq) {
			alert('No puedo crear una instancia AJAX');
			return false;
		}

		/*
		// Crea la instancia para crear llamadas.
		if (window.ActiveXObject != undefined) { // IE
			this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
			// Inicializa la función que comprobará la request
			this.httpReq.onreadystatechange = this.waitResponseHandler;
				
		} else {	// Mozilla
			this.httpReq = new XMLHttpRequest();
			// Inicializa la función que comprobará la request
			this.httpReq.onload = this.waitResponseHandler;
		}
		*/		
	
		this.url=this.url.replace('#','');
		//alert(this.url);
		//alert(this.params);
		
		if (this.skip_edit_mode) {
			//this.addPostParameter("switch_off_edit_environment", "1");
			if (this.params != "") this.params += "&";
			else this.params += "?";
			this.params += "switch_off_edit_environment=1";
		}
		
		// Llamada a la URL
		if (this.timeout>0) this.httpReq.timeout = this.timeout;
		this.httpReq.open("POST", process_ajax_url(this.url), this.async);	// Comunicación síncrona por el flag: false
		this.httpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		this.httpReq.send(this.params);

		// Sólo para comunicación sícrona
		if (!this.async)
			this.responseText = this.httpReq.responseText;
	
	};

	// Lanza un evento Ajax.
	// Recibe como entradas:
	//	Evento para lanzar.
	//	Parámetros para enviar en un array de strings.
	//	booleano indicando si la salida es un XMLDocument o como un string.
	this.throwEvent = function (sEvent, asParams, bDoXmlOutput, sUrl)
	{
		var xmlDoc;

		if (sUrl) this.url = sUrl;
		
		this.addLngParameter();

		this.params = "event=" + sEvent;
		if (asParams) {
			for (var i=0; i<asParams.length; i++)
				this.params += "&" + asParams[i];
		}
		// alert(this.params);

		// Llamada Ajax
		this.call();

		//alert(this.responseText);
		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;

		// La salida es XML Document.
		if (this.responseText=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}
		return xmlDoc.documentElement;
	};

	// Lanza una llamada a una url.
	this.throwCall2 = function (sUrl) {
		var xmlDoc;

		if (sUrl) this.url = sUrl;

		this.params = "";
		for (var i=0; i<this.parameters.length; i++) {
		  if (this.params!="") this.params += "&";
		  if (this.parameters[i]!=undefined)	this.params += this.parameters[i];
		}
		//alert(this.params);
		//alert(sUrl);
		
		//return;
		// Llamada Ajax
		this.call();
   }

	/* Lanza un evento Ajax que devuelve un objeto XML DOM
	// Recibe como entradas:
	//  Pgina que recoger?. */
	this.throwEventXML = function (sEvent)  {
    return this.throwEvent2(sEvent, true, this.xml_resource);
  }

	/* Lanza un evento Ajax.
	// Recibe como entradas:
	//	Evento para lanzar.
	//	booleano indicando si la salida es un XMLDocument o como un string.
	//  P?gina que recoger?. */
	this.throwEvent2 = function (sEvent, bDoXmlOutput, sUrl)
  {
		
		this.addLngParameter();
		this.addEventPostParameter("event", sEvent);
		this.throwCall2(sUrl);
	    
   		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;

		// La salida es XML Document.
		if (this.responseText == null || this.responseText == "") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}

		return xmlDoc.documentElement;
	};
		
	// Para Mozilla.
	// Carga el XML a partir de un string.
	this.LoadXMLMozilla = function (oDoc, s)
	{
		// parse the string to a new doc   
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		      
		// remove all initial children
		while (oDoc.hasChildNodes())
			oDoc.removeChild(this.lastChild);
		         
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			oDoc.appendChild(oDoc.importNode(doc2.childNodes[i], true));
		}
	};	

	// Lanza una llamada a una url.
	this.throwCall = function (asParams, bDoXmlOutput, sUrl)
	{
		var xmlDoc;

		if (sUrl) this.url = sUrl;
		if (asParams) {
			for (var i=0; i<asParams.length; i++)
				this.params += "&" + asParams[i];
		} else {
			this.params = "";
			for (var i=0; i<this.parameters.length; i++) {
				if (this.params!="") this.params += "&";
				if (this.parameters[i]!=undefined)	this.params += this.parameters[i];
			}
		}
		// alert(this.params);

		// Llamada Ajax
		this.call();

		// Salida de texto
		if (!bDoXmlOutput) return this.responseText;
		//alert(this.responseText);

		// La salida es XML Document.
		if (this.responseText=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, this.responseText);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(this.responseText);
			}
		}
		//alert(xmlDoc.documentElement);
		return xmlDoc.documentElement;
	};

	// Lanza una llamada a una url.
	this.createXmlDoc = function (sXml)
	{
		var xmlDoc;

		if (sXml=="") return null;

		if (document.implementation && document.implementation.createDocument) // For Nx, Mz
		{
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async = false;
			xmlDoc.onload = function() {  return (xmlDoc.readyState == 4);		};
			this.LoadXMLMozilla(xmlDoc, sXml);
		} else {
			if (window.ActiveXObject) { // For IE
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async = false;
				xmlDoc.onreadystatechange = function() {  return (xmlDoc.readyState == 4);		};
				xmlDoc.loadXML(sXml);
			}
		}
		//alert(xmlDoc.documentElement);
		return xmlDoc.documentElement;
	};
	
};


/************************************* 055-session-check.js *********************************************/
function ___WBECheckSession() {
	
	var httpReq;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		httpReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		try {
			httpReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httpReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (httpReq) {
		httpReq.open("POST", "session_check.aspx");
		httpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		httpReq.send("");
	}
	
	setTimeout('___WBECheckSession()', 900000);
}

// ********************************************************************************
// ********************************************************************************
// Clase utilizada para construir formularios.
// ********************************************************************************
// ********************************************************************************
function InmediaFormBuilder(iPosition)
{
	this.posId = iPosition;
	this.front = 1;

	//PINTADO DE FORMULARIOS

	// Gestión de las categorías de un usuario	
	this.selectedCatIds = new Array();
	this.selectedParentIds = new Array();
	
	// Añade una categoría seleccionada
	this.addSelectedCategory = function(iId) {
		this.selectedCatIds[this.selectedCatIds.length] = iId;
	}

	// Añade una categoría seleccionada
	this.addParentRelation = function(iId) {
		this.selectedParentIds[this.selectedParentIds.length] = iId;
	}

	// Indica si una categoría está seleccionada	
	this.arrayContainsValue = function(a_array, iId) {
		var i;
		if (a_array==null) return false;
		for (i=0; i<a_array.length; i++) {
			if (a_array[i]==iId) return true;	
		}
		return false;
	}
	
	// Recoge las categorías hijas y rellena el combo que se presenta
	this.GetCategoriesByParentId = function(iParentCat) {
		var oAjax = new WBE_AjaxClass();
		if (iParentCat==null) return null;
		oAjax.addPostParameter("cat_id", iParentCat);
		var oXmlDoc = oAjax.throwEventXML('cms_get_child_categories');
		var sStatus = oAjax.getXMLNodeValue(oXmlDoc, 's');
		if (sStatus=='0') {
			return oXmlDoc.getElementsByTagName("c");
		} else {
			alert('Error recuperando categorías');
			return null;
		}
	};

	// Crea opciones checkbox de una categoría padre
	this.createCategoryCheckBox = function(iParentCatId, sObjectName, bMultiple) {
		var i;
		var oDiv = document.getElementById(sObjectName);
		if (oDiv==null) return;
		var oNodeList = this.GetCategoriesByParentId(iParentCatId);
		var sOut = '';
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var bContains = this.arrayContainsValue(this.selectedCatIds ,iValue);
			var sSelected = (bContains || (!bMultiple && this.selectedCatIds.length==0 && i==0) ) ? 'checked' : '';
			var sType = (bMultiple) ? "checkbox" : "radio";
			sOut += "<input class='form_" + sType + "' type='" + sType + "' name='category_" + this.posId + "' value='" + 
				iValue + "' " + sSelected + "> " + sDesc + "<br/>"; 
		}
		oDiv.innerHTML = sOut;
	}
	
	// Crea opciones combobox de una categoría padre
	this.fillCategoryCombo = function(iParentCat, sObjectID) {
		var i;
		var oComboElem = document.getElementById(sObjectID);
		if (oComboElem==null) return;
		oComboElem.name="category_" + this.posId;
		var oNodeList = this.GetCategoriesByParentId(iParentCat);
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var opt = new Option(sDesc, iValue);
			opt.selected = (this.arrayContainsValue(this.selectedCatIds ,iValue));
			oComboElem.options[oComboElem.length] = opt;
		}
	}

	this.getContentListByTypeId = function(iCParentId) {
		var oAjax = new WBE_AjaxClass();
		if (iCParentId==null) return null;
		oAjax.addPostParameter("ctype_id", iCParentId);
		var oXmlDoc = oAjax.throwEventXML('cms_get_content_list');
		var sStatus = oAjax.getXMLNodeValue(oXmlDoc, 's');
		if (sStatus=='0') {
			return oXmlDoc.getElementsByTagName("c");
		} else {
			alert('Error recuperando contenidos');
			return null;
		}
	}
	
	this.getFrontContentListByTypeIdAndAtt = function(iCParentId,sAttCode) {
		var oAjax = new WBE_AjaxClass();
		if (iCParentId==null) return null;
		oAjax.addPostParameter("front", this.front);
		oAjax.addPostParameter("ctype_id", iCParentId);
		oAjax.addPostParameter("att_code", sAttCode);
		var oXmlDoc = oAjax.throwEventXML('cms_get_content_list_byAtt');
		var sStatus = oAjax.getXMLNodeValue(oXmlDoc, 's');
		if (sStatus=='0') {
			return oXmlDoc.getElementsByTagName("c");
		} else {
			alert('Error recuperando contenidos');
			return null;
		}
	}

	this.getFrontContentListByTypeId = function(iCParentId) {
		var oAjax = new WBE_AjaxClass();
		if (iCParentId==null) return null;
		oAjax.addPostParameter("ctype_id", iCParentId);
		oAjax.addPostParameter("front", this.front);
		var oXmlDoc = oAjax.throwEventXML('cms_get_content_list');
		var sStatus = oAjax.getXMLNodeValue(oXmlDoc, 's');
		if (sStatus=='0') {
			return oXmlDoc.getElementsByTagName("c");
		} else {
			alert('Error recuperando contenidos');
			return null;
		}
	}

	this.getContentListByTypeIdAndParents = function(iCParentId, oParentIds) {
		var oAjax = new WBE_AjaxClass();
		if (iCParentId == null) return null;
		oAjax.addPostParameter("ctype_id", iCParentId);
		
		if (oParentIds) {
			var sIds = '';
			for (var i = 0; i < oParentIds.length; i++) {
				if (oParentIds[i] != '')
					if (sIds.length > 0) sIds += ',';
					sIds += oParentIds[i];
			}
			oAjax.addPostParameter("parent_ids", sIds);
		}
		
		var oXmlDoc = oAjax.throwEventXML('cms_get_content_list');
		var sStatus = oAjax.getXMLNodeValue(oXmlDoc, 's');
		if (sStatus=='0') {
			return oXmlDoc.getElementsByTagName("c");
		} else {
			alert('Error recuperando contenidos');
			return null;
		}
	}
	// Crea opciones combobox con un tipo de contenido
	this.fillContentParentCombo = function(iContentTypeId, sObjectName) {
		var i;
		var oComboElem = document.getElementById(sObjectName);
		if (oComboElem==null) return;
		oComboElem.name="content_parent_" + this.posId;
		var oNodeList = this.getContentListByTypeId(iContentTypeId);
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var opt = new Option(sDesc, iValue);
			opt.selected = (this.arrayContainsValue(this.selectedParentIds ,iValue));
			oComboElem.options[oComboElem.length] = opt;
		}
	}
	
	// Crea opciones combobox con un tipo de contenido y su atributo a recuperar
	this.fillContentParentComboFrontByAtt = function(iContentTypeId, sAttCode, sObjectName) {
		var i;
		var oComboElem = document.getElementById(sObjectName);
		if (oComboElem==null) return;

		var oNodeList = this.getFrontContentListByTypeIdAndAtt(iContentTypeId, sAttCode);
		//oComboElem.options.length = 0;
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var opt = new Option(sDesc, iValue);
			//opt.selected = (this.arrayContainsValue(this.selectedParentIds ,opt.value)); no funciona bien en IE6
			oComboElem.options[oComboElem.length] = opt;
		}
		// Seleccionamos el marcado
		for (i=0; i<oComboElem.options.length; i++) {
			var opt = oComboElem.options[i];
			if (this.arrayContainsValue(this.selectedParentIds ,opt.value)) {
				opt.selected = true;
				break;
			}
		}
	}

	// Crea opciones combobox con un tipo de contenido
	this.fillContentParentComboFront = function(iContentTypeId, sObjectName) {
		var i;
		var oComboElem = document.getElementById(sObjectName);
		if (oComboElem==null) return;
		oComboElem.name="content_parent_" + this.posId;
		var oNodeList = this.getFrontContentListByTypeId(iContentTypeId);
		//oComboElem.options.length = 0;
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var opt = new Option(sDesc, iValue);
			//opt.selected = (this.arrayContainsValue(this.selectedParentIds ,opt.value)); no funciona bien en IE6
			oComboElem.options[oComboElem.length] = opt;
		}
		// Seleccionamos el marcado
		for (i=0; i<oComboElem.options.length; i++) {
			var opt = oComboElem.options[i];
			if (this.arrayContainsValue(this.selectedParentIds ,opt.value)) {
				opt.selected = true;
				break;
			}
		}
	}

	// Crea opciones combobox con un tipo de contenido, que están relacionados con los contenidos cuyos ids se les pasan
	this.fillContentParentComboWithParents = function(iContentTypeId, sObjectName, oParentIds) {
		var i;
		var oComboElem = document.getElementById(sObjectName);
		if (oComboElem==null) return;
		oComboElem.name="content_parent_" + this.posId;
		var oNodeList = this.getContentListByTypeIdAndParents(iContentTypeId, oParentIds);
		for (i=0; i<oNodeList.length; i++) {
			var oNode = oNodeList[i];
			var iValue = oNode.childNodes[0].firstChild.data;
			var sDesc = oNode.childNodes[1].firstChild.data;
			var opt = new Option(sDesc, iValue);
			opt.selected = (this.arrayContainsValue(this.selectedParentIds ,iValue));
			oComboElem.options[oComboElem.length] = opt;
		}
	}

	// Recupera los valores de la categoría	
	this.getFieldMultipleValues = function (sFieldName) {
		var i, j;
		var scat_id = '';
		var a_values = new Array();
		var oElems = document.getElementsByName(sFieldName);
		if (oElems==null) return scat_id;
		for (j=0; j<oElems.length; j++) {
			var oElem = oElems[j];
			if (oElem.options) {
				for (i=0;i<oElem.options.length;i++) {
					if (oElem.options[i].selected) {
						if (!this.arrayContainsValue(a_values, oElem.options[i].value)) {
							a_values[a_values.length] = oElem.options[i].value;
							if (scat_id!=null && scat_id!='') scat_id+=',';
							scat_id +=oElem.options[i].value;
						}
					}
				}
			} else {
				if (oElem.checked) {
					if (!this.arrayContainsValue(a_values, oElem.value)) {
						if (scat_id!=null && scat_id!='') scat_id+=',';
						scat_id +=oElem.value;
					}
				}
			}
		}
		return scat_id;
	}
	
}

/************************************* 070-form-validation.js*********************************************/

/*
 * Clase para realizar validaciones de formularios.
 */
function WBEFormValidator()
{
	this.NIFValidator = new NIF_CIFValidator();
	this.posId = 1;
	this.sLng = 'es';
	this.groupErrorMsg = false;	// Este atributo indica si agrupará los mensajes de error en 1 alert
	this.showAllErrorMsg = false; // Indica si se muestran todos los mensajes generados al validar, o se muestra uno genérico
	this.sMsgMandatoryField = "Por favor, introduzca un valor en el campo ";
	this.sMsgMaxLength = "El texto introducido es demasiado largo. Actualmente tiene #current# caracteres. El máximo permitido es #max#."
	this.oErrorLayer = null;


	// 'Constantes' que almacenan las expresiones regulares que definen
    // tipos de entrada estándar o utilizadas con mucha frecuencia	
	this.LOGIN= "^[a-zA-Z0-9_-]+$";
	this.PASSWORD= "^[a-zA-Z0-9_-]+$";
	this.EMAIL= "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$"; //"^(.+\@.+\..{3})$";// "^[a-zA-Z0-9_-]+(\.([a-zA-Z0-9_-])+)*@[a-zA-Z0-9_-]+[.][a-zA-Z0-9_-]+([.][a-zA-Z0-9_-]{2,3,4})*$";
	this.URL="(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\\.))+(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9\\&amp;%_\\./-~-]*)?";
	this.DIRECCIONWEB="(http://)*(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(/[a-zA-Z0-9\\&amp;%_\\./-~-]*)?";
	this.FECHA = "^\\d{1,2}/\\d{1,2}/\\d{4}$";
	this.HORA = "^\\d{1,2}:\\d{2}$";
	//this.MATRICULA = "^(\\d{4}[a-zA-Z]{3})|([a-zA-Z]{1,2}\\d{4}[a-zA-Z]{1,2})";
	this.MATRICULA = "^(\\d{4}[BCDFGHJKLMNPRSTVWXYZbcdfghjklmnprstvwxyz]{3})$|^([a-zA-Z]{1,2}\\d{4}[a-zA-Z]{1,2})$";
	
	//this.ENTERO = "^[0-9]+$";
	//this.ENTERO = "^(?:\-)?\d+$";			//Version acepta negativos (pero no va)
	this.ENTERO = "^(-|[0-9])[0-9]*$";		//Version acepta negativos
	//this.INT = "^(-|[0-9])[0-9]*$";		//Version acepta negativos
	//this.FLOAT = "^[0-9]+(,|\.)[0-9]+$";
	//this.FLOAT = "^(\-)?\d+(,|\.)\d+$";		//Version acepta negativos (pero no va)
	//this.FLOAT = "^(-)?\d+(,|\.)\d*$";		//Version acepta negativos (pero no va)
	this.FLOAT = "^(-|[0-9])[0-9]*(,|\.)[0-9]+$";	//Version acepta negativos
	
	this.POSTCODE = "^\\d{5}$";
	this.TELEFONO = "^\\d{9}$";//"[0-9]{2}\s[0-9]{3}\s[0-9]{2}\s[0-9]{2}";//"(^[0-9\s\+\-])+$"
	this.WEBDIR= "^[a-z0-9_·áàéèíïóòúüñç]+$";
	this.NOMBREDOMINIO="^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])";

	this.MONEDA = "^[0-9]{1,3}(\\.[0-9]{3})*(,[0-9]{1,2})?$|^[0-9]+(,[0-9]{1,2})?$";

	this.FLOAT2 = "^-?[0-9]+(,|\.)[0-9]+$";
	
	// Exp Reg adicionales:
	//	- NIF, CIF, NIF_CIF, TARJ_RESID
	//  - SEARCH_BOX
	
	this.LOGIN_MIN_LONG = 5;
	this.PASSWORD_MIN_LONG = 5;
	

	this.setErrorLayerById = function(sId){
		this.oErrorLayer = document.getElementById(sId);
	};
	this.setErrorLayer = function(elem){
		this.oErrorLayer = elem;
	};
	
	
	this.check_frames = false;
	this.bJustResult = false;
	
	/*	TEXTS	*/
	sInvalidDefault_es = "Formato inválido, por favor revise los datos";
	this.texts_es = new Array();
	this.texts_es[0] = "Por favor, rellene los campos obligatorios.";
	this.texts_es[1] = "El texto introducido es demasiado largo. Actualmente tiene #current# caracteres. El máximo permitido es #max#.";
	//msgInvalidFormat
	this.texts_es[2] = "Debe especificar un filtro de más de tres letras.";
	this.texts_es[3] = "El login o nombre de usuario sólo admite letras, números, guiones, y guiones bajos.\nLa longitud mínima es de " + this.LOGIN_MIN_LONG + " caracteres.";
	this.texts_es[4] = "El nombre de dominio no puede tener menos de tres caracteres.\n No debe contener la letra ñ ni vocales acentuadas.";
	this.texts_es[5] = "El password o clave de acceso sólo admite letras, números, guiones, y guiones bajos.\nLa longitud mínima es de " + this.PASSWORD_MIN_LONG + " caracteres.";
	this.texts_es[6] = "Debe escribir una dirección de correo válida";
	this.texts_es[7] = sInvalidDefault_es;
	this.texts_es[8] = sInvalidDefault_es;
	this.texts_es[9] = sInvalidDefault_es;
	this.texts_es[10] = "Formato de fecha incorrecto. Formato correcto: dd/mm/aaaa";
	this.texts_es[11] = sInvalidDefault_es;
	this.texts_es[12] = "NIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. 99999999P";
	this.texts_es[13] = "CIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. B99999999";
	this.texts_es[14] = "NIF / CIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. B99999999";
	this.texts_es[15] = "Tarjeta de residencia incorrecta.  No debe contener ni guiones ni espacios. Ej. X00000000P";
	this.texts_es[16] = "La matrícula debe ser de la forma: 1111BBB o AA1111AA";
	this.texts_es[17] = "Debe escribir un número entero";
	this.texts_es[18] = "Debe escribir un número decimal XX,XX";
	this.texts_es[19] = "Código postal incorrecto";
	this.texts_es[20] = "Número incorrecto.\nDebe ser de la forma: 991112233 y contener 9 dígitos.";
	this.texts_es[21] = "Directorio incorrecto. Sólo se pueden introducir caracteres en minúsculas, números y el carácter subrayado.";
	this.texts_es[22] = sInvalidDefault_es;
	this.texts_es[23] = "Fecha incorrecta";
	this.texts_es[24] = "Cuenta bancaria incorrecta";
	this.texts_es[25] = "El valor no coincide con su duplicado";
	this.texts_es[26] = "-> Existen campos obligatorios sin rellenar.\n";

	sInvalidDefault_ca = "Format invàlid. Per favor, revise les dades introduides";
	this.texts_ca = new Array();
	this.texts_ca[0] = "Per favor, cal introduir un valor al camp";
	this.texts_ca[1] = "El text introduit es massa llarg. Actualment te #current# caracters. El màxim permés es #max#.";
	//msgInvalidFormat
	this.texts_ca[2] = "Cal especificar un filtre de mes de 3 lletres.";
	this.texts_ca[3] = "El login sols admet lletres, nombres, guions, y guions baixos.\nLa longitud mínima es de " + this.LOGIN_MIN_LONG + " caracters.";
	this.texts_ca[4] = "El nom de domini no pot tenir menys de 3 caracters.\n No pot contindre la lletra ñ ni vocals acentuades.";
	this.texts_ca[5] = "El password sols admet lletres, nombres, guions, y guions baixos.\nLa longitud mínima es de " + this.PASSWORD_MIN_LONG + " caracters.";
	this.texts_ca[6] = "Deu escriure una adressa de email correcta";
	this.texts_ca[7] = sInvalidDefault_ca;
	this.texts_ca[8] = sInvalidDefault_ca;
	this.texts_ca[9] = sInvalidDefault_ca;
	this.texts_ca[10] = "Format de la data incorrecte. Format correcte: dd/mm/aaaa";
	this.texts_ca[11] = sInvalidDefault_ca;
	this.texts_ca[12] = "NIF incorrecte. No pot contindre ni guions ni espais.\n\nEj. 99999999P";
	this.texts_ca[13] = "CIF incorrecte. No pot contindre ni guions ni espais.\n\nEj. B99999999";
	this.texts_ca[14] = "NIF / CIF incorrecte. No pot contindre ni guions ni espais.\n\nEj. B99999999";
	this.texts_ca[15] = "Tarjeta de residencia incorrecta. No pot contindre ni guions ni espais. Ej. X00000000P";
	this.texts_ca[16] = "La matrícula deu ser de la forma: 1111BBB o AA1111AA";
	this.texts_ca[17] = "Deu escriure un nombre senser";
	this.texts_ca[18] = "Deu escriure un nombre decimal XX,XX";
	this.texts_ca[19] = "Codi postal incorrecte";
	this.texts_ca[20] = "Nombre incorrecte.\nDeu ser de la forma: 991112233 y contindre 9 dígits.";
	this.texts_ca[21] = "Directori incorrecte. Sóls es poden introduir caracters en minúscules, nombres y el subratllat.";
	this.texts_ca[22] = sInvalidDefault_ca;
	this.texts_ca[23] = "Data incorrecta";
	this.texts_ca[24] = "Compte bancari incorrecte";
	this.texts_ca[25] = "El valor no hi coincideix amb el duplicat";
	this.texts_ca[26] = "-> Existeixen camps obligatoris sense plenar.\n";

	sInvalidDefault_en = "Invalid format, please review input values";
	this.texts_en = new Array();
	this.texts_en[0] = "Text field required";
	this.texts_en[1] = "Text too long. You have typed #current# letters. Maximum letters allowed is #max# chars.";
	//msgInvalidFormat
	this.texts_en[2] = "At least must type 3 chars.";
	this.texts_en[3] = "The login only recognizes letters, numbers, hyphens, and underscores.\nThe minimum length is " + this.LOGIN_MIN_LONG + " characters.";
	this.texts_en[4] = "The domain name can not be less than 3 characters.\n You must not contain the letter ñ or accented vowels.";
	this.texts_en[5] = "The password only recognizes letters, numbers, hyphens, and underscores.\nThe minimum length is " + this.PASSWORD_MIN_LONG + " characters.";
	this.texts_en[6] = "Must enter a correct email address";
	this.texts_en[7] = sInvalidDefault_en;
	this.texts_en[8] = sInvalidDefault_en;
	this.texts_en[9] = sInvalidDefault_en;
	this.texts_en[10] = "Incorrect date format. Correct format: dd/mm/yyyy";
	this.texts_en[11] = sInvalidDefault_en;
	this.texts_en[12] = "NIF wrong. It must contain no spaces or hyphens.\n\nEj. 99999999P";
	this.texts_en[13] = "CIF wrong. It must contain no spaces or hyphens.\n\nEj. B99999999";
	this.texts_en[14] = "NIF / CIF wrong. It must contain no spaces or hyphens.\n\nEj. B99999999";
	this.texts_en[15] = "Residence card incorrectly. It must contain no spaces or dashes. Ej. X00000000P";
	this.texts_en[16] = "The plate must be of the form: 1111BBB o AA1111AA";
	this.texts_en[17] = "You must enter an integer";
	this.texts_en[18] = "Please enter a decimal number XX,XX";
	this.texts_en[19] = "Incorrect postal code";
	this.texts_en[20] = "Incorrect number.\nMust be of the form: 991112233 and contain 9 digits.";
	this.texts_en[21] = "Incorrect directory. You can only enter lowercase characters, numbers and underscores.";
	this.texts_en[22] = sInvalidDefault_en;
	this.texts_en[23] = "Incorrect date";
	this.texts_en[24] = "Incorrect Bank Account";
	this.texts_en[25] = "Check the value entered.";
	this.texts_en[26] = "-> Some obligatory fields have not been completed.\n";

	sInvalidDefault_fr = "Format non valide, s\'il vous plaît en revue les données";
	this.texts_fr = new Array();
	this.texts_fr[0] = "Texte champ obligatoire";
	this.texts_fr[1] = "Texte trop long. Vous avez tapé lettres #current#. Caractères maximum autorisé est de chars #max#.";
	//msgInvalidFormat
	this.texts_fr[2] = "Au moins doivent chars de type 3.";
	this.texts_fr[3] = "Le login ou nom d\'utilisateur prend en charge uniquement des lettres, chiffres, traits d\'unions et caractères de soulignement.\nLa durée minimum est de caractères " + this.LOGIN_MIN_LONG + ".";
	this.texts_fr[4] = "Le nom de domaine ne peut pas être inférieur à trois caractères.\n Vous ne doit pas contenir la lettre ñ, ou des voyelles accentuées.";
	this.texts_fr[5] = "Le mot de passe ou d'accès prend en charge uniquement des lettres, chiffres, traits d'unions et caractères de soulignement.\nLa durée minimum est de caractères " + this.PASSWORD_MIN_LONG + ".";
	this.texts_fr[6] = "Doit entrer une adresse électronique valide";
	this.texts_fr[7] = sInvalidDefault_fr;
	this.texts_fr[8] = sInvalidDefault_fr;
	this.texts_fr[9] = sInvalidDefault_fr;
	this.texts_fr[10] = "Date de format incorrect. Corriger format: dd/mm/aaaa";
	this.texts_fr[11] = sInvalidDefault_fr;
	this.texts_fr[12] = "NIF tort. Il doit contenir aucun espace ou trait d\'union.\n\Par exemple 99999999P";
	this.texts_fr[13] = "CIF tort. Il doit contenir aucun espace ou trait d\'union.\n\nPar exemple B99999999";
	this.texts_fr[14] = "NIF / CIF tort. Il doit contenir aucun espace ou trait d'union.\n\Par exemple B99999999";
	this.texts_fr[15] = "Carte de résidence de manière incorrecte. Il doit contenir aucun espace ou trait d\'union. Par exemple X00000000P";
	this.texts_fr[16] = "D\'inscription doit être de la forme: 1111BBB o AA1111AA";
	this.texts_fr[17] = "S\'il vous plaît entrer un nombre entier";
	this.texts_fr[18] = "S'il vous plaît entrer un nombre décimal XX,XX";
	this.texts_fr[19] = "Incorrect code postal";
	this.texts_fr[20] = "Wrong Number.\nDoit être de la forme: 991112233 et contenant 9 chiffres.";
	this.texts_fr[21] = "Wrong répertoire. Vous ne pouvez entrer des caractères minuscules, chiffres et le caractère de soulignement.";
	this.texts_fr[22] = sInvalidDefault_fr;
	this.texts_fr[23] = "Date non valide";
	this.texts_fr[24] = "Compte bancaire incorrect";
	this.texts_fr[25] = "La valeur ne correspond pas à son double";
	this.texts_fr[26] = "-> Il n'y a pas rempli les champs obligatoires.\n";
		
	sInvalidDefault_de = "Formato inválido, por favor revise los datos";
	this.texts_de = new Array();
	this.texts_de[0] = "Por favor, introduzca un valor en el campo";
	this.texts_de[1] = "El texto introducido es demasiado largo. Actualmente tiene #current# caracteres. El máximo permitido es #max#.";
	//msgInvalidFormat
	this.texts_de[2] = "Debes de especificar un filtro de más de 3 letras.";
	this.texts_de[3] = "El login solo admite letras, números, guiones, y guiones bajos.\nLa longitud mínima es de " + this.LOGIN_MIN_LONG + " caracteres.";
	this.texts_de[4] = "El nombre de dominio no puede tener menos de 3 caracteres.\n No debe contener la letra ñ ni vocales acentuadas.";
	this.texts_de[5] = "El password solo admite letras, números, guiones, y guiones bajos.\nLa longitud mínima es de " + this.PASSWORD_MIN_LONG + " caracteres.";
	this.texts_de[6] = "Debe escribir una direccion de correo correcta";
	this.texts_de[7] = sInvalidDefault_de;
	this.texts_de[8] = sInvalidDefault_de;
	this.texts_de[9] = sInvalidDefault_de;
	this.texts_de[10] = "Formato de fecha incorrecto. Formato correcto: dd/mm/aaaa";
	this.texts_de[11] = sInvalidDefault_de;
	this.texts_de[12] = "NIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. 99999999P";
	this.texts_de[13] = "CIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. B99999999";
	this.texts_de[14] = "NIF / CIF incorrecto. No debe contener ni guiones ni espacios.\n\nEj. 99999999B/B99999999";
	this.texts_de[15] = "Tarjeta de residencia incorrecta.  No debe contener ni guiones ni espacios. Ej. X00000000P";
	this.texts_de[16] = "La matricula debe ser de la forma: 1111BBB o AA1111AA";
	this.texts_de[17] = "Debe escribir un numero entero";
	this.texts_de[18] = "Debe escribir un numero decimal XX,XX";
	this.texts_de[19] = "Código postal incorrecto";
	this.texts_de[20] = "Número incorrecto.\nDebe ser de la forma: 991112233 y contener 9 dígitos.";
	this.texts_de[21] = "Directorio incorrecto. Sólo se pueden introducir caracteres en minúsculas, números y el subrayado.";
	this.texts_de[22] = sInvalidDefault_de;
	this.texts_de[23] = "Fecha incorrecta";
	this.texts_de[24] = "Cuenta bancaria incorrecta";
	this.texts_de[25] = "Compruebe el valor introducido.";
	this.texts_de[26] = "-> Einige Pflichtfelder wurden nicht vervollständigt.\n";
		
	// Simula la indexacion por string en javascript
	this.getText = function (sCode)
	{
		switch (this.sLng) {
			case 'es' : {
				switch (sCode) {
					case 'MandatoryField' : return this.texts_es[0]; break;
					case 'MaxLength' : return this.texts_es[1]; break;
					case 'InvalidFormat' : return sInvalidDefault_es; break;
					//msgInvalidFormat
					case 'SEARCH_BOX' : return this.texts_es[2]; break;
					case 'LOGIN' : return this.texts_es[3]; break;
					case 'NOMBREDOMINIO' : return this.texts_es[4]; break;
					case 'PASSWORD' : return this.texts_es[5]; break;
					case 'EMAIL' : return this.texts_es[6]; break;
					case 'URL' : return this.texts_es[7]; break;
					case 'DIRECCIONWEB' : return this.texts_es[8]; break;
					case 'MONEDA' : return this.texts_es[9]; break;
					case 'FECHA' : return this.texts_es[10]; break;
					case 'HORA' : return this.texts_es[11]; break;
					case 'NIF' : return this.texts_es[12]; break;
					case 'CIF' : return this.texts_es[13]; break;
					case 'NIF_CIF' : return this.texts_es[14]; break;
					case 'TARJ_RESID' : return this.texts_es[15]; break;
					case 'MATRICULA' : return this.texts_es[16]; break;
					case 'ENTERO' : 
					case 'INT' :
					case 'INTEGER' :return this.texts_es[17]; break;
					case 'FLOTANTE' : return this.texts_es[18]; break;
					case 'POSTCODE' : return this.texts_es[19]; break;
					case 'TELEFONO' : return this.texts_es[20]; break;
					case 'WEBDIR' : return this.texts_es[21]; break;
					case 'STRING' : return this.texts_es[22]; break;
					
					case 'threefieldsdate' : return this.texts_es[23]; break;
					case 'bankAccount' : return this.texts_es[24]; break;
					case 'compareWith' : return this.texts_es[25]; break;
					case 'errorMandatoryPresent' : return this.texts_es[26]; break;
				}
			} break;
			case 'ca' : {
				switch (sCode) {
					case 'MandatoryField' : return this.texts_ca[0]; break;
					case 'MaxLength' : return this.texts_ca[1]; break;
					case 'InvalidFormat' : return sInvalidDefault_ca; break;
					//msgInvalidFormat
					case 'SEARCH_BOX' : return this.texts_ca[2]; break;
					case 'LOGIN' : return this.texts_ca[3]; break;
					case 'NOMBREDOMINIO' : return this.texts_ca[4]; break;
					case 'PASSWORD' : return this.texts_ca[5]; break;
					case 'EMAIL' : return this.texts_ca[6]; break;
					case 'URL' : return this.texts_ca[7]; break;
					case 'DIRECCIONWEB' : return this.texts_ca[8]; break;
					case 'MONEDA' : return this.texts_ca[9]; break;
					case 'FECHA' : return this.texts_ca[10]; break;
					case 'HORA' : return this.texts_ca[11]; break;
					case 'NIF' : return this.texts_ca[12]; break;
					case 'CIF' : return this.texts_ca[13]; break;
					case 'NIF_CIF' : return this.texts_ca[14]; break;
					case 'TARJ_RESID' : return this.texts_ca[15]; break;
					case 'MATRICULA' : return this.texts_ca[16]; break;
					case 'ENTERO' : 
					case 'INT' :
					case 'INTEGER' : return this.texts_ca[17]; break;
					case 'FLOTANTE' : return this.texts_ca[18]; break;
					case 'POSTCODE' : return this.texts_ca[19]; break;
					case 'TELEFONO' : return this.texts_ca[20]; break;
					case 'WEBDIR' : return this.texts_ca[21]; break;
					case 'STRING' : return this.texts_ca[22]; break;
					
					case 'threefieldsdate' : return this.texts_ca[23]; break;
					case 'bankAccount' : return this.texts_ca[24]; break;
					case 'compareWith' : return this.texts_ca[25]; break;
					case 'errorMandatoryPresent' : return this.texts_ca[26]; break;
				}
			} break;
			case 'en' : {
				switch (sCode) {
					case 'MandatoryField' : return this.texts_en[0]; break;
					case 'MaxLength' : return this.texts_en[1]; break;
					case 'InvalidFormat' : return sInvalidDefault_en; break;
					//msgInvalidFormat
					case 'SEARCH_BOX' : return this.texts_en[2]; break;
					case 'LOGIN' : return this.texts_en[3]; break;
					case 'NOMBREDOMINIO' : return this.texts_en[4]; break;
					case 'PASSWORD' : return this.texts_en[5]; break;
					case 'EMAIL' : return this.texts_en[6]; break;
					case 'URL' : return this.texts_en[7]; break;
					case 'DIRECCIONWEB' : return this.texts_en[8]; break;
					case 'MONEDA' : return this.texts_en[9]; break;
					case 'FECHA' : return this.texts_en[10]; break;
					case 'HORA' : return this.texts_en[11]; break;
					case 'NIF' : return this.texts_en[12]; break;
					case 'CIF' : return this.texts_en[13]; break;
					case 'NIF_CIF' : return this.texts_en[14]; break;
					case 'TARJ_RESID' : return this.texts_en[15]; break;
					case 'MATRICULA' : return this.texts_en[16]; break;
					case 'ENTERO' : 
					case 'INT' :
					case 'INTEGER' : return this.texts_en[17]; break;
					case 'FLOTANTE' : return this.texts_en[18]; break;
					case 'POSTCODE' : return this.texts_en[19]; break;
					case 'TELEFONO' : return this.texts_en[20]; break;
					case 'WEBDIR' : return this.texts_en[21]; break;
					case 'STRING' : return this.texts_en[22]; break;
					
					case 'threefieldsdate' : return this.texts_en[23]; break;
					case 'bankAccount' : return this.texts_en[24]; break;
					case 'compareWith' : return this.texts_en[25]; break;
					case 'errorMandatoryPresent' : return this.texts_en[26]; break;
				}
            } break;
            case 'fr': {
                switch (sCode) {
                    case 'MandatoryField': return this.texts_fr[0]; break;
                    case 'MaxLength': return this.texts_fr[1]; break;
                    case 'InvalidFormat': return sInvalidDefault_fr; break;
                    //msgInvalidFormat 
                    case 'SEARCH_BOX': return this.texts_fr[2]; break;
                    case 'LOGIN': return this.texts_fr[3]; break;
                    case 'NOMBREDOMINIO': return this.texts_fr[4]; break;
                    case 'PASSWORD': return this.texts_fr[5]; break;
                    case 'EMAIL': return this.texts_fr[6]; break;
                    case 'URL': return this.texts_fr[7]; break;
                    case 'DIRECCIONWEB': return this.texts_fr[8]; break;
                    case 'MONEDA': return this.texts_fr[9]; break;
                    case 'FECHA': return this.texts_fr[10]; break;
                    case 'HORA': return this.texts_fr[11]; break;
                    case 'NIF': return this.texts_fr[12]; break;
                    case 'CIF': return this.texts_fr[13]; break;
                    case 'NIF_CIF': return this.texts_fr[14]; break;
                    case 'TARJ_RESID': return this.texts_fr[15]; break;
                    case 'MATRICULA': return this.texts_fr[16]; break;
                    case 'ENTERO' : 
					case 'INT' :
					case 'INTEGER' : return this.texts_fr[17]; break;
                    case 'FLOTANTE': return this.texts_fr[18]; break;
                    case 'POSTCODE': return this.texts_fr[19]; break;
                    case 'TELEFONO': return this.texts_fr[20]; break;
                    case 'WEBDIR': return this.texts_fr[21]; break;
                    case 'STRING': return this.texts_fr[22]; break;

                    case 'threefieldsdate': return this.texts_fr[23]; break;
                    case 'bankAccount': return this.texts_fr[24]; break;
                    case 'compareWith': return this.texts_fr[25]; break;
                    case 'errorMandatoryPresent': return this.texts_fr[26]; break;
                }
            } break;
			case 'de' : {
				switch (sCode) {
					case 'MandatoryField' : return this.texts_de[0]; break;
					case 'MaxLength' : return this.texts_de[1]; break;
					case 'InvalidFormat' : return sInvalidDefault_de; break;
					//msgInvalidFormat
					case 'SEARCH_BOX' : return this.texts_de[2]; break;
					case 'LOGIN' : return this.texts_de[3]; break;
					case 'NOMBREDOMINIO' : return this.texts_de[4]; break;
					case 'PASSWORD' : return this.texts_de[5]; break;
					case 'EMAIL' : return this.texts_de[6]; break;
					case 'URL' : return this.texts_de[7]; break;
					case 'DIRECCIONWEB' : return this.texts_de[8]; break;
					case 'MONEDA' : return this.texts_de[9]; break;
					case 'FECHA' : return this.texts_de[10]; break;
					case 'HORA' : return this.texts_de[11]; break;
					case 'NIF' : return this.texts_de[12]; break;
					case 'CIF' : return this.texts_de[13]; break;
					case 'NIF_CIF' : return this.texts_de[14]; break;
					case 'TARJ_RESID' : return this.texts_de[15]; break;
					case 'MATRICULA' : return this.texts_de[16]; break;
					case 'ENTERO' : return this.texts_de[17]; break;
					case 'FLOTANTE' : return this.texts_de[18]; break;
					case 'POSTCODE' : return this.texts_de[19]; break;
					case 'TELEFONO' : return this.texts_de[20]; break;
					case 'WEBDIR' : return this.texts_de[21]; break;
					case 'STRING' : return this.texts_de[22]; break;
					
					case 'threefieldsdate' : return this.texts_de[23]; break;
					case 'bankAccount' : return this.texts_de[24]; break;
					case 'compareWith' : return this.texts_de[25]; break;
					case 'errorMandatoryPresent' : return this.texts_de[26]; break;
				}
			} break;	
		}
	}
	
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ----------------------------- Funciones del 120-form-validator.js -------------------------------- */
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ------------------------------------------------------------------------------------------------------------ */
	 
	/* Funcion que recorre todos los campos de un formulario buscando
	 los atributos añadidos especiales y los procesa */
	this.validateForm = function  (formulario, pos_id, isRecursive, bJustResult)
	{
		this.bJustResult = bJustResult;
		
		//if (!isRecursive) {
			this.errorObjElements = new Array();
			this.errorFormatMsg = new Array();
		//}
		
		if (pos_id) pos_id = '' + pos_id;

	   // Recorremos los elementos del formulario    
	   for (var i=0; i<formulario.elements.length; i++)
	   {
		var elem = formulario.elements[i];
		var bvalidate = true;

		if (!elem.name) {
			bvalidate = false;
		} else {
			var iLPos = (pos_id!=null && elem.name.lastIndexOf('_' + pos_id)>=0) 
				? elem.name.length - (pos_id.length+1) 
				: 0;
			if (pos_id && (elem.name.lastIndexOf('_' + pos_id) != iLPos)) {
				bvalidate = false;
			}
		}

		//comprobamos que los campos tienen el prefijo asignado
		//para el caso de varios componentes en la misma página
		//Si es el mismo componente repetido entonces añadimos
		if (bvalidate) {
		
		  // Comprobamos que se han cumplimentado los elementos obligatorios
		  if (elem.getAttribute("required") == "1") 
		  {
			 var msgMandatoryField=elem.getAttribute("msgRequired");
			 if (msgMandatoryField==null) {
				msgMandatoryField = this.getText('MandatoryField');
			 }
			 elem.style.backgroundColor='';
			 switch (elem.type)
			 {
				case '':
				case 'hidden':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,null);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
					   
				case 'file':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,null);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
					
				case 'text':
					if (this.trimAll(elem.value)=='') {
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					if (elem.defaultVal && (elem.value == elem.defaultVal))
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
				case 'password':
					if (elem.value=='') {
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					if (elem.defaultVal && (elem.value == elem.defaultVal))
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
	
				case 'textarea':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
	
				case 'select-one':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
	
				case 'checkbox':
					if (!elem.checked)
					{
						this.ShowErrorMessage(msgMandatoryField,elem);
						if (!this.groupErrorMsg) return false;
					}
					break;
	
				case 'radio':
					var seleccionado=false;
					var j=0;
					while (formulario.elements[i+j].type=='radio' && 
					elem.name==formulario.elements[i+j].name)
					{
						if (formulario.elements[i+j].checked) seleccionado=true;
						if (i+j-1>=formulario.elements.length) break;
						j++;
					}
					j=0;
					while (formulario.elements[i-j].type=='radio' && 
					elem.name==formulario.elements[i-j].name)
					{
						if (formulario.elements[i-j].checked) seleccionado=true;
						if (i-j<=0) break;
						j++;					
					}				
					if (!seleccionado)
					{
						this.ShowErrorMessage(msgMandatoryField,elem);
						if (!this.groupErrorMsg) return false;				
					}
					break;
				 } // Fin del switch
		  }
	
		  // Comprobamos que se han cumplimentado los elementos obligatorios
		  if (elem.getAttribute("maxTextLength"))
		  {
			var msgMaxLength=elem.getAttribute("msgMaxLength");
			if (msgMaxLength==null) {
				msgMaxLength = this.getText('MaxLength');
			}
			
			if (elem.value.length > elem.getAttribute("maxTextLength"))
			{
				msgMaxLength = msgMaxLength.substring(0, msgMaxLength.indexOf('#current#')) + elem.value.length + msgMaxLength.substring(msgMaxLength.indexOf('#current#') + 9);
				msgMaxLength = msgMaxLength.substring(0, msgMaxLength.indexOf('#max#')) + elem.getAttribute("maxTextLength") + msgMaxLength.substring(msgMaxLength.indexOf('#max#') + 5);

				this.ShowErrorMessage(msgMaxLength,elem);                  
				if (!this.groupErrorMsg) return false;
			}
		  }
	

		  // Comprobamos que los datos se encuentran correctamente formateados	
		  var msgInvalidFormat=elem.getAttribute("msgInvalid");
		  if (msgInvalidFormat != null) msgInvalidFormat = this.getText('InvalidFormat').replace(/\\n/g,"\n");
		  var bForzeError = false;
		  switch (elem.type)
		  {
	
			 case '':
			 case 'text':
			 case 'password':
				if (elem.getAttribute("expresionRegular")!=null 
					&& elem.value!='') {
				   var expresionRegular=elem.getAttribute("expresionRegular");
				   var valor=elem.value;
				   var re;
				   switch (expresionRegular)
				   {
					  case 'SEARCH_BOX':  // Caja de busqueda
					 	 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('SEARCH_BOX');
						 }
						 bForzeError = (valor.length < 3);
						 re = null;
						 break;
					  case 'LOGIN':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('LOGIN');
						 }
						 bForzeError = (valor.length<this.LOGIN_MIN_LONG);
						 re=new RegExp(this.LOGIN);
						 break;
						 case 'NOMBREDOMINIO':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('NOMBREDOMINIO');
						 }
						 re=new RegExp(this.NOMBREDOMINIO);
						 break;
					  case 'PASSWORD':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('PASSWORD');
						 }
						 bForzeError = (valor.length < this.PASSWORD_MIN_LONG);
						 re=new RegExp(this.PASSWORD);
						 break;
					  case 'EMAIL':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('EMAIL');
						 }
						 re=new RegExp(this.EMAIL);
						 break;
					  case 'URL':
						 re=new RegExp(this.URL);
						 break;
					  case 'DIRECCIONWEB':
						 re=new RegExp(this.DIRECCIONWEB);
						 break;
						 
					  case 'MONEDA':
					  case 'MONEY':
						 re=new RegExp(this.MONEDA);
						 break;					 
					  case 'FECHA':
					  case 'DATE':
						 re=new RegExp(this.FECHA);
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('FECHA');
						 bForzeError = !this.chkdate(elem,null);
						 break;                     
					  case 'HORA':
				      case 'HOUR':
						 re=new RegExp(this.HORA);
						 bForzeError = !this.chkHora(elem);
						 break;        
					  case 'NIF':
						//Comprobacion inicial de NIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF');
						 re=null;
						 bForzeError = !this.NIFValidator.checkNIF(valor);
						 break;                             
					  case 'CIF':
						//Comprobacion inicial de CIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('CIF');
						 re=null;
						 bForzeError = !this.NIFValidator.checkCIF(valor);
						 break;                             
					  case 'NIF_CIF':
						//Comprobacion inicial de NIF y CIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF_CIF');
						 re=null;
						 bForzeError = !this.NIFValidator.checkAll(valor);
						 break;
					  case 'TARJ_RESID':
						//Comprobacion inicial de una 'Tarjeta de residencia' o 'NIF'
						if (msgInvalidFormat==null) msgInvalidFormat = this.getText('TARJ_RESID');
						 re=null;
						 bForzeError = !this.NIFValidator.checkTR(valor);
						 break;
					  case 'TARJ_RESID_NIF':
						//Comprobacion inicial de una 'Tarjeta de residencia' o 'NIF'
						 if ((valor.charAt(0).toUpperCase() != "X") && (valor.charAt(0).toUpperCase() != "Y") && (valor.charAt(0).toUpperCase() != "Z")){
							if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF');
							 bForzeError = !this.NIFValidator.checkNIF(valor);
						 }else{
							if (msgInvalidFormat==null) msgInvalidFormat = this.getText('TARJ_RESID');
							 bForzeError = !this.NIFValidator.checkTR(valor);
						 }
						 re=null;
						 break;
					  case 'MATRICULA':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('MATRICULA');
						 }
						 re=new RegExp(this.MATRICULA);
						 break;                                                               					 
					  case 'DECIMAL':
					  case 'ENTERO':
					  case 'INT':
					  case 'INTEGER':
						if (msgInvalidFormat==null) {                  
						 msgInvalidFormat = this.getText('ENTERO');
						 }
						 re=new RegExp(this.ENTERO);
						 break;   
					  case 'FLOTANTE':
					  case 'FLOAT':
						if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('FLOTANTE');
						 }
						 re=new RegExp(this.FLOAT);
						 break;
					  case 'FLOAT2':
						if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('FLOTANTE');
						 }
						 re=new RegExp(this.FLOAT2);
						 break;
					  case 'POSTCODE':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('POSTCODE');
						 }					
						 re=new RegExp(this.POSTCODE);
						 break;
					  case 'TELEFONO':
			          case 'PHONE':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('TELEFONO');
						 }					
						 re=new RegExp(this.TELEFONO);
						 break;						 
					  case 'WEBDIR':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('WEBDIR');
						 }					
						 re=new RegExp(this.WEBDIR);
						 break;						 
					  case 'STRING':
							re=null;
						break;
					  default:
						 re=new RegExp(expresionRegular);
					  //default:
			          //    re=null;
				   } // fin switch

				   // En caso de haber definido un mensaje de error personalizado, prevalece sobre el mensaje predefinido
				   var customMsg = elem.getAttribute("errorMessage");
				   if (customMsg && customMsg!='') msgInvalidFormat = customMsg;
	
				   if (msgInvalidFormat==null) msgInvalidFormat = this.getText('InvalidFormat');
				   
					//if (bForzeError || (re && !valor.match(re)) ) {
					if (bForzeError || (re && !re.test(valor)) ) {
			   			this.ShowErrorMessage(msgInvalidFormat,elem,true);
 						if (!this.groupErrorMsg) return false;
					}
				}
	
		  } // Fin del swith
	
		//Comprobacion de fechas con 3 campos
		if (elem.getAttribute("threefieldsdate")!=null && elem.value!='') {
			if (msgInvalidFormat==null) {
						msgInvalidFormat = this.getText('threefieldsdate');
			}
			var threeFieldsValue = elem.getAttribute("threefieldsdate_" + this.pos_id);
			var day,month,year;
			var fullDate;
			var aFields = threeFieldsValue.split(",");
			if (aFields.length==3) {
				day = document.getElementById(aFields[0]);
				month = document.getElementById(aFields[1]);
				year = document.getElementById(aFields[2]);
				fullDate = day.value +"/" + month.value + "/" + year.value;
				
				if (fullDate!=null) {
					if (!chkdate(null,fullDate)) {
						this.ShowErrorMessage(msgInvalidFormat,day);					
						if (!this.groupErrorMsg) return false;					
					}				
				}						
			}		
		} //Fin de comprobacion de fechas con 3 campos
			
		//Comprobacion de valor de cuenta corriente
		if (elem.getAttribute("bankAccount")!=null && elem.value!='') {
			if (msgInvalidFormat==null) {
						msgInvalidFormat = this.getText('bankAccount');
			}
			/*
			* IN:  cc1	 string	Primeros ocho dígitos de la cuenta corriente (entidad.oficina)
			* IN:  cc2  string  Últimos diez dígitos de la cuenta corriente  (#cuenta)
			* IN:  dc   string  Dígitos de control
			*/
			var accountValues = elem.getAttribute("bankAccount_" + this.pos_id)
			var entidad,oficina,cuenta,digitoControl;		
			var aFields = accountValues.split(",");				
			if (aFields.length==4) {
			
				entidad = document.getElementById(aFields[0]);
				oficina = document.getElementById(aFields[1]);
				digitoControl = document.getElementById(aFields[2]);
				cuenta = document.getElementById(aFields[3]);
		
				if (entidad.value!=null) {
					if (!checkDC(entidad.value+oficina.value,cuenta.value,digitoControl.value)) {
						this.ShowErrorMessage(msgInvalidFormat,entidad);					
						if (!this.groupErrorMsg) return false;					
					}				
				}									
			}		
		  } //Fin de comprobacion de valor de cuenta corriente

		  // Comprobamos si hay que comparar el campo
		  if (elem.getAttribute("compareWith"))
		  {
			var elem2 = formulario.elements[elem.getAttribute("compareWith")];
			if (elem.value != elem2.value) {
				var msgNotEqual = elem.getAttribute("msgNotEqual")
				if (msgNotEqual==null) {
					msgNotEqual = this.getText('compareWith');
				}
				this.ShowErrorMessage(msgNotEqual, elem);
				if (!this.groupErrorMsg) return false;
			}
		  }
		  
		} //Fin de la comprobación de si cumple con la condición de la posición
		
	   } // Fin del bucle para cada elemento del formulario

		if (!isRecursive)
		{
			var bFramesOk = true;
			if (this.check_frames) 
			{
				var nframes = window.frames.length;
				var oFrame;
				for (var i=0; i < nframes; i++) {
					oFrame = window.frames[i];
					try {
					if (oFrame.document.forms[0]) {
						var oFrmVal = new WBEFormValidator();
						//var errorObjectsNow = this.errorObjElements;
						//var errorFormatNow = this.errorFormatMsg;
						var bFrameOk = oFrmVal.validateForm(oFrame.document.forms[0], '', true, true);
						this.bJustResult = false; // ponemos a false otra vez pq en la llamada principal si tiene que pintar los errores
						//this.errorObjElements = errorObjectsNow; // Restauramos el vector de objectos con errores
						//this.errorFormatMsg = errorFormatNow; // Restauramos el vector de formatos de mensaje
						if (!bFrameOk)
							this.ShowErrorMessage(msgMandatoryField, oFrame.frameElement, false)
							//this.errorObjElements[this.errorObjElements.length] = oFrame.frameElement;
						bFramesOk = bFramesOk && bFrameOk;
					}
					} catch (err) {}
				}
			}// Fin de la comprobacion de ifrmaes
		}
		
	   
	   // En el caso de agrupar mensajes los pinta
	   if (this.groupErrorMsg) return this.showGroupedErrorMsgs();

	   return true;	
	}
	
	//todo:   refactorizar y extraer funcion comun para validar para usar en ambos validadores    arecondo 
	
	/* Funcion que recorre todos los campos con un prefijo de un formulario buscando
	 los atributos añadidos especiales y los procesa */
	this.validateFormWithPrefix = function  (formulario, prefix)
	{
		this.errorObjElements = new Array();
		this.errorFormatMsg = new Array();
		
		if (prefix) prefix = '' + prefix;

	   // Recorremos los elementos del formulario    
	   for (var i=0; i<formulario.elements.length; i++)
	   {
		var elem = formulario.elements[i];
		var bvalidate = true;

		if (!elem.name) {
			bvalidate = false;
		} else {
			if (prefix && prefix != '' && (elem.name.indexOf(prefix) != 0)) {
				bvalidate = false;
			}
		}

		//comprobamos que los campos tienen el prefijo asignado
		//para el caso de varios componentes en la misma página
		//Si es el mismo componente repetido entonces añadimos
		if (bvalidate) {
		
		  // Comprobamos que se han cumplimentado los elementos obligatorios
		  if (elem.getAttribute("required")) 
		  {
			 var msgMandatoryField=elem.getAttribute("msgRequired");
			 if (msgMandatoryField==null) {
				msgMandatoryField = this.getText('MandatoryField');
			 }
			 elem.style.backgroundColor='';
			 switch (elem.type)
			 {
				case '':
				case 'hidden':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,null);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
					   
				case 'file':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,null);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
					
					case 'text':
					case 'password':
					if (elem.value=='') {
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					if (elem.defaultVal && (elem.value == elem.defaultVal))
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
		
					case 'textarea':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
		
					case 'select-one':
					if (elem.value=='')
					{
						this.ShowErrorMessage(msgMandatoryField,elem);                  
						if (!this.groupErrorMsg) return false;
					}
					break;
		
					case 'checkbox':
					if (!elem.checked)
					{
						this.ShowErrorMessage(msgMandatoryField,elem);
						if (!this.groupErrorMsg) return false;
					}
					break;
		
					case 'radio':
					var seleccionado=false;
					var j=0;
					while (formulario.elements[i+j].type=='radio' && 
					elem.name==formulario.elements[i+j].name)
					{
						if (formulario.elements[i+j].checked) seleccionado=true;
						if (i+j-1>=formulario.elements.length) break;
						j++;
					}
					j=0;
					while (formulario.elements[i-j].type=='radio' && 
					elem.name==formulario.elements[i-j].name)
					{
						if (formulario.elements[i-j].checked) seleccionado=true;
						if (i-j<=0) break;
						j++;					
					}				
					if (!seleccionado)
					{
						this.ShowErrorMessage(msgMandatoryField,elem);
						if (!this.groupErrorMsg) return false;				
					}
					break;
				 } // Fin del switch
		  }
	
		  // Comprobamos que se han cumplimentado los elementos obligatorios
		  if (elem.getAttribute("maxTextLength"))
		  {
			var msgMaxLength=elem.getAttribute("msgMaxLength");
			if (msgMaxLength==null) {
				msgMaxLength = this.getText('MaxLength');
			}
			
			if (elem.value.length > elem.getAttribute("maxTextLength"))
			{
				msgMaxLength = msgMaxLength.substring(0, msgMaxLength.indexOf('#current#')) + elem.value.length + msgMaxLength.substring(msgMaxLength.indexOf('#current#') + 9);
				msgMaxLength = msgMaxLength.substring(0, msgMaxLength.indexOf('#max#')) + elem.getAttribute("maxTextLength") + msgMaxLength.substring(msgMaxLength.indexOf('#max#') + 5);

				this.ShowErrorMessage(msgMaxLength,elem);                  
				if (!this.groupErrorMsg) return false;
			}
		  }
	

		  // Comprobamos que los datos se encuentran correctamente formateados	
		  var msgInvalidFormat=elem.getAttribute("msgInvalid");
		  if (msgInvalidFormat != null) msgInvalidFormat = this.getText('InvalidFormat').replace(/\\n/g,"\n");
		  var bForzeError = false;
		  switch (elem.type)
		  {
	
			 case '':
			 case 'text':
			 case 'password':
				if (elem.getAttribute("expresionRegular")!=null 
					&& elem.value!='') {
				   var expresionRegular=elem.getAttribute("expresionRegular");
				   var valor=elem.value;
				   var re;
				   switch (expresionRegular)
				   {
					  case 'SEARCH_BOX':  // Caja de busqueda
					 	 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('SEARCH_BOX');
						 }
						 bForzeError = (valor.length < 3);
						 re = null;
						 break;
					  case 'LOGIN':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('LOGIN');
						 }
						 bForzeError = (valor.length<this.LOGIN_MIN_LONG);
						 re=new RegExp(this.LOGIN);
						 break;
						 case 'NOMBREDOMINIO':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('NOMBREDOMINIO');
						 }
						 re=new RegExp(this.NOMBREDOMINIO);
						 break;
					  case 'PASSWORD':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('PASSWORD');
						 }
						 bForzeError = (valor.length < this.PASSWORD_MIN_LONG);
						 re=new RegExp(this.PASSWORD);
						 break;
					  case 'EMAIL':
						 if (msgInvalidFormat==null) {
							msgInvalidFormat = this.getText('EMAIL');
						 }
						 re=new RegExp(this.EMAIL);
						 break;
					  case 'URL':
						 re=new RegExp(this.URL);
						 break;
						 
					  case 'MONEDA':
					  case 'MONEY':
						 re=new RegExp(this.MONEDA);
						 break;					 
					  case 'FECHA':
					  case 'DATE':
						 re=new RegExp(this.FECHA);
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('FECHA');
						 bForzeError = !this.chkdate(elem,null);
						 break;                     
					  case 'HORA':
				      case 'HOUR':
						 re=new RegExp(this.HORA);
						 bForzeError = !this.chkHora(elem);
						 break;        
					  case 'NIF':
						//Comprobacion inicial de NIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF');
						 re=null;
						 bForzeError = !this.NIFValidator.checkNIF(valor);
						 break;                             
					  case 'CIF':
						//Comprobacion inicial de CIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('CIF');					
						 re=null;
						 bForzeError = !this.NIFValidator.checkCIF(valor);
						 break;                             
					  case 'NIF_CIF':
						//Comprobacion inicial de NIF y CIF
						 if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF_CIF');
						 re=null;
						 bForzeError = !this.NIFValidator.checkAll(valor);
						 break;
					  case 'TARJ_RESID':
						//Comprobacion inicial de una 'Tarjeta de residencia' o 'NIF'
						if (msgInvalidFormat==null) msgInvalidFormat = this.getText('TARJ_RESID');
						 re=null;
						 bForzeError = !this.NIFValidator.checkTR(valor);
						 break;
					  case 'TARJ_RESID_NIF':
						//Comprobacion inicial de una 'Tarjeta de residencia' o 'NIF'
						 if ((valor.charAt(0).toUpperCase() != "X") && (valor.charAt(0).toUpperCase() != "Y") && (valor.charAt(0).toUpperCase() != "Z")){
							if (msgInvalidFormat==null) msgInvalidFormat = this.getText('NIF');
							 bForzeError = !this.NIFValidator.checkNIF(valor);
						 }else{
							if (msgInvalidFormat==null) msgInvalidFormat = this.getText('TARJ_RESID');
							 bForzeError = !this.NIFValidator.checkTR(valor);
						 }
						 re=null;
						 break;
					  case 'MATRICULA':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('MATRICULA');
						 }
						 re=new RegExp(this.MATRICULA);
						 break;                                                               					 
					  case 'ENTERO':
					  case 'INT':
					  case 'INTEGER':
						if (msgInvalidFormat==null) {                  
						 msgInvalidFormat = this.getText('ENTERO');
						 }
						 re=new RegExp(this.ENTERO);
						 break;   
					  case 'FLOTANTE':
					  case 'FLOAT':
						if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('FLOTANTE');
						 }
						 re=new RegExp(this.FLOAT);
						 break;
					  case 'POSTCODE':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('POSTCODE');
						 }					
						 re=new RegExp(this.POSTCODE);
						 break;
					  case 'TELEFONO':
			          case 'PHONE':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('TELEFONO');
						 }					
						 re=new RegExp(this.TELEFONO);
						 break;						 
					  case 'WEBDIR':
						 if (msgInvalidFormat==null) {
						 msgInvalidFormat = this.getText('WEBDIR');
						 }					
						 re=new RegExp(this.WEBDIR);
						 break;						 
					  case 'STRING':
							re=null;
						break;
					  default:
						 re=new RegExp(expresionRegular);
					  //default:
			          //    re=null;
				   } // fin switch

				   // En caso de haber definido un mensaje de error personalizado, prevalece sobre el mensaje predefinido
				   var customMsg = elem.getAttribute("errorMessage");
				   if (customMsg && customMsg!='') msgInvalidFormat = customMsg;
	
				   if (msgInvalidFormat==null) msgInvalidFormat = this.getText('InvalidFormat');
				   
					if (bForzeError || (re && !valor.match(re)) ) {
			   			this.ShowErrorMessage(msgInvalidFormat,elem,true);
 						if (!this.groupErrorMsg) return false;
					}
				}
	
		  } // Fin del swith
	
		//Comprobacion de fechas con 3 campos
		if (elem.getAttribute("threefieldsdate")!=null && elem.value!='') {
			if (msgInvalidFormat==null) {
						msgInvalidFormat = this.getText('threefieldsdate');
			}
			var threeFieldsValue = elem.getAttribute("threefieldsdate_" + this.pos_id);
			var day,month,year;
			var fullDate;
			var aFields = threeFieldsValue.split(",");
			if (aFields.length==3) {
				day = document.getElementById(aFields[0]);
				month = document.getElementById(aFields[1]);
				year = document.getElementById(aFields[2]);
				fullDate = day.value +"/" + month.value + "/" + year.value;
				
				if (fullDate!=null) {
					if (!chkdate(null,fullDate)) {
						this.ShowErrorMessage(msgInvalidFormat,day);					
						if (!this.groupErrorMsg) return false;					
					}				
				}						
			}		
		} //Fin de comprobacion de fechas con 3 campos
			
		//Comprobacion de valor de cuenta corriente
		if (elem.getAttribute("bankAccount")!=null && elem.value!='') {
			if (msgInvalidFormat==null) {
						msgInvalidFormat = this.getText('bankAccount');
			}
			/*
			* IN:  cc1	 string	Primeros ocho dígitos de la cuenta corriente (entidad.oficina)
			* IN:  cc2  string  Últimos diez dígitos de la cuenta corriente  (#cuenta)
			* IN:  dc   string  Dígitos de control
			*/
			var accountValues = elem.getAttribute("bankAccount_" + this.pos_id)
			var entidad,oficina,cuenta,digitoControl;		
			var aFields = accountValues.split(",");				
			if (aFields.length==4) {
			
				entidad = document.getElementById(aFields[0]);
				oficina = document.getElementById(aFields[1]);
				digitoControl = document.getElementById(aFields[2]);
				cuenta = document.getElementById(aFields[3]);
		
				if (entidad.value!=null) {
					if (!checkDC(entidad.value+oficina.value,cuenta.value,digitoControl.value)) {
						this.ShowErrorMessage(msgInvalidFormat,entidad);					
						if (!this.groupErrorMsg) return false;					
					}				
				}									
			}		
		  } //Fin de comprobacion de valor de cuenta corriente

		  // Comprobamos si hay que comparar el campo
		  if (elem.getAttribute("compareWith"))
		  {
			var elem2 = formulario.elements[elem.getAttribute("compareWith")];
			if (elem.value != elem2.value) {
				var msgNotEqual = elem.getAttribute("msgNotEqual")
				if (msgNotEqual==null) {
					msgNotEqual = this.getText('compareWith');
				}
				this.ShowErrorMessage(msgNotEqual, elem);
				if (!this.groupErrorMsg) return false;
			}
		  }
		  
		} //Fin de la comprobación de si cumple con la condición de la posición
		
	   } // Fin del bucle para cada elemento del formulario
		
	   // En el caso de agrupar mensajes los pinta
	   if (this.groupErrorMsg) return this.showGroupedErrorMsgs();
	   
	   return true;	
	}	

	///////// Pone el estilo al campo de error.
	this.SetFieldErrorStyle = function(_field, i) {
		if (_field!=null && _field.style.display != "none") {
			if ((!i) || (i==0)) _field.focus();
			_field.style.backgroundColor='#ffffcc';
		}
	}
	
	// Prepara o pinta un mensaje de error
	this.ShowErrorMessage = function  (msgMandatoryField,oField,bFormatErrorMsg) {
		// jaltava, para poder mostrar todos los mensajes
		if (bFormatErrorMsg == undefined) bFormatErrorMsg = this.showAllErrorMsg;
	
		//gestelles. para comprobar errores
		if (this.onErrorHandler!=null) this.onErrorHandler(oField);
		if(this.oErrorLayer == null){
			if (this.groupErrorMsg) {
				this.errorObjElements[this.errorObjElements.length] = oField;
				if (!bFormatErrorMsg) 
					this.errorMandatoryPresent = true;
				else 
					if (bFormatErrorMsg) this.errorFormatMsg[this.errorFormatMsg.length] = msgMandatoryField + '\n';
			} else {
				if ((typeof this.bJustResult == 'undefined') || (this.bJustResult == false)) this.alertMsg(msgMandatoryField);
				this.SetFieldErrorStyle(oField);
				/*if (oField!=null && oField.style.display != "none") {
					oField.focus();
					//oField.style.backgroundColor='#ffffcc';
				}*/
			}
		}else{
			oErrorLayer.innerHTML = '<p><b>' + msgMandatoryField + '</b></p>';
			oErrorLayer.style.display = '';
		}
	}

	// Pinta los mensajes agrupados en un alert
	this.showGroupedErrorMsgs = function () {
		if (this.errorObjElements.length == 0) return true;
		
		var sMsg = '';
		if (this.errorMandatoryPresent) sMsg += this.getText('errorMandatoryPresent');
		for (var i=0;i<this.errorFormatMsg.length;i++) {
			sMsg += '-> ' + this.errorFormatMsg[i];
		}
		if (sMsg!='') {
			for (var i=0;i<this.errorObjElements.length;i++) {
				oField = this.errorObjElements[i];
				if ((typeof this.bJustResult == 'undefined') || (this.bJustResult == false)) 
					this.SetFieldErrorStyle(oField, i);
				/*if (oField!=null && oField.style.display != "none") {
					if (i==0) oField.focus();
					//oField.style.backgroundColor='#ffffcc';
					this.SetFieldErrorStyle(oField);
				}*/
			}
			if ((typeof this.bJustResult == 'undefined') || (this.bJustResult == false)) this.alertMsg(sMsg);      
			return false;
		}
		return true;
	}

	// Para poder sobreescribir y por ejemplo mostrar en un lightbox
	this.alertMsg = function (sMsg){
		alert(sMsg);
	}
	
	/* Funcion para calcular la validez de una fecha */
	this.chkdate = function  (objName,sValue) {
		var strDatestyle = "eu"; 
		var strDate;
		var strDateArray;
		var strDay;
		var strMonth;
		var strYear;
		var intday;
		var intMonth;
		var intYear;
		var booFound = false;
		var datefield = objName;
		var strSeparatorArray = new Array("-"," ","/",".");
		var intElementNr;
		var err = 0;
		var strMonthArray = new Array(12);
	
		strMonthArray[0] = "/01/";
		strMonthArray[1] = "/2/";
		strMonthArray[2] = "/3/";
		strMonthArray[3] = "/4/";
		strMonthArray[4] = "/5/";
		strMonthArray[5] = "/6/";
		strMonthArray[6] = "/7/";
		strMonthArray[7] = "/8/";
		strMonthArray[8] = "/9/";
		strMonthArray[9] = "/10/";
		strMonthArray[10] = "/11/";
		strMonthArray[11] = "/12/";
		
		if (datefield!=null) {
			strDate = datefield.value;
		}
		
		if (sValue!= null) {
			strDate = sValue;
		}	
		
		if (strDate.length < 6) {
			return false;
		}
		
		for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
			if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
				strDateArray = strDate.split(strSeparatorArray[intElementNr]);
				if (strDateArray.length != 3) {
					err = 1;
					return false;
				}
				else {
					strDay = strDateArray[0];
					strMonth = strDateArray[1];
					strYear = strDateArray[2];
				}
				booFound = true;
			}
		}

		if (booFound == false) {
			if (strDate.length>5) {
				strDay = strDate.substr(0, 2);
				strMonth = strDate.substr(2, 2);
				strYear = strDate.substr(4);
			}
		}

		if (strYear.length == 2) {
			strYear = '20' + strYear;
		}

		// US style
		if (strDatestyle == "US") {
			strTemp = strDay;
			strDay = strMonth;
			strMonth = strTemp;
		}
		
		intday = parseInt(strDay, 10);
		if (isNaN(intday)) {
			err = 2;
			return false;
		}
		
		intMonth = parseInt(strMonth, 10);
		if (isNaN(intMonth)) {
			for (i = 0;i<12;i++) {
				if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
					intMonth = i+1;
					strMonth = strMonthArray[i];
					i = 12;
				}
			}
			if (isNaN(intMonth)) {
				err = 3;
				return false;
			}
		}
		
		intYear = parseInt(strYear, 10);
		if (isNaN(intYear)) {
			err = 4;
			return false;
		}
	
		if (intMonth>12 || intMonth<1) {
			err = 5;
			return false;
		}
	
		if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
			err = 6;
			return false;
		}
	
		if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
			err = 7;
			return false;
		}

		if (intMonth == 2) {
			if (intday < 1) {
				err = 8;
				return false;
			}
			if (this.LeapYear(intYear) == true) {
				if (intday > 29) {
					err = 9;
					return false;
				}
			}
			else {
				if (intday > 28) {
					err = 10;
					return false;
				}
			}
		}
	
		return true;
	}
	
	/* Año bisiesto */
	this.LeapYear = function  (intYear) {
		if (intYear % 100 == 0) {
			if (intYear % 400 == 0) { return true; }
		}
		else {
			if ((intYear % 4) == 0) { return true; }
		}
		return false;
	}
	
	/* Formato de hora */
	this.chkHora = function  (lahora) {
		var arrHora = (lahora.value).split(":");
		if (arrHora.length!=2) {
			return false;
		}
		if (parseInt(arrHora[0])<0 && parseInt(arrHora[0])>23) {
			return false;
		}
		
		if (parseInt(arrHora[1])<0 && parseInt(arrHora[1])>59) {
			return false;
		}
		return true;
	}
	
	/**
		* Validación de una cuenta corriente
		* 
		* Comprueba un número de cuenta corriente
		*
		* IN:  cc1	 string	Primeros ocho dígitos de la cuenta corriente (entidad.oficina)
		* IN:  cc2  string  Últimos diez dígitos de la cuenta corriente  (#cuenta)
		* IN:  dc   string  Dígitos de control
		* OUT:      bool    ¿Cuenta válida? 
	*/
	this.checkDC = function  (cc1,cc2,dc){
		
		/*
			* Comprobar que los datos son correctos
		*/				
		return true;
		if (!(cc1.match(/^\d{8}$/) && cc2.match(/^\d{10}$/) && dc.match(/^\d{2}$/) )) return false;
		
		var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6);	// vector de pesos
		var dc1=0, dc2=0;
		
		/*
			* Cálculo del primer dígito de cintrol
		*/
		for (i=7;i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
		dc1 = 11 - (dc1 % 11);
		if (11 == dc1) dc1 = 0;
		if (10 == dc1) dc1 = 1;
		
		/*
			* Cálculo del segundo dígito de control
		*/
		for (i=9;i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
		dc2 = 11 - (dc2 % 11);
		if (11 == dc2) dc2 = 0;
		if (10 == dc2) dc2 = 1;
		
		/*
			* Comprobar la coincidencia y delvolver el resultado
		*/
		return (10*dc1+dc2 == dc);	// Javascript infiere tipo entero para dc1 y dc2
	
	} // end checkDC()

	
	
	
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ----------------------- Funciones del original 070-form-validation.js ------------------------- */
	/* ------------------------------------------------------------------------------------------------------------ */
	/* ------------------------------------------------------------------------------------------------------------ */
	/*this.leftTrim = function (sString) {
			while (sString.substring(0,1) == ' ') {
				sString = sString.substring(1, sString.length);
			}
			return sString;
		};
		
	this.rightTrim = function (sString) {
			while (sString.substring(sString.length-1, sString.length) == ' ') {
				sString = sString.substring(0,sString.length-1);
			}
			return sString;
		};
		
	this.trimAll = function (sString) {
			return this.rightTrim(this.leftTrim(sString));
		};*/
	/*--------------------------------------------------------------------------------------------------------------------------*/
	/*--substituidas las funciones de trim con bucles por otras realizadas con  expresiones regulares--*/
	/*--------------------------------------------------------------------------------------------------------------------------*/
	this.leftTrim = function (stringToTrim) {
			return stringToTrim.replace(/^\s+/,"");
		};
		
	this.rightTrim = function (stringToTrim) {
			return stringToTrim.replace(/\s+$/,"");
		};
		
	this.trimAll = function (stringToTrim) {
			return stringToTrim.replace(/^\s+|\s+$/g,"");
		};
		
	this.checkMandatoryText = function (elem, error_elem, error_msg) {
			if (elem.value == '') {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMandatorySelect = function (elem, error_elem, error_msg) {
			if (elem.selectedIndex == -1) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMandatoryOpt = function (elem, error_elem, error_msg) {
			var bOK = false;
			if(elem.value) {
				bOK = elem.checked;
			} else {
				for (var i = 0; i < elem.length; i++) {
					if (elem[i].checked) {
						bOK = true;
						break;
					}
				}
			}
			if (!bOK) {
				error_elem.innerHTML += error_msg;
				return false;
			} 
			return true;
		};
		
	this.checkMinLengthText = function (elem, len, error_elem, error_msg) {
			if (this.trimAll(elem.value).length < len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMaxLengthText = function (elem, len, error_elem, error_msg) {
			if (elem.value.length > len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMinLengthSelect = function (elem, len, error_elem, error_msg) {
			var sels = 0;
			for (var i = 0; i < elem.options.length; i++) {
				if (elem.options[i].selected) sels++;
			}
			if (sels < len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMaxLengthSelect = function (elem, len, error_elem, error_msg) {
			var sels = 0;
			for (var i = 0; i < elem.options.length; i++) {
				if (elem.options[i].selected) sels++;
			}
			if (sels > len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMinLengthOpt = function (elem, len, error_elem, error_msg) {
			var sels = 0;	
			if (elem.value) {
				if (elem.checked) sels++;
			} else {
				for (var i = 0; i < elem.length; i++) {
					if (elem[i].checked) {
						sels++;
					}
				}
			}
			if (sels < len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};
		
	this.checkMaxLengthOpt = function (elem, len, error_elem, error_msg) {
			var sels = 0;
			if (elem.value) {
				if (elem.checked) sels++;
			} else {
				for (var i = 0; i < elem.length; i++) {
					if (elem[i].checked) {
						sels++;
					}
				}
			}
			if (sels > len) {
				error_elem.innerHTML += error_msg;
				return false;
			}
			return true;
		};

	this.getOptValue = function (elem) {
			var sResult = '';	
			if (elem.value) {
				if (elem.checked) sResult = elem.value;
			} else {
				for (var i = 0; i < elem.length; i++) {
					if (elem[i].checked) {
						if (sResult.length != 0) sResult += ",";
						sResult += elem[i].value;
					}
				}
			}
			return sResult;
		};
			
	this.getMultiSelectValue = function (elem) {
			var sResult = '';	
			for (var i = 0; i < elem.options.length; i++) {
				if (elem.options[i].selected) {
					if (sResult.length != 0) sResult += ",";
					sResult += elem[i].value;
				}
			}
			return sResult;
		};
		
	this.changeIds = function changeIds(elem, pattern, text) {
		var x = elem.childNodes;
		if (x) {
			for (var i = 0; i < x.length; i++) {
				changeIds(x[i], pattern, text);
				if (x[i].id) {
					x[i].id = x[i].id.replace(pattern, text);
				}
				if (x[i].attributes) {
					for (var j = 0; j < x[i].attributes.length; j++) {
						if ((x[i].attributes[j].nodeName.toLowerCase() == 'for') || 
								(x[i].attributes[j].nodeName.toLowerCase() == 'href') || 
								(x[i].attributes[j].nodeName.toLowerCase() == 'value')) {
							x[i].attributes[j].nodeValue = x[i].attributes[j].nodeValue.replace(pattern, text);
						}
					}
				}
			}
		}
	};

	this.showMsgs = function (sPosId, asMsgs) {
		var elem;
		var sText;
		elem = document.getElementById('messages_ok_' + sPosId);
		elem.innerHTML = '';
		elem.style.display = '';
		sText = '<ul>';
		for (var i = 0; i <asMsgs.length; i++) { 
			if (asMsgs[i].length > 0) {
				sText += '<li>' + asMsgs[i] + '</li>';
			}
		}
		sText += '</ul>';
		elem.innerHTML = sText;
	};

	this.showErrors = function (sPosId, asMsgs) {
		var elem;
		var sText;
		elem = document.getElementById('messages_error_' + sPosId);
		elem.innerHTML = '';
		elem.style.display = '';
		sText = '<ul>';
		for (var i = 0; i <asMsgs.length; i++) { 
			if (asMsgs[i].length > 0) {
				sText += '<li>' + asMsgs[i] + '</li>';
			}
		}
		sText += '</ul>';
		elem.innerHTML = sText;
	};

	this.hideMsgs = function (sPosId) {
		var elem;
		elem = document.getElementById('messages_ok_' + sPosId);
		elem.innerHTML = '';
		elem.style.display = 'none';
	};

	this.hideErrors = function (sPosId) {
		var elem;
		elem = document.getElementById('messages_error_' + sPosId);
		elem.innerHTML = '';
		elem.style.display = 'none';
	};

};



/* ------------------------------------------------------------------------------
* ------------------------------------------------------------------------------
*	Validador de CIF, NIF y Tarjeta de Residencia.
*	GEB.
*	------------------------------------------------------------------------------
*	------------------------------------------------------------------------------
*/
function NIF_CIFValidator() {

	this.NIF_Letters = "TRWAGMYFPDXBNJZSQVHLCKET";
	this.NIF_regExp = "^\\d{8}[a-zA-Z]{1}$";
	this.CIF_regExp = "^[a-zA-Z]{1}\\d{7}[a-jA-J0-9]{1}$";

	this.checkAll = function (value) {
		if (this.checkCIF(value))  { // Comprueba el CIF
			return true;
		} else if (this.checkTR(value)) { // Comprueba tarjeta de residencia
			return true;
		}else if (this.checkNIF(value)) { // Comprueba el NIF
			return true;
		} else  {           // Si no pasa por ninguno es false.
			return false;
		}
	}

	// VALIDA EL NIF
	this.checkNIF = function (nif) {
	// Comprueba la longitud. Los DNI antiguos tienen 7 digitos.
	if ((nif.length!=8) && (nif.length!=9)) return false;
	if (nif.length == 8) nif = '0' + nif; // Ponemos un 0 a la izquierda y solucionado
	
	// Comprueba el formato
	var regExp=new RegExp(this.NIF_regExp);
	if (!nif.match(regExp)) return false;

	var let = nif.charAt(nif.length-1);
	var dni = nif.substring(0,nif.length-1)
	var letra = this.NIF_Letters.charAt(dni % 23);
	return (letra==let.toUpperCase());
	}

	// VALIDA TARJETA DE RESIDENCIA
	this.checkTR = function (tr) {
		if ((tr.length!=10) && (tr.length!=9)) return false;
		if ((tr.charAt(0).toUpperCase() != "X") && (tr.charAt(0).toUpperCase() != "Y") && (tr.charAt(0).toUpperCase() != "Z")) return false;

		var leftNum = '0';
		if (tr.charAt(0).toUpperCase() == "Y") leftNum = '1';
		
		if (tr.length==9) {
			return this.checkNIF(leftNum + tr.substring(1,tr.length));
		} else {
			return this.checkNIF(tr.substring(1,tr.length));
		}
	}

	// VALIDA TARJETA DE RESIDENCIA
	this.checkCIF = function (cif) {
		var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
		var tempStr = cif.toUpperCase(); // pasar a mayúsculas
		var temp = 0;
		var temp1;
		var dc;

		// Comprueba el formato
			var regExp=new RegExp(this.CIF_regExp);
		if (!tempStr.match(regExp)) return false;    // Valida el formato?
		if (!/^[ABCDEFGHKLMNPQS]/.test(tempStr)) return false;  // Es una letra de las admitidas ?

		for( i = 2; i <= 6; i += 2 ) {
			temp = temp + v1[ parseInt(cif.substr(i-1,1)) ];
			temp = temp + parseInt(cif.substr(i,1));
		};
		temp = temp + v1[ parseInt(cif.substr(7,1)) ];
		temp = (10 - ( temp % 10));
		if (temp==10) temp=0;
		dc  = cif.toUpperCase().charAt(8);
    return (dc==temp) || (temp==1 && dc=='A') || (temp==2 && dc=='B') || (temp==3 && dc=='C') || (temp==4 && dc=='D') || (temp==5 && dc=='E') || (temp==6 && dc=='F') || (temp==7 && dc=='G') || (temp==8 && dc=='H') || (temp==9 && dc=='I') || (temp==0 && dc=='J');
	}
}






/*
 * jsanchez.
 * Clase para realizar operaciones con contenidos
 */
function CMSUtils()
{
	this.oAjax = new WBE_AjaxClass();
	
	this.add_child_to_user_in_relation = function (id_relation, iChildId) {
		oAjax.clear();
		oAjax.addPostParameter('cv_child_id', iChildId)
		oAjax.addPostParameter('relation_id', id_relation);
		oXmlDoc = oAjax.throwEventXML("cms_create_user_relation");
		
		if (oXmlDoc)
		{
			var respuesta = oAjax.getXMLNodeValue(oXmlDoc, "c");
			if(respuesta == '0')
			{
				//alert('No puedes añadirte a ti mismo como amigo');
				return 0;
			}
			else
			{
				//alert('Tu solicitud de amistad ha sido enviada');
				return 1;
			}
		} else {
			//alert('Ya tienes relación con este usuario');
			return -1;
		}
		
		return 0;
	}
	
		
	this.save_att_value = function (sVerId, sAttId, sLng, sValue) {
		var oAjax = new WBE_AjaxClass();
			
		oAjax.clear();
		oAjax.addPostParameter('ver_id', sVerId + '');
		oAjax.addPostParameter('att_id', sAttId);
		oAjax.addPostParameter('lng_id', sLng);
		oAjax.addPostParameter('text', sValue);
			
		oAjax.throwEventXML("css_save_att_value");
		
		return true;
	}
	
	// acepta códigos especiales "__stock__,__price__,__tag__,__date_start__,__date_end__"
	this.get_att_value = function (sVerId, sAttCode) {
		var oAjax = new WBE_AjaxClass();
			
		oAjax.clear();
		oAjax.addPostParameter('ver_id', sVerId + '');
		oAjax.addPostParameter('att_code', sAttCode);
			
		var sValue = '';
		xmlObj = oAjax.throwEventXML("os1_get_att_value");
		//alert(xmlObj);
		if (xmlObj){
			sValue = oAjax.getXMLNodeValue(xmlObj, 'value');
		}
		return sValue;
	}
}
