//===============================================================================================================================
// FUNCIONES DE MANEJO Y GESTION DEL XML
//===============================================================================================================================
// JavaScript Document
var codeClient = null;
var GQ_URL_RECUPERA_DATOS = "http://vw.comm.neuronics.es/volkswagen/ServiciosNeuronics/obtenerEncuesta.neu";
var GQ_URL_DATOS          = "http://vw.comm.neuronics.es/volkswagen/ServiciosNeuronics/guardarEncuesta.neu";
var GQ_URL_INICIO_SESSION = "http://vw.comm.neuronics.es/volkswagen/ServiciosNeuronics/iniciarSesion.neu";
var GQ_URL_OBTENER_DOMINIOS = "http://vw.comm.neuronics.es/volkswagen/ServiciosNeuronics/obtenerDominios.neu";

//FICHERO DE CONEXION
var URI_PROXY = 'includes/proxyGQ.php';
var us = "tribal";
var cl = "volkswagen";

// IMO
var SID = null;
var DATOS_RECUPERADOS;
var LNK_RESPUESTADOMINIO = Array();

//1) +++++++++++++++++++++++++++++++++++++ PETICIONES DE INICIO DE SESSION +++++++++++++++++++++++++++++++++++++++++++++

//1.1 PETICION DEL SID PARA ACCESO AL WEBSERVICE
function onLoadPagina() {
	LNK_iniciarSession();
}
//1.2 INICIAR SESSION
function LNK_iniciarSession(){
	var form = document.getElementsByTagName('form');	
	var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
	  + "<peticion tipo=\"iniciarSesion\"><encuesta token='" + form[0].id + "' formatVersion='1'>"
	  + "<usuario>" + us + "</usuario>"
	  + "<password>" + cl + "</password>"
	  + "</encuesta></peticion>";
	obtenerDatosServidor(xml, GQ_URL_INICIO_SESSION, 1);
}

function obtenerDatosServidor(xml, action, render) {
    var objHttp = GQ_getAjax();    
    if(objHttp)
    {
        if (objHttp.readyState==0 || objHttp.readyState==4)
        {
            // Con el id de la respuesta, obtendremos el id del grupo asociado
            // del cual devoler las lista de respuestas
			// action = "http://vw.comm.neuronics.es/AjaxWrapperVolkswagen/obtenerRespuestasDominioXML.html";
            objHttp.open("POST", URI_PROXY, true);
			objHttp.setRequestHeader("GQHost", action);
            objHttp.onreadystatechange=
                function()
            {
                if(objHttp.readyState==4){
                  if(objHttp.status == 200){
                      var respuesta = objHttp.responseText;
                      var xmlDoc;
                      //alert("AJAX ESP="+respuesta);
                      if(respuesta!=null && respuesta!=""){
	                      try //Internet Explorer
							{
								xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
								xmlDoc.async="true"; //changed if ie6
								xmlDoc.loadXML(respuesta);
							}
							catch(e){
							try //Firefox, Mozilla, Opera, etc.
							{
								parser=new DOMParser();
								xmlDoc=parser.parseFromString(respuesta,"text/xml");
								}
								catch(e) {/*alert(e.message)*/}
							}														
							renderRespuesta( xmlDoc, 1);
							// resto de DATOS del Dominio
							//LNK_obtenerResto("concurso", null);
							LNK_obtenerResto("lopd", null);
							LNK_obtenerResto("lssi", null);
												  
							if (codeClient!=null && codeClient!="" && codeClient!="undefined") { LNK_obtenerEncuesta(codeClient);}
							else { obtenerTodasRespuestasDominioXML();}
                    	}// FI respuesta!=NULL
                  }
              }
            }
            objHttp.send(xml);
        }
    }
	else{
			dest.options.length = 1;
    }
}
//OBTENCION DEL SID(si render=1)
function renderRespuesta(xmlDoc, render) {
	var valueOption, textOption, optionNode;
	var newopc, selectTag;
	var loptions, option;
	var nodeVal, nodeDesc;
	// alert(1);
	var OPTIONS = Array();
	loptions = xmlDoc.getElementsByTagName("respuesta");
	for (ind=0; ind < loptions.length; ind++)
    {
        option = loptions[ind];
		nodeVal = option.childNodes[0];   //-- valor
		OPTIONS[ind] = Array(nodeVal, nodeVal.childNodes[0].nodeValue);
	}
	// RENDER = 1 es RECUPERAR SID.
	if (render==1) {
		SID = OPTIONS[0][1];
	}
}

//2) ++++++++++++++++++++++++++++++++++++++ PETICIONES DE DOMINIO FIJO ++++++++++++++++++++++++++++++++++++++++++++++++++
//2.1 LISTADO DE CATALOGOS
//2.2 TRATAMIENTO
//2.3 TIPO VIA
//2.4 particular_provincia_1
//2.5 PAIS
//2.6 INTENCION COMPRA
//2.7 MARCA
//2.8 particular_provincia_1S TD
function obtenerTodasRespuestasDominioXML(datosRecuperados){
	var form = document.getElementsByTagName('form');	
	var elems = document.getElementsByTagName('select');	
	for(var i = 0; i < elems.length; i++){
		if (elems[i].name=="vactual_modelo_1" && datosRecuperados!=undefined) {
			var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			  + "<peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\"><encuesta token=\"" + form[0].id + "\" formatVersion=\"1\">"
			  + "<alias>vactual_marca_1</alias>"
			  + "<id>" + datosRecuperados["marcaActual"] + "</id>"
			  + "</encuesta></peticion>";
		}
		else if (elems[i].name=="vfuturo_deseo_Concesion_1" && datosRecuperados!=undefined) {
			var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			  + "<peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\"><encuesta token=\"" + form[0].id + "\" formatVersion=\"1\">"
			  + "<alias>vfuturo_provinciaTD_1</alias>"
			  + "<id>" + datosRecuperados["vfuturo_provinciaTD_1"] + "</id>"
			  + "</encuesta></peticion>";
		}
		else if(elems[i].name=="selected"){//elementos seleccionados del catalogo(por defecto vacio)
			continue;
		}
		else {
			var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			  + "<peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\"><encuesta token=\"" + form[0].id + "\" formatVersion=\"1\">"
			  + "<alias>" + elems[i].name + "</alias>"
			  + "</encuesta></peticion>";
		}
		// alert("obtenerResp: " + xml);
		obtenerRespuestasDominioXML(xml, elems[i], datosRecuperados);
	}
}

function obtenerRespuestasDominioXML(xml, dest, datosRecuperados)
{
    var objHttp = GQ_getAjax();
    if(objHttp)
    {
        if (objHttp.readyState==0 || objHttp.readyState==4)
        {
            // Con el id de la respuesta, obtendremos el id del grupo asociado
            // del cual devoler las lista de respuestas
			// action = "http://vw.comm.neuronics.es/AjaxWrapperVolkswagen/obtenerRespuestasDominioXML.html";
			action = GQ_URL_OBTENER_DOMINIOS;			
            objHttp.open("POST", URI_PROXY, true);
			objHttp.setRequestHeader("GQHost", action);
            objHttp.onreadystatechange= function(){
											if(objHttp.readyState==4){
												if(objHttp.status == 200){
												  var respuesta = objHttp.responseText;
												  var xmlDoc;
												  //alert("AJAX ESP="+respuesta);
												  if(respuesta!=null && respuesta!=""){
														  try //Internet Explorer
														  {
															xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
															xmlDoc.async="true";//changed if ie6
															xmlDoc.loadXML(respuesta);
															}catch(e){
															try //Firefox, Mozilla, Opera, etc.
															{
																parser=new DOMParser();
																xmlDoc=parser.parseFromString(respuesta,"text/xml");
															}catch(e) {/*alert(e.message)*/}
														   }													
														// Carreguem les OPTIONS als seus combos
														renderOptions(xmlDoc, dest.id, datosRecuperados);			  
												  }// FI respuesta!=NULL
                  							  }
              								}
            							}
            objHttp.send(xml);
        }
    }else{ dest.options.length = 1;}
}
//CARGA DE LOS COMBOS
function renderOptions(xmlDoc, idSelect, datosRecuperados)
{
	  var valueOption, textOption, optionNode;
	  var newopc, selectTag;
	  var loptions, option;
	  var nodeVal, nodeDesc;
  	var selectTag = document.getElementById(idSelect);
    while (selectTag.firstChild) selectTag.removeChild(selectTag.firstChild);

    if (selectTag != null)
    {
		if(idSelect!="catalogo_LCV"){//el combo de catalogos no tiene este primer elemento
    		newopc = document.createElement("option");
        	newopc.setAttribute("value", "");
        	optionNode = document.createTextNode("»Seleccione»");
        	newopc.appendChild(optionNode);
        	selectTag.appendChild(newopc);
		}
    	
      loptions = xmlDoc.getElementsByTagName("opcion");// 
      for (ind=0; ind < loptions.length; ind++)
      {
        option = loptions[ind];
        nodeVal = option.childNodes[0];   //-- valor
        valueOption = nodeVal.childNodes[0];
        nodeDesc = option.childNodes[1];   //-- description
        textOption = nodeDesc.childNodes[0];
        newopc = document.createElement("option");
        newopc.setAttribute("value", valueOption.nodeValue);		
		if (datosRecuperados!=undefined && datosRecuperados[idSelect]==valueOption.nodeValue) {
			 newopc.setAttribute("selected", "true");
		}
        optionNode = document.createTextNode(textOption.nodeValue)
        newopc.appendChild(optionNode);
        selectTag.appendChild(newopc);
      }
    } else
      alert("No existe Content: " + id);
} //-- renderOptions

//PETICION DE DOMINIO FIJO DE LOS DATOS ADICIONALES
function LNK_obtenerResto(source) {
		var xml = "<\?xml version=\"1.0\" encoding=\"UTF-8\"\?><peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\">"
		+ '<encuesta token="' + document.forms[0].id + '" formatVersion="1">'
		+	 "<alias>" + source + "</alias>"
		+ "</encuesta></peticion>";	
	obtenerDominioAsociado(source, null, xml);
}

//3) +++++++++++++++++++++++++++++++++++++ PETICION DE DOMINIO ASOCIADO +++++++++++++++++++++++++++++++++++++++++++++++++

//3.1 PETICION DE DOMINIO ASOCIADO DE LOS MODELOS ASOCIADOS A UNA MARCA
function obtenerDominioAsociadoMarca(source,dest) {
	var xml = "<\?xml version=\"1.0\" encoding=\"UTF-8\"\?><peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\">"
		+ '<encuesta token="' + document.forms[0].id + '">'
		+	 "<alias>vactual_marca_1</alias>"
		+	 "<id>"+getSelectValue("vactual_marca_1")+"</id>"
		+ "</encuesta></peticion>";		
	obtenerDominioAsociado(source,dest,xml)
}
//3.2 PETICION DE DOMINIO ASOCIADO DE LOS CONCESIONARIOS ASOCIADOS A UNA particular_provincia_1
function obtenerDominioAsociadoProv(source, dest) {
	var xml = "<\?xml version=\"1.0\" encoding=\"UTF-8\"\?><peticion tipo=\"obtenerDominios\" sid=\"" + SID + "\">"
		+ '<encuesta token="' + document.forms[0].id + '" formatVersion="1">'
		+	 "<alias>vfuturo_provinciaTD_1</alias>"
		+	 "<id>"+getSelectValue("vfuturo_provinciaTD_1")+"</id>"
		+ "</encuesta></peticion>";	
	obtenerDominioAsociado(source,dest,xml)
}
//3.3 PETICION DE LA ENCUESTA
function LNK_obtenerEncuesta(codeClient) {
		var xml = "<\?xml version=\"1.0\" encoding=\"UTF-8\"\?><peticion tipo=\"obtenerEncuesta\" sid=\"" + SID + "\">"
		+ '<encuesta token="' + document.forms[0].id + '" formatVersion="1">'
		+	 "<code>" + codeClient + "</code>"
		+ "</encuesta></peticion>";
	obtenerDominioAsociado(null, null, xml);
}

// Funci?n para obtener el dominio asociado de una respuesta
// dada en un campo de el formulario
function obtenerDominioAsociado(source,dest,xml) {
	if (source==null && dest== null && codeClient!="undefined" && codeClient!=null && codeClient!="" ) { LNK_obtenerEncuestaDominioXMLVar(xml);}
	else if (dest==null) {LNK_obtenerRespuestasDominioXMLVar(xml, source);}
	else {obtenerRespuestasDominioXML(xml, document.getElementById(dest));}
}

function LNK_obtenerRespuestasDominioXMLVar(xml, source)
{
    var objHttp = GQ_getAjax();    
    if(objHttp)
    {
        if (objHttp.readyState==0 || objHttp.readyState==4)
        {
            // Con el id de la respuesta, obtendremos el id del grupo asociado
            // del cual devoler las lista de respuestas
			// action = "http://vw.comm.neuronics.es/AjaxWrapperVolkswagen/obtenerRespuestasDominioXML.html";
			action = GQ_URL_OBTENER_DOMINIOS;
			
            objHttp.open("POST", URI_PROXY, true);
			objHttp.setRequestHeader("GQHost", action);
            objHttp.onreadystatechange=
                function()
            {
                if(objHttp.readyState==4){
                  if(objHttp.status == 200){
                      var respuesta = objHttp.responseText;
                      var xmlDoc;
                      //alert("AJAX ESP="+respuesta);
                      if(respuesta!=null && respuesta!=""){
	                      try //Internet Explorer
												  {
												  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
												  xmlDoc.async="true";//changed if ie6
												  xmlDoc.loadXML(respuesta);
												}catch(e){
												  try //Firefox, Mozilla, Opera, etc.
												    {
												    parser=new DOMParser();
												    xmlDoc=parser.parseFromString(respuesta,"text/xml");
												  }catch(e) {/*alert(e.message)*/}
												}													
												
												// Carreguem les OPTIONS als seus combos
												// renderOptions(xmlDoc, dest.id);
												
												LNK_RESPUESTADOMINIO[source] = Array();
												loptions = xmlDoc.getElementsByTagName("opcion");
											 	for (ind=0; ind < loptions.length; ind++) {
													option = loptions[ind];
											
													nodeVal = option.childNodes[0];   //-- valor
													valueOption = nodeVal.childNodes[0];
													nodeDesc = option.childNodes[1];   //-- description
													textOption = nodeDesc.childNodes[0];
													
													LNK_RESPUESTADOMINIO[source][ind] = Array(valueOption.nodeValue, textOption.nodeValue);
												 }
												 
												 // alert( LNK_RESPUESTADOMINIO[source] );
													 												 
												 // alert( xoption[0].childNodes[0].childNodes[0].nodeValue );
												 // alert( xoption[0].childNodes[0].childNodes[0].nodeValue );
												 // nodeVal = option.childNodes[0];
                    	}// FI respuesta!=NULL
                  }
              }
            }
            objHttp.send(xml);
        }
    }else{
			dest.options.length = 1;
  		//document.getElementById(dest).options.length = 1;
    }
}

function LNK_obtenerEncuestaDominioXMLVar(xml)
{
    var objHttp = GQ_getAjax();    
    if(objHttp)
    {
        if (objHttp.readyState==0 || objHttp.readyState==4)
        {
            // Con el id de la respuesta, obtendremos el id del grupo asociado
            // del cual devoler las lista de respuestas
			// action = "http://vw.comm.neuronics.es/AjaxWrapperVolkswagen/obtenerRespuestasDominioXML.html";
			action = GQ_URL_RECUPERA_DATOS;
            objHttp.open("POST", URI_PROXY, true);
			objHttp.setRequestHeader("GQHost", action);
            objHttp.onreadystatechange=
                function()
            {
                if(objHttp.readyState==4){
                  if(objHttp.status == 200){
                      var respuesta = objHttp.responseText;
                      var xmlDoc;
                      //alert("AJAX ESP="+respuesta);
                      if(respuesta!=null && respuesta!=""){
	                      try //Internet Explorer
												  {
												  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
												  xmlDoc.async="true";//changed if ie6
												  xmlDoc.loadXML(respuesta);
												}catch(e){
												  try //Firefox, Mozilla, Opera, etc.
												    {
												    parser=new DOMParser();
												    xmlDoc=parser.parseFromString(respuesta,"text/xml");
												  }catch(e) {/*alert(e.message)*/}
												}													
												
												// Carreguem les OPTIONS als seus combos
												// renderOptions(xmlDoc, dest.id);
												// alert(respuesta);
											    var x = xmlDoc.documentElement.childNodes[0].childNodes[0];
												if (x==undefined) {
													// alert("No hay datos");
													codeClient = "";
													obtenerTodasRespuestasDominioXML();
													//changePaso(4);
												}
												else {
													document.getElementsByName("idContacto")[0].value = x.attributes.getNamedItem("idContacto").nodeValue;
													loptions = xmlDoc.getElementsByTagName("encuesta");
													DATOS_RECUPERADOS = Array();
													for (ind=0; ind < loptions[0].childNodes.length; ind++) { 
														// alert(loptions[0].childNodes[ind].childNodes[0].nodeName);
														var nodoCampo = loptions[0].childNodes[ind].nodeName;
														var nodoValor = loptions[0].childNodes[ind].childNodes[0].nodeValue;
														
														// alert( nodoCampo + " = " + nodoValor );
														DATOS_RECUPERADOS[nodoCampo] = nodoValor;
														if (nodoCampo=="lssi") {
															// alert( nodoValor );
															var LNK_Si = 0;
															var LNK_No = 0;
															var tokenLocal = "lssi";
														
															// alert(LNK_RESPUESTADOMINIO[tokenLocal][0][1]);	
															if (LNK_RESPUESTADOMINIO[tokenLocal][0][1]=="PERMITIDO") {
																LNK_Si = LNK_RESPUESTADOMINIO[tokenLocal][0][0];
																LNK_No = LNK_RESPUESTADOMINIO[tokenLocal][1][0];
															}
															else {
																LNK_Si = LNK_RESPUESTADOMINIO[tokenLocal][1][0];
																LNK_No = LNK_RESPUESTADOMINIO[tokenLocal][0][0];
															}
															if (nodoValor==LNK_No) {document.forms[0].lssiCtrl.checked=true;}
														}
														else {
															try {
																document.getElementById(nodoCampo).value = nodoValor;
															}
															catch(e) {}
														}
													}	
													obtenerTodasRespuestasDominioXML( DATOS_RECUPERADOS );
												}	  
                    	}// FI respuesta!=NULL
                  }
              }
            }
            objHttp.send(xml);
        }
    }else{
			dest.options.length = 1;
  		//document.getElementById(dest).options.length = 1;
    }
}

//4) +++++++++++++++++++++++++++++++++++++ FUNCIONES AJAX +++++++++++++++++++++++++++++++++++++++++++++++++

// Esta funcion obtiene, si el navegador lo permite, el objeto HttpRequest
// que nos permitira realizar 	es asincronas (AJAX)
function GQ_getAjax()
{	var ajax;
    if (window.XMLHttpRequest) { // IE7, Mozilla, Safari,...
        ajax = new XMLHttpRequest();
        if (ajax.overrideMimeType) {
            ajax.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    return ajax;
}
//ENVIO DEL XML Y TRATAMIENTO DE LA RESPUESTA
/*
function sendXml(xml){
  	var objHttp = GQ_getAjax();
  	if(objHttp){
      	if (objHttp.readyState==0 || objHttp.readyState==4){
			objHttp.open("POST", 'peticion', true);
			objHttp.setRequestHeader("Content-Type", "text/xml");
			objHttp.onreadystatechange = function(){
												if(objHttp.readyState==4){
													  //alert("objHttp.readyState: " + objHttp.readyState + " - objHttp.status: " + objHttp.status);
													  if(objHttp.status == 200){
															var respuesta = objHttp.responseText;
															var resDiv = document.getElementById("res");
															//resDiv.innerText = respuesta;
															//alert(respuesta);
															respuesta = replace(respuesta,"<","&lt;");
															respuesta = replace(respuesta,">","&gt;");
															respuesta = replace(respuesta,"\n","<br>");
															resDiv.innerHTML = respuesta;
															//parseErrores(respuesta);
													  } else {
															var resDiv = document.getElementById("res");
															resDiv.innerHTML = "<b>objHttp.status != 200</b>";
													  }
												  }
											}
			objHttp.send(xml);
      	}
   	}
}*/
// Esta funcion genera una encuesta en formato XML, la envia al GQ, obtiene el resultado de 
// la grabacion y con dicho resultado ejecuta la funcion pasada para el tratamiento del mismo
function GQ_enviarDatos(form, funcionErrores, funcionOk,tipopeticion){
    var xml = GQ_generarEncuesta(form,tipopeticion);
	GQ_sendXml(xml, funcionErrores, funcionOk);
}
// Esta funcion envia asincronamente el XML con la encuesta y obtiene la respuesta del 
// GQ.
// Parametros: xml -> variable de cadena de texto conteniendo el XML con la encuesta
//			   tratamientoErrores -> nombre de la funcion que analizara la respuesta
//									 del GQ tras intentar guardar la encuesta
function GQ_sendXml(xml, funcionErrores, funcionOk){
    var objHttp = GQ_getAjax();
    if(objHttp)
    {
        if (objHttp.readyState==0 || objHttp.readyState==4)
        {
            objHttp.open("POST", URI_PROXY, true);
			// im - Proxy
			objHttp.setRequestHeader("GQHost", GQ_URL_DATOS);
            objHttp.setRequestHeader("Content-Type", "text/xml");	      	      
            objHttp.onreadystatechange=
                function()
            {
	      	if(objHttp.readyState==4){	
                    if(objHttp.status == 200){
                        var respuesta = objHttp.responseText;                        
                        //if(reset)	resetStyles();                        
                        GQ_parseErrores(respuesta, funcionErrores, funcionOk)
                    } 
			}
          }
            objHttp.send(xml);
        }
    }
}

// Esta funcion es un ejemplo de tratamiento de la respuesta del GQ tras una peticion
// para guardar una encuesta
// Parametros: errores -> variable de cadena de texto conteniendo el XML con la respuesta del GQ

function GQ_parseErrores(errores, funcionErrores, funcionOk){
	var status = 'OK';
    // Codigo para IE
    if (window.ActiveXObject){
        var doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="true";//changed if ie6
        doc.loadXML(errores);
    } else {
        // Codigo para Mozilla, Firefox, Opera, etc.
        var parser=new DOMParser();
        var doc=parser.parseFromString(errores,"text/xml");
    }
	//alert(errores);//XML DEVUELTO POR GQ
	if(errores){
		var root = doc.documentElement;		
		//BUSCAMOS LOS POSIBLES NODOS DE ERROR
		var hayerror = root.getElementsByTagName("error");
		var hayerror2 = root.getElementsByTagName("errores");
		//alert(hayerror.length);								
		//alert(root.attributes.getNamedItem("resultado").value.toUpperCase());
		if(hayerror.length >0 || hayerror2.length >0) {status = 'KO';} //se ha producido un error 
		if(root.attributes.getNamedItem("resultado")){
			//alert(root.attributes.getNamedItem("resultado").value);
			if(root.attributes.getNamedItem("resultado").value.toUpperCase()=="KO"){status = 'KO';} //se ha producido un error
		}				
	}	
    if (status == 'OK'){
        // La encuesta se ha guardado correctamente
       // if (funcionOk){ funcionOk();}
	  	 LK_funcionOK();
    } else {
        //if (funcionErrores){funcionErrores();}
		  LK_funcionError();
	}
}
//TODO OK
function LK_funcionOK() {
	alertaErrores.alert({
					     texto:"Sus datos se han guardado correctamente",
						 onclick: resetform
	//					 onclick: document.location.href="http://vw.ruralka.com?source=crm"
						});
}
//ERROR
function LK_funcionError() {
	alertaErrores.alert("Ha ocurrido un error al guardar los datos. Por favor, int&eacute;ntelo de nuevo.");
}
//reset form
function resetform(){
	document.forms[0].reset();
}
//===============================================================================================================================
// FUNCIONES AUXILIARES
//===============================================================================================================================
//TRIM
function trim(st){
  	var m = st.match(/^\s*(\S+(\s+\S+)*)\s*$/);
  	return((m == null) ? "" : m[1]);
}
//REPLACE
function replace(texto,s1,s2){
	return texto.split(s1).join(s2);
}
//SOLO NUMEROS (APLICABLE A Tlf Fijo,Tlf Movil,CP,Año MAtriculacion,Kilometraje)
function solamenteNumeros(e) {
	var evt = e?e:event;	
	//alert("which:::"+evt.which)
	//alert("keyCode:::"+evt.keyCode)
	if (evt.which)
	{
		if(evt.which!=46 && evt.which!=8 && evt.wich!=9 && (evt.which<48 || evt.which>57))
			return false;
	}
	else if(evt.keyCode)
	{
		if(evt.keyCode!=46 && evt.keyCode!=8 && evt.keyCode!=9 && (evt.keyCode<48 || evt.keyCode>57))
			return false;
	}
	return true;
}
//VALIDACION particular_email_1
function checkMail(cadena_mail)
{
	ext=cadena_mail.substring(cadena_mail.lastIndexOf("."),cadena_mail.length);
	if(ext.length<5 && ext.length>1)
	{	
		var Template = /^[a-z][a-z-_0-9.]+@[a-z-_=>0-9.]+.[a-z]{2,3}$/i //Formato de direccion de correo electronico
		//return (Template.test(cadena_mail)) ? 1 : 0 //Compara "cadena_mail" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
		if (Template.test(cadena_mail) == 0)
		{ return false; //errStr = "El campo particular_email_1 es incorrecto.\r ";
		} else{ return true;}
	} else { return false; //errStr = "El campo particular_email_1 es incorrecto.\r ";
	}
}
//CAMPO REQUERIDO 
function FieldNotEmpty(idName){
	if(getValue(idName)!="") return true;
	return false;
}
function FieldSelectEmpty(idName){
	if(getSelectValue(idName)!="") return true;
	return false;
}
function FieldChecked(idName){
	if (document.getElementById(idName).checked==true) return true;
	return false;
	}
//FECHA FORMATO CORRECTO
function FormatDateField(idName){
	var val = getValue(idName);
	var Template = /^((0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/(19[0-9][0-9]|2[0-9][0-9][0-9]))$/; //Formato de direccion de correo electronico	
	if (Template.test(val) == 0){ return false;} //fecha incorrecta
	else{ return true;}//fecha correcta
}
function formatNombreAp1Ap2(idName){
	var val = getValue(idName);
	var Template = /^[\s\-A-Za-zÑñÇçáéíóúäëïöüàèìòùâêîôû·ÁÉÍÓÚÄËÏÖÜÀÈÌÒÙÂÊÎÔÛªº\.]{0,60}$/; //Formato de direccion de correo electronico	
	if (Template.test(val) == 0){ return false;} //fecha incorrecta
	else{ return true;}//fecha correcta
}

//FUNCIONES AUXILIARES PARA OBTENCION DE LOS VALORES INTRODUCIDOS
function getValue(idName){ //acceso al valor de un campo 
	return trim(document.getElementById(idName).value);
}
function getSelectValue(idName){ //acceso al valor seleccionado de un combo
  	var fld = document.getElementById(idName);
  	var opc = fld.options[fld.selectedIndex];
  	return trim(opc.value);
}
//ACCESO A NODOS DEL XML ENFUNCION DE LOS VALORES
function getTag(tag){
  	return "<"+tag+">"+getValue(tag)+"</"+tag+">";
}
function getSelectTag(tag){
  	return "<"+tag+">"+getSelectValue(tag)+"</"+tag+">";
}
//===============================================================================================================================
// VALIDACION DE LOS FORMULARIOS
//===============================================================================================================================
//VALIDAR CONTACTO
function validar_contacto(){
	var texto="";
	var em = document.getElementById('particular_email_1');	
	if(!FieldNotEmpty('particular_nombre_1')){ texto+="<br><li> Por favor, introduzca el <strong>nombre</strong>";}
	if(FieldNotEmpty('particular_nombre_1') && !formatNombreAp1Ap2('particular_nombre_1')){ texto+="<br><li> El <strong>nombre</strong> s&oacute;lo debe incluir letras";}
	if(!FieldNotEmpty('particular_apellido1_1')){ texto+="<br> - Por favor, introduzca el <strong>1<sup>er</sup> Apellido</strong>";}
	if(FieldNotEmpty('particular_apellido1_1') && !formatNombreAp1Ap2('particular_apellido1_1')){ texto+="<br><li> El <strong>1er apellido</strong> solo debe incluir letras";}
	if(FieldNotEmpty('particular_apellido2_1') && !formatNombreAp1Ap2('particular_apellido2_1')){ texto+="<br><li> El <strong>2º apellido</strong> solo debe incluir letras";}
	if(!FieldNotEmpty('particular_fechaNac_1')){ texto+="<br><li> Por favor, introduzca la <strong>fecha de nacimiento</strong>";}
	if(FieldNotEmpty('particular_fechaNac_1') && !FormatDateField('particular_fechaNac_1')){texto+="<br><li> La fecha de nacimiento de tener el formato <strong>dd/mm/aaaa</strong>";}
	if(!FieldNotEmpty('particular_numeroVia_1')){ texto+="<br><li> Por favor, introduzca el <strong>n&uacute;mero de v&iacute;a</strong>";}
	if(!FieldNotEmpty('particular_codigoPostal_1')){ texto+="<br><li> Por favor, introduzca el <strong>c&oacute;digo postal</strong>";}
	if(!FieldNotEmpty('particular_localidad_1')){ texto+="<br><li> Por favor, introduzca la <strong>localidad</strong>";}
	if(!FieldNotEmpty('particular_provincia_1')){ texto+="<br><li> Por favor, introduzca la <strong>provincia</strong>";}	
	if(!FieldNotEmpty('particular_tfnoFijo_1') && !FieldNotEmpty('particular_tfnoMovil_1') && !FieldNotEmpty('particular_email_1') ){ texto+="<br><li> Por favor, debe introducir o el <strong>tel&eacute;fono, el m&oacute;vil o el eMail</strong>";}
	if(FieldNotEmpty('particular_tfnoFijo_1') && getValue('particular_tfnoFijo_1').charAt(0)!="8" && getValue('particular_tfnoFijo_1').charAt(0)!="9" ){ texto+="<br><li> El <strong>tel&eacute;fono</strong> debe comenzar por 8 o 9";}
	if(FieldNotEmpty('particular_tfnoMovil_1') && getValue('particular_tfnoMovil_1').charAt(0)!="6"){ texto+="<br><li> El <strong>tel&eacute;fono m&oacute;vil</strong> debe comenzar por 6";}
	if(FieldNotEmpty('particular_email_1') && !checkMail(trim(em.value))){ texto+="<br><li> El <strong>eMail</strong> introducido no es correcto";}
	if(!FieldNotEmpty('consulta')){ texto+="<br><li> Por favor, debes introducir la <strong>consulta</strong>";}
	if(FieldNotEmpty('consulta') && getValue('consulta').length >1000){ texto+="<br><li> La <strong>consulta</strong> no debe superar los 1000 caracteres";}
	//texto="";
	if(trim(texto)!=""){alertaErrores.alert(texto);}
	else{
		//GQ_enviarDatos(document.forms[0],LK_funcionError,LK_funcionOK,1);}
		GQ_enviarDatos(document.forms[0],LK_funcionOK,1);
	}
}
//VALIDAR CATALOGO
function validar_catalogo(){
	var texto="";
	var em = document.getElementById('particular_email_1');
	if(!FieldNotEmpty('brochures')){ texto+="<br><li> Por favor, seleccione al menos un <strong>cat&aacute;logo</strong>";}
	if(!FieldNotEmpty('particular_nombre_1')){ texto+="<br><li> Por favor, introduzca el <strong>nombre</strong>";}
	if(FieldNotEmpty('particular_nombre_1') && !formatNombreAp1Ap2('particular_nombre_1')){ texto+="<br><li> El <strong>nombre</strong> s&oacute;lo debe incluir letras";}
	if(!FieldNotEmpty('particular_apellido1_1')){ texto+="<br><li> Por favor, introduzca el <strong>1<sup>er</sup> Apellido</strong>";}
	if(FieldNotEmpty('particular_apellido1_1') && !formatNombreAp1Ap2('particular_apellido1_1')){ texto+="<br><li> El <strong>1<sup>er</er> apellido</strong> s&oacute;lo debe incluir letras";}
	if(FieldNotEmpty('particular_apellido2_1') && !formatNombreAp1Ap2('particular_apellido2_1')){ texto+="<br><li> El <strong>2º apellido</strong> s&oacute;lo debe incluir letras";}
	if(!FieldNotEmpty('particular_fechaNac_1')){ texto+="<br><li> Por favor, introduzca la <strong>fecha de nacimiento</strong>";}
	if(FieldNotEmpty('particular_fechaNac_1') && !FormatDateField('particular_fechaNac_1')){texto+="<br><li> La fecha de nacimiento de tener el formato <strong>dd/mm/aaaa</strong>";}
	if(!FieldNotEmpty('particular_nombreVia_1')){ texto+="<br><li> Por favor, introduzca  el <strong>nombre de la v&iacute;a</strong>";}
	if(!FieldNotEmpty('particular_numeroVia_1')){ texto+="<br><li> Por favor, introduzca el <strong>n&uacute;mero de v&iacute;a</strong>";}
	if(!FieldNotEmpty('particular_codigoPostal_1')){ texto+="<br><li> Por favor, introduzca el <strong>c&oacute;digo postal</strong>";}
	if(!FieldNotEmpty('particular_localidad_1')){ texto+="<br><li> Por favor, introduzca la <strong>localidad</strong>";}
	if(!FieldNotEmpty('particular_provincia_1')){ texto+="<br><li> Por favor, introduzca la <strong>provincia</strong>";}
	if(!FieldNotEmpty('particular_tfnoFijo_1') && !FieldNotEmpty('particular_tfnoMovil_1') && !FieldNotEmpty('particular_email_1') ){ texto+="<br><li> Por favor, debe introducir o el <strong>tel&eacute;fono, el m&oacute;vil o el eMail</strong>";}
	if(FieldNotEmpty('particular_tfnoFijo_1') && getValue('particular_tfnoFijo_1').charAt(0)!="8" && getValue('particular_tfnoFijo_1').charAt(0)!="9" ){ texto+="<br><li> El tel&eacute;fono fijo</strong> debe comenzar por 8 o 9";}
	if(FieldNotEmpty('particular_tfnoMovil_1') && getValue('particular_tfnoMovil_1').charAt(0)!="6"){ texto+="<br><li> El <strong>tel&eacute;fono m&oacute;vil</strong> debe comenzar por 6";}
	if(FieldNotEmpty('particular_email_1') && !checkMail(trim(em.value))){ texto+="<br><li> El <strong>eMail</strong> introducido no es correcto";}
	//texto="";
	if(trim(texto)!=""){alertaErrores.alert(texto);}	
	else{
		//alert("tod ok");
		GQ_enviarDatos(document.forms[0],LK_funcionError,LK_funcionOK,2);
	}
}
//VALIDAR TD
function validar_td(){
	var texto="";
	var em = document.getElementById('particular_email_1');
	if(!FieldNotEmpty('particular_nombre_1')){ texto+="<br><li> Por favor, introduzca el <strong>nombre</strong>";}
	if(FieldNotEmpty('particular_nombre_1') && !formatNombreAp1Ap2('particular_nombre_1')){ texto+="<br><li> El <strong>nombre</strong> s&oacute;lo debe incluir letras";}
	if(!FieldNotEmpty('particular_apellido1_1')){ texto+="<br><li> Por favor, introduzca el <strong>1<sup>er</sup> Apellido</strong>";}
	if(FieldNotEmpty('particular_apellido1_1') && !formatNombreAp1Ap2('particular_apellido1_1')){ texto+="<br><li> El <strong>1<sup>er</sup> apellido</strong> s&oacute;lo debe incluir letras";}
	if(FieldNotEmpty('particular_apellido2_1') && !formatNombreAp1Ap2('particular_apellido2_1')){ texto+="<br><li> El <strong>2º apellido</strong> s&oacute;lo debe incluir letras";}	
	if(!FieldNotEmpty('particular_fechaNac_1')){ texto+="<br><li> Por favor, introduzca la <strong>fecha de nacimiento</strong>";}
	if(FieldNotEmpty('particular_fechaNac_1') && !FormatDateField('particular_fechaNac_1')){texto+="<br><li> La fecha de nacimiento de tener el formato <strong>dd/mm/aaaa</strong>";}
//	if(!FieldNotEmpty('particular_nombreVia_1')){ texto+="<br><li> Por favor, introduzca  el <strong>nombre de la v&iacute;a</strong>";}
//	if(!FieldNotEmpty('particular_numeroVia_1')){ texto+="<br><li> Por favor, introduzca el <strong>n&uacute;mero de v&iacute;a</strong>";}
//	if(!FieldNotEmpty('particular_codigoPostal_1')){ texto+="<br><li> Por favor, introduzca el <strong>c&oacute;digo postal</strong>";}
//	if(!FieldNotEmpty('particular_localidad_1')){ texto+="<br><li> Por favor, introduzca la <strong>localidad</strong>";}
//	if(!FieldNotEmpty('particular_provincia_1')){ texto+="<br><li> Por favor, introduzca la <strong>provincia</strong>";}	
	if(!FieldNotEmpty('particular_email_1')){ texto+="<br><li> Por favor, introduzca un <strong>eMail</strong>";}	
	//if(!FieldNotEmpty('particular_tfnoFijo_1') && !FieldNotEmpty('particular_tfnoMovil_1') && !FieldNotEmpty('particular_email_1') ){ texto+="<br><li> Por favor, debe introducir o el <strong>tel&eacute;fono, el m&oacute;vil o el eMail</strong>";}
//	if(!FieldNotEmpty('particular_tfnoFijo_1') && !FieldNotEmpty('particular_tfnoMovil_1')){ texto+="<br><li> Por favor, debe introducir o el <strong>tel&eacute;fono fijo o el m&oacute;vil</strong>";}
	if(FieldNotEmpty('particular_tfnoFijo_1') && getValue('particular_tfnoFijo_1').charAt(0)!="8" && getValue('particular_tfnoFijo_1').charAt(0)!="9" ){ texto+="<br><li> El <strong>tel&eacute;fono fijo</strong> debe comenzar por 8 &oacute; 9";}
	if(FieldNotEmpty('particular_tfnoMovil_1') && getValue('particular_tfnoMovil_1').charAt(0)!="6"){ texto+="<br><li> El <strong>tel&eacute;fono m&oacute;vil</strong> debe comenzar por 6";}
	if(FieldNotEmpty('particular_email_1') && !checkMail(trim(em.value))){ texto+="<br><li> El <strong>eMail</strong> introducido no es correcto";}
	if(!FieldChecked('particular_aceptobases_1')){ texto+="<br><li> Por favor, debe leer y aceptar <strong>las bases legales</strong>";}	
	//	if(!FieldNotEmpty('vactual_marca_1')){ texto+="<br><li> Por favor, seleccione la <strong>marca</strong> de su coche actual";}
//	if(!FieldNotEmpty('vactual_modelo_1')){ texto+="<br><li> Por favor, seleccione el <strong>modelo</strong> de su coche actual";}
//	if(!FieldNotEmpty('vactual_kilometraje_1')){ texto+="<br><li> Por favor, introduzca el <strong>kilometraje actual</strong> de su coche";}
//	if(!FieldNotEmpty('vactual_anyoMatriculacion_1')){ texto+="<br><li> Por favor, introduzca el <strong>a&ntilde;o de matriculaci&oacute;n</strong> de su coche actual";}

//	if(!FieldNotEmpty('vfuturo_provinciaTD_1')){ texto+="<br><li> Por favor, introduzca la <strong>provincia</strong> en la que quiere recibir informaci&oacute;n del veh&iacute;culo";}
//	if(!FieldNotEmpty('vfuturo_deseo_Concesion_1')){ texto+="<br><li> Por favor, introduzca la <strong>concesi&oacute;n</strong> en la que quiere recibir informaci&oacute;n del veh&iacute;culo";}
	//texto="";
	if(trim(texto)!=""){alertaErrores.alert(texto);}	
	else{
		//alert("todito ok");
		GQ_enviarDatos(document.forms[0],LK_funcionError,LK_funcionOK,3); //alerta parse pruebas
		//GQ_enviarDatos(document.forms[0],LK_funcionOK,3);
	}
}
//VALIDAR NEWS
function validar_news(){
	var texto="";
	var em = document.getElementById('particular_email_1');
	if(!FieldNotEmpty('particular_nombre_1')){ texto+="<br><li> Por favor, introduzca el <strong>nombre</strong>";}
	if(FieldNotEmpty('particular_nombre_1') && !formatNombreAp1Ap2('particular_nombre_1')){ texto+="<br><li> El <strong>nombre</strong> solo debe incluir letras";}
	if(!FieldNotEmpty('particular_apellido1_1')){ texto+="<br><li> Por favor, introduzca el <strong>1er Apellido</strong>";}
	if(FieldNotEmpty('particular_apellido1_1') && !formatNombreAp1Ap2('particular_apellido1_1')){ texto+="<br><li> El <strong>1<sup>er</sup> apellido</strong> solo debe incluir letras";}
	if(FieldNotEmpty('particular_apellido2_1') && !formatNombreAp1Ap2('particular_apellido2_1')){ texto+="<br><li> El <strong>2º apellido</strong> solo debe incluir letras";}	
	if(!FieldNotEmpty('particular_fechaNac_1')){ texto+="<br><li> Por favor, introduzca la <strong>fecha de nacimiento</strong>";}
	if(FieldNotEmpty('particular_fechaNac_1') && !FormatDateField('particular_fechaNac_1')){texto+="<br><li> La fecha de nacimiento de tener el formato <strong>dd/mm/aaaa</strong>";}
	if(!FieldNotEmpty('particular_particular_tfnoFijo_1_1') && !FieldNotEmpty('particular_tfnoMovil_1') && !FieldNotEmpty('particular_email_1') ){ texto+="<br><li> Por favor, debe introducir o el <strong>tel&eacute;fono, el m&oacute;vil o el eMail</strong>";}
	if(FieldNotEmpty('particular_tfnoFijo_1') && getValue('particular_tfnoFijo_1').charAt(0)!="8" && getValue('particular_tfnoFijo_1').charAt(0)!="9" ){ texto+="<br><li> El <strong>tel&eacute;fono fijo</strong> debe comenzar por 8 o 9";}
	if(!FieldNotEmpty('particular_particular_nombreVia_1_1')){ texto+="<br><li> Por favor, introduzca  el <strong>nombre de la v&iacute;a</strong>";}
	if(!FieldNotEmpty('particular_numeroVia_1')){ texto+="<br><li> Por favor, introduzca el <strong>n&uacute;mero de v&iacute;a</strong>";}
	if(!FieldNotEmpty('particular_codigoPostal_1')){ texto+="<br><li> Por favor, introduzca el <strong>c&oacute;digo postal</strong>";}
	if(!FieldNotEmpty('particular_localidad_1')){ texto+="<br><li> Por favor, introduzca la <strong>localidad</strong>";}
	if(!FieldNotEmpty('particular_provincia_1')){ texto+="<br><li> Por favor, introduzca la <strong>provincia</strong>";}	
	if(!FieldNotEmpty('particular_pais_1')){ texto+="<br><li> Por favor, introduzca el <strong>pa&iacute;s</strong>";}	
	if(FieldNotEmpty('particular_tfnoMovil_1') && getValue('particular_tfnoMovil_1').charAt(0)!="6"){ texto+="<br><li> El <strong>tel&eacute;fono m&oacute;vil</strong> debe comenzar por 6";}
	if(FieldNotEmpty('particular_email_1') && !checkMail(trim(em.value))){ texto+="<br><li> El <strong>eMail</strong> introducido no es correcto";}
	if(!FieldNotEmpty('vactual_marca_1')){ texto+="<br><li> Por favor, seleccione la <strong>marca</strong> de su coche actual";}
	if(!FieldNotEmpty('vactual_modelo_1')){ texto+="<br><li> Por favor, seleccione el <strong>modelo</strong> de su coche actual";}
	//texto="";
	if(trim(texto)!=""){alertaErrores.alert(texto);}
	else{
		//alert("tod ok");
		GQ_enviarDatos(document.forms[0],LK_funcionError,LK_funcionOK,4);
	}
}

//===============================================================================================================================
// FUNCIONES PARA LOS SELECT DE CATALOGOS
//===============================================================================================================================
/**
 * validates brochure select input.
 * @param pSelectSelectedName name/id of input with selected brochures
 * @param pSelectNotSelectedName name/id of input with not selected brochures
 * @param pMaxBrochures maximum number of brochures allowed to be ordered at once
 * @param pIsOnClick true if validation is invoked on click, false if on submit
 * @param pErrorboxId id of html element representing error box
 */
function validateBrochureSelect(pSelectSelectedName, pSelectNotSelectedName, pMaxBrochures, pIsOnClick, pErrorboxId) {
  var theSelected = document.getElementById(pSelectSelectedName);
  // split up if-clause to increase readability
  // on click validation
  if(pIsOnClick) {
	var theNotSelected = document.getElementById(pSelectNotSelectedName);
	if(theSelected && theNotSelected && pMaxBrochures && getValidSelectOptions(theSelected, false) +  getValidSelectOptions(theNotSelected, true) <= pMaxBrochures) { return true;}
  }else { // on submit validation
    if(theSelected && pMaxBrochures && getValidSelectOptions(theSelected, false)   > 0 && getValidSelectOptions(theSelected, false) <= pMaxBrochures) {return true;}
  }
  return false;
}
/**
 * @param pSelect select object to be checked
 * @param pCheckSelection true if if only selected options shall be counted, false if not
 * @return # of options being not null
 */
function getValidSelectOptions(pSelect, pCheckSelection) {
  var countOptions = 0;
  if(pSelect) {
	for(i=0;i<pSelect.options.length;i++) {
      if(typeof(pSelect.options[i] != "object")){
        if(!pCheckSelection || pSelect.options[i].selected) {
          countOptions++;
        }
      }
    }
  }
  return countOptions
}

/**
 * moves option from one select imput to another
 * @param pFromSelect select box from where to remove item
 * @param pToSelect select box where to add item
 */
function moveItem(pFromSelect, pToSelect) {
  var fromSelect = document.getElementById(pFromSelect);
  var toSelect = document.getElementById(pToSelect);
  var notSelectedItems = new Array();
  var amountUnselected = 0;
  if(fromSelect && toSelect) {
    // detect and copy selected options
    for(i = 0; i < fromSelect.options.length; i++) {
     var newOpt = new Option(fromSelect.options[i].text, fromSelect.options[i].value, false, false);
      if(fromSelect.options[i].selected == true) {
        toSelect.options[toSelect.options.length] = newOpt;
      } else {
        notSelectedItems[amountUnselected++] = newOpt  ;
      }
    }
    // clear from-select box
    for(i = fromSelect.options.length -1; i >= 0; i--) {
      fromSelect.options[i] = null;
    }

    // refill from select box
    for(i = 0; i < notSelectedItems.length; i++) {
      fromSelect.options[i] = notSelectedItems[i];
    }
  }
}

/**
 * Builds comma separated list of selected carlines in given input.
 * @param pSelect select to retrieve values from
 * @param pHiddenKeyStore input to store names in
 */
function updateCarlines(pSelect, pHiddenKeyStore) {
  var select = document.getElementById(pSelect);
  //alert(select.id)
  var store = document.getElementById(pHiddenKeyStore);
  if(select && store) {
    store.value = "";
    for(var i = 0; i < select.options.length; i++) {
      if(store.value.length != 0){
        store.value += ";" ;
      }
      store.value += select.options[i].value;
    }
  }
  //alert(store.value);
}
 
