﻿var enProceso;
var http;
var idveh;

function getHTTPObject() {
var xmlhttp=false;
try 
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} 
catch (e) 
{
try 
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} 
catch (E) 
{
xmlhttp = false;
}
}

if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
{
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}

function cargarmodelos(marca){
  if (!enProceso) {
       var url = "actmodelos.php?marca=" + marca;
	   //alert(url);
	   var box = document.fnuevo.modelo;
	   box.length=1;
  	   box.options[0].value = '';
	   box.options[0].text = 'Cargando ...';
	   http = getHTTPObject();
       http.open("GET", url, true);
       http.onreadystatechange = cargandomodelos;
       enProceso = true;
       http.send(null);
  }
}

function cargandomodelos() { 
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
			 //alert(http.responseText);
             results = http.responseText.split("#");
			 var box = document.fnuevo.modelo;
			 //box.clear();
// ---------------------
			 box.length = results.length+1;
			 box.options[0].value = '';
		     box.options[0].text = ' - Elegir - ';
		     for (j=0;j<results.length;j++){
				//alert(results[j]);
			    box.options[j+1].value = results[j];
			    box.options[j+1].text = results[j];				
		     }
          } // no invalid
       } // status
    } // readystate
	enProceso = false;
}
// JavaScript Document

// funciones para consejos
function obtenerconsejo(tipo) {
	if (!enProceso) {
	   //alert(document.getElementById("idconsejo").innerHTML);	
	   var url = 'codigo/obtenerconsejo.php?id='+document.getElementById("idconsejo").innerHTML+'&T='+tipo;
	   //alert(url);
	   http = getHTTPObject();
       http.open("GET", url, true);
       http.onreadystatechange = cargandoconsejo;
       enProceso = true;
       http.send(null);
	}
}

function cargandoconsejo() {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				//alert(http.responseText);
				results = http.responseText.split("#");
				document.getElementById("consejo").innerHTML = "..."+results[1]+".";
				document.getElementById("idconsejo").innerHTML = results[0];
			}
		}
	}
	enProceso = false;
}

// funciones para consultas, citas y presupuestos

function limpiarsolicitud(solic){
	if (solic.value.substring(0,9) == 'Indícanos' || solic.value.substring(0,9) == 'Ind&iacut') solic.value = '';
}

function validaremail(email){
	var res = true;
	var p = email.indexOf('@');
	if (p > -1) {
		if (email.indexOf('.') > p) res = true;
		else res = false;
	} else res = false;
	return res;
}

function validartelefono(tel){
	var res = true;
	if (tel != '') {
		var c= '';
		for (i=0;i<9;i++) {
			c = tel.charAt(i);
//		alert(c);
			if ((c != '0') && (c != '1') && (c != '2') && (c != '3') && (c != '4') && (c != '5') && (c != '6') && (c != '7') && (c != '8') && (c != '9')) {
				res = false;
			}
		}
	}
	return res;
}

function enviarconsultaveh(form,tipo,idv){
	var msg = '';
	if (form.Nombre.value == '') msg = 'nombre';
	if (form.Email.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'email';	
	}
	if (form.Solicitud.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'solicitud';	
	}
	if (msg != '') alert('Introduce los siguientes campos: ' + msg);
	else {
		if (!validaremail(form.Email.value)) {
   	    	alert('El email tiene un formato incorrecto.');
		} else {
			if (!validartelefono(form.Telefono.value)) {
   		    	alert('El teléfono tiene un formato incorrecto.');
			} else {
		   var url = '../codigo/guardarconsulta.php?T='+tipo+'&V='+idv+'&N='+form.Nombre.value+'&TE='+form.Telefono.value+'&E='+form.Email.value+'&S='+form.Solicitud.value;
		   //alert(url);
		   http = getHTTPObject();
    	   http.open("GET", url, true);
	       http.onreadystatechange = consultaguardadaveh;
	       http.send(null);
			}
		}		
	}
}

function consultaguardadaveh(){
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
		   alert('La consulta ha sido enviada.');		
			document.fcons.Nombre.value='';
			document.fcons.Email.value='';
			document.fcons.Telefono.value='';
			document.fcons.Solicitud.value='';	
			}
		}
	}
}

// -------------------------------------

function enviarreserva(form,idv){
	var msg = '';
	if (form.Nombre.value == '') msg = 'nombre';
	if (form.Email.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'email';	
	}
	if (form.Solicitud.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'solicitud';	
	}
	if (msg != '') alert('Introduce los siguientes campos: ' + msg);
	else {
		if (!validaremail(form.Email.value)) {
   	    	alert('El email tiene un formato incorrecto.');
		} else {
			if (!validartelefono(form.Telefono.value)) {
   		    	alert('El teléfono tiene un formato incorrecto.');
			} else {
		   var url = '../codigo/guardarreserva.php?V='+idv+'&N='+form.Nombre.value+'&TE='+form.Telefono.value+'&E='+form.Email.value+'&S='+form.Solicitud.value+'&nom='+form.nom.value;
		   http = getHTTPObject();
    	   http.open("GET", url, true);
	       http.onreadystatechange = function () {
		    if (http.readyState == 4) { 
		       if (http.status == 200) {
		          if (http.responseText.indexOf('invalid') == -1) {
					alert('Reserva enviada. En breve recibirás un email con instrucciones.');
					document.fres.Nombre.value='';
					document.fres.Email.value='';
					document.fres.Telefono.value='';
					document.fres.Solicitud.value='';	
					}
				}
			}
		   }
	       http.send(null);
			}
		}
	}
}

/*function reservaguardada(){
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
			alert('Reserva enviada. En breve, recibirás un email con instrucciones.');
			document.fres.Nombre.value='';
			document.fres.Email.value='';
			document.fres.Telefono.value='';
			document.fres.Solicitud.value='';	
			}
		}
	}
}*/
// -------------------------------------

function enviarconsulta(form,tipo,idv,id_form,id_ok){
	var msg = '';
	if (form.Nombre.value == '') msg = 'nombre';
	if (form.Email.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'email';	
	}
	if (form.Solicitud.value == '') {
		if (msg != '') msg = msg + ', ';
		msg = 'solicitud';	
	}
	if (msg != '') alert('Introduce los siguientes campos: ' + msg);
	else {
		if (!validaremail(form.Email.value)) {
   	    	alert('El email tiene un formato incorrecto.');
		} else {
			if (!validartelefono(form.Telefono.value)) {
   		    	alert('El teléfono tiene un formato incorrecto.');
			} else {
		   document.getElementById(id_form).style.display = 'none';
		   var url = '../codigo/guardarconsulta.php?T='+tipo+'&V='+idv+'&N='+form.Nombre.value+'&TE='+form.Telefono.value+'&E='+form.Email.value+'&S='+form.Solicitud.value;
		   //alert(url);
		   http = getHTTPObject();
    	   http.open("GET", url, true);
	       http.onreadystatechange = function () {
				//alert('consultar ' + http.readyState);
			    if (http.readyState == 4) { 
			       if (http.status == 200) {
          				if (http.responseText.indexOf('invalid') == -1) {
						   document.getElementById(id_ok).style.display = 'block';		
						}
					}
				}
			}
	       http.send(null);
			}
		}
	}
}

/*function consultaguardada(id_ok){
	alert(http.readyState);
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
		   document.getElementById(id_ok).style.display = 'block';		
			}
		}
	}
}
*/
function limpiar(form,cad) {
	form.Nombre.value = '';
	form.Telefono.value = '';
	form.Email.value = '';	
	form.Solicitud.value = cad;
}

// -------------------------------------
function mostrarcita() {
	if (!enProceso) {
	document.getElementById('fade_form').style.display='block';
	document.getElementById('contenedor_form').style.display='block';
	   http = getHTTPObject();
	   //alert('../codigo/citaprevia.php');
       http.open("GET", '../codigo/citaprevia.php', true);
       http.onreadystatechange = mostrandocita;
       enProceso = true;
       http.send(null);
	}
}

function mostrandocita() {
//	alert(http.readyState);
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				document.getElementById("contenedor_form").innerHTML = http.responseText;
				document.getElementById('contenedor_form').style.display='block';
				limpiar(document.fcita,'Indícanos aquí la fecha y hora que desees para realizar la revisión pre-ITV. Recibirás confirmación vía email o por teléfono si así lo indicas.');
			}
		}
	}
	enProceso = false;
}

function mostrarconsulta() {
	if (!enProceso) {
	document.getElementById('fade_form').style.display='block';
	document.getElementById('contenedor_form').style.display='block';
	   http = getHTTPObject();
	   //alert('../codigo/citaprevia.php');
       http.open("GET", '../codigo/consulta.php', true);
       http.onreadystatechange = mostrandoconsulta;
       enProceso = true;
       http.send(null);
	}
}

function mostrandoconsulta() {
//	alert(http.readyState);
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				document.getElementById("contenedor_form").innerHTML = http.responseText;
				document.getElementById('contenedor_form').style.display='block';
				limpiar(document.fcons,'Indícanos aquí cualquier duda que tengas. Recibirás respuesta vía email o por teléfono si así lo indicas.');
			}
		}
	}
	enProceso = false;
}

function mostrarpresupuesto() {
	if (!enProceso) {
	document.getElementById('fade_form').style.display='block';
	document.getElementById('contenedor_form').style.display='block';
	   http = getHTTPObject();
	   //alert('../codigo/citaprevia.php');
       http.open("GET", '../codigo/presupuesto.php', true);
       http.onreadystatechange = mostrandopresupuesto;
       enProceso = true;
       http.send(null);
	}
}

function mostrandopresupuesto() {
//	alert(http.readyState);
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				document.getElementById("contenedor_form").innerHTML = http.responseText;
				document.getElementById('contenedor_form').style.display='block';
				limpiar(document.fpres,'Indícanos aquí la revisión o reparación que desees realizar añadiendo la marca, modelo y antigüedad del vehículo o cualquier otro dato relevante. Recibirás respuesta vía email o por teléfono si así lo indicas.');
			}
		}
	}
	enProceso = false;
}

// nuevo email
/*function nuevoemail(){
  if (validaremail(document.getElementById("email").value)) {
	if (!enProceso) {
	   url = "../codigo/nuevoemail.php?M="+document.getElementById("email").value;
	   //alert(url);	   
	   http = getHTTPObject();
       http.open("GET", url, true);
       http.onreadystatechange = emailañadido;
       enProceso = true;
       http.send(null);
	}
  } else {
	  alert('Email incorrecto. Introdúcelo de nuevo.');
	  document.getElementById("email").value = '';
  }
}
*/
function nuevoemail(){
  if (validaremail(document.getElementById("email").value)) {
	if (!enProceso) {
	   url = "../codigo/confirmacion.php?M="+document.getElementById("email").value;
	   //alert(url);	   
	   http = getHTTPObject();
       http.open("GET", url, true);
       http.onreadystatechange = emailañadido;
       enProceso = true;
       http.send(null);
	}
  } else {
	  alert('Email incorrecto. Introdúcelo de nuevo.');
	  document.getElementById("email").value = '';
  }
}


function emailañadido() {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				if (http.responseText == '0') {
					alert('Te has suscrito correctamente al boletín de Talleres V.Auto. Comprueba tu cuenta de correo para confirmar la suscripción.');
					document.getElementById("email").value = '';					
				}
				else alert('Ya estás suscrito en el boletín de Talleres V.Auto.');
			}
		}
	}
	enProceso = false;
}

// ------------------------
// --- EXPOSICIÓN
function changeProp(objId,x,theProp,theValue) { //v9.0
  var obj = null; with (document){ if (getElementById)
  obj = getElementById(objId); }
  if (obj){
    if (theValue == true || theValue == false)
      eval("obj.style."+theProp+"="+theValue);
    else eval("obj.style."+theProp+"='"+theValue+"'");
  }
}

function activarficha(name,id){
	changeProp(name,'','backgroundColor','#990000','TD');
	changeProp('id'+id,'','color','#FFFFFF');
	changeProp('co'+id,'','color','#FFFFFF');
	changeProp('pr'+id,'','color','#FFFFFF');
	changeProp('an'+id,'','color','#FFFFFF');	
	changeProp('es'+id,'','color','#999999');
}

function desactivarficha(name,id) {
	changeProp(name,'','backgroundColor','#FFFFFF','TD');
	changeProp('id'+id,'','color','#000000');	
	changeProp('an'+id,'','color','#000000');	
	changeProp('co'+id,'','color','#000000');	
	changeProp('pr'+id,'','color','#000000');
	if (document.getElementById('es'+id).innerHTML == 'reservado') changeProp('es'+id,'','color','#990000');
	else changeProp('es'+id,'','color','#009900');
}
// -------------------------------------
function eliminarcookiecomp(id) {
	if (!enProceso) {
	   url = '../concesionario/eliminarcookiecomp.php?id='+id;
//	   alert(url);
	   http = getHTTPObject();
       http.open("GET", url, true);
       http.onreadystatechange = eliminadacookiecomp;
       enProceso = true;
       http.send(null);
	}
}
function eliminadacookiecomp() {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
//				alert('Vehiculo añadido al comparador');
				location.reload();
			}
		}
	}
	enProceso = false;
}

function marcarcomp(id) {
//	alert('marcar');
  if ((document.getElementById('chkbox_expo'+id).checked) && (document.getElementById('ncomp').value == 4)) {
	alert('Has añadido el número máximo de vehículos que permite el comparador. Desmarca alguno para añadir éste.');
	document.getElementById('chkbox_expo'+id).checked = false;	
  } else {
	if (!enProceso) {
//	alert('marcar 2');		
	   if (document.getElementById('chkbox_expo'+id).checked) url = '../concesionario/crearcookiecomp.php?id='+id;
	   else url = '../concesionario/eliminarcookiecomp.php?id='+id;
//	   alert(url);
	   http = getHTTPObject();
       http.open("GET", url, true);
	   //alert(document.getElementById('chkbox_expo'+id).checked);
       if (document.getElementById('chkbox_expo'+id).checked) http.onreadystatechange = marcadocomp;
	   else http.onreadystatechange = desmarcadocomp;
       enProceso = true;
       http.send(null);
	}
  }
}

function marcadocomp() {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				//alert('Vehiculo añadido al comparador');
				document.getElementById('ncomp').value=parseInt(document.getElementById('ncomp').value)+1;
			}
		}
	}
	enProceso = false;
}

function desmarcadocomp() {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				//alert('Vehiculo quitado del comparador');
				document.getElementById('ncomp').value=parseInt(document.getElementById('ncomp').value)-1;
			}
		}
	}
	enProceso = false;
}
// ------------------------------------
// FUNCIONES PARA LA FICHA DE VEHICULO

function mostrarficha(id,marca,nombre,precio,estado) {
	document.getElementById('fade_ficha').style.display='block';
	document.getElementById('contenedor_form_tab').style.display='block';
	idveh = id;	
    http = getHTTPObject();
   //alert('obtenerficha ' +idveh);	   
    http.open("GET", '../concesionario/ficha.php?id='+id+'&N='+nombre+'&M='+marca+'&P='+precio+'&E='+estado, true);
    http.onreadystatechange = mostrandoficha;
    http.send(null);
}

function mostrandoficha(id) {
    if (http.readyState == 4) { 
       if (http.status == 200) {
          if (http.responseText.indexOf('invalid') == -1) {
				document.getElementById("contenedor_form_tab").innerHTML = http.responseText;
				CargarIni(idveh);					
				//document.getElementById('light_ficha').style.display='block';
				document.getElementById('contenedor_form_tab').style.display='block';	
				//document.getElementById('fade_ficha').style.display='block';
			}
		}
	}
	enProceso = false;
}

// funcion para la calculadora
function calcularcuota(form) {	
	lista = document.form.duracion;
	if (lista.selectedIndex == 0) document.form.plazos.value = 12;
	else if (lista.selectedIndex == 1) document.form.plazos.value = 24;
	else if (lista.selectedIndex == 2) document.form.plazos.value = 36;
	else if (lista.selectedIndex == 3) document.form.plazos.value = 48;
	else if (lista.selectedIndex == 4) document.form.plazos.value = 60;
	else if (lista.selectedIndex == 5) document.form.plazos.value = 72;
	else if (lista.selectedIndex == 6) document.form.plazos.value = 84;					
	else if (lista.selectedIndex == 7) document.form.plazos.value = 96;
	else if (lista.selectedIndex == 8) document.form.plazos.value = 108;		
	var precio = parseFloat(document.form.precioini.value);
	//alert(document.form.comision.value + ' ' + document.form.seguro.value);
	//if (document.form.check_comis.checked) precio += Math.round((document.form.comision.value*precio)/100);
	if (document.form.check_seguro.checked) precio += parseFloat(document.form.seguro.value);
	document.form.precio.value = precio;	
	//alert(precio);
	cuota = Math.round(precio*lista.options[lista.selectedIndex].value);
	document.form.cuota.value = cuota;	
}

function PhotoView(pag) {	
	if(document.all) document.all('ficha_img_g').src='../imagenes/'+pag;
	else document.getElementById('ficha_img_g').src='../imagenes/'+pag;
}

function comprobaremail() {
	if (document.getElementById('email').value.indexOf('tu email') > 0) {
		document.getElementById('email').value='';
	}
}
function getBrowserWidth () {
	if (window.innerWidth) return window.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth;
	else if (document.body) return document.body.clientWidth;
	else return 0;
}
function getBrowserHeight () {
	if (window.innerHeight) return window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight != 0) return document.documentElement.clientHeight;
	else if (document.body) return document.body.clientHeight;
	return 0;
}
function resize()
{
	if (getBrowserWidth() < 915 || getBrowserHeight() < 550) {
		document.getElementById("contenedor_form_tab").style.position = 'absolute';
		document.getElementById("contenedor_form_tab").style.margin = '40% 2.5% 0% 2.5%';
		document.getElementById("contenedor_form_tab").style.top = '0%';
		document.getElementById("contenedor_form_tab").style.left = '0%';
	} else {
		document.getElementById("contenedor_form_tab").style.position = 'fixed';
		document.getElementById("contenedor_form_tab").style.margin = '-275px 0px 0px -457px';
		document.getElementById("contenedor_form_tab").style.top = '50%';
		document.getElementById("contenedor_form_tab").style.left = '50%';
	}
window.onresize=resize;
}

function miniResize()
{
	if (getBrowserWidth() < 635 || getBrowserHeight() < 350) {
		document.getElementById("contenedor_form").style.position = 'absolute';
		document.getElementById("contenedor_form").style.margin = '2.5% 2.5% 0% 2.5%';
		document.getElementById("contenedor_form").style.top = '0%';
		document.getElementById("contenedor_form").style.left = '0%';
	} else {
		document.getElementById("contenedor_form").style.position = 'fixed';
		document.getElementById("contenedor_form").style.margin = '-178px 0px 0px -296px';
		document.getElementById("contenedor_form").style.top = '50%';
		document.getElementById("contenedor_form").style.left = '50%';
	}
window.onresize=miniResize;
}