﻿//------- ISIDRO JAVASCRIPT

function EnviarPassword( email )
{
   new Ajax.Request( 
                      'garisapi2public.dll?id=ee',
                      { 
                          method: 'post',
                          parameters: { e:email }
                      }
                   );
   
}


function EnviarFormularioBajaCatalogo( email )
{
  if ( email == '' )
  {
    alert('Debe introducir un email.');
    return;
  }   
  $('FormBajaCatalogo').submit();   
}


function EnviarFormularioInscribirseCatalogo()
{
   var param = new Object();
   
   if ( $('aceptod').checked == false )
   {
     alert('Debe aceptar las condiciones.');
     return; 
   }

   $('idbotonenviar').style.display="none";


   param.titulo = "Formulario Inscribirse catalogo.";
   param.nombre = $('nombre').value;
   param.apellidos = $('apellidos').value;
   param.empresa = $('empresa').value;
   param.email = $('email').value;
   
   new Ajax.Request( 'garisapi2public.dll?id=se',  
                     {
                       method: 'post',
                       parameters: param,
                       onSuccess: function(transport) 
                                  {
                                     alert('Información enviada con éxito. ');
                                     window.location = 'http://www.autoresiduos.com';
                                  },
                       onFailure: function(transport)
                                  {
                                     alert('Error realizando el envio.');
                                  }
                     }
                   );
}


function EnviarFormularioContactar()
{
   var param = new Object();
   
   param.titulo = "Formulario contactar.";
   param.empresa = $('empresa').value;
   param.nombre = $('nombre').value;
   param.direccion = $('direccion').value;
   param.cp = $('cp').value;
   param.poblacion = $('poblacion').value;
   param.provincia = $('provincia').value;
   param.telefono = $('telefono').value;
   param.email = $('email').value;
   param.mensaje = $('mensaje').value;
   
   new Ajax.Request( 'garisapi2public.dll?id=se',  
                     {
                       method: 'post',
                       parameters: param,
                       onSuccess: function(transport) 
                                  {
                                     alert('Información enviada con éxito. ');
                                     window.location = 'http://www.autoresiduos.com';
                                  },
                       onFailure: function(transport)
                                  {
                                     alert('Error realizando el envio.');
                                  }
                     }
                   );
}



function EnviarFormularioProfesional( )
{
   var param = new Object();
   
   param.titulo = "Formulario alta clientes-compradores.";
   param.razonsocial = $('razonsocial').value;
   param.cif = $('cif').value;
   param.direccionsocial = $('direccionsocial').value;
   param.cdireccionsocial = $('cdireccionsocial').value;
   param.poblacionsocial = $('poblacionsocial').value;
   param.provinciasocial = $('provinciasocial').value;
   param.cpsocial = $('cpsocial').value;
   param.nombre = $('nombre').value;
   param.nif = $('nif').value;
   param.direccion = $('direccion').value;
   param.c_direccion = $('c_direccion').value;
   param.poblacion = $('poblacion').value;
   param.provincia = $('provincia').value;
   param.cp = $('cp').value;
   param.nombrecontacto = $('nombrecontacto').value;
   param.telefono = $('telefono').value;
   param.movil = $('movil').value;
   param.fax = $('fax').value;
   param.email = $('email').value;
   
   new Ajax.Request( 'garisapi2public.dll?id=se',  
                     {
                       method: 'post',
                       parameters: param,
                       onSuccess: function(transport) 
                                  {
                                     alert('Información enviada con éxito. ');
                                     window.location = 'http://www.autoresiduos.com';
                                  },
                       onFailure: function(transport)
                                  {
                                     alert('Error realizando el envio.');
                                  }
                     }
                   );
}


function ActualizaLugarRecogida(cp, poblacion, provincia )
{
   new Ajax.Updater( 'idlugarrecogida', 'garisapi2public.dll?id=lr&cp=' + cp + '&po=' + poblacion + '&pro=' + provincia );
}

function ChangeCP()
{
   var cp = $F('idcp');
   
   if ( cp.length == 0 )
      ActualizaLugarRecogida( '', '-', $F('idprovincia') );
   else
      ActualizaLugarRecogida( cp, '-','-' );
}

function ChangePoblacion()
{
   ActualizaLugarRecogida( $F('idcp'), $F('idpoblacion'), $F('idprovincia') );
}

function ChangeProvincia()
{
   ActualizaLugarRecogida( '', '-', $F('idprovincia') );
}

function ActualizaFicherosEnviados()
{
   ventana_seleccion_vh.close();
   new Ajax.Updater( 'idlistficheros', 'garisapi2public.dll?id=lf');
}

function EliminarDocumento( tipo, codigo )
{
   new Ajax.Updater( 'idlistficheros', 'garisapi2public.dll?id=ef&t='+tipo+'&i='+codigo);
}


function FinSubirFicheros()
{
   FormularioParticular( '4' );
}


function ActivaFoto( fichero )
{
  $('idfoto'+fichero).style.display="block";
}

function ActivaFichero( fichero )
{
  $('idfichero'+fichero).style.display="block";
}

function CambiaTipoVh( tipo )
{
  var form1 = 'none';
  var form2 = 'none';
  
  // visibilidad
  if ( tipo == 'T' )
      form1 = 'block';
  if ( tipo == 'M' || tipo == 'I' )
      form2 = 'block';
  
  $('form1').style.display =  form1;
  $('form2').style.display =  form2;
}


function SeleccionarVh( tipo, codigo, descripcion, marca, modelo, version )
{
   $('idformtipovh').value = tipo;

   if ( tipo == 'T' )
   {
      $('idvh').value=codigo; 
      $('iddescripcionvh').innerHTML= descripcion; 
      $('idformmarca').value= marca;
      $('idformmodelo').value= modelo;
      $('idformversion').value= version;
   }
   else
   if ( tipo == 'M' || tipo == 'I' )
   {
      $('idvh').value='0'; 
      $('iddescripcionvh').innerHTML= descripcion; 
      $('idformmarca').value= marca;
      $('idformmodelo').value= modelo;
      $('idformversion').value= version;
   }
  
   ventana_seleccion_vh.close();
}

function Comprueba_SeleccionVh()
{
   var ok = true, titulo;   
   
   if ($('idfmatriculacion').value.length==0)
   {
     ok = false;
     titulo='Debe de introducir la fecha matriculación.';
     $('idfmatriculacion').focus(); 
   }
   else if ($('idcombustible').value.length==0 || $('idcombustible').value =='-' )
   {
     ok = false;
     titulo='Debe de introducir el tipo combustible.';
     $('idcombustible').focus(); 
   }
   
   if ( ok == false )
   {
     alert( titulo );
   }
 
   return ok;
}

function GetFMatriculacion( idfmatriculacion, matricula, aviso )
{
   // Obtiene fecha 1 matriculacion
   new Ajax.Request( 'garisapi2public.dll?id=getm&m='+matricula,
                     {
                       onSuccess: function (response)
                                  {
                                    var fecha = response.responseText;

                                    $(idfmatriculacion).value = '';

                                    if ( fecha != '-' )
                                    {
                                      if ( aviso == true )
                                         VentanaAviso( '¿ Es esta la fecha 1ª matriculación '+fecha+' ?', true, '$(\''+idfmatriculacion+'\').value=\''+fecha+'\'' , '' );
                                      else
                                         $(idfmatriculacion).value = fecha;
/*
                                      if ( confirm('¿ Es esta la fecha 1ª matriculación '+fecha+' ?') )
                                         $(idfmatriculacion).value = fecha; 
*/
                                    }
                                  },
                       onFailure: function () { $(idfmatriculacion).value ="Error"; }
                     } );
   
}


function CalculaFMatriculacion( idmatricula, idfmatriculacion, matricula, aviso )
{
   // Chequea matricula
   new Ajax.Request( 'garisapi2public.dll?id=chkm&m='+matricula,
                     {
                       onSuccess: function (response)
                                  {
                                    if ( response.responseText.length )
                                    {
                                       $( idmatricula ).value = response.responseText;
                                    
                                       // Calcula fecha matriculacion
                                       GetFMatriculacion( idfmatriculacion, matricula, aviso ); 
                                    }
                                  },
                       onFailure: function () { $(idfmatriculacion).value ="Error"; }
                     } );
   
}

function Actualiza_Modelos( marca, fmatriculacion, motor )
{
   new Ajax.Updater( 'idlistmodelos', 'garisapi2public.dll?id=sv&t=m&m='+marca+'&f='+fmatriculacion+'&tm='+motor );
   $('idlistvh').innerHTML = '';
}

function Actualiza_Versiones( marca,modelo, fmatriculacion, motor )
{
   new Ajax.Updater( 'idlistvh', 'garisapi2public.dll?id=sv&t=v&m='+marca+'&mo='+modelo+'&f='+fmatriculacion+'&tm='+motor );
}


function SeleccionarDanos()
{
   $('idseldanos').value = '1';
}

function CheckChk( id )
{
   var valor = '0';   
   if ( $(id) )
     if ( $(id).checked )
       valor = '1';
   return valor;       
}

function CheckTab4()
{
  var result = true;
  // Chequea formulario tag 4
  if ( $F('idTotalFicheros') == '0' )
  {
     result = confirm('No ha seleccionado ningún fichero. ¿Desea continuar?');
  } 
  return result;
}

function GrabaEncargoParticular()
{
   // Chequea formulario tag 5
   if ( $('idpublicidad').value == '-' )
   {
      alert( 'Debe seleccionar como nos ha conocido.' );
      return false;
   } 
   if ( $('idno_aviso').checked == false )
   {
      alert( 'Debe aceptar las condiciones de servicio.' );
      $('idno_aviso').focus();
      return false;
   } 

   new Ajax.Updater( 
                     'columna_ppal2', 
                     'garisapi2public.dll?id=gf',
                     {
                       method: 'post',
                       onComplete: function (response)
                                   {
                                   }
                     } 
                   );
}

function FormularioParticular( tab )
{
   // Chequea valores
   var taborigen = '';
   var error = false;
   var text = '';
   var parameters = new Object();
   
   if ( $('idtag') )
     taborigen = $('idtag').value;
   
   // Chequea formulario tag 1
   if ( taborigen == '1' )
   {
     if ( $('idnombre').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir el nombre';     
        $('idnombre').focus();
     } 
     else if ( $('idapellidos').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir los apellidos';     
        $('idapellidos').focus();
     } 
     else if ( $('idmovil').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir el número de móvil';
        $('idmovil').focus();
     } 
     else if ( $('idemail').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir su email';
        $('idemail').focus();
     } 
     else if ( $('idemail').value != $('idr_email').value )
     {
        error = true;
        if ( $('idr_email').value.length == 0 )
          text = 'Debe de repetir su email';
        else
          text = 'Los dos email deben de ser iguales.';
        $('idr_email').focus();
     } 
     else
     {
        // crea parametros a enviar     
        parameters.taborigen = $('idtag').value;
        parameters.nombre = $('idnombre').value;
        parameters.apellidos = $('idapellidos').value;
        parameters.movil = $('idmovil').value;
        parameters.telefono = $('idtelefono').value;
        parameters.email = $('idemail').value;
     }
   }
   
   // Chequea formulario tag 2
   if ( taborigen == '2' )
   {
     if ( $('idpais').value.length == 0 )
     {
        error = true;
        text = 'Debe seleccionar un país';     
        $('idpais').focus();
     } 
     else if ( $('idmatricula').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir la matrícula';     
        $('idmatricula').focus();
     } 
     else if ( $('idcombustible').value == '-' )
     {
        error = true;
        text = 'Debe seleccionar tipo combustible';
        $('idcombustible').focus();
     } 
     else if ( $('idfmatriculacion').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir fecha 1ª matriculación';
        $('idfmatriculacion').focus();
     } 
     else if ( $('idkilometraje').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir kilometraje';
        $('idkilometraje').focus();
     } 
     else if ( $('idformtipovh').value.length == 0 )
     {
        error = true;
        text = 'Debe seleccionar su vehículo';
     } 
     else if ( $('idcp').value.length == 0 )
     {
        error = true;
        text = 'Debe introducir su código postal';
        $('idcp').focus();
     } 
     else if ( $('idpoblacion').value == '-' )
     {
        error = true;
        text = 'Debe seleccionar la población';
        $('idpoblacion').focus();
     } 
     else if ( $('idprovincia').value == '-' )
     {
        error = true;
        text = 'Debe seleccionar provincia';
        $('idprovincia').focus();
     } 
     else
     {
        // crea parametros a enviar     
        parameters.taborigen = $('idtag').value;
        parameters.pais = $('idpais').value;
        parameters.matricula = $('idmatricula').value;
        parameters.kilometraje = $('idkilometraje').value;
        parameters.fmatriculacion = $('idfmatriculacion').value;
        parameters.combustible = $('idcombustible').value;
        parameters.tipovh = $('idformtipovh').value;
        parameters.vh = $('idvh').value;
        parameters.marca = $('idformmarca').value;
        parameters.modelo = $('idformmodelo').value;
        parameters.version = $('idformversion').value;
        parameters.cp = $('idcp').value;
        parameters.poblacion = $('idpoblacion').value;
        parameters.provincia = $('idprovincia').value;
     }
   }

   // Chequea formulario tag 3
   if ( taborigen == '3' )
   {
     if ( $('idtipovehiculo').value == '-' )
     {
        error = true;
        text = 'Debe seleccionar estado vehículo';     
        $('idtipovehiculo').focus();
     } 
     else if ( $('idseldanos').value.length == 0 )
     {
        error = true;
        text = 'Debe seleccionar estado de los daños';     
     } 
     else
     {
        // crea parametros a enviar     
        parameters.taborigen = $('idtag').value;
        parameters.tipovehiculo = $('idtipovehiculo').value;
        parameters.seldanos = $('idseldanos').value;
        parameters.dano1 = CheckChk('tras_izq');
        parameters.dano2 = CheckChk('lat_izq');
        parameters.dano3 = CheckChk('front_izq');
        parameters.dano4 = CheckChk('tras_cent');
        parameters.dano5 = CheckChk('front_cent');
        parameters.dano6 = CheckChk('tras_der');
        parameters.dano7 = CheckChk('lat_der');
        parameters.dano8 = CheckChk('front_der');
        parameters.dano9 = CheckChk('bajos');
        parameters.dano10 = CheckChk('techo');
        parameters.dano11 = CheckChk('interior');
        parameters.dano12 = CheckChk('airbag');
        parameters.dano13 = CheckChk('motor');
        parameters.dano14 = CheckChk('cambios');
        parameters.dano15 = CheckChk('suspension');
        parameters.dano16 = CheckChk('direccion');
     }
   }

   if ( error )
   {
     if ( text.length )
       alert( text );
     return false;     
   }

   if ( tab == '2' )
   {
      datePickerController.cleanUp();
   }
 
   new Ajax.Updater( 'contenido', 
                     'garisapi2public.dll?id=fp&t=' + tab,
                     {
                       method: 'post',
                       parameters: parameters,
                       onComplete: function (response)
                                   {
                                       if ( tab == '2' )
                                       {
                                         // Regenera los calendarios
                                         datePickerController.create();
                                         // Destruye ventana si ya existia
                                         if ( typeof(ventana_seleccion_vh) != 'undefined' )
                                           ventana_seleccion_vh.container.innerHTML = '';
                                         // Crea ventana seleccion vh
                                         ventana_seleccion_vh = window_factory($('lanzar_seleccion_vh'));
                                         ventana_seleccion_vh.href = 'garisapi2public.dll?id=sv';
                                         ventana_seleccion_vh.options.beforeOpen = Comprueba_SeleccionVh;
                                       }
                                       if ( tab == '3' )
                                       {
                                         // Destruye ventana si ya existia
                                         if ( typeof(ventana_seleccion_vh) != 'undefined' )
                                           ventana_seleccion_vh.container.innerHTML = '';
                                         // Crea ventana seleccion vh
                                         ventana_seleccion_vh = window_factory($('lanzar_seleccion_vh'));
                                         ventana_seleccion_vh.href = 'garisapi2public.dll?id=sd';
                                         ventana_seleccion_vh.options.afterClose = SeleccionarDanos;
                                       }
                                       if ( tab == '4')
                                       {
                                         // Sustituye check                                           
                                         FancyForm.start();
                                         // Destruye ventana
                                         if ( typeof(ventana_seleccion_vh) != 'undefined' )
                                           ventana_seleccion_vh.container.innerHTML = '';
                                         // Crea ventana seleccion files
                                         ventana_seleccion_vh = window_factory($('lanzar_seleccion_vh'));
                                         ventana_seleccion_vh.href = 'garisapi2public.dll?id=sf';
                                         ventana_seleccion_vh.options.afterClose = FinSubirFicheros;
                                      }
                                   }
                     } );
}


//---------- FIN ISIDRO JAVASCRIPT
function Muestra_Cuadro(id) {
	$('cuadro_generico').style.display = 'none';
	if(id=='cuadro_aseguradoras'){
		$('cuadro_cliente_profesional').style.display = 'none';
		$('cuadro_proveedor_profesional').style.display = 'none';
		$('cuadro_particular').style.display = 'none';
		new Effect.Appear('cuadro_aseguradoras'); 
		new Effect.Highlight('cuadro_aseguradoras', { startcolor: '#ebf1eb', endcolor: '#fbe285', restorecolor: '#fbe285', queue: 'end'});
		return false;
	}
	if(id=='cuadro_proveedor_profesional'){
		$('cuadro_cliente_profesional').style.display = 'none';
		$('cuadro_aseguradoras').style.display = 'none';
		$('cuadro_particular').style.display = 'none';
		new Effect.Appear('cuadro_proveedor_profesional'); 
		new Effect.Highlight('cuadro_proveedor_profesional', { startcolor: '#ebf1eb', endcolor: '#fbe285', restorecolor: '#fbe285', queue: 'end'});
		return false;
	}
	if(id=='cuadro_particular'){
		$('cuadro_cliente_profesional').style.display = 'none';
		$('cuadro_aseguradoras').style.display = 'none';
		$('cuadro_proveedor_profesional').style.display = 'none';
		new Effect.Appear('cuadro_particular'); 
		new Effect.Highlight('cuadro_particular', { startcolor: '#ebf1eb', endcolor: '#fbe285', restorecolor: '#fbe285', queue: 'end'});
		return false;
	}
	if(id=='cuadro_cliente_profesional'){
		$('cuadro_particular').style.display = 'none';
		$('cuadro_aseguradoras').style.display = 'none';
		$('cuadro_proveedor_profesional').style.display = 'none';
		new Effect.Appear('cuadro_cliente_profesional'); 
		new Effect.Highlight('cuadro_cliente_profesional', { startcolor: '#ebf1eb', endcolor: '#fbe285', restorecolor: '#fbe285', queue: 'end'});
		return false;
	}
	
}

function Desplegar_Vh(vh, tipo){
	fila_plegar=document.getElementsByClassName("fila_seleccionada");
	if(fila_plegar.length > 0){
		$($(fila_plegar[0]).id+'_datos2').innerHTML = '';
		$($(fila_plegar[0]).id+'_datos').style.display = 'none';
		$(fila_plegar[0]).className = '';
	}
	vh.className = 'fila_seleccionada';
	$(vh.id+'_datos').style.display = 'block';
	if(tipo == 'cliente')
	new Ajax.Updater(vh.id+'_datos2', 'vh_subasta_cliente.html', {method: 'get'});
	else
	new Ajax.Updater(vh.id+'_datos2', 'vh_subasta.html', {method: 'get'});	
	
	
}

function Cambiar_Clase_Listado(obj,clase){
	if($(obj).className != 'fila_seleccionada')
		$(obj).className = clase;
}

function Actualizar_menu_vh(div){
	// Resetear estado de todas las opciones
	$('generales').className = 'mtb_btn_off';
	$('documentos').className = 'mtb_btn_off';
	$('fotos').className = 'mtb_btn_off';
	$('economicos').className = 'mtb_btn_off';
	$('lugar').className = 'mtb_btn_off';
	$('recogida').className = 'mtb_btn_off';
	$('observaciones').className = 'mtb_btn_off';
	$('transporte').className = 'mtb_btn_off';
	$('danios').className = 'mtb_btn_off';
	
	// Poner en activo la opcion seleccionada
	$(div).className = 'mtv_btn_on';
	}
// ------------------------------------------------------ GENRICO -----------------------------------
function Cambiar_Clase(obj,clase){
	$(obj).className = clase;
}

function cpValid(cp) {
	var resultado;
	var n = Number(cp.value);
	if(isNaN(n) || cp.value.length!=5) {
		resultado = false;
	}
	else resultado = true;
	return resultado;
}

function Comprobar_Formulario_Respuesta(){
	var msg = 'Debe rellenar correctamente los siguientes campos:\n',correcto=true;		
	if($('tipo_vehiculo').value.length==0){
		msg = msg+'Tipo de vehiculo\n';
		correcto=false;
	}
	if($('estado_respuesta').value.length==0){
		msg = msg+'Estado de la respuesta\n';
		correcto=false;
	}
	
	if($('fecha_visita').value.length==0){
		msg = msg+'Fecha de la visita\n';
		correcto=false;
	}
		
		
	if(!correcto)
		alert(msg);
	return correcto;		
}

function Comprobar_Formulario_Nuevo(){
	var msg = 'Debe rellenar correctamente los siguientes campos:\n',correcto=true;
	if($('tipo_intervencion').value.length==0){
		msg = msg+'Tipo de intervencion\n';
		correcto=false;
	}
		
	if($('ref_master').value.length==0){
		msg = msg+'Ref. Master\n';
		correcto=false;
	}
		
	if($('n_siniestro').value.length==0){
		msg = msg+'N&deg; de Siniestro\n';
		correcto=false;
	}
		
	if($('tipo_siniestro').value.length==0){
		msg = msg+'Tipo de Siniestro\n';
		correcto=false;
	}
		
	if($('fecha_siniestro').value.length==0){
		msg = msg+'Fecha del siniestro\n';
		correcto=false;
	}
		
	if($('nombre_conductor').value.length==0){
		msg = msg+'Nombre del conductor\n';
		correcto=false;
	}
		
	if(!tlfValid($('tlf_conductor'))){
		msg = msg+'Telefono del conductor. Debe estar compuesto de 9 numeros.\n';
		correcto=false;
	}
		
	if($('fecha_declaracion').value.length==0){
		msg = msg+'Fecha de la declaracion\n';
		correcto=false;
	}
		
	if($('vehiculo_peritar').value.length==0){
		msg = msg+'Vehiculo a peritar\n';
		correcto=false;
	}
		
	if($('lesiones_si').checked==false && $('lesiones_no').checked==false){
		msg = msg+'Lesiones\n';
		correcto=false;
	}
		
	if($('lugar_siniestro').value.length==0){
		msg = msg+'Lugar del siniestro\n';
		correcto=false;
	}
		
	if($('version_siniestro').value.length==0){
		msg = msg+'Version del siniestro\n';
		correcto=false;
	}
		
	if($('compania').value.length==0){
		msg = msg+'Compania\n';
		correcto=false;
	}
		
	if($('poliza').value.length==0){
		msg = msg+'N de Poliza\n';
		correcto=false;
	}
		
	if($('garantia').value.length==0){
		msg = msg+'Garantia Contratada\n';
		correcto=false;
	}
		
	if($('nombre_asegurado').value.length==0){
		msg = msg+'Nombre del asegurado\n';
		correcto=false;
	}
		
	if($('tlf_asegurado').value.length==0){
		msg = msg+'Telefono del Asegurado\n';
		correcto=false;
	}
		
	if($('garantia').value.length==0){
		msg = msg+'Garantia Contratada\n';
		correcto=false;
	}
		
	if($('penalizaciones_si').checked==false && $('penalizaciones_no').checked==false){
		msg = msg+'Franquicia\n';
		correcto=false;
	}
		
	if($('tipo_f_fija').checked==false && $('tipo_f_per').checked==false){
		msg = msg+'Tipo de Franquicia\n';
		correcto=false;
	}
		
	if($('compromiso_pago_si').checked==false && $('compromiso_pago_no').checked==false){
		msg = msg+'Compromiso de Pago\n';
		correcto=false;
	}
		
	if($('matricula').value.length==0){
		msg = msg+'Matricula\n';
		correcto=false;
	}
		
	if($('fecha_1matriculacion').value.length==0){
		msg = msg+'Fecha de la 1a Matriculacion\n';
		correcto=false;
	}
		
	if($('combustible').value.length==0){
		msg = msg+'Combustible\n';
		correcto=false;
	}
		
	if($('tipo_vehiculo').value.length==0){
		msg = msg+'Tipo de vehiculo\n';
		correcto=false;
	}
		
	if($('marca').value.length==0){
		msg = msg+'Marca\n';
		correcto=false;
	}
		
	if($('modelo').value.length==0){
		msg = msg+'Modelo\n';
		correcto=false;
	}
		
	if($('chasis').value.length==0){
		msg = msg+'No de Chasis\n';
		correcto=false;
	}
		
	if($('color').value.length==0){
		msg = msg+'Color\n';
		correcto=false;
	}
		
	if($('kilometraje').value.length==0){
		msg = msg+'Kilometraje\n';
		correcto=false;
	}
		
	if($('observaciones_danos').value.length==0){
		msg = msg+'Observaciones sobre los danos\n';
		correcto=false;
	}
		
	if($('matricula_cont').value.length==0){
		msg = msg+'Matricula del vehiculo contrario\n';
		correcto=false;
	}
		
	if($('fecha_1matriculacion_cont').value.length==0){
		msg = msg+'Fecha de 1a matriculacion del vehiculo contrario\n';
		correcto=false;
	}
		
	if($('combustible_cont').value.length==0){
		msg = msg+'Combustible del veh&iacute;culo contrario\n';
		correcto=false;
	}
		
	if($('tipo_vehiculo_cont').value.length==0){
		msg = msg+'Tipo de vehiculo del contrario\n';
		correcto=false;
	}
		
	if($('marca_cont').value.length==0){
		msg = msg+'Marca del vehiculo contrario\n';
		correcto=false;
	}
		
	if($('modelo_cont').value.length==0){
		msg = msg+'Modelo del vehiculo contrario\n';
		correcto=false;
	}
		
	if($('color_cont').value.length==0){
		msg = msg+'Color del vehiculo contrario\n';
		correcto=false;
	}
		
	if($('nombre_cont').value.length==0){
		msg = msg+'Nombre y Apellidos del Contrario\n';
		correcto=false;
	}
		
	if($('tlf_cont').value.length==0){
		msg = msg+'Telefono del Contrario\n';
		correcto=false;
	}
		
	if($('observaciones_danos_cont').value.length==0){
		msg = msg+'Observaciones sobre los danos del contrario\n';
		correcto=false;
	}
		
	if($('tipo_lugar').value.length==0){
		msg = msg+'Tipo de lugar de intervencion\n';
		correcto=false;
	}
		
	if($('cif_taller').value.length==0){
		msg = msg+'CIF/NIF del Taller\n';
		correcto=false;
	}
		
	if($('direccion_lugar').value.length==0){
		msg = msg+'Direccion del lugar de intervencion\n';
		correcto=false;
	}
		
	if($('direccion_complemento').value.length==0){
		msg = msg+'Complemento Direccion del lugar de intervencion\n';
		correcto=false;
	}
		
	if($('poblacion_lugar').value.length==0){
		msg = msg+'Poblacion del lugar de intervencion\n';
		correcto=false;
	}
		
	if(!tlfValid($('fax_lugar'))){
		msg = msg+'Fax del lugar\n';
		correcto=false;
	}
		
	if($('mail_lugar').value.length==0){
		msg = msg+'E-mail del lugar\n';
		correcto=false;
	}
		
	if($('fecha_intervencion').value.length==0){
		msg = msg+'Fecha para la intervencion\n';
		correcto=false;
	}
		
	if($('precio_hora').value.length==0){
		msg = msg+'Precio por Hora\n';
		correcto=false;
	}
		
	if($('descuento_sobre_total').value.length==0){
		msg = msg+'% de Descuento sobre el Total\n';
		correcto=false;
	}
		
	if($('descuento_materiales').value.length==0){
		msg = msg+'% de Descuento en Materiales\n';
		correcto=false;
	}
		
	if($('descuento_mano_obra').value.length==0){
		msg = msg+'% de Descuento en Mano de Obra\n';
		correcto=false;
	}
		
	if($('descuento_pintura').value.length==0){
		msg = msg+'% de Descuento en Pintura\n';
		correcto=false;
	}
		
	if(!correcto)
		alert(msg);
	return correcto;		
}


// ------------------------------------------------------ MODELO ESPECFICO DE VEHCULO --------------
function Seleccionar_Fila(fila,sufijo,valor){
	if(valor)
		$('modelo_hidden'+sufijo).value = valor;

	var total = $(fila).cells.length;
	for(var i=0;i<total;i++){
		$('fila_seleccionada'+sufijo).cells.item(i).innerHTML = $(fila).cells.item(i).innerHTML;
		}
	$('div_result'+sufijo).style.display='inline';
	$('div_tabla'+sufijo).style.display='none';
}

function Mostrar_Tabla(sufijo){
	$('div_result'+sufijo).style.display='none';
	$('div_tabla'+sufijo).style.display='inline';
	}


//--------------------------------------------------------- PIEZAS DAADAS -----------------------
// Cambia la clase de plegado a desplegado o biceversa para que el icono del titulo sea el correspondiente al estado del fieldset
function Plegar_Desplegar(obj,num){
	if(!num) num = '';
	if($(obj).className == 'desplegar'+num){
		$(obj).className = 	'plegar'+num;
		
			
	}else
		$(obj).className = 	'desplegar'+num;
	}
	
	
	
function Actualizar_Sortables(sufijo){
	 Sortable.create('piezas_danadas'+sufijo,{
       tag:'div',
       dropOnEmpty: true, 
       containment:["piezas_danadas"+sufijo,"piezas_posibles"+sufijo],
       constraint:false});
      Sortable.create('piezas_posibles'+sufijo,{
       tag:'div',
       dropOnEmpty: true, 
       containment:['piezas_danadas'+sufijo,'piezas_posibles'+sufijo],
       constraint:false});
       Sortable.create('piezas'+sufijo,{
       tag:'div',
       only:'pieza'
       });
	   }
	   
	function ActualizarInput(div,input){
		document.getElementById(div).value = Sortable.serialize(input);
	}

// Elimina las piezas de una zona al des-seleccionarlo
function Elimina_Piezas(id,zona){
	var piezas,i,num_divs;
	piezas=document.getElementById(id).getElementsByTagName("div");
	for(i=0;i<piezas.length;i++){
		if(piezas[i].id.substring(0,zona.length)==zona){
			$(piezas[i]).remove();
			i--;
		}
	}
}

function Actualiza_Piezas(checkbox,sufijo){
	if(checkbox.checked==false){
		Elimina_Piezas('piezas'+sufijo,checkbox.id);
	} else{
		new Ajax.Updater('piezas_posibles'+sufijo, 'generico.php?zona='+checkbox.id+'&vehiculo='+$('tipo_vehiculo'+sufijo).options
				[$('tipo_vehiculo'+sufijo).selectedIndex].value, {onComplete:function(){Actualizar_Sortables(sufijo)},method: 'get',insertion:'bottom'});
		Effect.Pulsate('blink');
	} 
}
function Limpiar_Piezas(id,id2){
	var lista_piezas,i,inputs;
	lista_piezas=document.getElementById(id).getElementsByClassName("pieza");
	for(i=0;i<lista_piezas.length;i++){
		$(lista_piezas[i]).remove();
	}
	inputs=document.getElementById(id2).getElementsByTagName("input");
	for(i=0;i<inputs.length;i++){
		$(inputs[i]).checked=false;
	}
}

// ----------------------------------------------------------------------------- LUGAR DE INTERVENCION ------------------------

function Actualizar_Lugar(valor_lugar){
	if(valor_lugar=='Concertado'){
		$('cp_lugar_busq').disabled=false;
		$('provincia_lugar_busq').disabled=false;
		$('buscar_talleres').disabled=false;
		$('nombre_lugar_busq').disabled=false;
		$('tlf_lugar_busq').disabled=false;
		
	}else{
		$('cp_lugar_busq').disabled=true;
		$('provincia_lugar_busq').disabled=true;
		$('buscar_talleres').disabled=true;
		$('nombre_lugar_busq').disabled=true;
		$('tlf_lugar_busq').disabled=true;
	}
}

function Buscar_Talleres(){
	var cp = $('cp_lugar_busq').value;
	var provincia = $('provincia_lugar_busq').value;
	var nombre = $('nombre_lugar_busq').value;
	if(cpValid($('cp_lugar_busq')) || provincia != ''){
		new Ajax.Updater('div_tabla_taller', 'generico.php?cp='+cp+'&provincia='+provincia+'&nombre='+nombre, {method: 'get'});
	}else
		alert("Debe introducir al menos un valor correcto de cp o de provincia.");
	
}

function Cargar_Taller(taller_id){
	new Ajax.Request("generico.php?taller_id="+taller_id, {
  method: 'get',
  onSuccess: function(response) {
	var valores,input,txt,i;
    valores = response.responseText;
	valores = valores.split(",");
	for(i=1;i<=valores.length;i++){
		txt = valores[i];
		dato = txt.split(":");
		$(dato[0]).value = dato[1];
	}
  }
});
	}
	


function emailValid(el) { 
	 em=/[\w-\.]+@[\w-\.]+[a-z]+/i; 
	  if (!em.test(el.value)) { 
		  alert('Por favor, introduzca un email valido.'); 
		  el.select(); 
		  return false;
	  } 
	  else return true;
} 

function Input_Filled(nombre, element) {
	if((element.value=='')||(element.value=='nada')) {
		alert("Por favor, rellene el campo "+nombre+".");
		return false;
	}
	else return true;
}

function tlfValid(tlf){
	var n = Number(tlf.value);
	if(isNaN(n) || tlf.value.length!=9){
		return false;
	}
	else return true;
}

// Funcin que comprueba la entrada de datos
function CompruebaDatos(elCIF) 
{
  var resul = false;
  var temp = elCIF.value.toUpperCase(); // pasar a maysculas

  if (!/^[A-Za-z0-9]{9}$/.test(temp))  // Son 9 dgitos? 

    	alert("Longitud incorrecta, un CIF consta de 9 dgitos");

  else if (!/^[ABCDEFGHKLMNPQS]/.test(temp)) // Es una letra de las admitidas ?

     alert("El primer dgito es incorrecto, debe ser una letra de las siguientes: A,B,C,D,E,F,G,H,K,L,M,N,P,Q,S ");

  else 

     resul = true;

  return resul;
}




// Funcin de validacin del CIF, indica el dgito de control.
// La funcin recibe el CIF completo: A58818501
function ValidaCIF(elCIF) 
{

  var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
  var temp = 0; 
  var temp1;

  
  for( i = 2; i <= 6; i += 2 ) 
    {
      temp = temp + v1[ parseInt(elCIF.value.substr(i-1,1)) ];
      temp = temp + parseInt(elCIF.value.substr(i,1));
    };

  temp = temp + v1[ parseInt(elCIF.value.substr(7,1)) ];

  temp = (10 - ( temp % 10));

  if( temp == 10 )
    alert( "El dgito de control es: J  0" );
  else
    alert( "El dgito de control es: "+temp ); 

  return true;
}

function cambiar_visibilidad(div1, div2){
	if ($(div1).style.display != 'none'){
		$(div1).style.display='none';
		$(div2).style.display='block';
	}
}


function Actualizar_menu_bid_clientes(opcion){
	if (opcion == 'pujas'){
		$('pujas').className = 'mtv_btn_on';
		$('encargo').className ='mtb_btn_off';
		$('docs').className ='mtb_btn_off';
	}else if(opcion == 'encargo'){
			$('encargo').className = 'mtv_btn_on';
			$('pujas').className ='mtb_btn_off';
			$('docs').className ='mtb_btn_off';
		}else{
			$('docs').className = 'mtv_btn_on';
			$('pujas').className ='mtb_btn_off';
			$('encargo').className ='mtb_btn_off';
			}
}

// --------------------- PROVEEDOR NUEVO ENCARGO -------------------------------
function Switch_Taller(valor){
	switch(valor){
		case "taller":
			$('div_taller').style.display = 'block';
			$('div_otros').style.display = 'none';
		break;
		case "otros":
			$('div_taller').style.display = 'none';
			$('div_otros').style.display = 'block';
		break;
		
		
	}	
	
}

function Seleccionar_Taller(fila){
	$('tabla_taller').style.display = 'none';
	$('div_taller').style.display = 'none';
	$('div_otros').style.display = 'block';
	
	$('cp_lugar2').value = $(fila).cells.item(0).innerHTML;
	$('provincia_lugar2').value = $(fila).cells.item(1).innerHTML;
	$('poblacion_lugar2').value = $(fila).cells.item(2).innerHTML;
	$('tlf_fijo_lugar2').value = $(fila).cells.item(3).innerHTML;
	$('nombre_lugar2').value = $(fila).cells.item(4).innerHTML;
	
	
}

function Introducir_Manualmente(){
	$('tabla_taller').style.display = 'none';
	$('div_taller').style.display = 'none';
	$('div_otros').style.display = 'block';

	$('tipo_lugar').value = 'otros';
	
}

function Filtrar_Busqueda(){
	$('h1_listado').innerHTML = 'Resultados de la b&uacute;squeda / <a href="">Anular filtro</a>';
}



