/****************************************************************
/ Implentacion: 
/ Revision: 301106
/ Descripcion: Manejo del AJAX
'***************************************************************/
function getHTTPObject() {
	var xmlhttp;      
  
  /*@cc_on
  @if (@_jscript_version >= 5)
	try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	  try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
		xmlhttp = false;
	  }
	}
  @else
  xmlhttp = false;
  @end @*/
  
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {  
		try {
		  xmlhttp = new XMLHttpRequest();
		} catch (e) {
		  xmlhttp = false;
		}
	}
	return xmlhttp;
}
    
//--
var http = getHTTPObject(); 


//************ SECCION PRODCUTOS **************************************************
//*********************************************************************************
function ampliaProducto(pagina,id,tipo,galeria){
	if (tipo == 1){
//		alert(tipo);
		var ref = document.getElementById("pk_info"+id).value;
		if (ref != ""){
			document.getElementById("formularioAmplia" + id).action = document.getElementById("formularioAmplia" + id).action + "&ref="+ref;
		}
	}
	document.getElementById("formularioAmplia" + id).numPagina.value=pagina
	document.getElementById("formularioAmplia" + id).numGaleria.value=galeria
	document.getElementById("formularioAmplia" + id).submit();
}


/****************************************************************
/ Nombre: Paginacion
/ Implentacion: 
/ Revision: 301106
/ Descripcion: funcion para realizar la paginacion de los productos
'***************************************************************/
function paginacion(pagina){
	document.getElementById("formularioPaginacion").numPagina.value=pagina
	document.getElementById("formularioPaginacion").submit();
}

function volverCatalogo(pagina){
	document.getElementById("formularioVolver").numPagina.value=pagina
	document.getElementById("formularioVolver").submit();
}


/****************************************************************
/ Nombre: cambiaFondo
/ Implentacion: JBernalte
/ Revision: 301106
/ Descripcion: Cambia el fondo del obj como ID
'***************************************************************/
function cambiaFondo(pagina, obj){
		var fondo;
		fondo="";
		switch(pagina){
			
			case 1: 
				fondo= "url(images/top-background-grupo.jpg)";
				break;
			default:
				fondo= "url(images/top-background.jpg)";
		}
		document.getElementById(obj).style.backgroundImage =fondo;
	}


/****************************************************************
/ Nombre: cambiaClaseFamilia
/ Implentacion
/ Revision: 301106
/ Descripcion: Cambia ela clase del obj pasado como ID
'***************************************************************/
function cambiaClaseFamilia(obj){
	
	switch(obj){
			
			case 1: 
				clase= "x";
				break;
			default:
				clase= "x";
		}
	
	document.getElementById(obj).className=clase;
}


function quitaClaseFamilia(familia,marcado){
	
	if (familia==1 && marcado==0){
		clase="x";
	}
	
	document.getElementById("familia" + familia).className=clase;
}

//****************** SECCION CONTACTO ******************************************************************************************************************************/

/****************************************************************
/ Nombre: validarEmail
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida el formato del email
'***************************************************************/
function validarEmail(valor){
//funcion para validar el formato del email
	return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor));
	
}

/****************************************************************
/ Nombre: validar
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida los campos del formulario
'***************************************************************/
function validar(tipo){
//Funcion para la validar los datos enviados desde el formulario de contacto
	var texto;
	texto = "";

	var cadenaEnvio;
	cadenaEnvio = "";
	
	//Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
	
	if ( document.getElementById("formularioContacto").nombre.value == "" ) {
		texto+=" * Debe indicar su nombre.\n";
	}else{
		cadenaEnvio="nombre=" + document.getElementById("formularioContacto").nombre.value;
	}
	
	if ( document.getElementById("formularioContacto").email.value == "" ) {
		texto+=" * Debe indicar su e-mail.\n";
	}
	
	if(document.getElementById("formularioContacto").email.value!=""){
		if(!validarEmail(document.getElementById("formularioContacto").email.value)){
				texto+=" * Formato de E-mail incorrecto.\n";
		}else{
			cadenaEnvio+="&email=" + document.getElementById("formularioContacto").email.value;
		}
	}
	if (( document.getElementById("formularioContacto").telefono.value != "" ) && ( isNaN(document.getElementById("formularioContacto").telefono.value)) ){
		document.getElementById("formularioContacto").telefono.value = ""
		document.getElementById("formularioContacto").telefono.focus();
		texto+=" * El número de teléfono debe ser numérico.\n";
	}
	if (( document.getElementById("formularioContacto").movil.value != "" ) && ( isNaN(document.getElementById("formularioContacto").movil.value)) ){
		document.getElementById("formularioContacto").movil.value = ""
		document.getElementById("formularioContacto").movil.focus();
		texto+=" * El número de móvil debe ser numérico.\n";
	}
	if ( isNaN(document.getElementById("formularioContacto").cpostal.value) ){
		document.getElementById("formularioContacto").cpostal.value = ""
		document.getElementById("formularioContacto").cpostal.focus();
		texto+=" * El código postal debe ser numérico.\n";
	}

	if ( document.getElementById("formularioContacto").nick.value == "" ) {
		texto+=" * Debe indicar su nick.\n";
	}else if ( document.getElementById("formularioContacto").nick.value.length < 4 ) {
				texto+=" * El nick debe ser de al menos 4 carácteres.\n";
	}
	if ( document.getElementById("formularioContacto").pass.value == "" ) {
		texto+=" * Debe indicar su clave de acceso.\n";
	}else if ( document.getElementById("formularioContacto").pass.value.length < 4 ) {
				texto+=" * La clave debe ser de al menos 4 carácteres.\n";
	}
	
	//para controlar que las fechas sean correctas
	var dia, mes, anyo;
	
	dia = document.getElementById('formularioContacto').dia.value;
	mes = document.getElementById('formularioContacto').mes.value;
	anyo = document.getElementById('formularioContacto').anyo.value;
	
	if (!compruebaFecha(dia, mes, anyo)){
		texto+=" * La fecha intorducida es incorrecta.\n";
	}

//	if ( document.getElementById("formularioContacto").comentarios.value == "" ){
//		texto+=" * Debe incluir el motivo de su consulta.<br>";
//	}else{
		cadenaEnvio+="&=" + document.getElementById("formularioContacto").preferencias.value;
//	}	
	
	
	if ( texto != "" ){
			alert(texto);
//	/	document.getElementById("mensajeError").innerHTML=texto;
//		document.getElementById("capaError").style.display='block';
		
	}else{
		//alert(cadenaEnvio);
			document.getElementById("formularioContacto").op.value = 1;
			document.formularioContacto.submit();
/*		document.getElementById("mensaje-respuesta").innerHTML="";
		document.getElementById("mensajeError").innerHTML="";
		document.getElementById("capaError").style.display='none';
		http.open("POST", "registro/registro.asp?" + extension, true);
    	 http.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		http.send(cadenaEnvio);
		http.onreadystatechange = handleHttpResponseContacto;*/
	}
	
}

/****************************************************************
/ Nombre: validar
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida los campos del formulario
'***************************************************************/
function validarIns(tipo){
//Funcion para la validar los datos enviados desde el formulario de contacto
	var texto;
	texto = "";

	var cadenaEnvio;
	cadenaEnvio = "";
	
	//Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
	
/*	if ( document.getElementById("formRegistro").nombre.value == "" ) {
		texto+=" * Debe indicar su nombre.\n";
	}else{
		cadenaEnvio="nombre=" + document.getElementById("formRegistro").nombre.value;
	}*/
	
	if ( document.getElementById("formRegistro").email.value == "" ) {
		texto+=" * Debe indicar su e-mail.\n";
	}
	
	if(document.getElementById("formRegistro").email.value!=""){
		if(!validarEmail(document.getElementById("formRegistro").email.value)){
				texto+=" * Formato de E-mail incorrecto.\n";
		}else{
			cadenaEnvio+="&email=" + document.getElementById("formRegistro").email.value;
		}
	}
	if (( document.getElementById("formRegistro").telefono.value != "" ) && ( isNaN(document.getElementById("formRegistro").telefono.value)) ){
		document.getElementById("formRegistro").telefono.value = ""
		document.getElementById("formRegistro").telefono.focus();
		texto+=" * El número de teléfono debe ser numérico.\n";
	}
	if (( document.getElementById("formRegistro").movil.value != "" ) && ( isNaN(document.getElementById("formRegistro").movil.value)) ){
		document.getElementById("formRegistro").movil.value = ""
		document.getElementById("formRegistro").movil.focus();
		texto+=" * El número de móvil debe ser numérico.\n";
	}
	if ( isNaN(document.getElementById("formRegistro").cpostal.value) ){
		document.getElementById("formRegistro").cpostal.value = ""
		document.getElementById("formRegistro").cpostal.focus();
		texto+=" * El código postal debe ser numérico.\n";
	}

	if ( document.getElementById("formRegistro").nick.value == "" ) {
		texto+=" * Debe indicar su nick.\n";
	}else if ( document.getElementById("formRegistro").nick.value.length < 4 ) {
				texto+=" * El nick debe ser de al menos 4 carácteres.\n";
	}
	if ( document.getElementById("formRegistro").dia.value == "0" ) {
		texto+=" * Debe seleccionar el día de su fecha de nacimiento.\n";
	}
	if ( document.getElementById("formRegistro").mes.value == "0" ) {
		texto+=" * Debe seleccionar el mes de su fecha de nacimiento.\n";
	}
	if ( document.getElementById("formRegistro").anyo.value == "0" ) {
		texto+=" * Debe seleccionar el año de su fecha de nacimiento.\n";
	}
	
	//para controlar que las fechas sean correctas
	var dia, mes, anyo;
	
	dia = document.getElementById('formRegistro').dia.value;
	mes = document.getElementById('formRegistro').mes.value;
	anyo = document.getElementById('formRegistro').anyo.value;
	
	if (!compruebaFecha(dia, mes, anyo)){
		texto+=" * La fecha intorducida es incorrecta.\n";
	}

		cadenaEnvio+="&=" + document.getElementById("formRegistro").preferencias.value;

	if ( document.getElementById("formRegistro").condiciones.checked == false ) {
		texto+=" * Debe aceptar las condiciones legales para registrarse.\n";
	}
	
	var email = document.getElementById("formRegistro").email.value;
	var nick = document.getElementById("formRegistro").nick.value;
	
		if ( texto != "" ){
				alert(texto);
		}else{
			http.open("GET", "registro/compruebaEmail.asp?email=" + email +"&nick=" + nick, true);
			http.onreadystatechange = handleHttpResponseComprobar;
			http.send(null);
		}
	
	
}

function handleHttpResponseComprobar() {
	if (http.readyState == 4) {    	
		//Aqui va el nombre de la capa donde queramos cargar el contenido
			var t =  http.responseText;	
		if ( t != "" ){
				alert(t);
		}else{
				document.getElementById("formRegistro").op.value = 0;
				document.formRegistro.submit();
		}
	}    
}


/****************************************************************
/ Nombre: compruebaFecha()
/ Implentacion: Fperez

/ Revision:
/ Descripcion: Comprueba que las fechas sean correctas
'***************************************************************/
function compruebaFecha(dia, mes, anyo){
	var error;
	if ((dia > 30) && ((mes == 2) || (mes == 4) || (mes == 6) || (mes == 9) || (mes == 11))){
		return false;
	}
	if ((dia > 29) && (mes == 2)){
		return false;
	}
	var resto = parseInt(anyo)%4;
	if (resto != 0){
		if ((dia > 28) && (mes == 2)){
			return false;
		}
	}
	
	return true;
}


/****************************************************************
/ Nombre: cerrarAviso
/ Implentacion: 

/ Revision:
/ Descripcion: Cierra la capa del aviso del formulario
'***************************************************************/
function cerrarAviso(){
	document.getElementById("mensajeError").innerHTML="";
	document.getElementById("capaError").style.display='none';
}

function handleHttpResponseContacto() {
	if (http.readyState == 4) {    	
		//Aqui va el nombre de la capa donde queramos cargar el contenido
			alert(http.responseText);
//		document.getElementById("mensaje-respuesta").innerHTML = http.responseText;	
		document.getElementById("formularioContacto").reset();
	}    
}


//*********************************************************************************
//*********************************************************************************
function mostrarReferencia(id){
		if (document.getElementById("pk_info"+id).value == ""){
			document.getElementById("referencia").innerHTML = "";
			document.getElementById("referencia").style.display = "block";	
			return false;
		}
		var idReferencia = document.getElementById("pk_info"+id).value;
		document.getElementById("enlace_"+id).href = document.getElementById("enlace_"+id).href + "&ref=" + idReferencia
		document.getElementById("enlace_imagen_"+id).href = document.getElementById("enlace_imagen_"+id).href + "&ref=" + idReferencia
		document.getElementById("enlace_titulo_"+id).href = document.getElementById("enlace_titulo_"+id).href + "&ref=" + idReferencia
		http.open("GET", "./includes/getReferencia.asp?id=" + idReferencia, true);
		http.onreadystatechange = handleHttpResponseReferencia;
		http.send(null);
	
}

function handleHttpResponseReferencia() {
	if (http.readyState == 4) {    	
		//Aqui va el nombre de la capa donde queramos cargar el contenido
		document.getElementById("referencia").innerHTML = "-&nbsp;" + http.responseText + "<br><br>";	
		document.getElementById("referencia").style.display = "block";	
	}    
}

/****************************************************************
/ Nombre: openWindow
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Abre un popup
'***************************************************************/
	function openWindow(theURL,winName,features){
 		window.open(theURL,winName,features);
		return
	}


/****************************************************************
/ Nombre: muestraTema
/ Implentacion:
/ Revision:
/ Descripcion: Muestra los temas
'***************************************************************/
function muestraTema(id,numero) {
	for (i=1;i<=numero;i++){
		if (id != i){
			if (document.getElementById("filaContenidoTema"+ i).style.display == "block"){
				document.getElementById("filaContenidoTema"+ i).style.display = "none";
			}
				document.getElementById("enlaceTema"+ i).className = "desmarcado";
		}
	}
	if (document.getElementById("filaContenidoTema"+ id).style.display == "block") { 
		document.getElementById("filaContenidoTema"+ id).style.display = "none"; }
	else { 
		document.getElementById("filaContenidoTema"+ id).style.display = "block";
		document.getElementById("enlaceTema"+ id).className = "marcado";
		}
}


/****************************************************************
/ Nombre: capaPosition
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Posiciona una capa en el centro de la pantalla +- los pixeles deseados
'***************************************************************/
function capaPosition(layer, position){
		element = document.getElementById(layer);
		screenCenterX = document.body.clientWidth / 2;
		element.style.left = screenCenterX + position;
		element.style.display = 'inline';
	}


/****************************************************************************************
/ Nombre: ampliaImagen
/ Implentacion: PACO
/ Revision:
/ Descripcion: Muestra el PopUp de ampliacion de las imagenes y lo redimensiona
'***************************************************************************************/
function ampliaImagen(url){
	document.getElementById('imagenAmpliada').src = "images/" + url;
	}

function redimensionarImagen(img){
	var anchoImagen,altoImagen,anchoPantalla,altoPantalla;
	img1 = new Image(); 
	img1.src = img.src;
	anchoImagen = img1.width;
	altoImagen = img1.height;
//	anchoPantalla = window.screen.width;
	anchoPantalla = 930
	altoPantalla = window.screen.height - 240;
	posicionx = (anchoPantalla/2) - (anchoImagen/2);
	posiciony = (altoPantalla/2) - (altoImagen/2);
	
	// coloca la capa de la imagen y la redimensiona
	document.getElementById('capaImagenAmpliada').style.top = posiciony + 'px';
	document.getElementById('capaImagenAmpliada').style.left = posicionx + 'px';
	document.getElementById('capaImagenAmpliada').style.width = anchoImagen + 'px';
	document.getElementById('capaImagenAmpliada').style.height = altoImagen + 'px';
	// coloca un poco más arriba la capa del enlace para cerrar
	posicionCerrar = posiciony - 19;
	document.getElementById('cerrarImagenAmpliada').style.top = posicionCerrar + 'px';
	document.getElementById('cerrarImagenAmpliada').style.left = posicionx + 'px';

	document.getElementById('capaImagenAmpliada').style.display = 'block';
	document.getElementById('cerrarImagenAmpliada').style.display = 'block';
	// en caso del formulario de contacto, ocultamos el combo
	document.getElementById('pais').style.visibility = 'hidden';
}

function cerrarImagenAmpliada(){
	document.getElementById('imagenAmpliada').src = "";
	document.getElementById('capaImagenAmpliada').style.display = 'none';
	document.getElementById('cerrarImagenAmpliada').style.display = 'none';
	document.getElementById('pais').style.visibility = 'visible';
}
//***************************************************************************
//***************************************************************************



/****************************************************************************************
/ Nombre: autentifica
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) desautentifica (otra cosa) autentifica
/ Revision:
/ Descripcion: Login de usuario en la zona privada
'***************************************************************************************/
function autentifica(type){
	var strEnvio = '';
	
	if(type != 'off'){
		
		var campos = new Array();
		var mensajes = new Array();
		
		
		/* DENINE CAMPO A VALIDAR MENSAJE*/
		campos[0] = 'user'; mensajes[0] = 'Indique su usuario';
		campos[1] = 'password'; mensajes[1] = 'Indique su contraseña';
	
		
		valid = false; 
		i=0;
		
		for(campo in campos){
			valor = document.formLogin[campo].value;
			if (   (valor == '') || (valor == mensajes[i])  ) {
				document.formLogin[campo].value = mensajes[i];
				valid = false;
			}else{
				strEnvio += "" + campos[i] + "=" + document.formLogin[campo].value + "&";
				valid = true;
			}
			i++;
		}
		strEnvio += "login=on"
	}else{
		valid=true;
		strEnvio += "login=off"
		
	}
	
	if(valid){
//		window.location.href = "includes/loginEngine.asp?" + strEnvio;
		url = "includes/loginEngine.asp?" + strEnvio;
		http.open("GET", url , true);
		http.onreadystatechange = handleHttpResponseReload;
		http.send(null);		
	}else{
		return false;	
	}	
}


/****************************************************************************************
/ Nombre: autentifica
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) desautentifica (otra cosa) autentifica
/ Revision:
/ Descripcion: Login de usuario en la zona privada
'***************************************************************************************/
function autentifica2(type){
	var strEnvio = '';
	
	if(type != 'off'){
		
		var campos = new Array();
		var mensajes = new Array();
		
		
		/* DENINE CAMPO A VALIDAR MENSAJE*/
		campos[0] = 'user'; mensajes[0] = 'Indique su usuario';
		campos[1] = 'password'; mensajes[1] = 'Indique su contraseña';
	
		
		valid = false; 
		i=0;
		
		for(campo in campos){
			valor = document.formLogin2[campo].value;
			if (   (valor == '') || (valor == mensajes[i])  ) {
				document.formLogin2[campo].value = mensajes[i];
				valid = false;
			}else{
				strEnvio += "" + campos[i] + "=" + document.formLogin2[campo].value + "&";
				valid = true;
			}
			i++;
		}
		strEnvio += "login=on"
	}else{
		valid=true;
		strEnvio += "login=off"
		
	}
	
	if(valid){
//		window.location.href = "includes/loginEngine.asp?" + strEnvio;
		url = "includes/loginEngine.asp?" + strEnvio;
		http.open("GET", url , true);
		http.onreadystatechange = handleHttpResponseReload;
		http.send(null);		
	}else{
		return false;	
	}	
}



/****************************************************************************************
/ Nombre: edit, handleHttpResponseEdit
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) previsualiza (otra cosa) edita
/ Revision:
/ Descripcion: Cambia a modo edicion en la zona privada
'***************************************************************************************/
function edit(type){
	var strEnvio = '';
	

		strEnvio += "edicionMode=" + type;


		url = "includes/loginEngine.asp?" + strEnvio;
		http.open("GET", url , true);
		http.onreadystatechange = handleHttpResponseReload;
		http.send(null);		
}


/****************************************************************************************
/ Nombre: edit, handleHttpResponseReload
/ Implentacion: JBERNALTE
/ Revision:13/06/2007
/ Descripcion: Recarga la pagina despues de ejecutar AJAX
'***************************************************************************************/
function handleHttpResponseReload() {
	if (http.readyState == 4) {
		//window.location.reload();
		var respuesta=http.responseText;
		if (respuesta=="no"){
			document.getElementById("mensaje-alerta").style.display='block';
		}
		if (respuesta=="si"){
			var pagina=document.getElementById("login").pagina.value;
			var subpagina=document.getElementById("login").subpagina.value;
			var c=document.getElementById("login").c.value;
			document.location="index.asp?pagina=" + pagina + "&subpagina=" + subpagina + "&c=" + c;
		}
	}    
}

/****************************************************************************************
/ Nombre: edit, handleHttpResponseEdit
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) previsualiza (otra cosa) edita
/ Revision:
/ Descripcion: Cambia a modo edicion en la zona privada
'***************************************************************************************/
function edit2(type){
	var strEnvio = '';
	

		strEnvio += "edicionMode=" + type;


		url = "includes/loginEngine.asp?" + strEnvio;
		http.open("GET", url , true);
		http.onreadystatechange = handleHttpResponseReload2;
		http.send(null);		
}


/****************************************************************************************
/ Nombre: edit, handleHttpResponseReload
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Recarga la pagina despues de ejecutar AJAX
'***************************************************************************************/
function handleHttpResponseReload2() {
	if (http.readyState == 4) {
		window.location.href= "index.asp?pagina=ficha-de-usuario";
	}    
}



/****************************************************************************************
/ Nombre: changeAccountData, handleHttpResponseAccount
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Actualiza los datos del usuario
'***************************************************************************************/
function changeAccount(type){
	
	alert("GUAU! ( o )( o )");
	
	
	strEnvio='';
	
	//FALTA MONTAR EL ENVIO
	
	if(type == 'new'){
		strEnvio += "account=new"
	}else{
		strEnvio += "account=update"
	}
	
	url = "includes/AccountEngine.asp?" + strEnvio;
	http.open("GET", url , true);
	http.onreadystatechange = handleHttpResponseAccount;
	http.send(null);
}


function handleHttpResponseAccount() {
	if (http.readyState == 4) {    	
		document.getElementById("resultado").innerHTML = http.responseText;
	}    
}

/****************************************************************************************
/ Nombre: changePicture
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Cambia una imagen
'***************************************************************************************/
function changePicture(id, picture){
		
		document.getElementById(id).src = picture;
}

function muestraCapa(){
	document.getElementById('recordarPassword').style.display = 'block';
}
/****************************************************************************************
/ Nombre: enviarEmail
/ Implentacion: Fperez
/ Revision:
/ Descripcion: Envia el recordatorio de la contraseña por email
'***************************************************************************************/
function enviarEmail(email){
//	alert(document.formrecuerdo.email.value);
		cadenaEnvio = 'email='+document.formrecuerdo.email.value;
		http.open("GET", "actualizer/formcorreosMultiple/envioEmail.asp?" + cadenaEnvio, true);
		http.onreadystatechange = handleHttpResponseEmail;
		http.send(null);
}
function handleHttpResponseEmail() {
	if (http.readyState == 4) {    	
		//Aqui va el nombre de la capa donde queramos cargar el contenido
		document.getElementById("recordarPassword").style.display = 'none';	
		document.getElementById("respuestaRecuerdo").style.display = 'block';	
		document.getElementById("respuestaRecuerdo").innerHTML = http.responseText;	
		document.getElementById("formrecuerdo").reset();
	}    
}


/***** SCRIPT PARA MOTORPOINT *********/

/** COCHES NUEVOS **/
function imprimeRivales(pk_cochesnuevos){
	//alert();
	window.open("includes/rivales_imprimir.asp?pk_cochesnuevos=" + pk_cochesnuevos, 'imprimir');
}

function abreFoto(pfoto,ancho,alto){

	var ventana=window.open("includes/coches_nuevos_ampliacion.asp?foto="+pfoto,"fotoCoche","width=" + ancho + ", height=" + alto);
}

function abreFoto2(pfoto,ancho,alto){

	var ventana=window.open("includes/coches_nuevos_ampliacion.asp?foto="+pfoto,"fotoCoche","width=" + ancho + ", height=" + alto);
}

function Suma(tipo)
	{		
		if (1*document.f.PRECIO.value && 1*document.f.ENTRADA.value && 1*document.f.INTERES.value)
		{
			var Vrble1=1*document.f.PRECIO.value;
			var Vrble2=1*document.f.ENTRADA.value;
  			var i = 1*document.f.PLAZO.selectedIndex;
  			var Vrble3 = 1*document.f.PLAZO.options[i].value;
			var Vrble4=1*document.f.INTERES.value;
		}
		else
		{
			var Vrble1=document.f.PRECIO.value;
			var Vrble2=document.f.ENTRADA.value;
  			var i = document.f.PLAZO.selectedIndex;
  			var Vrble3 = document.f.PLAZO.options[i].value;
			var Vrble4=document.f.INTERES.value;
		}
		cadena1=Vrble1-Vrble2;
		cadena2=Vrble4/100;
		cadena3=cadena2/12;
        var cadena4=1;
        for (var j = 0; j < Vrble3; j++)
        {
        cadena4 = cadena4 * (1 + cadena3);
cuotasapagar=(cadena1*cadena4*cadena3)/(cadena4-1);}
if (tipo==1){
   cambio = parseFloat(cuotasapagar * 166.386);
   numerotostring = (cambio * 1000).toString();
   numerotostring = (cambio * 1000) + '';
   pospunto = numerotostring.indexOf(".");
   (pospunto == -1) ? stringparteentera = numerotostring 
		     : stringparteentera = numerotostring.substring(0,pospunto);
   euros = ((Math.round(stringparteentera / 10)) / 100);
   eurostostring = euros.toString();
   eurostostring = euros + '';
   pospunto = eurostostring.indexOf(".");
   if ( pospunto == -1 )
   {
      eurosformateado = eurostostring;
   }
   else
   {
      if ( pospunto == 0 )
      {
         eurosformateado = "0," + eurostostring.substring
			   (pospunto+1,eurostostring.length);
      }
      else
      {
         eurosparteentera = eurostostring.substring(0,pospunto);
         var resto = eurosparteentera;
         var eurosformateado = "";

         while ( resto.length > 3 )
         {
            eurosformateado = "." + resto.substring
			      (resto.length-3,resto.length) + eurosformateado;
            resto = resto.substring(0,resto.length-3);
         }
         eurosformateado = resto + eurosformateado ;
      }
   }
document.f.RESULTADO.value=eurosformateado+" Ptas.";}
else{
cambio = parseFloat(cuotasapagar / 1);
   numerotostring = (cambio * 1000).toString();
   numerotostring = (cambio * 1000) + '';
   pospunto = numerotostring.indexOf(".");
   (pospunto == -1) ? stringparteentera = numerotostring 
		     : stringparteentera = numerotostring.substring(0,pospunto);
   euros = ((Math.round(stringparteentera / 10)) / 100);
   eurostostring = euros.toString();
   eurostostring = euros + '';
   pospunto = eurostostring.indexOf(".");
   if ( pospunto == -1 )
   {
      eurosformateado = eurostostring;
   }
   else
   {
      if ( pospunto == 0 )
      {
         eurosformateado = "0," + eurostostring.substring
			   (pospunto+1,eurostostring.length);
      }
      else
      {
         eurosparteentera = eurostostring.substring(0,pospunto);
         var resto = eurosparteentera;
         var eurosformateado = "";
         while ( resto.length > 3 )
         {
            eurosformateado = "." + resto.substring
			      (resto.length-3,resto.length) + eurosformateado;
            resto = resto.substring(0,resto.length-3);
         }
         eurosformateado = resto + eurosformateado + ",";
      }
   }
document.f.RESULTADO.value=eurosformateado+" euros";
}	
if (tipo==2){
document.f.PRECIO.value='';
document.f.ENTRADA.value='';
document.f.INTERES.value='';
document.f.RESULTADO.value='';}
	}


function calculos(form){
var moneda;
if(form.moneda[0].checked){moneda=" Ptas.";}
if(form.moneda[1].checked){moneda=" Euros";}

importe=form.importe.value*1;
var frecuencia;
if (form.frecuencia.value=="f0" ) {alert("Debe seleccionar la frecuencia de pago de su préstamo");}
if (form.frecuencia.value=="f1") {frecuencia=12;ajuste=1;}
if (form.frecuencia.value=="f2") {frecuencia=4;ajuste=3;}
if (form.frecuencia.value=="f3") {frecuencia=3;ajuste=4;}
if (form.frecuencia.value=="f4") {frecuencia=2;ajuste=6;}
if (form.frecuencia.value=="f5") {frecuencia=1;ajuste=12;}

interes=form.interes.value/(100*frecuencia);
plazo=form.plazo.value*1*frecuencia;

var pagomes;
pagomes=cuota(importe,interes,plazo);
form.pago.value=pagomes+moneda;

function cuota(importe,interes,plazo){
potencia=1+interes;
multiplicador=Math.pow(potencia,-plazo);
multiplicador1=importe*interes;
pagomes=multiplicador1/(1-multiplicador);
pagomes=Math.round(pagomes);
return pagomes;
}

}

function cambiaPrecio(chk){
	//alert(chk);
	//alert(document.getElementById("chkeq" + chk).value);
	
	var iCoste=eval("document.getElementById('chkeq"+chk+"').value");
	
	if (eval("document.getElementById('chkeq"+chk+"').checked")){ // le sumamos
		document.getElementById('preciototal').value=parseFloat(document.getElementById('preciototal').value) + parseFloat(iCoste)
	}
	else{ // le restamos
		document.getElementById('preciototal').value-=parseFloat(iCoste)
	}
	
	
}

function openCenteredWindow(URL, WIDTH, HEIGHT) {
	day = new Date();
	id = day.getTime();
	var width = WIDTH;
	var height = HEIGHT;
	var left = parseInt((screen.availWidth/2) - (width/2));
	var top = parseInt((screen.availHeight/2) - (height/2));
	var windowFeatures = "width=" + width + ",height=" + height + 
		",status='no',resizable='no',scrollbars='no',left=" + left + ",top=" + top + 
		",screenX=" + left + ",screenY=" + top;
	eval("page" + id + "  = window.open(URL, '" + id + "', windowFeatures);");
}


 

function handleHttpResponse() {
	if (http.readyState == 4) {    	
		capaModelos.innerHTML = http.responseText;        		 
	}    
}

function actualizaModelos() {
var url="includes/getModelos.asp?m=";   
  capaModelos.innerHTML = "Cargando...";        		 
 // alert(document.getElementById("fk_marcas").value);
  var pk_marcas = document.getElementById("fk_marcas").value;    
  
  http.open("GET", url + escape(pk_marcas), true);  
  http.onreadystatechange = handleHttpResponse;
  http.send(null);  
}

function actualizaConcesionarios() {
var url="includes/getLocalidad.asp?m=";   
  capaModelos.innerHTML = "Cargando ...";        		 
  var pk_marcas = document.getElementById("fk_marcas").value;    
  
  http.open("GET", url + escape(pk_marcas), true);  
  http.onreadystatechange = handleHttpResponse;
  http.send(null);  
}


function buscarCochesNuevos(){ 
   var aviso;
	aviso="";
	//alert(document.getElementById("buscadorCochesNuevos").fk_marcas.value);
   if (document.getElementById("buscadorCochesNuevos").co_precio_desde.value!="" && document.getElementById("buscadorCochesNuevos").co_precio_hasta.value!="")
   {
     if(parseInt(document.getElementById("buscadorCochesNuevos").co_precio_desde.value)>parseInt(document.getElementById("buscadorCochesNuevos").co_precio_hasta.value))aviso+=" - El precio hasta debe ser mayor que el precio desde.\n";   
   } 
   if (document.getElementById("buscadorCochesNuevos").co_potencia_desde.value!="" && document.getElementById("buscadorCochesNuevos").co_potencia_hasta.value!="")
   {
      if(parseInt(document.getElementById("buscadorCochesNuevos").co_potencia_desde.value)>parseInt(document.getElementById("buscadorCochesNuevos").co_potencia_hasta.value))aviso+=" - La potencia hasta debe ser mayor que la potencia desde.\n";
   } 
   if (aviso!=""){
     alert("Se han encontrado los siguientes problemas:\n\n"+aviso);
     //return false;
   }else{
      document.getElementById("buscadorCochesNuevos").submit();
      //return true;
   }   
}




/***** MOTOS NUEVAS *******/

function abreFotoM(pfoto,ancho,alto){
	var ventana=window.open("includes/motos_nuevas_ampliacion.asp?foto="+pfoto,"fotoMoto","width=" + ancho + ", height=" + alto);
	
}

function abreFotoM2(pfoto,ancho,alto){

	var ventana=window.open("includes/motos_nuevas_ampliacion.asp?foto="+pfoto,"fotoMoto","width=" + ancho + ", height=" + alto);
	
}


function SumaM(tipo){		
	if (1*document.f.PRECIO.value && 1*document.f.ENTRADA.value && 1*document.f.INTERES.value)
	{
		var Vrble1=1*document.f.PRECIO.value;
		var Vrble2=1*document.f.ENTRADA.value;
  		var i = 1*document.f.PLAZO.selectedIndex;
  		var Vrble3 = 1*document.f.PLAZO.options[i].value;
		var Vrble4=1*document.f.INTERES.value;
	}
	else
	{
		var Vrble1=document.f.PRECIO.value;
		var Vrble2=document.f.ENTRADA.value;
  		var i = document.f.PLAZO.selectedIndex;
  		var Vrble3 = document.f.PLAZO.options[i].value;
		var Vrble4=document.f.INTERES.value;
	}
		cadena1=Vrble1-Vrble2;
		cadena2=Vrble4/100;
		cadena3=cadena2/12;
        var cadena4=1;
        for (var j = 0; j < Vrble3; j++){
			cadena4 = cadena4 * (1 + cadena3);
			cuotasapagar=(cadena1*cadena4*cadena3)/(cadena4-1);}
			if (tipo==1){
				cambio = parseFloat(cuotasapagar * 166.386);
				numerotostring = (cambio * 1000).toString();
				numerotostring = (cambio * 1000) + '';
				pospunto = numerotostring.indexOf(".");
				(pospunto == -1) ? stringparteentera = numerotostring : stringparteentera = numerotostring.substring(0,pospunto);
				euros = ((Math.round(stringparteentera / 10)) / 100);
				eurostostring = euros.toString();
				eurostostring = euros + '';
				pospunto = eurostostring.indexOf(".");
				if ( pospunto == -1 )
				{
					eurosformateado = eurostostring;
				}
				else
				{
					if ( pospunto == 0 )
					{
						eurosformateado = "0," + eurostostring.substring
							(pospunto+1,eurostostring.length);
					}
					else
					{
						eurosparteentera = eurostostring.substring(0,pospunto);
						var resto = eurosparteentera;
						var eurosformateado = "";

						while ( resto.length > 3 )
						{
							eurosformateado = "." + resto.substring
								(resto.length-3,resto.length) + eurosformateado;
							resto = resto.substring(0,resto.length-3);
						}
						eurosformateado = resto + eurosformateado ;
					}
				}
				document.f.RESULTADO.value=eurosformateado+" Ptas.";}
				else{
					cambio = parseFloat(cuotasapagar / 1);
					numerotostring = (cambio * 1000).toString();
					numerotostring = (cambio * 1000) + '';
					pospunto = numerotostring.indexOf(".");
					(pospunto == -1) ? stringparteentera = numerotostring : stringparteentera = numerotostring.substring(0,pospunto);
					euros = ((Math.round(stringparteentera / 10)) / 100);
					eurostostring = euros.toString();
					eurostostring = euros + '';
					pospunto = eurostostring.indexOf(".");
				if ( pospunto == -1 )
				{
					eurosformateado = eurostostring;
				}
				else
				{
					if ( pospunto == 0 )
					{
						eurosformateado = "0," + eurostostring.substring
							(pospunto+1,eurostostring.length);
					}
					else
					{
						eurosparteentera = eurostostring.substring(0,pospunto);
						var resto = eurosparteentera;
						var eurosformateado = "";
						while ( resto.length > 3 )
						{
							eurosformateado = "." + resto.substring
								(resto.length-3,resto.length) + eurosformateado;
							resto = resto.substring(0,resto.length-3);
						}
						eurosformateado = resto + eurosformateado + ",";
					}
				}
				document.f.RESULTADO.value=eurosformateado+" euros";
				}	
				if (tipo==2){
					document.f.PRECIO.value='';
					document.f.ENTRADA.value='';
					document.f.INTERES.value='';
					document.f.RESULTADO.value='';}
				}

function calculosM(form){
	var moneda;
	if(form.moneda[0].checked){moneda=" Ptas.";}
	if(form.moneda[1].checked){moneda=" Euros";}

	importe=form.importe.value*1;
	var frecuencia;
	if (form.frecuencia.value=="f0" ) {alert("Debe seleccionar la frecuencia de pago de su préstamo");}
	if (form.frecuencia.value=="f1") {frecuencia=12;ajuste=1;}
	if (form.frecuencia.value=="f2") {frecuencia=4;ajuste=3;}
	if (form.frecuencia.value=="f3") {frecuencia=3;ajuste=4;}
	if (form.frecuencia.value=="f4") {frecuencia=2;ajuste=6;}
	if (form.frecuencia.value=="f5") {frecuencia=1;ajuste=12;}

	interes=form.interes.value/(100*frecuencia);
	plazo=form.plazo.value*1*frecuencia;

	var pagomes;
	pagomes=cuotaM(importe,interes,plazo);
	form.pago.value=pagomes+moneda;

	function cuotaM(importe,interes,plazo){
		potencia=1+interes;
		multiplicador=Math.pow(potencia,-plazo);
		multiplicador1=importe*interes;
		pagomes=multiplicador1/(1-multiplicador);
		pagomes=Math.round(pagomes);
		return pagomes;
	}
}

function cambiaPrecioM(chk){
	var iCoste=eval("document.ficha.chkeq"+chk+".value");
	
	if (eval("document.ficha.chkeq"+chk+".checked")){ // le sumamos
		document.ficha.preciototal.value=parseFloat(document.ficha.preciototal.value) + parseFloat(iCoste)
	}
	else{ // le restamos
		document.ficha.preciototal.value-=iCoste
	}		
}

function openCenteredWindowM(URL, WIDTH, HEIGHT) {
	day = new Date();
	id = day.getTime();
	var width = WIDTH;
	var height = HEIGHT;
	var left = parseInt((screen.availWidth/2) - (width/2));
	var top = parseInt((screen.availHeight/2) - (height/2));
	var windowFeatures = "width=" + width + ",height=" + height + 
		",status='no',resizable='no',scrollbars='no',left=" + left + ",top=" + top + 
		",screenX=" + left + ",screenY=" + top;
	eval("page" + id + "  = window.open(URL, '" + id + "', windowFeatures);");
}

 

function handleHttpResponseM() {
	if (http.readyState == 4) {    	
		capaModelos.innerHTML = http.responseText;        		 
	}    
}

function actualizaModelosM() { 
  var url="includes/getModelosMotos.asp?m=";   
  capaModelos.innerHTML = "Cargando...";        		 
  var pk_marcas = document.getElementById("fk_marcas").value;    
  http.open("GET", url + escape(pk_marcas), true);  
  http.onreadystatechange = handleHttpResponseM;
  http.send(null);  
}

function buscarMotosNuevas(){ 
   var aviso;
	aviso="";
   if (document.getElementById("buscadorMotosNuevas").mo_precio_desde.value!="" && document.getElementById("buscadorMotosNuevas").mo_precio_hasta.value!="")
   {
     if(parseInt(document.getElementById("buscadorMotosNuevas").mo_precio_desde.value)>parseInt(document.getElementById("buscadorMotosNuevas").mo_precio_hasta.value))aviso+=" - El precio hasta debe ser mayor que el precio desde.\n";   
   } 
   if (document.getElementById("buscadorMotosNuevas").mo_potencia_desde.value!="" && document.getElementById("buscadorMotosNuevas").mo_potencia_hasta.value!="")
   {
      if(parseInt(document.getElementById("buscadorMotosNuevas").mo_potencia_desde.value)>parseInt(document.getElementById("buscadorMotosNuevas").mo_potencia_hasta.value))aviso+=" - La potencia hasta debe ser mayor que la potencia desde.\n";
   } 
   if (aviso!=""){
     alert("Se han encontrado los siguientes problemas:\n\n"+aviso);
     //return false;
   }else{
      document.getElementById("buscadorMotosNuevas").submit();
      //return true;
   }   
}

/******************* COCHES DE OCASION *******************/

function abreFotoCU(pfoto,ancho,alto){
	//var itop=(screen.availHeight-<%=iheight%>)/2
	//var ileft=(screen.availWidth-<%=iwidth%>)/2
	var ventana=window.open("includes/coches_usados_ampliacion.asp?foto=" + pfoto,"fotoCoche","width="+ ancho + ", height=" + alto);
}

function btnVolver_click(){
	window.history.go(-1);
}

function buscarCochesUsados(){ 
   var aviso;
	aviso="";
	//alert(document.getElementById("buscadorCochesNuevos").fk_marcas.value);
   if (document.getElementById("buscadorCochesUsados").co_precio_desde.value!="" && document.getElementById("buscadorCochesUsados").co_precio_hasta.value!="")
   {
     if(parseInt(document.getElementById("buscadorCochesUsados").co_precio_desde.value)>parseInt(document.getElementById("buscadorCochesUsados").co_precio_hasta.value))aviso+=" - El precio hasta debe ser mayor que el precio desde.\n";   
   } 
   if (document.getElementById("buscadorCochesUsados").co_anyo_desde.value!="" && document.getElementById("buscadorCochesUsados").co_anyo_hasta.value!="")
   {
      if(parseInt(document.getElementById("buscadorCochesUsados").co_anyo_desde.value)>parseInt(document.getElementById("buscadorCochesUsados").co_anyo_hasta.value))aviso+=" - El año hasta debe ser mayor que el año desde.\n";
   } 
   if (aviso!=""){
     alert("Se han encontrado los siguientes problemas:\n\n"+aviso);
     //return false;
   }else{
      document.getElementById("buscadorCochesUsados").submit();
      //return true;
   }   
}

function validarUsuariosCU(){
	var strTexto="";
	if (document.getElementById("us_login").value.length<1){
		strTexto+="\n - Usuario."	
	}
	if (document.getElementById("us_password").value.length<1){
		strTexto+="\n - Contraseña."	
	}
	if (strTexto==""){
		document.getElementById("iOp").value=1;
		//alert(document.getElementById("formularioValidacion").document.getElementById("iOp").value);
		document.formularioValidacion.submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

function borrarCoche(pk_coche){

	if (confirm("¿ Esta seguro que desea dar de baja este coche ?")){
		//alert(document.getElementById("form1"));
		document.getElementById("borrarCoche").pk_cochesusados.value=pk_coche;
		document.getElementById("borrarCoche").iOp.value=1
		document.getElementById("borrarCoche").submit();
	}
}

function paginacionCU(pagina){
	document.getElementById("formularioPaginacionCU").numPagina.value=pagina
	document.getElementById("formularioPaginacionCU").submit();
}

/*------> PARA LA ZONA DE USUARIOS DE COCHES USADOS -------*/
function validarInsercionCU(op){	

	var strTexto="";		
			
	if (document.getElementById("formularioInsertarCU").fk_marcas.selectedIndex == 0){
		strTexto+=" - Marca\n"
	}
	if (document.getElementById("formularioInsertarCU").fk_modelos.selectedIndex == 0){
		strTexto+=" - Modelo\n"
	}	
	if (document.getElementById("formularioInsertarCU").fk_combustibles.selectedIndex == 0){
		strTexto+=" - Combustible\n"
	}	
	if (document.getElementById("formularioInsertarCU").co_precio.value.length == 0){
		strTexto+=" - Precio\n"
	}
	if (document.getElementById("formularioInsertarCU").co_anyo.selectedIndex == 0){
		strTexto+=" - Año\n"
	}
	if (document.getElementById("formularioInsertarCU").co_km.value.length == 0 ){
		strTexto+=" - Km\n"
	}
			
	if (strTexto==""){	
		document.getElementById("formularioInsertarCU").iOp.value=op//segun la operacion que hagamos;				
		//document.forms[0].submit();
		document.getElementById("formularioInsertarCU").submit();
	}
	else{
		alert("Los siguientes campos son requeridos:\n\n"+strTexto)
	}	
}

//function btnVolver_click(){
//	document.location="cusados_entrada.asp"
//}

function btnUpfoto_click(){
	var strTexto="";
	var nombre;
		
	if (document.upFotos.foto.value.length<1){
		strTexto+=" - Foto\n"
	}
	else{
		nombre = document.upFotos.foto.value;		
	}
	
	if (strTexto==""){		
		document.upFotos.submit();
		document.upFotos.foto.value = nombre;
	}
	else{
		alert("Los siguientes campos son requeridos:\n\n"+strTexto)
	}	
}

function validarMarca(){
	if (document.getElementById("formularioInsertarCU").fk_marcas.selectedIndex == 0){
		alert("Marca requerida.")
	}else{		
		var fk = document.getElementById("formularioInsertarCU").fk_marcas[document.getElementById("formularioInsertarCU").fk_marcas.selectedIndex].value;		
		openCenteredWindow('htm/usados/setModelos.asp?m=' + fk, 550, 180);
	}	
}

function actualizaModelosCU() {
var url="includes/getModelos.asp?m=";   
  capaModelosCU.innerHTML = "Cargando...";        		 
   var pk_marcas = document.getElementById("formularioInsertarCU").fk_marcas.value;    
  http.open("GET", url + escape(pk_marcas), true);  
  http.onreadystatechange = handleHttpResponse2;
  http.send(null);  
}

function handleHttpResponse2() {
	if (http.readyState == 4) {    	
		capaModelosCU.innerHTML = http.responseText;        		 
	}    
}

function validarModUsu(){

	document.getElementById("modificarDatos").iOp.value=2
	document.getElementById("modificarDatos").submit();
	
}

/* ---------> PARA EL ALTA DE USUARIOS ---*/
function validarAlta(){

	var strTexto="";
	
	if (document.getElementById("usuarios").us_nombreapellidos.value.length<1){
		strTexto+=" - Nombre y Apellidos\n"
	}
	if (document.getElementById("usuarios").us_tipo[0].checked){
		if (document.getElementById("usuarios").us_empresa.value.length<1){
			strTexto+=" - Nombre del concesionario\n"
		}
	}
	if (document.getElementById("usuarios").us_email.value.length<1){
		strTexto+=" - Email\n"
	}
	if (strTexto==""){
		document.getElementById("usuarios").iOp.value=1;
		document.getElementById("usuarios").submit();
	}
	else{
		alert("Los siguientes campos son requeridos: \n\n"+strTexto);
	}

}
function cambiaTipo(iTipo){

	if (iTipo==1){
		document.getElementById("capaConcesionario").style.display="none";
	}
	else{
		document.getElementById("capaConcesionario").style.display="block";
	}

}

function validarRecordar(){

	var strTexto="";
	if (document.getElementById("recordarPass").us_email.value.length<1){
		strTexto+="\n - Email."	
	}
	if (strTexto==""){
		document.getElementById("recordarPass").iOp.value=1
		document.getElementById("recordarPass").submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

/****** PARA MOTOS USADAS ********************/
function abreFotoMU(pfoto,ancho,alto){

	var ventana=window.open("includes/motos_usadas_ampliacion.asp?foto="+pfoto,"fotoMoto","width=" + ancho + ", height=" + alto);
}

function buscarMotosOcasion(){ 
   var aviso;
	aviso="";
   if (document.getElementById("buscadorMotosOCasion").mo_precio_desde.value!="" && document.getElementById("buscadorMotosOCasion").mo_precio_hasta.value!="")
   {
     if(parseInt(document.getElementById("buscadorMotosOCasion").mo_precio_desde.value)>parseInt(document.getElementById("buscadorMotosOCasion").mo_precio_hasta.value))aviso+=" - El precio hasta debe ser mayor que el precio desde.\n";   
   } 
   if (document.getElementById("buscadorMotosOCasion").mo_potencia_desde.value!="" && document.getElementById("buscadorMotosOCasion").mo_potencia_hasta.value!="")
   {
      if(parseInt(document.getElementById("buscadorMotosOCasion").mo_potencia_desde.value)>parseInt(document.getElementById("buscadorMotosOCasion").mo_potencia_hasta.value))aviso+=" - La potencia hasta debe ser mayor que la potencia desde.\n";
   } 
   if (aviso!=""){
     alert("Se han encontrado los siguientes problemas:\n\n"+aviso);
   //  return false;
   }else{
      document.getElementById("buscadorMotosOCasion").submit();
     // return true;
   }   
}

function validarUsuariosMU(){

	var strTexto="";
	if (document.getElementById("validacionUsuariosMU").us_login.value.length<1){
		strTexto+="\n - Usuario."	
	}
	if (document.getElementById("validacionUsuariosMU").us_password.value.length<1){
		strTexto+="\n - Contraseña."	
	}
	if (strTexto==""){
		document.getElementById("validacionUsuariosMU").iOp.value=1
		document.getElementById("validacionUsuariosMU").submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

function borrarMoto(pk_moto){

	if (confirm("¿ Esta seguro que desea dar de baja esta moto ?")){
		document.getElementById("validarUsuMotosUsadas").pk_motosusadas.value=pk_moto;
		document.getElementById("validarUsuMotosUsadas").iOp.value=1
		document.getElementById("validarUsuMotosUsadas").submit();
	}
}

function validarInsertarMU(op){	

	var strTexto="";		
			
	if (document.getElementById("insertarMotoU").fk_marcas.selectedIndex == 0){
		strTexto+=" - Marca\n"
	}
	if (document.getElementById("insertarMotoU").fk_modelos.selectedIndex == 0){
		strTexto+=" - Modelo\n"
	}		
	if (document.getElementById("insertarMotoU").mo_precio.value.length == 0){
		strTexto+=" - Precio\n"
	}
	if (document.getElementById("insertarMotoU").mo_anyo.selectedIndex == 0){
		strTexto+=" - Año\n"
	}
	if (document.getElementById("insertarMotoU").fk_provincias.selectedIndex == 0){
		strTexto+=" - Provincia\n"
	}
	if (document.getElementById("insertarMotoU").mo_km.value.length == 0 ){
		strTexto+=" - Km\n"
	}
			
	if (strTexto==""){	
		document.getElementById("insertarMotoU").iOp.value=op //valor de iOp;				
		document.getElementById("insertarMotoU").submit();
	}
	else{
		alert("Los siguientes campos son requeridos:\n\n"+strTexto)
	}	
}

//function btnVolver_click(){
//	document.location="musados_entrada.asp"
//}

function btnUpfoto_clickMU(){
	var strTexto="";
	var nombre;
		
	if (document.upFotos.foto.value.length<1){
		strTexto+=" - Foto\n"
	}
	else{
		nombre = document.upFotos.foto.value;		
	}
	
	if (strTexto==""){		
		document.upFotos.submit();
		document.upFotos.foto.value = nombre;
	}
	else{
		alert("Los siguientes campos son requeridos:\n\n"+strTexto)
	}	
}

function handleHttpResponseMU() {
	if (http.readyState == 4) {    	
		capaModelosMU.innerHTML = http.responseText;        		 
	}    
}

function actualizaModelosMU() { 
  var url="includes/getModelosMotos.asp?m=";   
  capaModelosMU.innerHTML = "Cargando...";        		 
  var pk_marcas = document.getElementById("insertarMotoU").fk_marcas.value;    
  http.open("GET", url + escape(pk_marcas), true);  
  http.onreadystatechange = handleHttpResponseMU;
  http.send(null);  
}

function validarMarcaMU(){
	if (document.getElementById("insertarMotoU").fk_marcas.selectedIndex == 0){
		alert("Marca requerida.")
	}else{		
		var fk = document.getElementById("insertarMotoU").fk_marcas[document.getElementById("insertarMotoU").fk_marcas.selectedIndex].value;		
		openCenteredWindow('htm/usados_motos/setModelos.asp?m=' + fk, 530, 180);
	}	
}

function validarDatosMU(){

	document.getElementById("datosUsuarioMU").iOp.value=2
	document.getElementById("datosUsuarioMU").submit();
	
}

function validarPrensa(){

	var strTexto="";
	if (document.getElementById("formularioPrensa").usuario.value.length<1){
		strTexto+="\n - Usuario."	
	}
	if (document.getElementById("formularioPrensa").password.value.length<1){
		strTexto+="\n - Password."	
	}
	if (strTexto==""){
		document.getElementById("formularioPrensa").iOp.value=1
		document.getElementById("formularioPrensa").submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

function validarUsuMU(){

	var strTexto="";
	
	if (document.getElementById("usuariosMotosUsadas").us_nombreapellidos.value.length<1){
		strTexto+=" - Nombre y Apellidos\n"
	}
	if (document.getElementById("usuariosMotosUsadas").us_tipo[0].checked){
		if (document.getElementById("usuariosMotosUsadas").us_empresa.value.length<1){
			strTexto+=" - Nombre del concesionario\n"
		}
	}
	if (document.getElementById("usuariosMotosUsadas").us_email.value.length<1){
		strTexto+=" - Email\n"
	}
	if (strTexto==""){
		document.getElementById("usuariosMotosUsadas").iOp.value=1;
		document.getElementById("usuariosMotosUsadas").submit();
	}
	else{
		alert("Los siguientes campos son requeridos: \n\n"+strTexto);
	}

}
function cambiaTipoMU(iTipo){

	if (iTipo==1){
		document.getElementById("capaConcesionarioMU").style.display="none";
	}
	else{
		document.getElementById("capaConcesionarioMU").style.display="block";
	}

}

function validarRecordarMU(){

	var strTexto="";
	if (document.getElementById("recordarMU").us_email.value.length<1){
		strTexto+="\n - Email."	
	}
	if (strTexto==""){
		document.getElementById("recordarMU").iOp.value=1
		document.getElementById("recordarMU").submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

/*************** SALA DE PRENSA *****************/
function validarPrensa(){

	var strTexto="";
	if (document.getElementById("formularioPrensa").usuario.value.length<1){
		strTexto+="\n - Usuario."	
	}
	if (document.getElementById("formularioPrensa").password.value.length<1){
		strTexto+="\n - Password."	
	}
	if (strTexto==""){
		document.getElementById("formularioPrensa").iOp.value=1
		document.getElementById("formularioPrensa").submit();
	}
	else{
		alert("Rellene los siguientes campos para continuar:\n"+strTexto)
	}
	
}

/*************** SECCION SERVICIOS ***************/
function Suma(tipo)	{		
   if (1*document.getElementById("f").PRECIO.value && 1*document.getElementById("f").ENTRADA.value && 1*document.getElementById("f").INTERES.value){
			var Vrble1=166.386*document.getElementById("f").PRECIO.value;
			var Vrble2=166.386*document.getElementById("f").ENTRADA.value;
            var i = 1*document.getElementById("f").PLAZO.selectedIndex;
            var Vrble3 = 1*document.getElementById("f").PLAZO.options[i].value;
			var Vrble4=1*document.getElementById("f").INTERES.value;
		}
		else
		{
			var Vrble1=166.386*document.getElementById("f").PRECIO.value;
			var Vrble2=166.386*document.getElementById("f").ENTRADA.value;
  var i = document.getElementById("f").PLAZO.selectedIndex;
  var Vrble3 = document.getElementById("f").PLAZO.options[i].value;
			var Vrble4=document.getElementById("f").INTERES.value;
		}
		cadena1=Vrble1-Vrble2;
		cadena2=Vrble4/100;
		cadena3=cadena2/12;
        var cadena4=1;
        for (var j = 0; j < Vrble3; j++)
        {
        cadena4 = cadena4 * (1 + cadena3);
        
cuotasapagar=(cadena1*cadena4*cadena3)/(cadena4-1);}

if (tipo==1){
   cambio = parseFloat(cuotasapagar / 166.386);
   numerotostring = (cambio * 1000).toString();

   numerotostring = (cambio * 1000) + '';
   pospunto = numerotostring.indexOf(".");
   (pospunto == -1) ? stringparteentera = numerotostring 
		     : stringparteentera = numerotostring.substring(0,pospunto);
		
   euros = ((Math.round(stringparteentera / 10)) / 100);
   eurostostring = euros.toString();

   eurostostring = euros + '';
   pospunto = eurostostring.indexOf(".");

   if ( pospunto == -1 )
   {
      eurosformateado = eurostostring;
   }
   else
   {
      if ( pospunto == 0 )
      {
         eurosformateado = "0," + eurostostring.substring
			   (pospunto+1,eurostostring.length);
      }
      else
      {

         eurosparteentera = eurostostring.substring(0,pospunto);
         var resto = eurosparteentera;
         var eurosformateado = "";

         while ( resto.length > 3 )
         {
            eurosformateado = "." + resto.substring
			      (resto.length-3,resto.length) + eurosformateado;
            resto = resto.substring(0,resto.length-3);
         }

         eurosformateado = resto + eurosformateado + "," +
         eurostostring.substring(pospunto+1,eurostostring.length);

      }
   }

document.getElementById("f").RESULTADO.value=eurosformateado+" euros";}
else{
cambio = parseFloat(cuotasapagar / 1);
   numerotostring = (cambio * 1000).toString();

   numerotostring = (cambio * 1000) + '';
   pospunto = numerotostring.indexOf(".");
   (pospunto == -1) ? stringparteentera = numerotostring 
		     : stringparteentera = numerotostring.substring(0,pospunto);
		
   euros = ((Math.round(stringparteentera / 10)) / 100);
   eurostostring = euros.toString();

   eurostostring = euros + '';
   pospunto = eurostostring.indexOf(".");

   if ( pospunto == -1 )
   {
      eurosformateado = eurostostring;
   }
   else
   {
      if ( pospunto == 0 )
      {
         eurosformateado = "0," + eurostostring.substring
			   (pospunto+1,eurostostring.length);
      }
      else
      {

         eurosparteentera = eurostostring.substring(0,pospunto);
         var resto = eurosparteentera;
         var eurosformateado = "";

         while ( resto.length > 3 )
         {
            eurosformateado = "." + resto.substring
			      (resto.length-3,resto.length) + eurosformateado;
            resto = resto.substring(0,resto.length-3);
         }

         eurosformateado = resto + eurosformateado + " ";

      }
   }

document.getElementById("f").RESULTADO.value=eurosformateado+" Ptas.";
}	

if (tipo==2){
document.getElementById("f").PRECIO.value='';
document.getElementById("f").ENTRADA.value='';
document.getElementById("f").INTERES.value='';
document.f.RESULTADO.value='';}
}
	
function abrirVentanaCondiciones(){
	var ventana=window.open("includes/condiciones.htm","condiciones","width=500, height=550")
	ventana.focus()
}

/*********** BUSCADOR MOTORPOINT **************/
function buscarMotorpoint(){			
	if (document.getElementById("busqueda").textobusqueda.value.length<1){
		alert("Introduzca el texto de búsqueda");
	}
	else{
		document.getElementById("busqueda").submit()
	}				
}	

function handleHttpResponseBusc() {
	if (http.readyState == 4) {	
		window.open(http.responseText);
		
	}    
}

function actualizaContador(numeroBanner) {          		  
	http.open("GET","includes/actualizaContador.asp?numeroBanner=" + numeroBanner, true);  
	http.onreadystatechange = handleHttpResponseBusc;
	http.send(null);  
}
function actualizaContadorFlash(numeroBanner,tipo) {        		  
	http.open("GET","actualizaContador.asp?numeroBanner=" + numeroBanner + "&tipo=" + tipo, true);    
	http.send(null);  
}	

function openCenteredWindowBusc(URL, WIDTH, HEIGHT) {
	day = new Date();
	id = day.getTime();
	var width = WIDTH;
	var height = HEIGHT;
	var left = parseInt((screen.availWidth/2) - (width/2));
	var top = parseInt((screen.availHeight/2) - (height/2));
	var windowFeatures = "width=" + width + ",height=" + height + 
		",status='no',resizable='no',scrollbars='no',left=" + left + ",top=" + top + 
		",screenX=" + left + ",screenY=" + top;
	eval("page" + id + "  = window.open(URL, '" + id + "', windowFeatures);");
}

/********* BUZON QUEJAS ********/
function boton_participar(){ 
   var y;
	y="";
	if (document.getElementById("formularioQuejas").nombre.value==""){
		y=y+"- Debe rellenar el campo Nombre.\n";
	} 
	if (document.getElementById("formularioQuejas").email.value==""){
		y=y+"- Debe rellenar el campo Email.\n";
	}
	else{
		if(!validarEmail(document.getElementById("formularioQuejas").email.value)){
			 y+="- Formato de E-mail incorrecto.\n";
		}
	}
	if (document.getElementById("formularioQuejas").fk_marcas.value=="0"){
	 y=y+"- Debe seleccionar una marca.\n";
	};
	if (document.getElementById("formularioQuejas").fk_modelos.value=="0"){
	 y=y+"- Debe seleccionar un modelo.\n";
	};
	if (document.getElementById("formularioQuejas").queja.value==""){
	 y=y+"- Debe formular su queja.\n";
	}
	if (y!=""){
		alert("Se han encontrado los siguientes problemas:\n\n"+y);
	}
	else{
		//checkVisible();		
	    document.getElementById("formularioQuejas").iOp.value=1;
		document.getElementById("formularioQuejas").submit();
	}
}

function checkVisible(){
	if (document.getElementById("formularioQuejas").visible.checked==true){
		document.getElementById("formularioQuejas").visible.value=1;
	}else{
		document.getElementById("formularioQuejas").visible.value=0;
	}
}

/************* AGENDA *********/
function MesAnterior(mesAux,anyoAux){	
	mesAux=parseInt(mesAux);
	anyoAux=parseInt(anyoAux);	
	if (mesAux==1){
		anyoAux=anyoAux-1
		document.getElementById("miform").action='index.asp?pagina=agenda&mes=12&anyo=' + anyoAux;
	}else{
		mesAux=mesAux-1;		
		document.getElementById("miform").action='index.asp?pagina=agenda&mes=' + mesAux + '&anyo=' + anyoAux;
	}	
	document.getElementById("miform").submit();
}

function MesSiguiente(mesAux,anyoAux){	
	mesAux=parseInt(mesAux);
	anyoAux=parseInt(anyoAux);	
	if (mesAux==12){
		anyoAux=anyoAux+1;
		document.getElementById("miform").action='index.asp?pagina=agenda&mes=1&anyo=' + anyoAux;
	}else{
		mesAux=mesAux+1;
		document.getElementById("miform").action='index.asp?pagina=agenda&mes=' + mesAux + '&anyo=' + anyoAux;
	}	
	document.getElementById("miform").submit();
}

/******** CONCESIONARIOS ******/
function boton_buscarConce(){ 
   var aviso;
	aviso="";
   if (document.getElementById("FrmCocheNew").fk_marcas.value == "Todos" )
   {	aviso+=" No ha seleccionado la marca.\n";   
   } 
   if (aviso!=""){
     alert("Se han encontrado los siguientes problemas:\n\n"+aviso);
     //return false;
   }else{
      document.getElementById("FrmCocheNew").submit();
    //  return true;
   }   
}

//******** SECCION VIDEOS *********/

function handleHttpResponseVideos() {
	if (http.readyState == 4) {    	
		capaModelos.innerHTML = http.responseText; 
	}    
}

function actualizaModelosVideos() {    

  capaModelos.innerHTML = "<span style='font-family:arial;font-size:11px;'><b>Cargando...</b></span>";
  var pk_marcas = document.getElementById("fk_marcas").value;
  http.open("GET","includes/getModelosVideos.asp?marcas=" + pk_marcas, true); 
  http.onreadystatechange = handleHttpResponseVideos;
  http.send(null);  
}

function cargaVideo(){

	var strVideo = document.getElementById("fk_modelos").value;
	if (strVideo!=0){
		document.getElementById("MPlay1").Stop();
		document.getElementById("MPlay1").filename="mms://stream.hooping.net/MotorPoint/Coches/"+strVideo
		document.getElementById("MPlay1").src="mms://stream.hooping.net/MotorPoint/Coches/"+strVideo
		Play();
	}
}

function cargaVideoExterno(strArchivo){

	document.getElementById("MPlay1").Stop();
	document.getElementById("MPlay1").filename="mms://stream.hooping.net/MotorPoint/"+strArchivo
	document.getElementById("MPlay1").src="mms://stream.hooping.net/MotorPoint/"+strArchivo
	Play();
	
}

function Play() {
	
	document.getElementById("MPlay1").Play();
	
}

function Pausar() {

	document.getElementById("MPlay1").Pause();

}

function Parar() {

	document.getElementById("MPlay1").currentPosition=0;
	document.getElementById("MPlay1").Stop();

}

function Avanzar(tiempo){

	document.getElementById("MPlay1").currentPosition=MPlay1.currentPosition+tiempo;
	Play();
	
}

function Retroceder(tiempo){

	document.getElementById("MPlay1").currentPosition=MPlay1.currentPosition-tiempo;
	Play();
	
}

/************ SUSCRIPCION DEPORTES ******/
function validarSusDeportes(){

	var y=""; 
	if (document.getElementById("formularioSusDeportes").nombre.value==""){
		y=y+"- Nombre.\n";
	} 
	if (document.getElementById("formularioSusDeportes").email.value==""){
		y=y+"- Email.\n";
	}
	else{
		if(!validarEmail(document.getElementById("formularioSusDeportes").email.value)){
			 y+="- Formato de E-mail incorrecto.\n";
		}
	}
	if (y!=""){
		alert("Debe rellenar los siguientes campos:\n\n"+y);
	}
	else{
		document.getElementById("formularioSusDeportes").submit();
	}
}


/****************************************************************
/ Implentacion: Hugo Alva Crisólogo
/ Revision: 301106
/ Descripcion: Valida los campos del formulario
'***************************************************************/
function validarContacto(){
//Funcion para la validar los datos enviados desde el formulario de contacto
	var texto;
	texto = "";

	var cadenaEnvio;
	cadenaEnvio = "";
	
	//Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
	
	if ( document.getElementById("formularioContacto").nombre.value == "" ) {
		texto+=" * Debe indicar su nombre.<br>";
	}else{
		cadenaEnvio="nombre=" + document.getElementById("formularioContacto").nombre.value;
	}
	
	if ( document.getElementById("formularioContacto").email.value == "" ) {
		texto+=" * Debe indicar su e-mail.<br>";
	}
	
	if(document.getElementById("formularioContacto").email.value!=""){
		if(!validarEmail(document.getElementById("formularioContacto").email.value)){
				texto+=" * Formato de E-mail incorrecto.<br>";
		}else{
			cadenaEnvio+="&email=" + document.getElementById("formularioContacto").email.value;
		}
	}
	if ( document.getElementById("formularioContacto").comentarios.value == "" ){
		texto+=" * Debe incluir el motivo de su consulta.<br>";
	}else{
		cadenaEnvio+="&comentarios=" + document.getElementById("formularioContacto").comentarios.value;
	}	
	
	//Aqui vamos añadiendo los demas campos sino estan vacios
	
	if ( document.getElementById("formularioContacto").direccion.value != "" ){
		cadenaEnvio+="&direccion=" + document.getElementById("formularioContacto").direccion.value;
	}
	
	if ( document.getElementById("formularioContacto").poblacion.value != "" ){
		cadenaEnvio+="&poblacion=" + document.getElementById("formularioContacto").poblacion.value;
	}
	
	if ( document.getElementById("formularioContacto").provincia.value != "" ){
		cadenaEnvio+="&provincia=" + document.getElementById("formularioContacto").provincia.value;
	}
	
	if ( document.getElementById("formularioContacto").telefono.value != "" ){
		cadenaEnvio+="&telefono=" + document.getElementById("formularioContacto").telefono.value;
	}
	
	if ( document.getElementById("formularioContacto").movil.value != "" ){
		cadenaEnvio+="&movil=" + document.getElementById("formularioContacto").movil.value;
	}
	
	if ( document.getElementById("formularioContacto").cpostal.value != "" ){
		cadenaEnvio+="&cpostal=" + document.getElementById("formularioContacto").cpostal.value;
	}

	//if ( document.getElementById("formularioContacto").pais2.value != "" ){
		cadenaEnvio+="&pais=" + document.getElementById("formularioContacto").pais.options[document.getElementById("formularioContacto").pais.selectedIndex].text
	//}
	
	//Si falta algun campo obligatorio o el email no tiene un formato correcto
	//mostramos un mensaje de avios
	
	if ( texto != "" ){
		document.getElementById("mensajeError").innerHTML=texto;
		document.getElementById("capaError").style.display='block';
		
	}else{
		//alert(cadenaEnvio);
		document.getElementById("mensaje-respuesta").innerHTML="";
		document.getElementById("mensajeError").innerHTML="";
		document.getElementById("capaError").style.display='none';
		//http.open("GET", "actualizer/formcorreosMultiple/envioSinBd.asp?" + cadenaEnvio, true);
		http.open("GET", "envioContacto.asp?" + cadenaEnvio, true);
		http.onreadystatechange = handleHttpResponseContacto2;
		http.send(null);
	}
	
}

function handleHttpResponseContacto2() {
	if (http.readyState == 4) {    	
		//Aqui va el nombre de la capa donde queramos cargar el contenido
		document.getElementById("mensaje-respuesta").innerHTML = http.responseText;	
		document.getElementById("formularioContacto").reset();
	}    
}
