var contador=1;
var cabece ;
var cabeza="";
var tabla2;
var valor="";
var indice="";
var repe = 0;
var repe2 = 0;
var textojava="";
var valorjava="";
var solouno=0;
var provin= "Província";
var cambioDomicilio = false; // control para saber si se ha seleccionado cambio de domicilio en la busqueda
titulos = new Array(); // array para guardar los titulos de los tbodys que voy poniendo
nombres = new Array(); // array para los repetidos
peticion = new Array(); // array para las query
query_pedido = new Array();
var guarda_datos;
criteriosGeograficos = new Array(); //array con los criterios geograficos para borrar;
var contadorGeo = 1;
criterioDireccion = new Array(); //array con los criterios de direccion para borrar;
var contadorDireccion = 1;

function aniadeCondicion(tipo,comparador,desc,modelo,nombre_campo){

	document.getElementById('contenedor').style.backgroundColor="#ffffff";
	document.getElementById('FILTROS').style.backgroundColor="#ffffff";
	
	switch(modelo) {
		case 'combo':
			if(desc.options[desc.selectedIndex].value!=0) { // si el indice no es el del texto 'Seleccione una provincia...'
				indice=desc.options[desc.selectedIndex].value; // esto me devuelve el indice
				valor=desc.options[desc.selectedIndex].text; // esto me devuelve el texto
			}
		break;
		case 'combo2':
			var segmentacion=desc.split("#");
			if(segmentacion[0]!=desc) { // si es distinto es que tengo datos separados por el simbolo
				indice=segmentacion[0];
				valor=segmentacion[1];				
				//DEMP_COD_LOCALIDAD_LITERAL		
			}
		break;		
		case 'libre':
			valor=desc;	  
		break;	
		case 'check':
			if(desc.checked == true) envioDatos("SOLO_ACTIVAS","1");		
			else if(desc.checked == false) envioDatos("SOLO_ACTIVAS","0");
			valor="";
		break;	
		case 'check2':
			valor=desc.value;
			if(valor == "1") {
				document.getElementById("SOLO_ACTIVAS").checked = true;
				envioDatos("SOLO_ACTIVAS","1");		
			} else if(valor == "0") {
				envioDatos("SOLO_ACTIVAS","0");
			}	
			valor="";
		break;	
		default:
			 valor=desc.value;
	}	
	
	if(valor != "") {
	
		var donde="";
		var texto="";
		var finTexto="";	
		var alerta = "El valor està repetit";
	
		var tabla = document.getElementById("latabla");
		
	if(tipo == "Municipi") {
		valorjava = valor;
		valor = valor.substr(6,valor.length);
	}	
		
	
		texto_escrito=document.createTextNode(valor); 
		titulo = document.createTextNode(tipo);
		
	
		// comprobacion de que el municipio este relleno antes que la direccion
		if(tipo == 'Adreça') {
			repe2 = repetido2('Municipi',contador);
			alerta = "És necessari afegir un municipi per a segmentar per adreça";
			var tabla_s=document.getElementById("latabla"); //cojo mi tabla
			var body=tabla_s.getElementsByTagName("TBODY");
			if(body.length <= 1) { 
				document.getElementById('contenedor').style.backgroundColor="#eaeaea";
				document.getElementById('FILTROS').style.backgroundColor="#eaeaea";
				document.getElementById('FILTROS').style.borderColor="#eaeaea";
			} // si solo me 
		}
	
		// solo puede quedar uno !! (financieros, antiguedad, matriz, importa - exporta)
		if(tipo=='Empleats' || tipo=='Vendes' || tipo=='Beneficis' || tipo=='Capital Social' || tipo=='Total Actiu' || tipo=='Patrimoni Net' || tipo=='Data' || tipo=='Pais Matriu' || tipo=='Deno. Matriu' ||  tipo=='Imp / Exp') {
			repe2 = soloUno(tipo,contador);
			alerta="Ja té afegit aquest criteri en els filtres de segmentació, per a canviar el seu valor primer ha d'eliminar l'anterior.";
		}
	
		repe = repetido(tipo,contador,valor);
		// Control de cambios de domicilio
		if (tipo == provin && valor == "Canvis en Domicili") {
			if (repe == 0) {
				alert("Empreses que han canviat el seu domicili a una altre Comunitat Autònoma en els últims 12 mesos");
				quitarTodo();
				nombres = new Array();
				cambioDomicilio = true;
			}
		} else {
				if (cambioDomicilio) {
					repe = 1;
					if (confirm("La Segmentació per Canvis en Domicili no és compatible amb la Segmentació per criteris Geográfics.\n\nPremi Acceptar si vol esborrar la Segmentació per Canvis en Domicili i segmentar per criteris Geográfics.\n\nPremi Cancel.lar si vol mantenir la Segmentació per Canvis en Domicili.")) {
						quitarTodo();
						nombres = new Array();
						cambioDomicilio = false;
						repe = 0;
					}
				}
		}
		//alert("aniadecondicion: "+tipo+comparador+desc+modelo+nombre_campo);
		
		if(repe == 0 && repe2 == 0) {
	
			nombres[tipo+contador] = valor;
	
			if(!document.getElementById(tipo+"0")){ 	
				if(tipo !='' ) titulos[contador] = tipo+0;
				tablebody = document.createElement("TBODY"); //creo mi elemento tbody
				tablebody.setAttribute("id",tipo+0);
				columna_t=document.createElement("tr"); //creo el tr
				fila_t=document.createElement("td");	//creo el primer td
				fila_t.setAttribute("width","295");
				fila_t.className="texto_titulo";
				fila_t.setAttribute("style","padding-left:5px;");
				fila_t.setAttribute("colSpan",2); 
				fila_t.appendChild(titulo);
				columna_t.appendChild(fila_t);
				tablebody.appendChild(columna_t);
				tabla.appendChild(tablebody);
			} else tablebody=document.getElementById(tipo+"0");
		
			if(valor!='') { // aqui se guardan los datos en un array que se pasara a java para la query
				if(indice!='') enviodado=indice;
				else enviodado=valor;
				if(modelo == "libre" && valorjava!="") enviodado = valorjava;
				if(tipo == 'Municipi') {
					enviodado = valorjava;
					indice = valorjava;				
				} else if(tipo == 'CNAE' || tipo == 'SIC' || tipo == 'Codi Postal') {
					indice = valor;
				}	
				//alert("envio: "+nombre_campo+" ; "+enviodado)
				envioDatos(nombre_campo,enviodado);
				enviodado="";
				valorjava="";			
				//if(tipo=="Localidad") envioDatos("DEMP_COD_LOCALIDAD_LITERAL",valor); //DEMP_COD_LOCALIDAD_LITERAL
			}	
		
			//alert("query_pedido: "+query_pedido["DEMP_FECHA_CONSTITUCION_COMPARADOR"]);
		
			columna=document.createElement("tr"); //creo el tr
			columna.setAttribute("id",""+tipo+contador+"");
		
			fila=document.createElement("td");	//creo el primer td
			fila.setAttribute("width","240");
			fila.className="texto_hijo";
			fila.appendChild(texto_escrito);
		
			fila2=document.createElement("td");	//creo el primer td
			fila2.setAttribute("width","55");
			fila2.className="texto";
			
			href3=document.createElement("a");
			//alert("javascript:quitar('"+tipo+contador+"','"+contador+"','"+nombre_campo+"','"+indice+"');");
			href3.setAttribute("href","javascript:preguntar('"+tipo+contador+"','"+contador+"','"+nombre_campo+"','"+indice+"');"); //creo el href para el enlace
		
			//alert("href3: "+href3);
			
			texto2=document.createElement("img");
			texto2.setAttribute("src","/img/Cata40M/bot/bot_quitar_azul.gif"); // imagen del boton 'quitar'
			texto2.setAttribute("border","0"); // le doy un border 0 a la tabla
			texto2.setAttribute("width","55"); // le meto un width
			texto2.setAttribute("height","18"); // le meto un height
		
			href3.appendChild(texto2);	
			fila2.appendChild(href3);
			columna.appendChild(fila);
			columna.appendChild(fila2);
			tablebody.appendChild(columna);
	
			tabla.appendChild(tablebody);
		
			if(document.getElementById("contenedor").style.visibility == 'hidden') document.getElementById("contenedor").style.visibility = 'visible';
	
			if(tipo=="Comarca"  || tipo==provin || tipo=="Codi postal" ){
				criteriosGeograficos[contadorGeo]="quitar('"+tipo+contador+"','"+contador+"','"+nombre_campo+"','"+indice+"')";
				contadorGeo++;
			}
			if(tipo==direc){
				criterioDireccion[contadorDireccion]="quitar('"+tipo+contador+"','"+contador+"','"+nombre_campo+"','"+indice+"')";
				contadorDireccion++;
			}
			contador++;		
	
		} else {
			if (!cambioDomicilio) {
			 	alert(alerta);
			 }	
			 repe2 = 0;
			 repe = 0;
		}	 
	} else if(valor=="" && tipo!="Activas") {
		alert("Falta un valor per a " + tipo);	
	}
	//alert(tabla.innerHTML);
	indice="";
	
}



function eliminaElemento(arrayi,elemento) {
	for(var i=0;i<arrayi.length;i++) {
		if(arrayi[i]==elemento) arrayi.splice(i,1);
	}	
	return arrayi;
}

function condicionJunta(tipo,comparador,cond1,cond2,nose,nombreca) {
 
 var compara='';

	switch (comparador) {
	case '1':
		compara = '=';
		cond2 = "";
		textojava = "EQUAL";	
		valorjava = cond1;			
	break;
	case '2':
		compara = '>';	
		cond2 = "";
		textojava = "GREATER";
		valorjava = cond1;
	break;
	case '3':
		compara = '<';
		cond2 = "";
		textojava = "LESS";
		valorjava = cond1;
	break;
	case '4':
		compara = 'Entre';
		textojava = "BETWEEN";
		valorjava = cond1+'#'+cond2;
	break;
	case '6':
		compara = 'Empieza';
		textojava = "LIKE";
		valorjava = cond1 + '%';		
	break;
	case '7':
		compara = 'Contiene';
		textojava = "LIKE";
		valorjava = '%'+cond1+'%';
	break;	
	case 'EQUAL':
		compara = '=';
		cond2 = "";
		textojava = "EQUAL";	
		valorjava = cond1;			
	break;
	case '2':
		compara = '>';	
		cond2 = "";
		textojava = "GREATER";
		valorjava = cond1;
	break;
	case 'LESS':
		compara = '<';
		cond2 = "";
		textojava = "LESS";
		valorjava = cond1;
	break;
	case 'BETWEEN':
		compara = 'Entre';
		textojava = "BETWEEN";
		valorjava = cond1+'#'+cond2;
	break;
	case 'LIKE':
		compara = 'Empieza / Contiene';
		textojava = "LIKE";
		valorjava = cond1;
		cond1=cond1.replace('%','');
	break;
	}
	if (cond2 != "") {
		//En este caso, se trata de un intervalo de dos fechas (en antigüedad), y no se debe hacer parseInt
		if(cond2.length > 2 && cond2.charAt(2) == '/') {
			var desc = compara + ' ' + cond1 + ' i ' + cond2 ;
			aniadeCondicion(tipo,comparador,desc,'libre',nombreca);
		}
		//En cualquier otro caso, se trata de un intervalo de cifras numéricas
		else if(parseInt(cond1) <= parseInt(cond2)) { 
			var desc = compara + ' ' + cond1 + ' i ' + cond2 ;
			aniadeCondicion(tipo,comparador,desc,'libre',nombreca);
		} else alert("Si us plau, escrigui el valor mes petit primer");	
	} else {
		var desc = compara + ' ' + cond1;
		aniadeCondicion(tipo,comparador,desc,'libre',nombreca);
	}	
	
	cond2=null;	
}
function quitarGeo(){	
	for (i = 1; i < criteriosGeograficos.length; i++) {
		eval(criteriosGeograficos[i]);
	}
	criteriosGeograficos = new Array(); //aaray con los criterios geograficos para borrar;
	contadorGeo = 1;
	
}
function quitarDireccion(){	
	for (i = 1; i < criterioDireccion.length; i++) {
		eval(criterioDireccion[i]);
	}
	criterioDireccion = new Array(); //aaray con los criterios geograficos para borrar;
	contadorDireccion = 1;
	
}
function preguntar(id,contador,valorid,valor){	
	if(confirm('Realment desitja eliminar-lo?')){
		quitar(id,contador,valorid,valor);
		if (valorid == "DEMP_COD_PROVINCIA" && valor == "99") {
			cambioDomicilio = false;
		}
	}	
}
function quitar(id,contador,valorid,valor){	
//alert(id+"--"+contador+"--"+valorid+"--"+valor+"--"+query_pedido[valorid]);
	var conforme=true;
//alert(query_pedido[valorid]);	
	if (conforme) {
		var i=0;
		var o=0;
		tabla_s=document.getElementById("latabla"); //cojo mi tabla
		body=tabla_s.getElementsByTagName("TBODY");
		for (i = 0; i < body.length; i++) { //los recorro los tbodys
			tr = body.item(i).getElementsByTagName("tr"); 
		  	for(o=0; o < tr.length; o++) { //recorro los tr
				if(tr.item(o).getAttribute("id")==id) { //si tengo alguno que coincide el idendificador con mi entrada
					body.item(i).removeChild(tr.item(o)); //lo borro
					//HAY QUE QUITAR EL CAMPO DEL ARRAY		
					if(peticion[contador]) peticion[contador]="";
					if(nombres[id]) nombres[id]="";
					if(query_pedido[valorid]) {
						// antes de borrar el elemento tengo q comprobar si es compuesto
						var elemento=query_pedido[valorid];
						var resto="";
						segmenta=elemento.split("#");
						if(segmenta[0]!=elemento && (valorid == 'DEMP_CNAE' || valorid == 'DEMP_SIC' || valorid == 'DEMP_COD_LOCALIDAD' || valorid == 'DEMP_COD_COMARCA')) { // si es distinto es que tengo datos separados por el simbolo
						
							for(var u=0;u<=segmenta.length;u++) {
								if(segmenta[u]!=valor && segmenta[u]!=undefined && segmenta[u]!='undefined' && segmenta[u]!='') {
									if(valor != segmenta[u]) resto += segmenta[u]+'#';
								  }							  
							}
						  	resto=resto.substring(0,resto.length-1);
							query_pedido[valorid]=resto;
						} else {
							query_pedido = eliminaElemento(query_pedido,query_pedido[valorid]);
							query_pedido[valorid]="";
						}	
					}	
					if(tr.length <= 1) { 
						tabla_s.removeChild(body.item(i)); 
					} // si solo me queda el item del titulo lo borro tambien 							
				} //fin if(tr.item..
			} // fin for(var o=0...
			
			if(body.length <= 1) { 
				document.getElementById('contenedor').style.backgroundColor="#eaeaea";
				document.getElementById('FILTROS').style.backgroundColor="#eaeaea";
				document.getElementById('FILTROS').style.borderColor="#eaeaea";
			} // si solo me queda el item del titulo lo borro tambien 				
		} // fin for(var i=0..
  	}
//alert(query_pedido[valorid]);	  		
}


function repetido(tipo,contador,valor){	
	var devuelta=0;
	for(var i=0;i<=contador;i++) {
		if(nombres[tipo+i] == valor ) devuelta = 1;
	}
	return devuelta;	
}


// para cuando solo puede quedar uno
function repetido2(tipo,contador){	
	var devuelta=1;
	for(var i=0;i<=contador;i++) {
		if(nombres[tipo+i]) devuelta = 0;
	}
	return devuelta;	
}


function soloUno(tipo,contador) {
	if(tipo=='Empleats' || tipo=='Vendes' || tipo=='Beneficis' || tipo=='Capital Social' || tipo=='Total Actiu' || tipo=='Patrimoni Net' || tipo=='Data' || tipo=='Pais Matriu' || tipo=='Deno. Matriu' ||  tipo=='Imp / Exp') {
	var devuelta=0;
		for(var i=0;i<=contador;i++) {
			if(nombres[tipo+i]!='' && nombres[tipo+i]!=undefined)  {
				devuelta = 1;
			}	
		}
	} 
	return devuelta;
}

function quitarTodo(){	
	tabla_s=document.getElementById("latabla"); //cojo mi tabla
	var cuerpos;
	for(var i=0;i<=titulos.length;i++) { // recorro mi array de nombres
		if(document.getElementById(titulos[i]))  // si existe...
			tabla_s.removeChild(document.getElementById(titulos[i])); // lo borro
	}
	document.getElementById('SOLO_ACTIVAS').checked = false;
 	document.getElementById('contenedor').style.backgroundColor="#eaeaea";
 	document.getElementById('FILTROS').style.backgroundColor="#eaeaea";
	document.getElementById('FILTROS').style.borderColor="#eaeaea";
	
 
 	// vacio el array del formulario
 	for(var e=0;e<=query_pedido.length;e++) {
 		query_pedido.splice(e,1);
 	}	 
 
}	

function cambiaBoton(obj, up){
	if (up){
		obj.src='/img/Cata40M/bot/bot_quitar_azul.gif';
	}else{
		obj.src='/img/Cata40M/bot/bot_quitar_rojo.gif';
	}			
}
		
function popUp(pagina){
   	var opciones="left=1,top=1,width=700px,height=400px,scrollbars=no";
	ventana = window.open(root_page+'/prod/'+pagina,'',opciones);
   	ventana.focus()   
}

function ventana_local(provincia) {
	if(provincia.options[provincia.selectedIndex].value!=0) { // si el indice no es el del texto 'Seleccione una provincia...'
		indice_provincia=provincia.options[provincia.selectedIndex].value; // esto me devuelve el indice
		var w=(screen.width - 434)/2;
		var h=(screen.height - 434)/2;
		var ventana=window.open( root_page+'/prod/ventana_localidad.html/txt/'+indice_provincia+'','ventana_localidad','scrollbars=0,width=434,height=434,status=yes,top='+ h +',left='+w); //,scrollbars=yes
		ventana.focus();
	}	
}

function limpiarCNAESIC(objeto){
	var obj = objeto.value;
	var retorno = '';
	var i = 0;
	var cambio="0";
	for (i = 0; i < obj.length; i++){
		if ((obj.charAt(i) != ' ')&&(obj.charAt(i) != '-')&&(obj.charAt(i) != '.')&&(obj.charAt(i) != '/')){
			if(obj.charAt(i) != ',' ){
				if(validarEntero(obj.charAt(i))){
					retorno += obj.charAt(i);
				}else{
					cambio="1";
				}
			}else{
				if(obj.length > i+1){
					if(i==0){
						cambio="1";
					}else{
						if(obj.charAt(i+1) != ','){
							retorno += obj.charAt(i);
						}else{
							cambio="1";
						}
					}
				}else{
					//quitamos el ultimo caracter que es ,
					cambio="1";
				}
			}
		}else{
			cambio="1";
		}
	}
	if(cambio=="1") {
		objeto.value= retorno;
		return false;
	}else{
		return true;
	}
}

function comprobacion(valor,valor1,valor2) {
	if(valor == 4) {
		document.getElementById(valor1).style.visibility = "visible";
		document.getElementById(valor2).style.visibility = "visible";
	} else {
		document.getElementById(valor1).style.visibility = "hidden";
		document.getElementById(valor2).style.visibility = "hidden";
	}
}


function envioDatos(nombre_camp,valor_camp) {
	// campos especiales con comparadores
	if(valorjava!="") valor_camp=valorjava;

	switch(nombre_camp) {
	case 'DEMP_EMPLEADOS':
		query_pedido["DEMP_EMPLEADOS_COMPARADOR"]=textojava;	
	break;
	case 'DEMP_VENTAS_N':
		query_pedido["DEMP_VENTAS_N_COMPARADOR"]=textojava;
	break;	
	case 'DEMP_BENEFICIO_PERDIDA':
		query_pedido["DEMP_BENEFICIO_PERDIDA_COMPARADOR"]=textojava;
	break;
	case 'DEMP_CAPITAL_SOCIAL':
		query_pedido["DEMP_CAPITAL_SOCIAL_COMPARADOR"]=textojava;
	break;
	case 'DEMP_TOTAL_ACTIVO':
		query_pedido["DEMP_TOTAL_ACTIVO_COMPARADOR"]=textojava;
	break;
	case 'DEMP_PATRIMONIO_NETO':
		query_pedido["DEMP_PATRIMONIO_NETO_COMPARADOR"]=textojava;
	break;
	case 'DEMP_FECHA_CONSTITUCION':
		query_pedido["DEMP_FECHA_CONSTITUCION_COMPARADOR"]=textojava;	
	break;
	case 'DEMP_DENO_MATRIZ':
		query_pedido["DEMP_DENO_MATRIZ_COMPARADOR"]=textojava;	
	break;		
	}
	
	if(query_pedido[nombre_camp]!='' && query_pedido[nombre_camp]!=undefined) query_pedido[nombre_camp]+='#'+valor_camp;
	else query_pedido[nombre_camp]=valor_camp;
}

function recepcionDatos() {
 	if(document.formu_segmentacion) { 
  		var formulario = document.formu_segmentacion;
  		if(document.getElementById("ENVIADO").value != null && document.getElementById("ENVIADO").value == 1) {
			for(var i=0;i<formulario.length;i++) {
  				var nombre = formulario.elements[i].name;
  			//alert("nombre campo "+ nombre);
				var valor =	 formulario.elements[i].value;
				//alert("valor campo "+ valor);
				if(nombre!="" && valor!="") {
					var nombre_comun = document.getElementById(nombre).name;	
					var documento = document.getElementById(nombre);
					documento.value = valor; 
					var segmenta;
					switch(nombre) {
						case 'DEMP_COD_CCAA':							
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('Comarca',':',documento,'combo',nombre);
									documento.value="";
								}	
							} else {
								aniadeCondicion('Comarca',':',documento,'combo',nombre);
								documento.value="";
							}
						break;
						case 'DEMP_COD_COMARCA':			
						//alert("comarca");	
						//alert("segmente " + segmenta);			
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('Comarca',':',documento,'combo',nombre);
									documento.value="";
								}	
							} else {
								aniadeCondicion('Comarca',':',documento,'combo',nombre);
								documento.value="";
							}
						break;
						case 'DEMP_COD_PROVINCIA':
//							aniadeCondicion('Provincia',':',documento,'combo',nombre);
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('Província',':',documento,'combo',nombre);
									documento.value="";
								}	
							} else {
								aniadeCondicion('Província',':',documento,'combo',nombre);
								documento.value="";
							}
						break;
						case 'DEMP_COD_LOCALIDAD':
//							aniadeCondicion('Localidad',':',documento,'libre',nombre);
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('Municipi',':',documento,'texto',nombre);
									documento.value = "";
								}	
							} else {
								aniadeCondicion('Municipi',':',documento,'texto',nombre);
								documento.value="";
							}							
						break;
						case 'DEMP_CODIGO_POSTAL':
							segmenta=valor.split("#");
								if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
							for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('Codi postal',':',documento,'texto',nombre);
									documento.value = "";
								}	
							} else {
								aniadeCondicion('Codi postal',':',documento,'texto',nombre);
								documento.value="";
							}
							
							//aniadeCondicion('Codigo Postal',':',documento,'texto',nombre);
						break;
						case 'DEMP_DIRECCION':
							aniadeCondicion('Adreça',':',documento,'texto',nombre);
							documento.value="";
						break;
						case 'DEMP_CNAE':
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('CNAE',':',documento,'texto',nombre);
									documento.value = "";
								}	
							} else {
								aniadeCondicion('CNAE',':',documento,'texto',nombre);
								documento.value="";
							}
						break;
						case 'DEMP_SIC':
							segmenta=valor.split("#");
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								for(var e=0;e<segmenta.length;e++) {
									documento.value = segmenta[e];
									aniadeCondicion('SIC',':',documento,'texto',nombre);
									documento.value = "";
								}	
							} else {
								aniadeCondicion('SIC',':',documento,'texto',nombre);
								documento.value="";
							}
						break;
						case 'DEMP_EMPLEADOS':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_EMPLEADOS1");
							var documento3 = document.getElementById("DEMP_EMPLEADOS2");
							var comparador = document.getElementById("DEMP_EMPLEADOS_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Empleats',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Empleats',comparador,documento.value,documento2,'libre',nombre);
								documento.value = ""; 
							}	
						break;
						case 'DEMP_VENTAS_N':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_VENTAS_N1");
							var documento3 = document.getElementById("DEMP_VENTAS_N2");
							var comparador = document.getElementById("DEMP_VENTAS_N_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Vendes',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Vendes',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
						break;
						case 'DEMP_BENEFICIO_PERDIDA':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_BENEFICIO_PERDIDA1");
							var documento3 = document.getElementById("DEMP_BENEFICIO_PERDIDA2");
							var comparador = document.getElementById("DEMP_BENEFICIO_PERDIDA_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Beneficis',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Beneficis',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
						break;
						case 'DEMP_CAPITAL_SOCIAL':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_CAPITAL_SOCIAL1");
							var documento3 = document.getElementById("DEMP_CAPITAL_SOCIAL2");
							var comparador = document.getElementById("DEMP_CAPITAL_SOCIAL_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Capital Social',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Capital Social',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
						break;
						case 'DEMP_TOTAL_ACTIVO':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_TOTAL_ACTIVO1");
							var documento3 = document.getElementById("DEMP_TOTAL_ACTIVO2");
							var comparador = document.getElementById("DEMP_TOTAL_ACTIVO_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Total Actiu',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Total Actiu',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
						break;
						case 'DEMP_PATRIMONIO_NETO':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_PATRIMONIO_NETO1");
							var documento3 = document.getElementById("DEMP_PATRIMONIO_NETO2");
							var comparador = document.getElementById("DEMP_PATRIMONIO_NETO_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Patrimoni Net',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Patrimoni Net',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
						break;
						case 'DEMP_FECHA_CONSTITUCION':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_FECHA_CONSTITUCION1");
							var documento3 = document.getElementById("DEMP_FECHA_CONSTITUCION2");
							var comparador = document.getElementById("DEMP_FECHA_CONSTITUCION_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Data',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Data',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}	
						break;
						case 'DEMP_COD_PAIS_MATRIZ':
							aniadeCondicion('Pais Matriu',':',documento,'combo',nombre);
							documento.value="";
						break;
						case 'DEMP_DENO_MATRIZ':
							segmenta=valor.split("#");
							var documento1 = document.getElementById("DEMP_DENO_MATRIZ1");
							var documento3 = document.getElementById("DEMP_DENO_MATRIZ2");
							var comparador = document.getElementById("DEMP_DENO_MATRIZ_COMPARADOR").value;
							if(segmenta[0]!=valor) { // si es distinto es que tengo datos separados por el simbolo
								documento1.value = segmenta[0];									
								documento3.value = segmenta[1];
								condicionJunta('Pais Matriu',comparador,documento1.value,documento3.value,'libre',nombre);
								documento1.value = "";									
								documento3.value = "";
								
							} else {
								documento.value = valor; 
								documento2 = "";
								condicionJunta('Pais Matriu',comparador,documento.value,documento2,'libre',nombre);
								documento.value = "";
							}
							
						break;
						case 'DEMP_COD_IMPORTA_EXPORTA':
							aniadeCondicion('Imp / Exp',':',documento,'combo',nombre);
							documento.value="";
						break;
						case 'SOLO_ACTIVAS':
							aniadeCondicion('Activas',':',documento,'check2',nombre);
							documento.value="";
						break;						
					}			
				}
			}
  		}	
 	} else alert("Perdida de comunicacion");
}

function rellenoformulario() {
	var formulaQ = document.formu_segmentacion;
	if(query_pedido) {
		for(keyv in query_pedido) {
			if(keyv != undefined && keyv != 'undefined' && keyv != '') {
				var campo = eval('document.formu_segmentacion.'+keyv);	
			  	campo.value=query_pedido[keyv];
		    }
		}	
		document.formu_segmentacion.submit();
		contador=1;
	}		
}

function accion () {
	rellenoformulario();	
}

function textoNumerico(nombre,valorForm,valorForm2,valorForm3,modo,nombreCampo) {
  if(nombre != "Data")  {
	if (!/^([0-9])*$/.test(valorForm2) || !/^([0-9])*$/.test(valorForm3)) {
		alert("Indicar xifres sense punts ni comas");
	
	} else condicionJunta(nombre,valorForm,valorForm2,valorForm3,modo,nombreCampo);
  } else {
	
  	var digitos=valorForm2.substr(0,2);
  	var digitos1=valorForm3.substr(0,2);
  	
  	if((valorForm3!="") && (digitos > 12 || digitos1 > 12 || digitos < 01 || digitos1 < 01)) {
  		alert("No existe el mes");
  	} else if(digitos > 12 || digitos < 01 ) {
  		alert("No existe el mes");
  	} else if(/^([0-9]){2}\/([0-9]){4}$/.test(valorForm2)) {
  		if(valorForm3!="" && (/^([0-9]){2}\/([0-9]){4}$/.test(valorForm3))) condicionJunta(nombre,valorForm,valorForm2,valorForm3,modo,nombreCampo);
  		else if(valorForm3 == "") condicionJunta(nombre,valorForm,valorForm2,valorForm3,modo,nombreCampo);
  		else alert("El valor de la segona data no coincideix amb el patró");	
  	} else alert("El valor de la data no coincideix amb el patró");
   }
}

////////////////////////////////////////////////////
/////////// VALIDAR ////////////////////////////////
//////////////////////////////////////////////////

function insertOption(objSelect, opcion, valor) {
	var y = document.createElement('option');
	y.text = opcion;
	y.value = valor;
	try {
		objSelect.add(y, null); // standards compliant
	} catch (ex) {
		objSelect.add(y); // IE only
	}
}
function removeOptionsSelect(objSelect) {
	if (objSelect.options.length > 0) {
		objSelect.remove(0);
		if (objSelect.options.length > 0)
			removeOptionsSelect(objSelect);

	}
}

function cargaProvincias(code) {
	var objSelect = document.getElementById('DEMP_COD_PROVINCIA');
	removeOptionsSelect(objSelect);
	var variable;
	switch (code) {
	case '01':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Almería", "04");
		objSelect.options[1] = variable;
		variable = new Option("Cádiz", "11");
		objSelect.options[2] = variable;
		variable = new Option("Córdoba", "14");
		objSelect.options[3] = variable;
		variable = new Option("Granada", "18");
		objSelect.options[4] = variable;
		variable = new Option("Huelva", "21");
		objSelect.options[5] = variable;
		variable = new Option("Jaén", "23");
		objSelect.options[6] = variable;
		variable = new Option("Málaga", "29");
		objSelect.options[7] = variable;
		variable = new Option("Sevilla", "41");
		objSelect.options[8] = variable;
		break;
	case '02':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Huesca", "22");
		objSelect.options[1] = variable;
		variable = new Option("Teruel", "44");
		objSelect.options[2] = variable;
		variable = new Option("Zaragoza", "50");
		objSelect.options[3] = variable;
		break;
	case '03':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Asturias", "33");
		objSelect.options[1] = variable;
		break;
	case '04':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Cantabria", "39");
		objSelect.options[1] = variable;
		break;
	case '05':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Albacete", "02");
		objSelect.options[1] = variable;
		variable = new Option("Ciudad Real", "13");
		objSelect.options[2] = variable;
		variable = new Option("Cuenca", "16");
		objSelect.options[3] = variable;
		variable = new Option("Guadalajara", "19");
		objSelect.options[4] = variable;
		variable = new Option("Toledo", "45");
		objSelect.options[5] = variable;
		break;
	case '06':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Ávila", "05");
		objSelect.options[1] = variable;
		variable = new Option("Burgos", "09");
		objSelect.options[2] = variable;
		variable = new Option("León", "24");
		objSelect.options[3] = variable;
		variable = new Option("Palencia", "34");
		objSelect.options[4] = variable;
		variable = new Option("Salamanca", "37");
		objSelect.options[5] = variable;
		variable = new Option("Segovia", "40");
		objSelect.options[6] = variable;
		variable = new Option("Soria", "42");
		objSelect.options[7] = variable;
		variable = new Option("Valladolid", "47");
		objSelect.options[8] = variable;
		variable = new Option("Zamora", "49");
		objSelect.options[9] = variable;
		break;
	case '07':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Barcelona", "08");
		objSelect.options[1] = variable;
		variable = new Option("Girona", "17");
		objSelect.options[2] = variable;
		variable = new Option("Lleida", "25");
		objSelect.options[3] = variable;
		variable = new Option("Tarragona", "43");
		objSelect.options[4] = variable;
		break;
	case '08':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Ceuta", "51");
		objSelect.options[1] = variable;
		break;
	case '16':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Melilla", "52");
		objSelect.options[1] = variable;
		break;
	case '09':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Alicante", "03");
		objSelect.options[1] = variable;
		variable = new Option("Castellón", "12");
		objSelect.options[2] = variable;
		variable = new Option("Valencia", "46");
		objSelect.options[3] = variable;
		break;
	case '10':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Badajoz", "06");
		objSelect.options[1] = variable;
		variable = new Option("Cáceres", "10");
		objSelect.options[2] = variable;
		break;
	case '11':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("A Coruña", "15");
		objSelect.options[1] = variable;
		variable = new Option("Lugo", "27");
		objSelect.options[2] = variable;
		variable = new Option("Ourense", "32");
		objSelect.options[3] = variable;
		variable = new Option("Pontevedra", "36");
		objSelect.options[4] = variable;
		break;
	case '12':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Baleares", "07");
		objSelect.options[1] = variable;
		break;
	case '13':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Tenerife", "38");
		objSelect.options[1] = variable;
		variable = new Option("Las Palmas", "35");
		objSelect.options[2] = variable;
		break;
	case '14':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("La Rioja", "26");
		objSelect.options[1] = variable;
		break;
	case '15':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Madrid", "28");
		objSelect.options[1] = variable;
		break;
	case '17':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Murcia", "30");
		objSelect.options[1] = variable;
		break;
	case '18':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Navarra", "31");
		objSelect.options[1] = variable;
		break;
	case '19':
		variable = new Option("Todas", "");
		objSelect.options[0] = variable;
		variable = new Option("Álava", "01");
		objSelect.options[1] = variable;
		variable = new Option("Guipúzcoa", "20");
		objSelect.options[2] = variable;
		variable = new Option("Vizcaya", "48");
		objSelect.options[3] = variable;
		break;
	}

}
function cambiaBotonAnadir(code) {
	switch (code) {
	case 'COM':
		document.getElementById('contenedorCOM').style.visibility = 'visible';
		document.getElementById('contenedorPROV').style.visibility = 'hidden';
		document.getElementById('completaMunicipio').innerHTML='Municipi';
		break;
	case 'PROV':
		document.getElementById('contenedorPROV').style.visibility = 'visible';
		document.getElementById('contenedorCOM').style.visibility = 'hidden';
		break;
	}
}
function confirmacion() {
	if (confirm("Esta seguro de desea borrar todos los filtros?")) {
		document.buscarEmpresasForm.reset();
		quitarTodo();
		document.location.href = root_page + '/prod/SEGMENTACION/ACC/NEW';
	}
}
function sic(id) {
	if (id == "") {
		alert("Para buscar por palabra clave, escriba la palabra que desea buscar");
	} else {
		var w = (screen.width - 705) / 2;
		var h = (screen.height - 435) / 2;
		// var venta=window.open('ventana_sic.html/txt/'+id,'ventana_sic','scrollbars=0,width=705,height=435,top='+ h +',left='+w);
		var ventana = window.open(root_page + '/prod/ventana_sic.html/txt/' + id + '', 'ventana_sic', 'scrollbars=0,width=434,height=434,status=yes,top=' + h + ',left=' + w); // ,scrollbars=yes
		ventana.focus();
	}
}

function cnae(id) {
	if (id == "") {
		alert("Para buscar por palabra clave, escriba la palabra que desea buscar");
	} else {
		var w = (screen.width - 705) / 2;
		var h = (screen.height - 435) / 2;
		// var venta=window.open('ventana_sic.html/txt/'+id,'ventana_sic','scrollbars=0,width=705,height=435,top='+ h +',left='+w);
		var ventana = window.open(root_page + '/prod/ventana_cnae.html/txt/' + id + '', 'ventana_cnae', 'scrollbars=0,width=434,height=434,status=yes,top=' + h + ',left=' + w); // ,scrollbars=yes
		ventana.focus();
	}
}

function preAlertaGeograficos() {

	var valorCCAA = document.getElementById('DEMP_COD_CCAA');
	valorCCAA = valorCCAA.options[valorCCAA.selectedIndex].value;

	var valorPROV = document.getElementById('DEMP_COD_PROVINCIA');
	valorPROV = valorPROV.options[valorPROV.selectedIndex].value;

	var valorCP = document.getElementById('DEMP_CODIGO_POSTAL').value;

	if (valorCP != "") {
		alertaGeograficos('CP');
	} else if (contadorLocalidad > 0) {
		for ( var i = 0; i < textoLocalidad.length; i++) {
			aniadeCondicion('Municipi', ':', codLocalidad[i] + ' ' + textoLocalidad[i], 'libre', 'DEMP_COD_LOCALIDAD');
		}
	} else if (valorPROV != "") {
		alertaGeograficos('PROV');
	} else if (valorCCAA != "") {
		alertaGeograficos('COM');
	}
}
function alertaGeograficos(tipo) {
	var comprobacion = 1;
	if (tipo == "CP") {
		var numero = document.buscarEmpresasForm.cp.value;
		if (!/^([0-9])*$/.test(numero)) {
			alert("El valor " + numero + " no es numerico");
			comprobacion = 2;
		}
	}

	if (comprobacion == 1) {
		if (contadorDireccion > 1) {
			if (confirm(" La " + segmentacionMay + " por Criterios " + geograficos + " no es compatible con la " + segmentacionMay + " por " + direccion + ".\n\nPulse 'Aceptar' si desea borrar las direcciones y Segmentar por Criterios " + geograficos + ".\n\nPulse 'Cancelar' si desea conservar las direcciones.")) {
				quitarDireccion();
				aniadeNewCondicion(tipo);
			}
		} else {
			aniadeNewCondicion(tipo);
		}
	}

}

function alertaDireccion() {
	if (contadorGeo > 1) {
		if (confirm(" La " + segmentacionMay + " por " + direccion + " no es compatible con la " + segmentacionMay + " por Criterios " + geograficos + ".\n\nPulse 'Aceptar' si desea borrar los Criterios " + geograficos + " y Segmentar por la " + direccion + ".\n\nPulse 'Cancelar' si desea conservar los criterios " + geograficos + ".")) {
			quitarGeo();
			aniadeCondicion('Adreça', ':', document.buscarEmpresasForm.direccion, 'texto', 'DEMP_DIRECCION');
		}
	} else {
		aniadeCondicion('Adreça', ':', document.buscarEmpresasForm.direccion, 'texto', 'DEMP_DIRECCION');
	}

}


function aniadeNewCondicion(tipo) {
	if (tipo == "COM") {
		aniadeCondicion('Comarca', ':', document.buscarEmpresasForm.comarca, 'combo', 'DEMP_COD_COMARCA');
	} else if (tipo == "PROV") {
		aniadeCondicion('Província', ':', document.buscarEmpresasForm.provincia, 'combo', 'DEMP_COD_PROVINCIA');
	} else if (tipo = "CP") {
		aniadeCondicion('Codi Postal', ':', document.buscarEmpresasForm.cp, 'texto', 'DEMP_CODIGO_POSTAL');
	}
}

/** -------------------------------------------------------- * */
/** ------------FUNCIONES DE AJAX--------------------------- * */
/*
 * function nuevoAjax() {
 * 
 * //Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por lo que se puede copiar tal como esta aqui
 * 
 * var xmlhttp = false; try { // Creacion del objeto AJAX para navegadores no IE xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { // Creacion del objet AJAX para IE xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest != "undefined") { xmlhttp = new XMLHttpRequest(); }
 * 
 * return xmlhttp; }
 * 
 * function eliminaEspacios(cadena) { // Funcion equivalente a trim en PHP var x = 0, y = cadena.length - 1; while (cadena.charAt(x) == " ") x++; while (cadena.charAt(y) == " ") y--; return cadena.substr(x, y - x + 1); }
 * 
 * function validaIngreso(valor) { if (valor == "") return false; return true; } function limpiadiv() { var divMensaje = document.getElementById("espera"); divMensaje.innerHTML = ""; } function buscaLocalidades(codProvincia) { var ajax = nuevoAjax(); ajax.open("POST", "/servlet/app/prod/LOCALIDADES/txt/"+codProvincia, true); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("txt=" + codProvincia); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { // input.value=""; // Muestro el mensaje enviado desde el servidor var respuesta = ajax.responseText; divMensaje.innerHTML = "<font color='blue'><i>Email Enviado a " + codProvincia + "</i></font>"; } } }
 */
