//Caracteres Documentos DNI-CIF-...
function Validar_Caracteres(evento,objeto)
{
	if(evento.keyCode) 
	{
		if(evento.keyCode != 20 && evento.keyCode != 144 && evento.keyCode != 16 && evento.keyCode != 192 && evento.keyCode != 8 && evento.keyCode != 37 && evento.keyCode != 38 && evento.keyCode != 39 && evento.keyCode != 40 && evento.keyCode != 13 && evento.keyCode != 9)
		{
			if(evento.keyCode < 96 || evento.keyCode > 105)
			{
				
				if(evento.keyCode < 48 || evento.keyCode > 90)
				{
					objeto.value = objeto.value.substring(0,(objeto.value.length)-1);
				}
				else
					if(evento.keyCode < 65 && evento.keyCode > 57 )
					{
						if(evento.keyCode > 31 )objeto.value = objeto.value.substring(0,(objeto.value.length)-1);
					}
			}
		}
	}
}

//Solo Texto
function esTexto(evento,objeto)
{
	if(evento.keyCode) 
	{
			if((evento.keyCode < 65 || evento.keyCode > 90) && (evento.keyCode != 16 && evento.keyCode != 222 && evento.keyCode != 219 && evento.keyCode != 32 && evento.keyCode != 8 && evento.keyCode != 46 && evento.keyCode != 192 && evento.keyCode != 9))
			{
					objeto.value = objeto.value.substring(0,(objeto.value.length)-1);
			}
	}
}


//Formato númerico 1.000,00
function number_format (number, decimals, dec_point, thousands_sep)
{
	var exponent = "";
	var numberstr = number.toString ();
	var eindex = numberstr.indexOf ("e");
	if (eindex > -1)
	{
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
	}
	
	if (decimals != null)
	{
		var temp = Math.pow (10, decimals);
		number = Math.round (number * temp) / temp;
	}
	var sign = number < 0 ? "-" : "";
	var integer = (number > 0 ? 
	  Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
	
	var fractional = number.toString ().substring (integer.length + sign.length);
	dec_point = dec_point != null ? dec_point : ".";
	fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
			   (dec_point + fractional.substring (1)) : "";
	if (decimals != null && decimals > 0)
	{
		for (i = fractional.length - 1, z = decimals; i < z; ++i)
		  fractional += "0";
	}
	
	thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
				  thousands_sep : null;
	if (thousands_sep != null && thousands_sep != "")
	{
		for (i = integer.length - 3; i > 0; i -= 3)
		  integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
	}
	
	return sign + integer + fractional + exponent;
}

//Fomarto frances 1.000,00
function formato_frances($num)
{
	return number_format($num,2,',','.')
}

//Solo acepta caracteres numéricos 
function Numerico(texto)
{
	var i=0;
	var caracter = texto.charAt((texto.length)-1);
	
	if( caracter != '0' && caracter != '1' && caracter != '2' && caracter != '3' && caracter != '4' && caracter != '5' && caracter != '6' && caracter != '7' && caracter != '8' && caracter != '9' )
		texto=texto.substring(0,(texto.length)-1);
	
	while(i < texto.length)
	{
		if( texto.charAt(i) != '0' && texto.charAt(i) != '1' && texto.charAt(i) != '2' && texto.charAt(i) != '3' && texto.charAt(i) != '4' && texto.charAt(i) != '5' && texto.charAt(i) != '6' && texto.charAt(i) != '7' && texto.charAt(i) != '8' && texto.charAt(i) != '9' )
			texto=texto.replace(texto.charAt(i),'');
		i++;
	}

	return texto;
}

//Solo acepta caracteres numéricos y el más:
function telefono_internacional(texto)
{
	var i;
	var caracter = texto.charAt((texto.length)-1);
	
	
	if( caracter != '+' && caracter != '0' && caracter != '1' && caracter != '2' && caracter != '3' && caracter != '4' && caracter != '5' && caracter != '6' && caracter != '7' && caracter != '8' && caracter != '9' )
	{
		texto=texto.substring(0,(texto.length)-1);
	}
	
	for(i = 0; i < texto.length; i++)
	{
		if(i == 0)
		{
			if( texto.charAt(i) != '+' && texto.charAt(i) != '0' && texto.charAt(i) != '1' && texto.charAt(i) != '2' && texto.charAt(i) != '3' && texto.charAt(i) != '4' && texto.charAt(i) != '5' && texto.charAt(i) != '6' && texto.charAt(i) != '7' && texto.charAt(i) != '8' && texto.charAt(i) != '9' )
					texto=texto.replace(texto.charAt(i),'');
		}
		else
		{
			if(texto.charAt(i) == '+')
				texto=texto.substring(0,i);
			else
			{
				if( texto.charAt(i) != '0' && texto.charAt(i) != '1' && texto.charAt(i) != '2' && texto.charAt(i) != '3' && texto.charAt(i) != '4' && texto.charAt(i) != '5' && texto.charAt(i) != '6' && texto.charAt(i) != '7' && texto.charAt(i) != '8' && texto.charAt(i) != '9' )
					texto=texto.replace(texto.charAt(i),'');
			}
		}
	}
	
	return texto;
}


function MensError(campo,mensaje)
{
  alert(mensaje);
  campo.focus();
  return false;
}
  

function esNIF(campo,obligatorio)
{
  var inicio;
 // Cojo todo menos la letra del NIF
  var resto;
  // Cojo la letra del NIF
  var patron = /\D/;
  // Todo menos digitos.
  var patron1 = /T|R|W|A|G|M|Y|F|P|D|X|B|N|J|Z|S|Q|V|H|L|C|K|E/;
  //Letras posibles.
  var Letras_Posibles = "TRWAGMYFPDXBNJZSQVHLCKE" ;
  inicio = campo.value.substring(0,campo.value.length-1);
  resto = campo.value.substring(campo.value.length-1,campo.value.length);
  resto = resto.toUpperCase();
  if(obligatorio && campo.value.length == 0)
    return(MensError(campo,"Introduzca su NIF"));
  if(campo.value.length > 0)  {
    //Busco que la letra este al final y el resto sean numeros 
   if((inicio.length == 0) || (inicio.match(patron)) || (!resto.match(patron1)))      return(MensError(campo,"El formato del NIF es incorrecto"));
    var numero_documento = ""    
for (var i=0; i < inicio.length; i++)
      numero_documento = numero_documento + inicio.charAt(i)
    // Comprueba la letra del NIF 
   var pos_corr = (numero_documento%23);
    var letra_correcta = Letras_Posibles.charAt(pos_corr);
    if (resto != letra_correcta)
      return(MensError(campo,"La letra del NIF es incorrecta"));  }  
return true;
}

function esCP(codPos,numProv,obligatorio)
	{
  var patron = /\D/;
  // Todo menos digitos.
  if(obligatorio && codPos.value.length == 0)
    return(MensError(codPos,"Introduzca el Código Postal"));
  if(codPos.value.length > 0)  { 
   if ((codPos.value.length != 5) || (codPos.value.match(patron))) 
     return(MensError(codPos,"El Código Postal debe ser un número de 5 cifras"));
    var cad1=codPos.value.substring(0,2); 
    var cad2=numProv.substring(0,2);
   
   if (cad2.length==1)
	cad2='0'+ cad2;  
   
  if (cad1 == cad2)      return true; 
   return(MensError(codPos,"El Código Postal no coincide con la Provincia seleccionada"));  }
  return true;
}

function esProvincia(nomProvincia)
{
	
	if(nomProvincia)
			return true
	else
	{
			alert('La Provincia introducida no es válida');
			return false;
	}
}


function esVia(nomVia)
{
	
	if(nomVia)
			return true
	else
	{
			alert('El tipo de Vía introducido no es correcto');
			return false;
	}
}


function esCIF(campo,obligatorio)
{
  var inicio;  	// Cojo la letra del NIF
  var resto;	// Cojo el resto -1
  var ultimo;
  var patron1 = /A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z/ //Letras posibles
  var patron3 = new RegExp(String.fromCharCode(91)+'A-J'+String.fromCharCode(93));
  var patron4 = /0|1|2|3|4|5|6|7|8|9/; //Digitos

  if(obligatorio && campo.value.length == 0)
    return(MensError(campo,"Introduzca su CIF"));

  if(campo.value.length > 0)
  {
  	inicio = campo.value.substring(0,1);
  	inicio = inicio.toUpperCase();
  	resto = campo.value.substring(1,campo.value.length-1);
  	ultimo = campo.value.substring(campo.value.length-1,campo.value.length);
  	ultimo = ultimo.toUpperCase();

    if (campo.value.length != 9)
      return(MensError(campo,"El CIF debe estar compuesto de 9 caracteres"));

    if (!inicio.match(patron1))
      return(MensError(campo,"La letra del CIF es incorrecta"));

    for(i=0;i<resto.length;i++)
    {
      if( !resto.substring(i,i+1).match(patron4) )
        return(MensError(campo,"Las posiciones del 2 al 8 del CIF solo pueden ser numeros "));
    }

    if (!ultimo.match(patron4) && !ultimo.match(patron3))
   	  return(MensError(campo,"El ultimo caracter es incorrecto"));

   	//Comprueba que la letra es correcta
    N1 = resto.charAt(0)
    dosN1 = "0" + (N1 * 2)
    sumaN1 = parseInt(dosN1.charAt(dosN1.length-1)) + parseInt(dosN1.charAt(dosN1.length-2))

    N3 = resto.charAt(2)
    dosN3 = "0" + (N3 * 2)
    sumaN3 = parseInt(dosN3.charAt(dosN3.length-1)) + parseInt(dosN3.charAt(dosN3.length-2))

    N5 = resto.charAt(4)
    dosN5 = "0" + (N5 * 2)
    sumaN5 = parseInt(dosN5.charAt(dosN5.length-1)) + parseInt(dosN5.charAt(dosN5.length-2))

    N7 = resto.charAt(6)
    dosN7 = "0" + (N7 * 2)
    sumaN7 = parseInt(dosN7.charAt(dosN7.length-1)) + parseInt(dosN7.charAt(dosN7.length-2))

    N2 = resto.charAt(1)
    N4 = resto.charAt(3)
    N6 = resto.charAt(5)

    total = sumaN1 + parseInt(N2) + sumaN3 + parseInt(N4) + sumaN5 + parseInt(N6) + sumaN7
    T = "0" + total
    unidades_total = T.charAt(T.length-1)
    if(ultimo.match(patron4))
    {
      SumaFinal = parseInt(unidades_total) + parseInt(ultimo)
      SF = "0" + SumaFinal
      UNIDAD = SF.charAt(SF.length-1)
      if (UNIDAD == 0)
        return true
      else
        return(MensError(campo,"El CIF es incorrecto"));
    }
    else
    {
      if (ultimo == "A")
        numero_control = 1
      else if (ultimo == "B")
        numero_control = 2
      else if (ultimo == "C")
        numero_control = 3
      else if (ultimo == "D")
        numero_control = 4
      else if (ultimo == "E")
        numero_control = 5
      else if (ultimo == "F")
        numero_control = 6
      else if (ultimo == "G")
        numero_control = 7
      else if (ultimo == "H")
        numero_control = 8
      else if (ultimo == "I")
        numero_control = 9
      else if (ultimo == "J")
        numero_control = 0

      SumaFinal = parseInt(unidades_total) + parseInt(numero_control)
      SF = "0" + SumaFinal
      UNIDAD = SF.charAt(SF.length-1)

      if (UNIDAD == 0)
        return true
      else
        return(MensError(campo,"El CIF es incorrecto"));
    }
  }
  return true
}

function esMovil(valor)
{

	if(valor.value.length==9 && valor.value.substr(0,1)==6)
		return true;
	else
	{
		alert('El Movil de contacto debe tener 9 digitos y comenzar por 6');
		return false;
	}
}



function esFijo(valor)
{

	if(valor.value.substr(0,1)==9 || valor.value.substr(0,1)==6)
		return true;
	else
	{
		alert('El Telefono de contacto debe comenzar por 9 o por 6.');
		return false;
	}
}

function esFax(valor)
{

	if(valor.value.substr(0,1)==9)
		return true;
	else
	{
		alert('El Fax debe comenzar por 9.');
		return false;
	}
}

function esTelefonoInternacional(valor)
{

	if(valor.value.substr(0,1)==9 || valor.value.substr(0,1)==6 || valor.value.substr(0,1)=='+')
		return true;
	else
	{
		alert('El Telefono de contacto, debe comenzar por 9 o por 6 si es nacional(955444333) y si es internacional por + (+34955444333).');
		return false;
	}
}

// Validación general y llamada a la comprobación de cuenta corriente
function esCCC(cc1,cc2,cc3,cc4)
{
       
       		var str_error = "";
       		var arrCC = new Array(cc1,cc2,cc3,cc4);
       		
       	    /*
       	     * Si algún campo no ha sido completado satisfactoriamente cambiar su estilo,
       	     * darle el foco y mostrar el error
       	    */
       		for (i=3;i>=0;i--){
       			if (arrCC[i].getAttribute("maxlength") != arrCC[i].value.length) {
       				arrCC[i].setAttribute("class","incompleto");
       				str_error = "No ha completado todos los datos";
       				arrCC[i].focus();
       			};
       		};
       		
       		if ("" != str_error) {
       			alert (str_error);
       			return false;
			};
       		
			/*
			 * Comprobar la cuenta corriente introducida
			*/
 	  		if (checkDC(arrCC[0].value+arrCC[1].value,arrCC[3].value,arrCC[2].value))
			   return true;
    		else
			{
    			alert ("La cuenta corriente introducida no es correcta.\nPor favor, compruebe los datos.");
				return false;
			}
       		
} // end validate()
		
		/**
		 * Validación de una cuenta corriente
		 * 
		 * Comprueba un número de cuenta corriente
		 *
		 * IN:  cc1	 string	 Primeros ocho dígitos de la cuenta corriente (entidad.oficina)
		 * IN:  cc2  string  Últimos diez dígitos de la cuenta corriente  (#cuenta)
		 * IN:  dc   string  Dígitos de control
		 * OUT:      bool    ¿Cuenta válida? 
		*/
function checkDC(cc1,cc2,dc)
{
            
			/*
			 * Comprobar que los datos son correctos
			*/
     		if (!(cc1.match(/^\d{8}$/) && cc2.match(/^\d{10}$/) && dc.match(/^\d{2}$/) )) return false;
       	    
	   	    var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6);	// vector de pesos
    		var dc1=0, dc2=0;
       	    
    		/*
    		 * Cálculo del primer dígito de cintrol
    		*/
   		    for (i=7;i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
    		dc1 = 11 - (dc1 % 11);
  		    if (11 == dc1) dc1 = 0;
   		    if (10 == dc1) dc1 = 1;
       	    
   		    /*
   		     * Cálculo del segundo dígito de control
   		    */
   		    for (i=9;i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
    		dc2 = 11 - (dc2 % 11);
   		    if (11 == dc2) dc2 = 0;
    		if (10 == dc2) dc2 = 1;
       	    
    		/*
    		 * Comprobar la coincidencia y delvolver el resultado
    		*/
     		return (10*dc1+dc2 == dc);	// Javascript infiere tipo entero para dc1 y dc2
 } // end checkDC()

//Verificar Email
function esMail(campo,obligatorio){
  //var patron1=/&#91;^\w\-@\.&#93;/;
  var patron1=new RegExp(String.fromCharCode(91) + '^\\w\\-@\\.' +  String.fromCharCode(93));
   //var patron2=/&#91;@.&#93;{2}/;
  var patron2=new RegExp(String.fromCharCode(91) + '@.'  +String.fromCharCode(93) + '{2}');
  //var patron3=/^&#91;.@&#93;|&#91;.@&#93;$/;
  var patron3=new RegExp('^' + String.fromCharCode(91) + '.@' +  String.fromCharCode(93) + '|' + String.fromCharCode(91) + '.@' +  String.fromCharCode(93) + '$');
  //var patron4=/@&#91;\w\-&#93;*\.&#91;\w\-&#93;*/;
   var patron4=new RegExp('@' + String.fromCharCode(91) + '\\w\\-' +  String.fromCharCode(93) + '*\\.' + String.fromCharCode(91) + '\\w\\-'  + String.fromCharCode(93) + '*');
  var patron5=/@.*@/;
  //var patron6=/\.&#91;a-z&#93;*\-&#91;a-z&#93;*$/;
  var patron6=new RegExp('\\.' + String.fromCharCode(91) + 'a-z' +  String.fromCharCode(93) + '*\\-' + String.fromCharCode(91) + 'a-z' +  String.fromCharCode(93) + '*$');
  //var patron7=/\.&#91;a-z&#93;*\_&#91;a-z&#93;*$/;
  var patron7=new RegExp('\\.' + String.fromCharCode(91) + 'a-z' +  String.fromCharCode(93) + '*\\_' + String.fromCharCode(91) + 'a-z' +  String.fromCharCode(93) + '*$');
   if(obligatorio && campo.value.length == 0){alert("Formato de correo electrónico incorrecto.");return false;}
   if(campo.value.length > 0)  {if(!(!campo.value.match(patron1)&&!campo.value.match(patron2)&&! campo.value.match(patron3)&&campo.value.match(patron4)&&! campo.value.match(patron5)&&!campo.value.match(patron6)&&! campo.value.match(patron7))){ alert("Formato de correo electrónico incorrecto.");    return false;  } }  
   
   return true;
}

function Verificar()
{
	
	if(document.form.txt_Telefono.value.substr(0,1)==9)
	{
		seleccionado=1;
		document.form.telefono.checked=0;
		if(document.form.txt_Producto.value=='banda_ancha' || document.form.txt_Producto.value=='34' || document.form.txt_Producto.value=='35' || document.form.txt_Producto.value=='36' || document.form.txt_Producto.value=='37')
		Elegir_Producto(34);
		else
		Elegir_Producto(1);
	}
	else
	{
		seleccionado=1;
		document.form.telefono.checked=0;
		Elegir_Producto(1);
		alert('El número de línea debe comenzar por 9');
	}
}

function Verificar_Linea()
{
	if(document.form.txt_Telefono.value.substr(0,1)==9)
	{
		if(document.form.txt_Telefono.value.length == 9)
			return true;	
		else
		{
			alert('El número de línea debe tener 9 dígitos');
			return false;	
		}
	}
	else
	{
		alert('El número de línea debe comenzar por 9');
		return false;
	}
}



//////////////////////////////////////////////////////
/////validar que la fecha que se escribe en el formulario (con el evento onBlur="javascript:fecha_valida(this.value)) sea correcta
// Uso: Simple... se debe pasar la cadena de la fecha y devuelve false si no es válida...
// El Formato es dd/mm/aaaa
// Ejemplo: if (fecha_valida('14/08/1981')==false) { alert('Entrada Incorrecta') }
// Uso en formularios: onSubmit="return fecha_valida(this.fecha.value)"
/////////////////////////////////////////////////////
function fecha_valida(Cadena)
{
	var Fecha = new String(Cadena);	// Crea un string
	var RealFecha = new Date();	// Para sacar la fecha de hoy
	var Esbisiesto = false;		//para año bisiesto
	// Cadena Año
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("/")+1,Fecha.length));
	// Cadena Mes
	var Mes= new String(Fecha.substring(Fecha.indexOf("/")+1,Fecha.lastIndexOf("/")));
	// Cadena Día
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("/")));

	// Valido el año
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900)
	{
       	alert('El formato de fecha no es correcto ( dd/mm/aaaa ).');
			return false;
	}
	// Valido el Mes
	if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12)
	{
		alert('El formato de fecha no es correcto ( dd/mm/aaaa ).');
			return false;
	}
	// Valido el Dia
	if (isNaN(Dia) || parseInt(Dia, 10)<1 || parseInt(Dia, 10)>31){
		alert('El formato de fecha no es correcto ( dd/mm/aaaa ).');
			return false;
	}
	//meses de 30 días
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 && Dia>30) {
		alert('El mes seleccionado no puede tener más de 30 días.');
			return false;
	}
	//año bisiesto o no:
	if (Mes==2)
	{
		if (Ano % 4 == 0 && (Ano % 100 != 0 || Ano % 400 == 0))
			Esbisiesto = true;
		else
			Esbisiesto = false;
		
		if(Esbisiesto == true && Dia > 29)
		{
			alert('El año '+Ano+' es bisiesto, por tanto, febrero no puede tener más de 29 días.');
			return false;
		}
		else if(Esbisiesto == false && Dia > 28)
		{
			alert('El año '+Ano+' no es bisiesto, por tanto, febrero no puede tener más de 28 días.');
			return false;
		}
		else
			return true;
	}
}

////////////////////////////////////////////////////////////////
/////Formatos de texto (negrita, rojo...) para los textarea:
//////////////////////////////////////////////////////////////
//TExto en español
function negrita() {
	var str = document.selection.createRange().text;
	document.getElementById('texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<strong>' + str + '</strong>';
	return;
}

function rojo() {
	var str = document.selection.createRange().text;
	document.getElementById('texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<span class=\"txtRojo\">' + str + '</span>';
	return;
}
//Texto en ingles:
function negrita2() {
	var str = document.selection.createRange().text;
	document.getElementById('i_texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<strong>' + str + '</strong>';
	return;
}

function rojo2() {
	var str = document.selection.createRange().text;
	document.getElementById('i_texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<span class=\"txtRojo\">' + str + '</span>';
	return;
}

//Texto en francés:
function negrita3() {
	var str = document.selection.createRange().text;
	document.getElementById('f_texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<strong>' + str + '</strong>';
	return;
}

function rojo3() {
	var str = document.selection.createRange().text;
	document.getElementById('f_texto').focus();
	var sel = document.selection.createRange();
	sel.text = '<span class=\"txtRojo\">' + str + '</span>';
	return;
}

