var nav4 = window.event ? true : false;
function acceptNum(evt) {
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57,'.' =46, ','=44
	var key = nav4 ? evt.which : evt.keyCode;
	return key <= 13 || key >= 48 && key <= 57;
}
function validarFCuota() {
	var error = '';
	var i;
	var seleccionada;
	for (i = 0; i < document.fCuota.cuota_tarifa_id.length; i++) {
		if (document.fCuota.cuota_tarifa_id[i].checked) {
			seleccionada = i;
			break;
		}
	}
	if (seleccionada == i) {
// var valor = document.fCuota.cuota_tarifa_id[i].value;
// if (document.fCuota['cuota_tarifa_periodicidad_id[' + valor + ']'].value ==
// '') {
// error += "Seleccione la periodicidad.\n\r";
// }

	} else {
		error += "Seleccione el servicio.\n\r";
	}

	if (document.fCuota.acepto.checked == false) {
		error += "Acepte los términos de los contratos y la política de protección de datos.\n\r";
	}
	if (error) {
		alert(error);
		return false;
	} else {
		document.fCuota.submit();
	}
}
function validaEmailBlur(objeto) {
	if (objeto.value != ''
			&& (objeto.value.indexOf('@', 0) == -1 || objeto.value.indexOf('.',
					0) == -1)) {
		alert("El email introducido no es válido.\r\n");
		objeto.value = '';
		objeto.focus();
	}
	return false;
}
/*
 * function validarNIFCIFBlur(objeto) { var devuelve_nif_nie = true; var
 * devuelve_cif = true; if (objeto.value != '') { devuelve_nif_nie =
 * validarNIFNIE(objeto); devuelve_cif = validarCIFCliente(objeto);
 * 
 * if (devuelve_nif_nie == false && devuelve_cif == false) { alert('El NIF/CIF
 * introducido no es correcto.'); objeto.value = ''; objeto.focus(); return
 * false; } else { return false; } } else { return false; } }
 */

// VALIDACIONES
function validarNIFCIFBlur(objeto){
	if(objeto.value != ''){
	// haremos una comprobacion con ajax por si acaso...
	var validarnifcifnie = {
		success:escorrectonifcifnie,
		failure:escorrectonifcifnie,
		argument: {nombre:objeto}
	}
	var request = YAHOO.util.Connect.asyncRequest('GET', document.forms[0].dir_ajax.value+"/ajax/validarUsuario.php?tipo=validar_nif_cif_nie&nif_cif_nie="+objeto.value, validarnifcifnie); 
	return false;
	} else {
		return false;
	}
}
function escorrectonifcifnie(o){
	var recojo = o.responseText; 
	var aux; 
	aux = o.argument.nombre;
 // alert(recojo);
	if(trim(recojo) == 'ko') {
		alert('El NIF/CIF introducido no es correcto.');
		aux.value='';
		return false;
	}
}

function compruebaPaisProvincias(objeto) {
	if (objeto.value != 'ES') {
		document.fCliente.provincia_id.value = '';
	}
	return false;
}
function compruebaPais(objeto) {
	if (objeto.value != '') {
		document.fCliente.iso3166.value = 'ES';
	}
	return false;
}
function compruebaFormatoEntero(objeto){
	error = '';
	punto = objeto.value.indexOf('.');
	cantidad = parseInt(objeto.value);
	 if(objeto.value != ""){
		if (isNaN(objeto.value) || (punto != -1) || (objeto.value < 0)) {
			alert("El texto introducido no es un número entero válido.");
			objeto.value = '';
			objeto.select();
			objeto.focus();
		}
	 }
	return false;
}
// funcion que comprueba si un numero de cuenta introducido es correcto
function esCorrectoBlur(objeto){
	numeroCuenta = objeto.value;
	if(numeroCuenta != ''){
		var valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
		var controlCS = 0;
		var controlCC = 0;
		for (i=0; i<=7; i++) {controlCS += parseInt(numeroCuenta.charAt(i)) * valores[i+2];}
		controlCS = 11 - controlCS % 11;
		if (controlCS == 11){controlCS = 0;}else if (controlCS == 10){controlCS = 1;}

		for (i=10; i<=19; i++) {controlCC += parseInt(numeroCuenta.charAt(i)) * valores[i-10];}
		controlCC = 11 - controlCC % 11;
		if (controlCC == 11){controlCC = 0;}else if (controlCC == 10){controlCC = 1;}

		if (numeroCuenta.charAt(8)==controlCS && numeroCuenta.charAt(9)==controlCC ) {
			return true;
		}else{
			alert('El Número de Cuenta introducido no es correcto.');
	     	objeto.value = '';
			return false;
		}
	} else {
		return false;
	}
}
function validaCliente() {
	var error = '';
	if (document.fCliente.nombre.value == '') {
		alert('Debe introducir el nombre de la empresa.\n\r ');
		document.fCliente.nombre.focus();
		return false;
	}
	if (document.fCliente.persona_contacto.value == '') {
		alert('Debe introducir el nombre de la persona de contacto.\n\r ');
		document.fCliente.persona_contacto.focus();
		return false;
	}
	if (document.fCliente.email.value == '') {
		alert('No ha introducido email de origen. Sin éste no podrá enviar emails a sus usuarios.\r\n');
		document.fCliente.email.focus();
		return false;
	}
	if (document.fCliente.email2.value == ''
			| document.fCliente.email2.value != document.fCliente.email.value) {
		alert('Los email no son iguales. Sin éste no podrá enviar emails a sus usuarios.\r\n');
		document.fCliente.email2.focus();
		return false;
	}
	if (document.fCliente.cif.value == '') {
		alert('Debe introducir el NIF/CIF.\r\n');
		document.fCliente.cif.focus();
		return false;
	}
	if (document.fCliente.razon_social.value == '') {
		alert('Debe introducir la razón social.\r\n');
		document.fCliente.razon_social.focus();
		return false;
	}
	if (document.fCliente.direccion.value == '') {
		alert('Debe introducir la dirección.\r\n');
		document.fCliente.direccion.focus();
		return false;
	}
	if (document.fCliente.cp.value == '') {
		alert('Debe introducir el código postal.\r\n');
		document.fCliente.cp.focus();
		return false;
	}
	if (document.fCliente.ciudad.value == '') {
		alert('Debe introducir la ciudad.\r\n');
		document.fCliente.ciudad.focus();
		return false;
	}
	if (document.fCliente.iso3166.value == 'ES'
			& document.fCliente.provincia_id.value == '') {
		alert('Debe introducir la provincia.\r\n');
		document.fCliente.provincia_id.focus();
		return false;
	}
	if (document.fCliente.telefono.value == '') {
		alert('Debe introducir el teléfono.\r\n');
		document.fCliente.telefono.focus();
		return false;
	}
	/*
	 * if (document.fCliente.fax.value == '') { alert('Debe introducir el
	 * fax.\r\n'); document.fCliente.fax.focus(); return false; }
	 */
	if (document.fCliente.email_empresa.value == '') {
		alert('Debe introducir el email de la empresa.\r\n');
		document.fCliente.email_empresa.focus();
		return false;
	}

	if(document.fCliente.precio_a_pagar.value!=0) {
		var i;
		var seleccionada;
		for (i = 0; i < document.fCliente.forma_pago_id.length; i++) {
			if (document.fCliente.forma_pago_id[i].checked) {
				seleccionada = i;
				break;
			}
		}
		if (seleccionada != i) {
			alert('Debe seleccionar la forma de pago.\r\n');
			return false;
		}
		if (document.fCliente.banco.value == ""  || document.fCliente.sucursal.value == "" ||
				document.fCliente.dc.value == "" || document.fCliente.cuenta.value == ""){
					alert("Por favor, introduzca los datos de su cuenta bancaria.");
					document.fCliente.banco.focus();
					return false;
		}else {
		    if (document.fCliente.banco.value.length != 4 || document.fCliente.sucursal.value.length != 4 ||
		    		document.fCliente.dc.value.length != 2 || document.fCliente.cuenta.value.length != 10){
		    	alert("Por favor, introduzca correctamente los datos de su cuenta bancaria no están completos.");
		    	document.fCliente.banco.focus();
				return false;
		    }else {
		      if (!numerico(document.fCliente.banco.value) || !numerico(document.fCliente.sucursal.value) ||
		          !numerico(document.fCliente.dc.value) || !numerico(document.fCliente.cuenta.value)){
		    	  	alert("Por favor, introduzca correctamente los datos de su cuenta bancaria; no son numéricos.");
		    	  	document.fCliente.banco.focus();
					return false;
		      }else {
		        if (!(obtenerDigito("00" + document.fCliente.banco.value + document.fCliente.sucursal.value) ==
		              parseInt(document.fCliente.dc.value.charAt(0))) ||
		            !(obtenerDigito(document.fCliente.cuenta.value) ==
		              parseInt(document.fCliente.dc.value.charAt(1)))){
		        	alert("Los dígitos de control no se corresponden con los demás números de la cuenta bancaria.");
		        	document.fCliente.banco.focus();
					return false;
					}
		      }
		    }
	  }
	}
	if (document.fCliente.usuario_cliente_origen.value == '') {
		alert('Debe introducir el nombre de usuario. Sin éste no podrá acceder a la Extranet.\r\n');
		document.fCliente.fax.focus();
		return false;
	}

	if (document.fCliente.clave_cliente_origen.value == '' | document.fCliente.clave_cliente_origen.value.length<6 | document.fCliente.clave_cliente_origen.value.length>12) {
		alert('Debe introducir una clave entre 6 y 12 carácteres. Sin ésta no podrá acceder a la Extranet.\r\n');
		document.fCliente.clave_cliente_origen.focus();
		return false;
	}
	if (document.fCliente.clave_cliente_origen.value != document.fCliente.clave_cliente_origen2.value) {
		alert('La claves no son iguales.\r\n');
		document.fCliente.clave_cliente_origen2.focus();
		return false;
	}
	if(document.fCliente.como_nos_conocio.value=='Seleccione'){
		alert('Seleccione como nos conocio.\r\n');
		document.fCliente.como_nos_conocio.focus();
		return false;
	}
	document.fCliente.submit();

}
/**
 * Funciones para el evento onblur
 */
// AJAX
function validaUsuario(objeto,usuario_id){
	if(objeto.value != ''){
		var validarnbusuario = {
			success:escorrectousuario,
			failure:escorrectousuario,
			argument: {nombre:objeto}
		}
		var request = YAHOO.util.Connect.asyncRequest('GET', document.fCliente.dir_ajax.value+"/ajax/validarUsuario.php?tipo=validar_login&login="+objeto.value+'&usuario_id='+usuario_id, validarnbusuario);
		return false;
	}
}
function escorrectousuario(o){
	var recojo = o.responseText;
	var aux;
	aux = o.argument.nombre;
// alert(recojo);
	if(trim(recojo) == 'existe') {
		alert("El usuario '"+aux.value+"' introducido ya existe, deberá cambiarlo.");
		aux.value = '';
		aux.focus();
		return false;
	}
}



function numerico(valor){
	  cad = valor.toString();
	  for (var i=0; i<cad.length; i++) {
	    var caracter = cad.charAt(i);
		if (caracter<"0" || caracter>"9") {
			return false;
		}
	  }
	  return true;
	}
function obtenerDigito(valor){
	  valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
	  control = 0;
	  for (i=0; i<=9; i++) {control += parseInt(valor.charAt(i)) * valores[i];}
	  control = 11 - control % 11;
	  if (control == 11){control = 0;}else if (control == 10){control = 1;}
	  return control;
	}