var precio_internet = 0.0, precio_real = 0.0;
//COMPRUEBA SI ES UNA DIRECCION DE CORREO ELECTRÓNICO CORRECTA
function validaEmail(elEmail){
	/*Con expresiones regulares
	NOTA: No se contemplan extensiones de dominio de más de 4 caracteres (.museum, .store) son mut poco frecuentes
	      No se contemplan las direcciones de correo con formato IP
	1.- \w+							---> que tenga al menos una palabra
	2.- ((-\w+)|(\.\w+)|(\_\w+))*	---> que tenga cero o más palabras precedidas de un (.), un (-) o un (_)
	3.- \@							---> una y sólo una @
	4.- [A-Za-z0-9]					---> sólo caracteres normales y números
	5.- ((.|-)[A-Za-z0-9]+)*		---> solo caracteres normales y números precedidos de un (.) o un (-)
	6.- \.							---> el último punto
	7.- [A-Za-z]{2,4}				---> de 2 a 4 caracteres después del punto. (4 por .info, .name)
	*/
	//	return (elEmail.search( /\w+((-\w+)|(\.\w+)|(\_\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{2,4}/ ) != -1);
	// ¿Soporta expresiones regulares?
	var soporta = false;
	if (window.RegExp) {
		var aux = "a";
		var auxReg = new RegExp(aux);
		if (auxReg.test(aux)) soporta = true;
	}
	if (!soporta) return (elEmail.indexOf(".") > 2) && (elEmail.indexOf("@") > 0);
	var exp1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)");
	var exp2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
	return (!exp1.test(elEmail) && exp2.test(elEmail));
}

//COMPRUEBA QUE NO SE TECLEAN ESPACIOS, GUIONES, ETC
function quitaEspacios(cad){
	var malos = new String(' -.:_,');
	var nueva_cad = '';
	for (i=0;i<cad.length;i++){
		s=cad.substring(i, i+1);
		if (malos.indexOf(s)==-1) nueva_cad = nueva_cad + s;
	}
	return nueva_cad;
}

function sinEspacios(campo){
	var correcta = quitaEspacios(campo.value);
	if (correcta != campo.value){
		alert('Please, fill in this field without spaces, full stops, dashes, etc');
		campo.value = correcta;
		campo.focus();
		campo.select();
		return false;
	}else
		return true;
}

//CAMBIA EL NOMBRE DEL CAMPO PARA EL MENSAJE DE ERRORES
function nombreCampo(nomcam){
	switch (nomcam){
	   	case 'Nombre': 
			return 'First name or Trade name';
			break;
	   	case 'Apellidos': 
			return 'Surname or Contact person';
			break;
	   	case 'NumCliente': 
			return 'Licence';
			break;
	   	case 'Direccion': 
			return 'Address';
			break;
	   	case 'Poblacion':
			return 'City';
			break;
	   	case 'CodigoPostal':
			return 'ZIP / Postal code';
			break;
	   	case 'TelNumero':
			return 'Phone';
			break;
	   	case 'FaxNumero':
			return 'Fax';
			break;
	   	case 'profesion':
			return 'Profession';
			break;
	   	case 'NIF':
			return 'V.A.T. identification number';
			break;
	   	case 'CorreoElectronico':
			return 'e-mail';
			break;
	   	case 'fecha_entrega':
			return 'Preferred delivery date';
			break;
	   	default: return nomcam;
	}
}

//CONVIERTE UNA CADENA EN UN OBJETO x EL NOMBRE
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//COMPRUEBA SI LO CAMPOS CUMPLIMENTADOS SON CORRECTOS
function validaPedido(){
	var i,p,q,nm,test,num,min,max,errors='',args=validaPedido.arguments;
	for (i=0; i<(args.length-2); i+=3){
		test=args[i+2];
		val=MM_findObj(args[i]);
		if (val){ 
			nm=nombreCampo(val.name);
			if ((val=val.value)!=""){
				if (test.indexOf('isEmail')!=-1){
					p=validaEmail(val);
					if (!p) errors+='- '+nm+' must contain an e-mail address.\n';
				}else if (test!='R'){
					if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
					if (test.indexOf('inRange') != -1) {
						p=test.indexOf(':');
						min=test.substring(8,p);
						max=test.substring(p+1);
						if (val<min || max<val) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
					}
				}
			}else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n';
		}
 	}
	val=MM_findObj('tot_pedido');
	if (parseFloat(val.value) <= 0) errors+='- You must select at least one user of a product.\n';
	laProv=document.Pedido.Provincia.value;
	if (document.Pedido.Condiciones.checked==false) errors+='- You must read and accept the Terms and Conditions.\n';
	if (document.Pedido.Cliente)
		if (document.Pedido.Cliente[0].checked==true && document.Pedido.NumCliente.value=="") errors+='- If you are a client, Licence is required.\n';
//	if (document.Pedido.pastilla)
//	   if (!(document.Pedido.pastilla[0].checked || document.Pedido.pastilla[1].checked) && document.Pedido.Cliente[1].checked==true)
//	      errors+='- Debe seleccionar el tipo de dispositivo de llave electrónica .\n';
	if (errors) alert('The following error(s) occurred:\n'+errors);

	document.MM_returnValue = (errors == '');
}

if (document.images){
  var obligado=new Image();
  obligado.src="http://www.cype.es/principal/imagen/formularios/obligacionP.gif";
  var NOobligado=new Image();
  NOobligado.src="http://www.cype.es/principal/transparent.gif";
}

//PONER MARCA DE CAMPO OBLIGATORIO
function ponerObli(nombreImg,campo){
  if (document.images){
	objto=MM_findObj(campo);
    document[nombreImg].src=obligado.src;
	objto.disabled=0;

	var tb = document.getElementById('tbNOCliente');
	if (campo == 'NumCliente' && tb){
		tb.style.display = "block";
		var nc = document.getElementById('NumCliente');
		nc.focus();
	}
  }
}
//QUITAR MARCA DE CAMPO OBLIGATORIO
function quitarObli(nombreImg,campo){
  if (document.images){
	objto=MM_findObj(campo);
    document[nombreImg].src=NOobligado.src;
	objto.value="";
	objto.disabled=1;
	var tb = document.getElementById('tbNOCliente');
	if (campo == 'NumCliente' && tb) tb.style.display = "none";
  }
}

//COMPRUEBA FORMA DE PAGO EN CANARIAS
function comprobar(){
  lista =document.Pedido.Provincia;  
  laProv=lista.options[lista.selectedIndex].value;
  if (laProv.substring(0,1)=="2"){
       canarias=0; 
     }else{
       canarias=1;    
     };
  if (document.Pedido.FormaPago[0].checked && canarias==0){
      alert("La Forma de Pago para esta Provincia debe ser Tarjeta o Transferencia Bancaria");
      document.Pedido.FormaPago[1].checked=true;
  }
}

//ABRE UNA VENTANA NUEVA DEL NAVEGADOR
function AbreVentana(pagina, nombre, ancho, alto, barra_scroll,resiz) {
	var winl = (screen.width - ancho) / 2;
	var wint = (screen.height - alto) / 2;
	winprops = 'height='+alto+',width='+ancho+',top='+wint+',left='+winl+',scrollbars='+barra_scroll+',resizable='+resiz;
	win = window.open(pagina, nombre, winprops);
	if (parseInt(navigator.appVersion) >= 4) win.focus();
}

//FORMATEA UN DATO NUMERICO PARA PONER LOS PUNTOS DE LOS MILES
function PonPuntos(numero) {
 if (numero == NaN) numero = "0";
 numero = ""+numero; 
 if (numero.length > 3) {
   mod = numero.length % 3;
   resultado = (mod > 0 ? (numero.substring(0,mod)) : "");
   for (i=0 ; i < Math.floor(numero.length / 3); i++) {
    if ((mod == 0) && (i == 0))
      resultado += numero.substring(mod+ 3 * i, mod + 3 * i + 3);
    else
      resultado+= "." + numero.substring(mod + 3 * i, mod + 3 * i + 3);
   }
   return (resultado);
 }
 else return numero;
}

//FORMATEA UN DATO NUMERICO PARA PONERLO EN EUROS
function PonEuros(numeuro) {
//Redondeo a dos decimales el valor en Euros
   euros_red=""+(Math.round(numeuro*100)/100);
//Cambio el punto decimal por una coma
   punto = euros_red.indexOf(".");
   if (punto >= 0){ 
     aux = euros_red.substring(0,punto);
     aux=PonPuntos(aux)+",";
     decimales = ""+euros_red.substring(punto+1,euros_red.length);
     if (decimales.length == 1)
        decimales+= "0";
     aux += decimales;
   }else{
     aux=PonPuntos(euros_red)+",00";
   }
   return (aux);
}
//CÁLCULO DEL CARACTER DEL CONTROL DEL CIF
function controlCIF(n){
	if (!isNaN(n)){
		var digitos = new Array();
		for (i=0;i<7;i++) digitos[i]=parseInt(n.substring(i,i+1));
		var A = digitos[1] + digitos[3] + digitos[5];
		var B = 0;
		var impar = "";
		for (i=0;i<7;i+=2){
			impar = ""+(digitos[i] * 2);
			if (impar.length == 2) B = B + (parseInt(impar.substring(0,1))+parseInt(impar.substring(1,2)))
			else B = B + parseInt(impar);
		}
		var C = A + B;
		C = ""+C;
		var l = C.length;
		var uniC = 10 - parseInt(C.substring(l-1,l));
		var letras = "JABCDEFGHI";
		return(uniC+letras.charAt(uniC));
	}else return '  ';
}
//CÁLCULO DEL CARACTER DEL CONTROL DEL NIF
function controlNIF(n){
	if (!isNaN(n)){
		var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
		var resto = n % 23;
		return(letras.charAt(resto));
	}else return ' ';
}

//VALIDA UN CIF o NIF SI ES ESPAÑOL
function validaNIFCIF (campo,quePais){
	var letrasCIF = new String('ABCDEFGHKLMNPQS');
	var nifcif = quitaEspacios(campo.value);
	var v = true;
	nifcif = nifcif.toUpperCase();
	campo.value = nifcif;
	elPais = document.Pedido.Pais.value;  
	if (elPais.substring(0,1)=="1"){
		digi1=nifcif.substring(0,1);
		if (letrasCIF.indexOf(digi1)!=-1){
			if (nifcif.length != 9) v = false
			else{
				digi2=nifcif.substring(1,8);
				digi3=nifcif.substring(8,9);
				cc = controlCIF(digi2);
				v = (digi3 == cc.substring(0,1) || digi3 == cc.substring(1,2));
			}
		}else{
			l=nifcif.length;
			digi1=nifcif.substring(0,l-1);
			digi3=nifcif.substring(l-1,l);
			v = (digi3 == controlNIF(digi1));
		}
		if (!v) alert('This NIF/CIF is not correct.\nPlease, check the form and correct it.');
	}
}
function calculaImporte(uni, imp, licenciaRed){
	var suma = 0.0;
	var aux = 0.0;
	var cad = "Unidades=" + uni + ": ";
	if (uni > 1){
		for (i=2;i<=uni;i++){
			if (licenciaRed){
				if (i>3){
					aux = imp - ((imp * dto_red4) / 100);
					cad += " dto: " + dto_red4;
				}else{
					aux = imp - ((imp * dto_red23) / 100);
					cad += " dto: " + dto_red23;
				}
				if (aux < dto_red_min) aux = dto_red_min;
				suma += aux;
			}else{
				if (i>2){
					aux = imp - ((imp * dto_mono3) / 100);
					cad += " dto: " + dto_mono3;
				}else{
					aux = imp - ((imp * dto_mono2) / 100);
					cad += " dto: " + dto_mono2;
				}
				if (aux < dto_mono_min) aux = dto_mono_min;
				suma += aux;
			}
			cad += " (" + aux + ")";
		}
		//alert(cad);
	}
	return suma;
}
//CÁLCULO DEL TOTAL DEL PEDIDO INCLUIDOS LOS PORTES
function suma(){
	var pvp_eur=0.0, imp_eur = 0.0, iva_eur = 0, tot_eur = 0.0, tot_eur_prod = 0.0, iva=0, i=0, unidades=0;
	var tot_kg=0.0, imp_portes=0.0, pesodemas=0.0, preciodemas=0.0;
	var fpago=document.Pedido.FormaPago;
	var licenciaRed = false;
	var contrareembolso = (fpago[0].value == "Contra reembolso");
	var todos1 = 1, pvCjto = 0.0, tot_sinIVA = -1;
	var productoBase = false, esCliente=false, idProd = "", desProd = "", msgMod="", esModulo=false;
	var alguna_unidad = false;
	
// PRODUCTOS
	esCliente = document.Pedido.Cliente[0].checked;
	i=0;
	while (document.Pedido["uni"+i]){
//		document.Pedido["imp"+i].value="";
		document.Pedido["tot"+i].value="";
		unidades = parseInt(document.Pedido["uni"+i].value);
		if (isNaN(unidades) || unidades < 0) unidades = 0;

		document.Pedido["uni"+i].value=unidades;
		if (unidades > 1){
			todos1 = 0; 
			if (!document.Pedido.pastilla[0].checked && !document.Pedido.pastilla[1].checked){
				unidades = 0;
				document.Pedido["uni"+i].value="0";				
				alert("If you want to request several users, please, mark the type of license first");
				return false;
			}else{
				licenciaRed = document.Pedido.pastilla[0].checked;
			}
		}
		if (unidades > 0){
			cad_aux=document.Pedido["pes"+i].value;
			cad_aux=cad_aux.replace(",",".");
			tot_kg = tot_kg + (parseFloat(cad_aux) * unidades);

			cad_aux=document.Pedido["pvi"+i].value;
			cad_aux=cad_aux.replace(",",".");
			pvp_eur = parseFloat(cad_aux);
			imp_eur = pvp_eur + calculaImporte(unidades, pvp_eur, licenciaRed);
			tot_sinIVA = tot_sinIVA + imp_eur;
//			document.Pedido["imp"+i].value=PonEuros(imp_eur);
			tot_eur_prod = imp_eur + iva_eur;
			document.Pedido["tot"+i].value=PonEuros(tot_eur_prod);
			tot_eur = tot_eur + (Math.round(tot_eur_prod*100)/100);
		}
		if (document.Pedido["uni"+i].value != "0") alguna_unidad = true; //Para saber si calculo los portes
		i++;
	}

// PORTES
	document.Pedido.tot_portes.value="";
	if (alguna_unidad == true){
		if (tot_kg <= 2) imp_portes = 50.00
		else imp_portes = 60.00;
		document.Pedido.tot_portes.value = PonEuros(imp_portes);
	}
// TOTAL PEDIDO
	tot_eur = tot_eur + imp_portes;	
	document.Pedido.tot_pedido.value=PonEuros(tot_eur);
}
