// JavaScript Document
var textstring='';



function cogefecha() {
	var hoy  = new Date();
	var dia  = hoy.getDate();
	var mes  = hoy.getMonth() +1;
	var anyo = hoy.getFullYear();
	var fh   = dia + '/' + mes + '/' + anyo;
	return fh
}

function quitaacentos(a)
{
	var newStr = a;
	newStr = newStr.replace(/[áâäà]/g, "a");
	newStr = newStr.replace(/[ÁÀÄÂ]/g, "A");
	newStr = newStr.replace(/[éèëê]/g, "e");
	newStr = newStr.replace(/[ÉÈËÊ]/g, "E");
	newStr = newStr.replace(/[íìïî]/g, "i");
	newStr = newStr.replace(/[ÍÌÏÎ]/g, "I");
	newStr = newStr.replace(/[óòöô]/g, "o");
	newStr = newStr.replace(/[ÓÒÖÎ]/g, "O");
	newStr = newStr.replace(/[úûüû]/g, "u");
	newStr = newStr.replace(/[ÚÙÜÛ]/g, "U");
	newStr = newStr.replace(/[ç]/g, "c");
	newStr = newStr.replace(/[Ç]/g, "C");
	newStr = newStr.replace(/[ñ]/g, "n");
	newStr = newStr.replace(/[Ñ]/g, "N");
	newStr = newStr.replace(/[´¨`^]/g, "");
	return newStr;
}

function finaliza()
{
	var elements = document.formulario;
    for(i = 0; i < elements.length; i++) {
        var element = elements[i];
		if (element.type == "text")
	 		element.value = quitaacentos(element.value);
	}
}

function inicializa()
{

	for (i=0;i<4;i++) {
		var indice = 13 + (i*5);
		document.formulario.elements[indice+0].selectedIndex=0;
	}
/*
	//	Solo para testear 
	var box = document.formulario;
	box.cliente.value = 'Joselito';
	box.nombreComercial.value = 'La transportista';
	box.direccion.value = 'Av. de los Ordenadores, 47';
	box.localidad.value = 'Villar de los Villarejos';
	box.provincia.value = 'Madrid';
	box.codigoPostal.value = '28555';
	box.persona.value = 'Juan luis de los palotes';
	box.cargo.value = 'Director Comercial';
	box.telefono.value = '918755555';
	box.movil.value = '636555555';
	box.fax.value = '918735556';
	box.mail.value = 'aaa@aaa.com';
	
	for (i=0;i<1;i++) {
		var indice = 13 + (i*5);
		box.elements[indice+0].selectedIndex=1;
		box.elements[indice+1].value="10.5m";
		box.elements[indice+2].value="2.3m";
		box.elements[indice+3].value="2.4m";
		box.elements[indice+4].value="10.5tm";
		for (j=1;j<5;j++)
		{
			box.elements[indice+j].disabled=false;
			box.elements[indice+j].style.backgroundColor = "#ffffff";
		}
	}
	box.LocalidadOrigen.value = 'Santiago de Compostela';
	box.ProvinciaOrigen.value = 'A Coruña';
	box.LocalidadDestino.value = 'Las Alquerias del Niño Perdido Por Burriana';
	box.ProvinciaDestino.value = 'Valencia';
*/
	

	document.formulario.fecha.value = cogefecha();
	textstring = '';

	document.formulario.cliente.focus();
}

function activabotones(valor)
{
	for (i=0;i<4;i++) 
	{
	   	var numero=(i+1).toString();
		if (numero==(valor))
		{
			var indice = 13 + (i*5);
		    dato=(document.formulario.elements[indice].selectedIndex<1);
			for (j=1;j<5;j++)
			{	
				box=document.formulario.elements[indice+j];
				box.disabled=dato;
			
				if (dato) {
					box.value="";
					box.style.backgroundColor = "#cccccc";
				}
				else
				{
					box.style.backgroundColor = "#ffffff";
				}
			}
		}
	}
	return (true);
}

function checkMail()
{
	var x = document.formulario.mail.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) {
		return(true);
	} else  {
		alert('CORREO ELECTRONICO incorrecto');
		document.formulario.mail.focus();
		return (false);
	}
	return (true);
}

function checkCodigoPostal()
{

	var x = document.formulario.codigoPostal.value.toString();
	if ((x>=1001) && (x<=52999)) {
		return (true);
	} else {
		alert('CODIGO POSTAL incorrecto');
		document.formulario.codigoPostal.focus();
		return (false);
	}
	return (true);
}


function checkit()
{
	
	// In textstring I gather the data that are finally written to the textarea.
	var errCl = new Array ( "Debe especificar la FECHA",
						    "Debe especificar el CLIENTE",
						 	"Debe especificar el NOMBRE COMERCIAL",
   						 	"Debe especificar la DIRECCION",
						 	"Debe especificar la LOCALIDAD",
						 	"Debe especificar la PROVINCIA",
						 	"Debe especificar el CODIGO POSTAL",
						 	"Debe especificar la PERSONA DE CONTACTO",
						 	"Debe especificar el CARGO",
						 	"Debe especificar el TELEFONO DE CONTACTO",
						 	"Debe especificar el MOVIL",
						 	"Debe especificar el FAX",
							"Debe especificar el CORREO ELECTRONICO");
	var datCl = new Array ( "FECHA: ",
						    "CLIENTE: ",
						 	"N.COMERCIAL: ",
   						 	"DIRECCION: ",
						 	"LOCALIDAD: ",
						 	"PROVINCIA: ",
						 	"C.POSTAL: ",
						 	"P.CONTACTO: ",
						 	"CARGO: ",
						 	"TEL.CONTACTO: ",
						 	"MOVIL: ",
						 	"FAX: ",
							"EMAIL: ");
	
//	var textstring = '';
	
	// Ponemos la fecha en textstring
	
	textstring = 'FECHA: '+document.formulario.fecha.value+'\n';
	

	// First of all, have all the text boxes been filled in?
	// This part is treated in the normal page.
	// I put all boxes and their values in textstring

	// Empezamos con i=1 proque el campo fecha se rellena automaticamete
	for (i=1;i<13;i++) {
		var box = document.forms[0].elements[i];
		if ((i!=10) && (i!=11)) { //movil y fax no son obligatorios
			if (!box.value) {
				alert(errCl[i]);
				box.focus()
				return (false);
			}
		}
		textstring += datCl[i]+ box.value + '\n';
		box.value = unescape(escape(box.value));
	}
	
	if (!checkCodigoPostal())
		return(false);
	if (!checkMail())
		return(false);
		

	
	// Comprobamos los vehículos Empiezan en el 13 y acaban en el 36
	// See what checkboxes are checked. They are elements 13-16
	var errVh = new Array ( "Debe seleccionar un TIPO DE VEHICULO",
						 	"Debe especificar el LARGO DEL VEHICULO",
   						 	"Debe especificar el ANCHO DEL VEHICULO",
						 	"Debe especificar el ALTO DEL VEHICULO",
							"Debe especificar el PESO DEL VEHICULO");
	var datVh = new Array ( "   Tipo: ",
						 	"   Largo: ",
   						 	"   Ancho ",
   						 	"   Alto: ",
   						 	"   Peso: ");
	
	var rellenado = new Array (false, false, false, false);
	rellenadoalguno=false;
	for (i=0;i<4;i++)
	{
		indice = 13 + (i*5);
		rellenado[i]=(document.formulario.elements[indice].selectedIndex>0);
		rellenadoalguno |= rellenado[i];
	}
	if (!rellenadoalguno){
		alert(errVh[0]);
		document.formulario.elements[13].focus();
		return (false);
	}
	for (i=0;i<4;i++)
	{
		if (rellenado[i]) 
		{
			textstring += 'VEHICULO '+(i+1)+'\n';
			indice = 13 + (i*5);
			textstring += datVh[0];
			textstring += document.formulario.elements[indice].value + ' ';
			for (j=1;j<5;j++) 
			{
				var box = document.formulario.elements[indice+j];
				// comprobamos que en la lista haya un tipo de vehículo seleccionado
				if (box.value=="")
				{
					alert(errVh[j]);
					box.focus();
					return (false);
				} 
				textstring += datVh[j];
				textstring += document.formulario.elements[indice+j].value + ' ';
				if (j==5) 
					textstring +='\n';
			}
		}
	}

	// Comprobamos la ruta que va del 33 al 38
	var errRut = new Array ("   Debe especificar la LOCALIDAD DE ORIGEN",
       					 	"   Debe especificar la PROVINCIA DE ORIGEN",
   						 	"   Debe especificar el PAIS DE ORIGEN",
       					 	"   Debe especificar la LOCALIDAD DE DESTINO",
       					 	"   Debe especificar la PROVINCIA DE DESTINO",
   						 	"   Debe especificar el PAIS DE DESTINO");
	var datRut = new Array ("ORIGEN\n   LOCALIDAD: ",
							"   PROVINCIA: ",
							"   PAIS: ",
							"\n   DESTINO\n   LOCALIDAD: ",
							"   PROVINCIA: ",
							"   PAIS: ");

	for (i=33;i<39;i++) {
		var box = document.forms[0].elements[i];
		if (box.value == "") {
			alert(errRut[i-33]);
			box.focus()
			return (false);
		}
		textstring += datRut[i-33]+box.value;
	}
	
	textstring += '\n\n';
	// por ultimo si en el campo obsevaciones hay algun dato se lo añadimos a teststring
	var box = document.forms[0].elements[39];
	if (box.value != "")
	{
		if (box.value.length>500)
		{
			alert("Ha sobrepasado la longitud máxima del campo OBSERVACIONES\nEl límite es de 500 y actualmente ocupa "+box.value.length.toString()+" caracteres.");
			
			box.focus();
			return (false);
		}
		textstring += 'OBSERVACIONES: \n' + box.value + '\n';
	}
	// Write textstring to the textarea.
	return (true);
}

function getletter(num) {
	if (num < 10) {
		return num;
	}
	else {
	    if (num == 10) { return "A" }
	    if (num == 11) { return "B" }
	    if (num == 12) { return "C" }
	    if (num == 13) { return "D" }
	    if (num == 14) { return "E" }
	    if (num == 15) { return "F" }
	}
}

function hexfromdec(num) {
	if (num > 65535) { return ("err!") }
	first = Math.round(num/4096 - .5);
	temp1 = num - first * 4096;
	second = Math.round(temp1/256 -.5);
	temp2 = temp1 - second * 256;
	third = Math.round(temp2/16 - .5);
	fourth = temp2 - third * 16;
	return (""+getletter(third)+getletter(fourth));
}


function transform(s){
	var hex=''
	var i
	for (i=0; i<s.length; i++)
	{
	
	// for debugging:
	// alert('Hex values are:' + hexfromdec( s.charCodeAt(i) ));
	// break;
		
	hex += '%'+hexfromdec( s.charCodeAt(i) )

    }
	return hex;
}



function EnviarEmail ()
{
	finaliza();

/*
	alert(textstring);
	var datos2 = transform(textstring);
	var mail_str = "lagondolesa@lagondolesa.com?subject=Solicitud de presupuesto desde la web LA GONDOLESA";
	mail_str += "&body="+datos2;
	parent.location.href = mail_str;
*/
}

	
function ValidarFormulario ()
{
	if (checkit()) {
		EnviarEmail();
		return (true);
	}
	else
		return (false);
}


function SelectAllItems()
{
   var intCount = window.document.formulario.Tipo1.options.length;
   for (i = 0; i < intCount; i++)
   {
	window.document.formulario.Tipo1.options(i).selected = true;
  }
}
