// constante que almacena el nmero de pasos del deslizador
var PASOS_DESLIZADOR = 250;

// scripts realizados a partir del cdigo de Sergi Meseguer - www.zigotica.com

var DESPLEGABLES = {

	init : function() {
		if (document.getElementById('busquedas').className == '')
			document.getElementById('busquedas').className = 'buscar-coche';
		var etiquetas = document.getElementById('contenidos').getElementsByTagName('label');
		for (i=0;i<etiquetas.length;i++) {
			if (etiquetas[i].parentNode.parentNode.nodeName.indexOf('FORM') != -1) {
				etiquetas[i].onclick = function() {
					DESPLEGABLES.desplegar(this);
					return false;
				}
			}
		}
	},

	desplegar : function(cual) {
		cual.parentNode.parentNode.parentNode.className = cual.attributes['for'].nodeValue;
	}

}




var FORMULARIOS = {

	init : function() {
		document.getElementById('busquedas').getElementsByTagName('form')[0].onsubmit = function() {
			//alert('N-C:'+document.getElementById('nuevos-coche').checked+';SN-C:'+document.getElementById('seminuevos-coche').checked);
			if (document.getElementById('nuevos-coche').checked){
					document.getElementById('nuevos-coche').value=1;
			}else{
				document.getElementById('nuevos-coche').value=0;
			}
			if (document.getElementById('seminuevos-coche').checked){
				document.getElementById('seminuevos-coche').value=1;
			}else{
				document.getElementById('seminuevos-coche').value=0;
			}
			//alert('N-C:'+document.getElementById('nuevos-coche').value+';SN-C:'+document.getElementById('seminuevos-coche').value);
			
			if (!document.getElementById('nuevos-coche').checked && !document.getElementById('seminuevos-coche').checked) {
				/*document.getElementById('nuevos-coche').checked=false;
				document.getElementById('nuevos-coche').value=0;
				document.getElementById('seminuevos-coche').checked=false;
				document.getElementById('seminuevos-coche').value=0;
				*/
				alert('Para poder buscar debe elegir al menos un tipo de vehculo nuevo o seminuevo/km. 0');
				return false;
			}
			return true;
		}
		document.getElementById('busquedas').getElementsByTagName('form')[1].onsubmit = function() {
			if (!document.getElementById('nuevos-precio').checked && !document.getElementById('seminuevos-precio').checked) {
				alert('Para poder buscar debe elegir al menos un tipo de vehculo nuevo o seminuevo/km. 0');
				return false;
			} else if ((document.getElementById('importe').value == 0) && (document.getElementById('cuota').value == 0)) {
				alert('Para poder buscar debe elegir al menos un importe o una cuota');
				return false;
			} else if ((document.getElementById('elegir-importe').checked?!validaNumero(document.getElementById('importe').value):0) || (document.getElementById('elegir-cuota').checked?!validaNumero(document.getElementById('cuota').value):0)) {
				alert('Para poder buscar debe introducir un valor de importe o cuota que sea numrico');
				return false;
			}
			return true;
		}
		document.getElementById('busquedas').getElementsByTagName('form')[2].onsubmit = function() {
			if ((document.getElementById('nombre-caracteristicas').value == '') || (document.getElementById('apellidos-caracteristicas').value == '')) {
				alert('Debes rellenar todos los datos para enviar la solicitud');
				return false;
			} else if (!validaTelefono(document.getElementById('telefono-caracteristicas').value)) {
				alert('Debes introducir un telfono vlido para poder enviar la solicitud');
				return false;
			} else if (!validaEMail(document.getElementById('email-caracteristicas').value)) {
				alert('Debes introducir una direccin de e-mail vlida para poder enviar la solicitud');
				return false;
			} else if (document.getElementById('provincias-caracteristicas').selectedIndex == 0) {
				alert('Debes elegir una provincia para poder enviar la solicitud');
				return false;
			} else if (!document.getElementById('aceptar-condiciones-caracteristicas').checked) {
				alert('Debes aceptar las condiciones legales para poder enviar la solicitud');
				return false;
			}
			return true;
		}
	}

}




var instanciaCarga;
var instanciaCarrusel;
var instanciaExtras;


var VEHICULO = {

	init : function() {
		document.getElementById('marca-coche').selectedIndex = 0;
		document.getElementById('marca-caracteristicas').selectedIndex = 0;
		document.getElementById('marca-coche').onchange = function() {
			if (this.selectedIndex == 0)
				document.getElementById('modelo-coche').disabled = true;
			else
				document.getElementById('modelo-coche').disabled = false;
			borraDesplegable(document.getElementById('modelo-coche'));
			borraDesplegable(document.getElementById('combustible-coche'));
			borraDesplegable(document.getElementById('carroceria-coche'));
			borraDesplegable(document.getElementById('puertas-coche'));
			/*marcaModelo = false;*/
			cargaDatos(instanciaCarga,'coche',INSTALL_DIR + '/xml_response/vehiculos.php');
		}
		document.getElementById('modelo-coche').onchange = function() {
			/*if (document.getElementById('modelo-coche').selectedIndex != 0)
				marcaModelo = true;
			else
				marcaModelo = false;*/
			cargaDatos(instanciaCarga,'coche',INSTALL_DIR + '/xml_response/vehiculos.php');
		}
		document.getElementById('combustible-coche').onchange = function() {
			cargaDatos(instanciaCarga,'coche',INSTALL_DIR + '/xml_response/vehiculos.php');
		}
		document.getElementById('carroceria-coche').onchange = function() {
			cargaDatos(instanciaCarga,'coche',INSTALL_DIR + '/xml_response/vehiculos.php');
		}
		document.getElementById('puertas-coche').onchange = function() {
			cargaDatos(instanciaCarga,'coche',INSTALL_DIR + '/xml_response/vehiculos.php');
		}
		document.getElementById('marca-caracteristicas').onchange = function() {
			borraDesplegable(document.getElementById('modelo-caracteristicas'));
			borraDesplegable(document.getElementById('combustible-caracteristicas'));
			borraDesplegable(document.getElementById('version-caracteristicas'));
			//borraComplementos();
			if (this.selectedIndex != 0)
				cargaDatos(instanciaCarga,'caracteristicas',INSTALL_DIR + '/xml_response/modelo.php');
		}
		document.getElementById('modelo-caracteristicas').onchange = function() {
			borraDesplegable(document.getElementById('combustible-caracteristicas'));
			borraDesplegable(document.getElementById('version-caracteristicas'));
			//borraComplementos();
			if (this.selectedIndex != 0)
				cargaDatos(instanciaCarga,'caracteristicas',INSTALL_DIR + '/xml_response/combustibles.php');
		}
		document.getElementById('combustible-caracteristicas').onchange = function() {
			borraDesplegable(document.getElementById('version-caracteristicas'));
			//borraComplementos();
			if (this.selectedIndex != 0)
				cargaDatos(instanciaCarga,'caracteristicas',INSTALL_DIR + '/xml_response/versiones.php');
		}
		document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('a')[1].onclick = function() {
			/*document.getElementById('formulario-caracteristicas').style.display = 'block';*/
			if (navigator.appName.indexOf('Internet Explorer') != -1) {
				var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
				for (m=0;m<selects.length;m++) {
					if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
						selects[m].style.visibility = 'hidden';
				}
			}
			var posicion = (navigator.appName.indexOf('Opera') != -1)?0:parseInt(document.documentElement.scrollTop);
			document.getElementById('datos-envio').style.top = ((parseInt(document.documentElement.clientHeight) - 60)/2) + posicion + 'px';
			document.getElementById('contenedor-datos').style.width = document.documentElement.scrollWidth + 'px';
			document.getElementById('contenedor-datos').style.height = document.documentElement.scrollHeight + 'px';
			document.getElementById('contenedor-datos').className = 'activo';
			return false;
		}
		document.getElementById('cerrar_datos').onclick = function() {
			document.getElementById('contenedor-datos').className = '';
			if (navigator.appName.indexOf('Internet Explorer') != -1) {
				var selects = document.getElementById('busquedas').getElementsByTagName('select');
				for (m=0;m<selects.length;m++) {
					if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
						selects[m].style.visibility = 'visible';
				}
			}
		}
		desplegableMarca = document.getElementById('marca-coche').cloneNode(true);
		desplegableMarca.onchange = document.getElementById('marca-coche').onchange;
		desplegableCombustible = document.getElementById('combustible-coche').cloneNode(true);
		desplegableCombustible.onchange = document.getElementById('combustible-coche').onchange;
		desplegableCarroceria = document.getElementById('carroceria-coche').cloneNode(true);
		desplegableCarroceria.onchange = document.getElementById('carroceria-coche').onchange;
		desplegablePuertas = document.getElementById('puertas-coche').cloneNode(true);
		desplegablePuertas.onchange = document.getElementById('puertas-coche').onchange;
		fieldsetDesplegables = document.getElementById('formulario-buscar-coche').getElementsByTagName('fieldset')[0];
	}

}




var cargaCarrusel;

var CARRUSEL = {

	init : function() {
		cargado = true;
		cargaCarrusel = setTimeout('CARRUSEL.carga()',TIEMPO_CARRUSEL);
	},

	carga : function() {
		cargaDatos(instanciaCarrusel,'carrusel',INSTALL_DIR + '/xml_response/carrusel.php?tipo=1');
		cargaCarrusel = setTimeout('CARRUSEL.carga()',TIEMPO_CARRUSEL);
	}

}



var cargandoExtras = false;

var EXTRAS = {

	init: function() {
		document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('fieldset')[1].getElementsByTagName('a')[0].onclick = function() {
			if (document.getElementById('version-caracteristicas').selectedIndex != 0) {
				cargandoExtras = true;
				cargaDatos(instanciaExtras,'extras',INSTALL_DIR + '/xml_response/extras_index_empresas.php');
			} else
				alert('Para ver los extras debe elegir antes una marca, un modelo, un combustible y una versin');
			return false;
		}
		document.getElementById('cerrar').onclick = function() {
			document.getElementById('contenedor-extras').className = '';
			if (navigator.appName.indexOf('Internet Explorer') != -1) {
				var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
				for (m=0;m<selects.length;m++) {
					if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
						selects[m].style.visibility = 'visible';
				}
			}
		}
	},

	relacionar : function(cual) {
		var total = Number(cual.value.split('|')[0]);
		var totales = document.getElementById('contenidos-extras').getElementsByTagName('div')[0].getElementsByTagName('input');
		var identificador = cual.id;
		if (identificador.split('_')[0] == 'e')
			return false;
		var marcado = false;
		// comprobamos que ese mismo campo no est marcado en otra parte
		if (cual.checked) {
			// comprobamos que uno de primer nivel no est marcado en un segundo nivel
			if (cual.id.split('_').length == 1) {
				for (k=0;k<totales.length;k++) {
					if ((totales[k].id.split('_').length > 1) && (totales[k].id.split('_')[2] == identificador)) {
						if (totales[k].checked) {
							alert('El extra elegido ya sido seleccionado');
							cual.checked = false;
							marcado = true;
						}
					}
				}
			} else {
				for (k=0;k<totales.length;k++) {
					// comprobamos que uno de segundo nivel no est marcado en un primer nivel
					if ((totales[k].id.split('_').length == 1) && (totales[k].id == identificador.split('_')[2])) {
						if (totales[k].checked) {
							alert('El extra elegido ya sido seleccionado');
							cual.checked = false;
							marcado = true;
						}
					// comprobamos que uno de segundo nivel no est marcado en un segundo nivel
					} else if ((totales[k].id.split('_').length > 1) && (totales[k].id.split('_')[2] == identificador.split('_')[2]) && (totales[k].id != identificador)) {
						if (totales[k].checked) {
							alert('El extra elegido ya sido seleccionado');
							cual.checked = false;
							marcado = true;
						}
					}
				}
			}
		}
		if (!marcado) {
			var siguiente = (cual.parentNode.nextSibling.nodeType == 3)?cual.parentNode.nextSibling.nextSibling:cual.parentNode.nextSibling;
			// comprobamos si el input es de primer o segundo nivel
			if ((siguiente != null) && (siguiente.nodeName == 'FIELDSET')) {
				// obtenemos la accin y comprobamos cual es
				var accion = siguiente.getElementsByTagName('input')[0].id.split('_')[0];
				if (accion == 'e') {
					if (cual.checked) {
						// deseleccionamos todos los que hay dentro y restamos su valor
						var contiene = siguiente.getElementsByTagName('input');
						for (k=0;k<contiene.length;k++) {
							if (contiene[k].checked) {
								total -= Number(contiene[k].value.split('|')[0]);
								contiene[k].checked = false;
							}
							// obtenemos el identificador de cada extra excluido
							identificador = contiene[k].id.split('_')[2];
							// buscamos si existe fuera
							for (m=0;m<totales.length;m++) {
								// en caso afirmativo, si est seleccionado lo deseleccionamos y restamos su valor
								if (totales[m].id == identificador) {
									if (totales[m].checked) {
										total -= Number(totales[m].value.split('|')[0]);
										totales[m].checked = false;
										alert('El extra elegido excluye ' + totales[m].nextSibling.nodeValue + '. Se ha desmarcado automticamente la anterior seleccin');
									}
								}
							}
						}
					}
				} else if (accion == 'i') {
					// actualizamos todos los que hay dentro
					var contiene = siguiente.getElementsByTagName('input');
					for (k=0;k<contiene.length;k++) {
						contiene[k].checked = cual.checked;
					}
				} else if (accion == 'r') {
					if (cual.checked) {
						// comprobamos si alguno de los que hay dentro est seleccionado
						var seleccionado = false;
						var contiene = siguiente.getElementsByTagName('input');
						for (k=0;k<contiene.length;k++) {
							if (contiene[k].checked) {
								seleccionado = true;
								k = contiene.length-1;
							}
						}
						// si no hay ninguno, miramos en los que hay fuera, como extras individuales
						if (!seleccionado) {
							for (k=0;k<contiene.length;k++) {
								// obtenemos el identificador de cada extra excluido
								identificador = contiene[k].id.split('_')[2];
								// buscamos si existe fuera
								for (m=0;m<totales.length;m++) {
									// en caso afirmativo, actualizamos la variable que controla si hay alguno marcado
									if (totales[m].id == identificador) {
										if (totales[m].checked) {
											seleccionado = true;
											m = totales.length-1;
										}
									}
								}
								if (seleccionado)
									k = contiene.length-1;
							}
						}
						// si an as no hay ninguno seleccionado, marcamos por defecto el ms barato e informamos al usuario
						if (!seleccionado) {
							var precioBarato = Number(contiene[0].value.split('|')[0]);
							var indiceBarato = 0;
							for (k=0;k<contiene.length;k++) {
								if (Number(contiene[k].value.split('|')[0]) < precioBarato) {
									precioBarato = Number(contiene[k].value.split('|')[0]);
									indiceBarato = k;
								}
							}
							alert('El extra elegido requiere seleccionar al menos uno de los indicados. Por defecto se elegir el ms econmico, y podr modificarlo al cerrar esta ventana');
							total += Number(contiene[indiceBarato].value.split('|')[0]);
							contiene[indiceBarato].checked = true;
						}
					}
				}
			} else {
				// obtenemos el extra del que dependen
				var superior = (cual.parentNode.parentNode.previousSibling.nodeType == 3)?cual.parentNode.parentNode.previousSibling.previousSibling:cual.parentNode.parentNode.previousSibling;
				superior = superior.getElementsByTagName('input')[0];
				// obtenemos la accin y comprobamos cual es
				var accion = cual.id.split('_')[0];
				if (accion == 'e') {
					if (cual.checked) {
						// deseleccionamos el superior y restamos su valor
						if (superior.checked) {
							total -= Number(superior.value.split('|')[0]);
							superior.checked = false;
						}
						// obtenemos el identificador del extra excluido
						identificador = superior.id;
						// buscamos si existe fuera, como extra secundario
						for (m=0;m<totales.length;m++) {
							// en caso afirmativo, si est seleccionado lo deseleccionamos y restamos su valor
							if (totales[m].id.split('_')[2] == identificador) {
								if (totales[m].checked) {
									total -= Number(totales[m].value.split('|')[0]);
									totales[m].checked = false;
								}
							}
						}
					}
				} else if (accion == 'r') {
					if (cual.checked) {
						// comprobamos si hay algn otro requerido marcado, y si es as lo deseleccionamos y restamos su valor
						var contiene = cual.parentNode.parentNode.getElementsByTagName('input');
						for (k=0;k<contiene.length;k++) {
							if ((contiene[k].checked) && (contiene[k].id != cual.id)) {
								total -= Number(contiene[k].value.split('|')[0]);
								contiene[k].checked = false;
							}
						}
					} else {
						// si est seleccionado, deseleccionamos el superior y aadimos su valor a lo que restaremos ms adelante
						if (superior.checked) {
							total += Number(superior.value.split('|')[0]);
							superior.checked = false;
						}
					}
				}
			}
		}
		return true;
	}

}




addLoadEvent(function() {
	DESPLEGABLES.init();
});

addLoadEvent(function() {
	DESLIZADORES.init(document.getElementById('formulario-buscar-precio').getElementsByTagName('label')[2]);
});

addLoadEvent(function() {
	FORMULARIOS.init();
});

addLoadEvent(function() {
	VEHICULO.init();
});

addLoadEvent(function() {
	CARRUSEL.init();
});

addLoadEvent(function() {
	VIDEO.init();
});

addLoadEvent(function() {
	EXTRAS.init();
});






/***********************************************************
*********** FUNCIONES DE CARGA CON XMLHttpRequest **********
***********************************************************/


function cargaDatos(instancia,datos,url) {
	// comprobamos si hay algn valor seleccionado
	if ((datos == 'coche') && (document.getElementById('marca-coche').selectedIndex == 0) && (document.getElementById('modelo-coche').selectedIndex == 0) && (document.getElementById('combustible-coche').selectedIndex == 0) && (document.getElementById('carroceria-coche').selectedIndex == 0) && (document.getElementById('puertas-coche').selectedIndex == 0))
		volverInicio();
	else {
		// inicializamos la instancia
		instancia = false;
	    // comprobamos si existe el objeto XMLHttpRequest (Mozilla/Netscape/Safari/Opera)
	    if (window.XMLHttpRequest) {
	    	try {
	    		instancia = new XMLHttpRequest();
	        } catch(e) {
				instancia = false;
	        }
	    // si no, utilizamos la versin ActiveX de Windows IE5+
	    } else if(window.ActiveXObject) {
	       	try {
	        	instancia = new ActiveXObject("Msxml2.XMLHTTP");
	      	} catch(e) {
	        	try {
	          		instancia = new ActiveXObject("Microsoft.XMLHTTP");
	        	} catch(e) {
	          		instancia = false;
	        	}
			}
	    }
	    // comprobamos si hemos podido crear la instancia del objeto XMLHttpRequest
		if (instancia) {
			// asociamos a la funcin correspondiente el manejador de eventos que indica un cambio en el estado de la peticin
			instancia.onreadystatechange = function() {
				procesaCambios(instancia,datos);
			}
			// abrimos la conexin, especificando el mtodo usado, la URL de donde recoger los datos y si ha de ser asncrona o no
			instancia.open("POST", url, true);
			// especificamos la codificacin de los datos enviados
			instancia.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			// enviamos la peticin
			instancia.send(construirParametros(datos));
			if (datos != 'carrusel') {
				// actualizamos la variable que controla si se ha terminado la carga de datos
				cargado = false;
				// comprobamos si hay que mostrar o no el aviso
				if (!cargado) {
					CARGANDO.mostrar();
					if (navigator.appName.indexOf('Internet Explorer') != -1) {
						var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
						for (m=0;m<selects.length;m++) {
							if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
								selects[m].style.visibility = 'hidden';
						}
					}
				} else {
					if (!cargandoExtras) {
						CARGANDO.ocultar();
						if (navigator.appName.indexOf('Internet Explorer') != -1) {
							var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
							for (m=0;m<selects.length;m++) {
								if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
									selects[m].style.visibility = 'visible';
							}
						}
					}
				}
			}
		} else {
			// accin a realizar si no hemos podido crear la instancia del objeto XMLHttpRequest
			alert('Se ha producido un error al intentar crear el objeto');
		}
	}
}


function construirParametros(cual) {
	if (cual == 'coche') {
		var cadena = "marca=" + document.getElementById('marca-coche').value;
		cadena += "&modelo=" + document.getElementById('modelo-coche').value;
		cadena += "&combustible=" + document.getElementById('combustible-coche').value;
		cadena += "&carroceria=" + document.getElementById('carroceria-coche').value;
		cadena += "&puertas=" + document.getElementById('puertas-coche').value;
	} else if (cual == 'extras') {
		var cadena = 'idversion=' + document.getElementById('version-caracteristicas').value;
	} else if (cual == 'caracteristicas') {
		var cadena = "marca=" + document.getElementById('marca-caracteristicas').value;
		cadena += "&modelo=" + document.getElementById('modelo-caracteristicas').value;
		cadena += "&combustible=" + document.getElementById('combustible-caracteristicas').value;
		cadena += "&version=" + document.getElementById('version-caracteristicas').value;
	} else {
		cadena = cual;
	}
	return cadena;
}


/*var marcaModelo = false;*/

function procesaCambios(instancia,cual) {
	// comprobamos que la peticin se ha completado
	if (instancia.readyState == 4) {
		// comprobamos que la peticin ha finalizado con xito (200)
		// y que ha habido cambios en los datos recibidos (304) (slo si la peticin se ha hecho por GET)
		if ((instancia.status == 200) || (instancia.status == 304)) {
			// accedemos a los hijos del nodo padre
			// para ello los datos devueltos debe tener el "Content-Type" como "text/xml"
			if (cual == 'coche') {
				var nodos = instancia.responseXML.documentElement.childNodes;
				// recorremos todos los hijos...
				for (i=0;i<nodos.length;i++) {
					// ... comprobando que no sean nodos de texto
					if (nodos[i].nodeType != 3) {
						switch (nodos[i].nodeName) {
							case 'marcas'		: 	actualizaDesplegable(document.getElementById('marca-coche'),nodos[i]);
													if (document.getElementById('marca-coche').options.length == 2)
														document.getElementById('marca-coche').selectedIndex = 1;
													break;
							case 'modelos'		: 	actualizaDesplegable(document.getElementById('modelo-coche'),nodos[i]);
													if (document.getElementById('modelo-coche').options.length == 2)
														document.getElementById('modelo-coche').selectedIndex = 1;
													break;
							case 'combustibles'	: 	actualizaDesplegable(document.getElementById('combustible-coche'),nodos[i]);
													if (document.getElementById('combustible-coche').options.length == 2)
														document.getElementById('combustible-coche').selectedIndex = 1;
													break;
							case 'carrocerias'	: 	actualizaDesplegable(document.getElementById('carroceria-coche'),nodos[i]);
													if (document.getElementById('carroceria-coche').options.length == 2)
														document.getElementById('carroceria-coche').selectedIndex = 1;
													/*if (marcaModelo && (document.getElementById('carroceria-coche').options.length > 1)) {
														document.getElementById('carroceria-coche').selectedIndex = 1;
													}*/
													break;
							case 'puertas'		: 	actualizaDesplegable(document.getElementById('puertas-coche'),nodos[i]);
													if (document.getElementById('puertas-coche').options.length == 2)
														document.getElementById('puertas-coche').selectedIndex = 1;
													break;
						}
					}
				}
			} else if (cual == 'caracteristicas') {
				var nodos = instancia.responseXML.documentElement.childNodes;
				switch(instancia.responseXML.documentElement.nodeName) {
					case 'modelos'		:	actualizaDesplegable(document.getElementById('modelo-caracteristicas'),instancia.responseXML.documentElement);
											document.getElementById('modelo-caracteristicas').focus();
											break;
					case 'combustibles'	:	actualizaDesplegable(document.getElementById('combustible-caracteristicas'),instancia.responseXML.documentElement);
											document.getElementById('combustible-caracteristicas').focus();
											break;
					case 'versiones'	:	actualizaDesplegable(document.getElementById('version-caracteristicas'),instancia.responseXML.documentElement);
											document.getElementById('version-caracteristicas').focus();
											break;
					/*case 'equipamientos':	procesaEquipamiento();
											break;*/
				}
			} else if (cual == 'extras') {
				document.getElementById('contenedor-extras').getElementsByTagName('div')[0].innerHTML = instancia.responseText;
				var campos = document.getElementById('contenidos-extras').getElementsByTagName('div')[0].getElementsByTagName('input');
				for (i=0;i<campos.length;i++) {
					campos[i].onclick = function() {
						EXTRAS.relacionar(this);
					}
				}
				var posicion = (navigator.appName.indexOf('Opera') != -1)?0:parseInt(document.documentElement.scrollTop);
				document.getElementById('extras').style.top = ((parseInt(document.documentElement.clientHeight) - 60)/2) + posicion + 'px';
				document.getElementById('contenedor-extras').style.width = document.documentElement.scrollWidth + 'px';
				document.getElementById('contenedor-extras').style.height = document.documentElement.scrollHeight + 'px';
				document.getElementById('contenedor-extras').className = 'activo';
				cargandoExtras = false;
			} else if (cual == 'carrusel') {
				procesaCarrusel(instancia);
			}
			cargado = true;
		} else {
			// accin a realizar si se ha producido algn error en la peticin
			//alert("Se produjo un error al intentar recuperar los datos XML:\n" + instancia.status);
		}
	}
	// comprobamos si hay que mostrar o no el aviso
	if (!cargado) {
		CARGANDO.mostrar();
		if (navigator.appName.indexOf('Internet Explorer') != -1) {
			var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
			if ((cual == 'extras') || (document.getElementById('contenedor-extras').className == 'activo') || (document.getElementById('contenedor-datos').className == 'activo')) {
				for (m=0;m<selects.length;m++) {
					if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
						selects[m].style.visibility = 'visible';
				}
			} else {
				for (m=0;m<selects.length;m++) {
					if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
						selects[m].style.visibility = 'hidden';
				}
			}
		}
	} else {
		if (!cargandoExtras) {
			CARGANDO.ocultar();
			if (navigator.appName.indexOf('Internet Explorer') != -1) {
				var selects = document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('select');
				if ((cual == 'extras') || (document.getElementById('contenedor-extras').className == 'activo') || (document.getElementById('contenedor-datos').className == 'activo')) {
					for (m=0;m<selects.length;m++) {
						if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
							selects[m].style.visibility = 'hidden';
					}
				} else {
					for (m=0;m<selects.length;m++) {
						if (selects[m].parentNode.parentNode.id != 'contenidos-datos')
							selects[m].style.visibility = 'visible';
					}
				}
			}
		}
	}
}


/*function procesaEquipamiento() {
	var indiceTabulacion = 23;
	borraComplementos();
	var nodos = instancia.responseXML.documentElement.childNodes;
	for (i=0;i<nodos.length;i++) {
		if (nodos[i].nodeType != 3) {
			var texto = '';
			var etiqueta = document.createElement('label');
			var atributo = document.createAttribute("for");
			atributo.value = nodos[i].attributes[0].nodeValue;
			etiqueta.setAttributeNode(atributo);
			var campo = document.createElement('input');
			campo.id = nodos[i].attributes[0].nodeValue;
			campo.name = nodos[i].attributes[0].nodeValue;
			campo.type = 'checkbox';
			campo.className = 'check';
			atributo = document.createAttribute("tabindex");
			atributo.value = indiceTabulacion;
			campo.setAttributeNode(atributo);
			var span = document.createElement('span');
			span.className = 'precio';
			for (j=0;j<nodos[i].childNodes.length;j++) {
				if (nodos[i].childNodes[j].nodeType != 3) {
					if (nodos[i].childNodes[j].nodeName.indexOf('nombre') != -1)
						texto = document.createTextNode(nodos[i].childNodes[j].firstChild.nodeValue);
					else if (nodos[i].childNodes[j].nodeName.indexOf('precio') != -1)
						span.innerHTML = '[' + nodos[i].childNodes[j].firstChild.nodeValue + ' &euro;]';
				}
			}
			etiqueta.appendChild(campo);
			etiqueta.appendChild(texto);
			etiqueta.appendChild(span);
			document.getElementById('equipamiento-opcional').appendChild(etiqueta);
			indiceTabulacion++;
		}
	}
	document.getElementById('equipamiento-opcional').style.display = 'block';
	document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('a')[0].style.display = 'inline';
}


function borraComplementos() {
	document.getElementById('equipamiento-opcional').style.display = 'none';
	document.getElementById('formulario-buscar-caracteristicas').getElementsByTagName('a')[0].style.display = 'none';
	var etiquetas = document.getElementById('equipamiento-opcional').getElementsByTagName('label');
	var cuantos = etiquetas.length;
	for (i=0;i<cuantos;i++) {
		document.getElementById('equipamiento-opcional').removeChild(etiquetas[0]);
	}
}*/

// variable que indica el primer coche mostrado actualmente de todos los disponibles
var indice = 1;

function procesaCarrusel(instancia) {
	// inicializamos las variables
	var nombre;
	var posicionLista = 0;
	var posicionDatos = 0;
	var nodos = instancia.responseXML.documentElement.childNodes;
	for (i=0;i<nodos.length;i++) {
		if (nodos[i].nodeType != 3) {
			// recorremos los atributos
			document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('a')[0].setAttribute('title',nodos[i].attributes[2].nodeValue);
			document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('a')[0].innerHTML = nodos[i].attributes[2].nodeValue;
			document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('a')[1].setAttribute('title',nodos[i].attributes[2].nodeValue);
			document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('img')[0].setAttribute('alt',nodos[i].attributes[2].nodeValue);
			// recorremos los nietos...
			for (j=0;j<nodos[i].childNodes.length;j++) {
				// ... comprobando que no sean nodos de texto
				if (nodos[i].childNodes[j].nodeType != 3) {
					if (posicionDatos == 0)
						document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('img')[0].src = nodos[i].childNodes[j].firstChild.nodeValue;
					else if (posicionDatos == 9)
						document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('dd')[1].getElementsByTagName('strong')[0].innerHTML = nodos[i].childNodes[j].firstChild.nodeValue + ' &euro;';
					else if (posicionDatos == 12)
						document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('dd')[2].getElementsByTagName('strong')[0].innerHTML = nodos[i].childNodes[j].firstChild.nodeValue + ' &euro;/mes';
					else if (posicionDatos == 14) {
						document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('a')[0].href = nodos[i].childNodes[j].firstChild.nodeValue;
						document.getElementById('carrusel').getElementsByTagName('li')[posicionLista].getElementsByTagName('a')[1].href = nodos[i].childNodes[j].firstChild.nodeValue;
					}
					posicionDatos++;
				}
			}
			posicionDatos = 0;
			posicionLista++;
		}
	}
}