/*La parte del Login implementado Neubox*/
var navegador = 1;
if(navigator.userAgent.indexOf("MSIE") >= 0) navegador = 0;


function objetoAjax()
{
	/*var xmlhttp=false;
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e){
    	try{
    		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 	  	}
 	    catch (E){
 	    	xmlhttp = false;
 	    }
 	}
 	if (!xmlhttp && typeof XMLHttpRequest!='undefined'){
 		xmlhttp = new XMLHttpRequest();
 	}
 	return xmlhttp;*/
	
	
	var xmlHttp=null;
		try{
		// Firefox, Opera 8.0+, Safari
			xmlHttp=new XMLHttpRequest();
		}
		catch (e){// Internet Explorer
			try{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e){
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		return xmlHttp;

}

//Valida si se esta accediendo desde adminX a la cuenta de algun usuario.
function UsuarioAdminEquis(archPhp,correo,ident,div,redir){		
	var divE = document.getElementById(div);	
	//escribir_mensaje(div,archPhp+correo+div+redir, 'rojo')
	ajax=objetoAjax();	
	////////////////////////////////////////////////////////////////
	//prototipo que sirve para tratar la respuesta que recibes de AJAX
	String.prototype.tratarResponseText = function() {		
		var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
		var pat2=/\b\s+src=[^>\s]+\b/g;
		var elementos = this.match(pat) || [];		
		for (i = 0; i < elementos.length; i++) {			
			var nuevoScript = document.createElement('script');
			nuevoScript.type = 'text/javascript';
			var tienesrc=elementos[i].match(pat2) || [];			
			if (tienesrc.length) 
				nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
			else {				
				var elemento = elementos[i].replace(pat,'$1');
				nuevoScript.text = elemento;				
			}			
			document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
		}		
		return this.replace(pat,'');
	} 
	///////////////////////////////////////////////////////////////		
  	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
         if (ajax.readyState==1) {
             //divE.innerHTML = "Verificando Datos ... ... ...";
			 escribir_mensaje_1(div,' Verificando Datos ', 'amarillo');

         }
         else if(ajax.readyState==4){//si se recibe respuesta de AJAX
			 	//divE.innerHTML = ajax.responseText.tratarResponseText();
				escribir_mensaje_1(div,ajax.responseText.tratarResponseText(), 'rojo');

		      }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=ValidaUser&mail=" + correo + "&pass=" + ident + "&tipo=admin&redirect="+redir);	
  //ajax.send("funcion=ValidaUser&mail=" + mail + "&pass=" + pass + "&tipo=user&redirect="+redir);
}

//Valida si el usuario a introducido sus datos correctamente, si no es asi lo registra en la bd para el control de abuso de IP.
function ValidaUsuario(archPhp,div,redir,nameM,nameP,pag)
{
	//escribir_mensaje_2(div,cukie, 'amarillo')
	//Obtener los datos del Usuario
	var divE = document.getElementById(div);
	var mail = document.getElementById(nameM).value;
	var pass = document.getElementById(nameP).value;	
	if(mail != "" && pass != ""){
	//Crea Objeto Ajax
		ajax=objetoAjax();		
		////////////////////////////////////////////////////////////////
		//prototipo que sirve para tratar la respuesta que recibes de AJAX
		String.prototype.tratarResponseText = function() {		
			var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
			var pat2=/\b\s+src=[^>\s]+\b/g;
			var elementos = this.match(pat) || [];		
			for (i = 0; i < elementos.length; i++) {			
				var nuevoScript = document.createElement('script');
				nuevoScript.type = 'text/javascript';
				var tienesrc=elementos[i].match(pat2) || [];			
				if (tienesrc.length) 
					nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
				else {				
					var elemento = elementos[i].replace(pat,'$1');
					nuevoScript.text = elemento;				
				}			
				document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
			}		
			return this.replace(pat,'');
		} 
		///////////////////////////////////////////////////////////////		
		ajax.open("POST",archPhp,true);
		ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				 //divE.innerHTML = "Verificando Datos ... ... ...";
				 if(pag == 'contrata_p_2')
				 	escribir_mensaje_2(div,' <br>Verificando Datos ', 'amarillo')
				 else
				 	escribir_mensaje_1(div,' <br>Verificando Datos ', 'amarillo')
			 }
			 else if(ajax.readyState==4){//si se recibe respuesta de AJAX
					//divE.innerHTML = ajax.responseText.tratarResponseText();
					if(ajax.responseText == 'error_datoserror_datos' || ajax.responseText == 'error_datos'){						
						if(pag == 'contrata_p_2')
							escribir_mensaje_2(div,'El e-mail o la contrase&ntilde;a no son v&aacute;lidos. Verifica tus datos de acceso.', 'rojo');
						 else
							escribir_mensaje_1(div,'El e-mail o la contrase&ntilde;a no son v&aacute;lidos. Verifica tus datos de acceso.', 'rojo');
						RegistraAbusoIP(mail,'Login Neubox');
						Recaptcha.reload();												
						ValidaCaptcha('botonEntrar','captcha');
						LimpiaForma();						
					}
					else
						if(pag == 'contrata_p_2')
				 			escribir_mensaje_2(div,' Verificando Datos ', 'amarillo')
				 		else
							escribir_mensaje_1(div,ajax.responseText.tratarResponseText(), 'rojo');
				  }
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		var cuki = 'no';
		if(document.getElementById('chkR').checked == true)	
			cuki = 'si';
		ajax.send("funcion=ValidaUser&mail=" + mail + "&pass=" + pass + "&tipo=user&redirect="+redir+"&cuki="+cuki);
	}
	else if(pag == 'contrata_p_2')
			escribir_mensaje_2(div,' LLena los campos e-mail y password, a continuaci&oacute;n presiona el boton de Ingresar', 'rojo');
		 else
			escribir_mensaje_1(div,' LLena los campos e-mail y password, a continuaci&oacute;n presiona el boton de Ingresar', 'rojo');		
}

//Metodo para cerrar una sesion actual, recibe el nombre del archivo donde se encuantra el Cierre de la sesion  y a donde se desea redireccionar
function CierraSesion(archPhp,div,redir){
	document.location.href = archPhp + '?redir=' + redir;
	//escribir_mensaje(div,archPhp+div+redir, 'rojo')	
	/*var divE = document.getElementById(div);
	ajax=objetoAjax();	
	////////////////////////////////////////////////////////////////
	//prototipo que sirve para tratar la respuesta que recibes de AJAX
	String.prototype.tratarResponseText = function() {		
		var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
		var pat2=/\b\s+src=[^>\s]+\b/g;
		var elementos = this.match(pat) || [];		
		for (i = 0; i < elementos.length; i++) {			
			var nuevoScript = document.createElement('script');
			nuevoScript.type = 'text/javascript';
			var tienesrc=elementos[i].match(pat2) || [];			
			if (tienesrc.length) 
				nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
			else {				
				var elemento = elementos[i].replace(pat,'$1');
				nuevoScript.text = elemento;				
			}			
			document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
		}		
		return this.replace(pat,'');
	} 
	///////////////////////////////////////////////////////////////		
  	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
         if (ajax.readyState==1) {
             //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,'Verificando Datos ... ... ...', 'amarillo')

         }
         else if(ajax.readyState==4){//si se recibe respuesta de AJAX
			 	divE.innerHTML = ajax.responseText.tratarResponseText();
				//escribir_mensaje(div,ajax.responseText.tratarResponseText(), 'rojo')

		      }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=CierraSesion&redirect="+redir);	*/
}


function escribir_mensaje_2(div, msg, color){
	if ( div == '' ) {
		return false;
	}
	else {
		if(msg == "")
			document.getElementById(div).innerHTML = "";
		else if(color == "amarillo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#FAEA32;" align="center"><div style="background-color:#FFF; border:1px solid #EF9B52; 	padding:5px;"><img src="load_black.gif" />'+msg+'</div></div>';	
		else if(color == "rojo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#D02626;" align="center"><div style="background-color:#FFF; border:1px solid #D05616; padding:5px;">'+msg+'</div></div>';	
		else
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#5FA83C;" align="center"><div style="background-color:#FFF; border:1px solid #9CD65E; padding:5px;">'+msg+'</div></div>';	
	}
}

//Escribe una cadena que recibe por parametro y la escribe en un div k recibe por parametro
function escribir_mensaje_1(div, msg, color){
	if ( div == '' ) {
		return false;
	}
	else {
		if(msg == "")
			document.getElementById(div).innerHTML = "";
		else if(color == "amarillo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; " align="center"><div style=" padding:5px;"><img src="load_black.gif" />'+msg+'</div></div>';	
		else if(color == "rojo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#D02626;" align="center"><div style="background-color:#FFF; border:1px solid #D05616; padding:5px;">'+msg+'</div></div>';	
			/*'<div style="margin:5px; padding:3px; " align="center"><div style="padding:5px;">'+msg+'</div></div>';	*/
		else
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; " align="center"><div style="background-color:#FFF;  padding:5px;">'+msg+'</div></div>';	
	}
}

//Verifica cuando un cliente quiere entrar al panel de clientes y si esta abierta su sesion, inicializa las variables de sesion pertinentes.
function ValidaPanelClientes(archPhp,div,redir){		
	//escribir_mensaje(div,archPhp+div+redir, 'rojo')	
	var divE = document.getElementById(div);
	ajax=objetoAjax();	
	////////////////////////////////////////////////////////////////
	//prototipo que sirve para tratar la respuesta que recibes de AJAX
	String.prototype.tratarResponseText = function() {		
		var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
		var pat2=/\b\s+src=[^>\s]+\b/g;
		var elementos = this.match(pat) || [];		
		for (i = 0; i < elementos.length; i++) {			
			var nuevoScript = document.createElement('script');
			nuevoScript.type = 'text/javascript';
			var tienesrc=elementos[i].match(pat2) || [];			
			if (tienesrc.length) 
				nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
			else {				
				var elemento = elementos[i].replace(pat,'$1');
				nuevoScript.text = elemento;				
			}			
			document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
		}		
		return this.replace(pat,'');
	} 
	///////////////////////////////////////////////////////////////		
  	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
         if (ajax.readyState==1) {
             //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,'Verificando Datos ... ... ...', 'amarillo')

         }
         else if(ajax.readyState==4){//si se recibe respuesta de AJAX		 		
			 		if(ajax.responseText.tratarResponseText() == 'correcto')
						return (true);
					else
						return (false);				
		      }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=ValidaPanelC&redirect="+redir);	
}

//Valida que la estructura del campo mail sea la adecuada para los E-Mail
function ValidaMail(campo){
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(campo))
		return (true);
	else 
		return (false);
}

//Prueba que se pueda acceder a la funcion de validaForma
function ValidaFormaPrueba(){
	escribir_mensaje_1('error','asdasdsa', 'rojo');
}
//Valida que el llenado de los datos del Usuario sean los correctos y que no tenga datos vacios
function ValidaForma(redir){
	var mensaje = "";
	var enviar = 1;
	var cuki = 'no';
	
	if(document.datos.mail.value == ""){
		mensaje += "Introduce tu E-Mail<br>";
		enviar = 0;
	}
	else{
		if(!ValidaMail(document.datos.mail.value)){
			mensaje += "El e-mail introducido no tiene un formato v&aacute;lido<br>";
			enviar = 0;
		}			
	}		
	if(document.datos.pass.value == ""){
		mensaje += "Introduce tu Contrase&ntilde;a<br>";
		enviar = 0;
	}	
		
	if(enviar == 1) {					
		ValidaUsuario('includes/Login/Funciones_Login.php','error',redir,'tMail','tPass');
	}
	else{
		escribir_mensaje_1('error',mensaje, 'rojo');
		LimpiaForma();
	}
}
	

/*****************************************************************************************************************************
//Muestra el div flotante que contiene la pantalla de Login neubox
*****************************************************************************************************************************/
function MuestraLogin(div){		
	document.getElementById('tMail').value = '';
	document.getElementById('tPass').value = '';
	document.getElementById('error').innerHTML='';
	mostrar_div(div);
	centrar_div(div);
}


/*****************************************************************************************************************************
//Muestra el div flotante que contiene la pantalla de Login neubox
*****************************************************************************************************************************/
function MuestraRegistro(div){		
	//document.getElementById('tMail').value = '';
	//document.getElementById('tPass').value = '';
	//document.getElementById('error').innerHTML='';
	mostrar_div(div);
	centrar_div(div);
}


/*****************************************************************************************************************************
//Registra un Cliente en la Base de Datos de Adminx
*****************************************************************************************************************************/
function RegistraCliente(archPhp,divRespuesta){		
			
	datos_cliente = ValidaDatosCliente();
			
	if( datos_cliente){//si los datos del cliente han sido llenados adecuadamente
		nombre = escape(trim( document.getElementById('txtNombre_r').value ));
		apellidos = escape(trim( document.getElementById('txtApellidos_r').value ));
		email = escape(trim( document.getElementById('txtMail_r').value ));
		email2 = escape(trim( document.getElementById('txtMailConfirm_r').value ));
		empresa = escape(trim( document.getElementById('txtEmpresa_r').value ));
		direccion = escape(trim( document.getElementById('txtDireccion_r').value ));
		ciudad = escape(trim( document.getElementById('txtCiudad_r').value ));
		cp = escape(trim( document.getElementById('txtCp_r').value ));
		telefono = escape(trim( document.getElementById('txtTelefono_r').value ));
		pais = escape(trim( document.getElementById('cmbPais_r').value ));
		estado = escape(trim(document.getElementById('cmbEstado_r').value));
		empresa = escape(trim(document.getElementById('txtEmpresa_r').value));		
		var divE = document.getElementById(divRespuesta);	
		//escribir_mensaje(divRespuesta,archPhp+nombre+apellidos+email+email2+empresa+direccion+ciudad+cp+telefono+pais+estado, 'rojo')
		////////////////////////////////////////////////////////////////		
		ajax=objetoAjax();		
		ajax.open("POST",archPhp,true);
		ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {
				 divE.innerHTML = '<img src="load_black.gif" />';
				 //escribir_mensaje_1(divRespuesta,' Creando Registro ... ', 'amarillo');
			 }
			 else if(ajax.readyState==4){//si se recibe respuesta de AJAX
					//divE.innerHTML = ajax.responseText.tratarResponseText();
					switch (ajax.responseText){
						case 'registrado':							
							document.getElementById(divRespuesta).innerHTML ='<div style="padding-top:50px;"><table cellpadding="0" cellspacing="0" border="0" width="100%" height="250"><tr><td align="left" width="155" colspan="2"><div style="text-align:center"><img src="images/registrook_form.gif" alt="Registro Correcto" border="0" style="width:366px; height:109px;"/><br><br><br><br><span style="font-size:12px; color:#FF0000;">Te hemos enviado un correo a la direcci&oacute;n que nos proporcionaste.</span><br><span style="font-size:12px; color:#000000; font-weight:bold;">Sigue el enlace que aparece y tu cuenta estar&aacute; activada. </span></div></td></tr><tr><td align="right" width="50%"><a href="#" style="border:none" onClick="ocultar_div_opaco(\'registrar\');"><img alt="Cerrar" style="width:73px; height:24px;" src="images/registro_salir.gif"></a></td><td align="left" width="50%"><a href=\"javascript:ocultar_div_opaco(\'registrar\');MuestraRegistro(\'loginn\');" style="border:none;"><img src="images/registro_inicia.gif" alt="Iniciar Sesi&oacute;n" border="0" style="width:88px; height:24px;"/></a></td></tr></table></div>';
						break;
						case 'error_registro':
							document.getElementById(divRespuesta).innerHTML = '<table cellpadding="0" cellspacing="0" border="0" width="100%" height="250"><tr><td align="left" width="155" colspan="2"><div style="text-align:center"><strong style="font-size:16px">Ha ocurrido un error al procesar tu registro, por favor intenta mas tarde</strong></div></td></tr><tr><td align="left" width="155"><a href="#" style="border:none" onClick="ocultar_div_opaco(\'registrar\');"><img alt="Cerrar" style="width:17px; height:32px;" src="images/cierra_emergente.gif"></a></td><td align="left"><a href=\"javascript:ocultar_div_opaco(\'registrar\');MuestraRegistro(\'registrar\');" style="border:none;"><img src="images/in_sesion_p1.gif" alt="Iniciar Sesi&oacute;n" border="0" style="width:112px; height:30px;"/></a></td></tr></table>';							
						break;
						case 'error_datos':
							document.getElementById(divRespuesta).innerHTML = '<table cellpadding="0" cellspacing="0" border="0" width="100%" height="250"><tr><td align="left" width="155" colspan="2"><div style="text-align:center"><strong style="font-size:16px">Ha ocurrido un error al enviar los datos de tu registro, por favor intenta mas tarde</strong></div></td></tr><tr><td align="left" width="155"><a href="#" style="border:none" onClick="ocultar_div_opaco(\'registrar\');"><img alt="Cerrar" style="width:17px; height:32px;" src="images/cierra_emergente.gif"></a></td><td align="left"><a href=\"javascript:ocultar_div_opaco(\'registrar\');MuestraRegistro(\'registrar\');" style="border:none;"><img src="images/in_sesion_p1.gif" alt="Iniciar Sesi&oacute;n" border="0" style="width:112px; height:30px;"/></a></td></tr></table>';
						break;						
					}					
	
				  }
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("funcion=RegistraCliente&nom=" + nombre + "&apelli=" + apellidos + "&mail=" + email + "&mail2=" + email2 + "&dir=" + direccion + "&pai=" + pais + "&edo=" + estado + "&ciu=" + ciudad + "&cod_p=" + cp + "&tel=" + telefono + "&emp=" + empresa + "&clave=" + pass + "&clave2=" + pass2);	  	
	}
	else{//si los datos del cliente fueron llenados erroneamente
		//poner que la contraseña deber ser iwal y que debe ser mayor de 4 caracteres y menor de 15
	}
}



/************************************************************************************
NOMBRE:
	validaDatosCliente
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCIÓN:
	Valida que los datos introducidos por el cliente sean correctos
************************************************************************************/
function ValidaDatosCliente() {
	// bandera de errores
	errores = 0;
	// obtener los datos escritos por el cliente
	nombre = trim( document.getElementById('txtNombre_r').value );
	apellidos = trim( document.getElementById('txtApellidos_r').value );
	email = trim( document.getElementById('txtMail_r').value );
	email2 = trim( document.getElementById('txtMailConfirm_r').value );
	empresa = trim( document.getElementById('txtEmpresa_r').value );
	direccion = trim( document.getElementById('txtDireccion_r').value );
	ciudad = trim( document.getElementById('txtCiudad_r').value );
	cp = trim( document.getElementById('txtCp_r').value );
	telefono = trim( document.getElementById('txtTelefono_r').value );
	pais = trim( document.getElementById('cmbPais_r').value );
	pass = trim(document.getElementById('txtPass_r').value);
	pass2 = trim(document.getElementById('txtPass2_r').value);	
	
	//estado = trim( document.getElementById('cmbEstado').value );
	
	// borrar rastros de errores
	LimpiaDivsRegistro();
	
	// validar el nombre
	if ( !validar_nombre(nombre) ) {
		document.getElementById('div_nombre_r').innerHTML = '* Escribe un nombre correcto';
		errores ++;
	}
	// validar el apellidos
	if ( !validar_nombre(apellidos) ) {
		document.getElementById('div_apellidos_r').innerHTML = '* Escribe un apellido correcto';
		errores ++;
	}
	// validar el mail
	if ( !ValidaMail(email) ) {
		document.getElementById('div_mail_r').innerHTML = '* Escribe un E-Mail correcto';
		errores ++;
	}
	else {
		if ( email != email2 ) {
			document.getElementById('div_mailconfirm_r').innerHTML = '* Los correos no coinciden';
			errores ++;
		}
	}
	// validar el direccion
	exp_dir = /^[a-z0-9áéíóúüñ#_\-\.\:\,\/ ]{3,130}$/i
	if ( !exp_dir.test(direccion) ) {
		document.getElementById('div_direccion_r').innerHTML = '* El formato de Direccion es incorrecto';
		errores ++;
	}
	// validar el ciudad
	if ( !validar_nombre(ciudad) ) {
		document.getElementById('div_ciudad_r').innerHTML = '* Escribe una ciudad correcta';
		errores ++;
	}
	
	exp_cp = /^[a-z0-9\- ]{3,10}$/i;
	//if ( isNaN(cp) || cp.length < 5 ) {
	if ( !exp_cp.test(cp) ){
		document.getElementById('div_cp_r').innerHTML = '* Escribe un codigo postal correcto';
		errores ++;
	}
	if ( isNaN(telefono) || telefono.length < 7 ) {
		document.getElementById('div_telefono_r').innerHTML = '* Escribe un telefono correcto';
		errores ++;
	}
	
	if(pass.length > 4 && pass.length < 15 && pass2.length > 4 && pass2.length < 15){
		if(pass != pass2){
			document.getElementById('div_pass_r').innerHTML = '* La contrase&ntilde;a no coincide con la verificaci&oacute;n de contrase&ntilde;a';
			errores ++;
		}		
	}
	else{
		document.getElementById('div_pass_r').innerHTML = '* La contraseña tiene un formato incorrecto, esta debe tener mas de cuatro letras &oacute; numeros y menos de 15';
			errores ++;
	}
	
	
	if ( errores > 0 ) {
		//document.location.href = '#a_datos_cliente';
		return (false);
	}
	else {
		cliente_ok = true;
		return (true);
	}
}


/************************************************************************************
NOMBRE:
	LimpiaDivsRegistro
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCIÓN:
	Limpia los divs de errores de la forma de registro de cuenta
************************************************************************************/
function LimpiaDivsRegistro() {
	// limpiar los mensajes de error
	document.getElementById('div_nombre_r').innerHTML = '';
	document.getElementById('div_apellidos_r').innerHTML = '';
	document.getElementById('div_mail_r').innerHTML = '';
	document.getElementById('div_mailconfirm_r').innerHTML = '';
	document.getElementById('div_direccion_r').innerHTML = '';
	document.getElementById('div_ciudad_r').innerHTML = '';
	document.getElementById('div_cp_r').innerHTML = '';
	document.getElementById('div_telefono_r').innerHTML = '';
	document.getElementById('div_pass_r').innerHTML = '';
	document.getElementById('div_pass2_r').innerHTML = '';
	
}


/************************************************************************************
NOMBRE:
	ExisteMailRegistrado
ENDTRADAS:
	txt_mail -> id del imput mail, txt_mail_2 -> id del imput mail de confirmacion, div_mail -> id del div de error de mail 
SALIDAS: 
	<< ninguna >>
DESCRIPCIÓN:
	busca un si un cliente existe en la base de datos
************************************************************************************/
function ExisteMailRegistrado(txt_mail,txt_mail_2,div_mail) {
	// lipiar cualquier posible mensaje
	document.getElementById(div_mail).innerHTML = '';
	// obtener los datos y crear las variables post
	correo_nuevo = document.getElementById(txt_mail).value;
	variables = 'accion=buscar_cliente_bd&correo='+escape(correo_nuevo);
	
	// eliminar los espacios en blanco al inicio y fin de la cadena
	if ( trim(correo_nuevo) != '' ) {
		// poner imagen de espera
		document.getElementById(div_mail).innerHTML = '<img src="load_black.gif" />';
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		// funcion de regreso
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			if ( regreso == 'existe' ) {
				// si exiete, apagar la bandera de cliente ok y limpiar los text del mail. notificar.
				cliente_ok = false;
				document.getElementById(txt_mail).value = '';
				document.getElementById(txt_mail_2).value = '';
				
				document.getElementById(txt_mail).focus();
				document.getElementById(div_mail).innerHTML = 'El correo ya esta registrado.';
			}
			else {
				document.getElementById(div_mail).innerHTML = '';
			}
		};
		
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
	}
}





/*************************************************************************************************************************
//Confirma una cuenta que ha sido creada con anterioridad
*************************************************************************************************************************/
function ConfirmaCuenta(archPhp,divResp){	
	email = escape(trim( document.getElementById('txt_mail').value ));
	pass = escape(trim( document.getElementById('txt_pass').value ));
	cod = escape(trim( document.getElementById('txt_cod').value ));	
	var divE = document.getElementById(divResp);
	//escribir_mensaje_1(divResp,archPhp+divResp+email+pass+cod, 'verde');
	////////////////////////////////////////////////////////////////		
	ajax=objetoAjax();		
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {
			 //divE.innerHTML = "Verificando Datos ... ... ...";
			 divE.innerHTML = '<img src="load_black.gif" />';

		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX
				//divE.innerHTML = ajax.responseText.tratarResponseText();
				escribir_mensaje_1(divRespuesta,ajax.responseText, 'verde');

			  }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=ConfirmaCuenta&mail=" + email + "&pasword=" + pass + "&codigo=" + cod);
}


/*************************************************************************************************************************
//Realiza una validacion de los datos introducidos por el cliente para registrarse
*************************************************************************************************************************/
/*function ValidaDatosRegistro() {
	// bandera de errores
	errores = 0;
	// obtener los datos escritos por el cliente
	nombre = trim( document.getElementById('txtNombre').value );
	apellidos = trim( document.getElementById('txtApellidos').value );
	email = trim( document.getElementById('txtMail').value );
	email2 = trim( document.getElementById('txtMailConfirm').value );
	empresa = trim( document.getElementById('txtEmpresa').value );
	direccion = trim( document.getElementById('txtDireccion').value );
	ciudad = trim( document.getElementById('txtCiudad').value );
	cp = trim( document.getElementById('txtCp').value );
	telefono = trim( document.getElementById('txtTelefono').value );
	pais = trim( document.getElementById('cmbPais').value );
	//estado = trim( document.getElementById('cmbEstado').value );
	
	// borrar rastros de errores
	LimpiaErrorReg();
	
	// validar el nombre
	if ( !validar_nombre(nombre) ) {
		document.getElementById('div_nombre').innerHTML = '* Escribe un nombre correcto';
		errores ++;
	}
	// validar el apellidos
	if ( !validar_nombre(apellidos) ) {
		document.getElementById('div_apellidos').innerHTML = '* Escribe un apellido correcto';
		errores ++;
	}
	// validar el mail
	if ( !validar_correo(email) ) {
		document.getElementById('div_mail').innerHTML = '* Escribe un E-Mail correcto';
		errores ++;
	}
	else {
		if ( email != email2 ) {
			document.getElementById('div_mailconfirm').innerHTML = '* Los correos no coinciden';
			errores ++;
		}
	}
	// validar el direccion
	exp_dir = /^[a-z0-9áéíóúüñ#_\-\.\:\,\/ ]{3,130}$/i
	if ( !exp_dir.test(direccion) ) {
		document.getElementById('div_direccion').innerHTML = '* El formato de Direccion es incorrecto';
		errores ++;
	}
	// validar el ciudad
	if ( !validar_nombre(ciudad) ) {
		document.getElementById('div_ciudad').innerHTML = '* Escribe una ciudad correcta';
		errores ++;
	}
	
	exp_cp = /^[a-z0-9\- ]{3,10}$/i;
	//if ( isNaN(cp) || cp.length < 5 ) {
	if ( !exp_cp.test(cp) ){
		document.getElementById('div_cp').innerHTML = '* Escribe un codigo postal correcto';
		errores ++;
	}
	if ( isNaN(telefono) || telefono.length < 7 ) {
		document.getElementById('div_telefono').innerHTML = '* Escribe un telefono correcto';
		errores ++;
	}
	
	if ( errores > 0 ) {
		document.location.href = '#a_datos_cliente';
		return (false);
	}
	else {
		cliente_ok = true;
		return (true);
	}
}*/

/*************************************************************************************************************************
limpia el contenido de posibles errores señalados en los divs destinados para ello
*************************************************************************************************************************/
function LimpiaErrorReg() {
	// limpiar los mensajes de error
	document.getElementById('div_nombre').innerHTML = '';
	document.getElementById('div_apellidos').innerHTML = '';
	document.getElementById('div_mail').innerHTML = '';
	document.getElementById('div_mailconfirm').innerHTML = '';
	document.getElementById('div_direccion').innerHTML = '';
	document.getElementById('div_ciudad').innerHTML = '';
	document.getElementById('div_cp').innerHTML = '';
	document.getElementById('div_telefono').innerHTML = '';
	document.getElementById('div_pass').innerHTML = '';
	document.getElementById('div_pass2').innerHTML = '';
}


/*****************************************************************************************************************************
//Centra un determinado div.
*****************************************************************************************************************************/
function centrar_div(div_id){
	var yScroll = 0;
	var top;
	var left;
	var factorIE = 0;

  var browser=navigator.appName.split(" ");
  if(browser[0]=="Microsoft")
  {
	  factorIE = -300;
  }
	
	if ( document.getElementById(div_id) ) 
	{			
		var ancho_total,alto_total;

		if (document.all) 
		{
			ancho_total = document.body.clientWidth;
			alto_total = document.body.clientHeight;
		}
		else
		{
			ancho_total = window.innerWidth
			alto_total = window.innerHeight
		}

		ancho_div = document.getElementById(div_id).offsetWidth;
		alto_div = document.getElementById(div_id).offsetHeight;

		if ( navegador == 0 ) { yScroll = document.documentElement.scrollTop+document.body.scrollTop }
		else { yScroll = self.pageYOffset; }

		top = (alto_total / 2) - (alto_div / 2) + yScroll;
		left = (ancho_total / 2) - (ancho_div / 2);

		top = parseInt(top)+factorIE;
		left = parseInt(left);

		if( navegador == 0 ) 
		{ 
			top = top - 100;
			//document.getElementById(div_id).style.filter='';
		}

		document.getElementById(div_id).style.top = top+'px';
		document.getElementById(div_id).style.left = left+'px';

		//carga_estilos_formularios();
	}
}

	
/***********************************************************************************************************
Funcion:		mostrar_div
Descripcion:	Despliega la ventana cuyo id es div_id
Entradas:		<< ninguna >>
Salidas:		<< ninguna >>
***********************************************************************************************************/
function mostrar_div(div_id){	
	if ( document.getElementById(div_id) ) 
	{
		cargar_div_opaco();
		
		document.getElementById(div_id).style.display = 'block';
		
		if(navegador==0) document.getElementById(div_id).style.filter='alpha(opacity=1)';
		else document.getElementById(div_id).style.opacity=1;

		if( navegador == 0 ) document.getElementById(div_id).style.filter='';
		
		centrar_div(div_id);
	}
}


/***********************************************************************************************************
Funcion:		cargar_div_opaco
Descripcion:	Bloquea la pantalla para que solo se pueda utilizar la ventana de compartir correo
Entradas:		<< ninguna >>
Salidas:		<< ninguna >>
***********************************************************************************************************/
function cargar_div_opaco(){
	var id = 'div___bk';
	var color = '#000000';
	var opacity = 80;

	if(!document.getElementById('div___bk'))
	{
		var frame = document.createElement("iframe");
		frame.id='frame__'+id;
		frame.style.position='absolute';
		frame.style.top=0;
		frame.style.left=0;
		frame.style.zIndex=11000;

		document.body.appendChild(frame);

		if(navegador==0) frame.style.filter='alpha(opacity=1)';
		else frame.style.opacity=1;

		var layer=document.createElement('div');
		layer.id=id;
		layer.style.backgroundColor=color;
		layer.style.position='absolute';
		layer.style.top=0;
		layer.style.left=0;
		layer.style.zIndex=11001;

		if(navegador==0) layer.style.filter='alpha(opacity='+opacity+')';
		else layer.style.opacity=opacity/100;

		document.body.appendChild(layer);
	}

	document.getElementById(id).style.width = document.body.offsetWidth+'px';
	document.getElementById(id).style.height = (parseInt(document.body.offsetHeight)+65)+'px';
	document.getElementById('frame__'+id).style.width = (parseInt(document.getElementById(id).style.width)-5)+ 'px';
	document.getElementById('frame__'+id).style.height = document.getElementById(id).style.height;
	document.getElementById('frame__'+id).style.display = "block";
	document.getElementById(id).style.display = "block";
}


/***********************************************************************************************************
Funcion:		ocultar_div_opaco
Descripcion:	Desbloquea la pantalla, y oculta la ventana para compartir noticias
Entradas:		div_contenido -> nombre del div que actua como ventana emergente
Salidas:		<< ninguna >>
***********************************************************************************************************/
function ocultar_div_opaco(div_contenido){
	if(document.getElementById(div_contenido))
	{
		document.getElementById(div_contenido).style.display = "none";
	}

	var id = 'div___bk';
	if(document.getElementById(id))
	{
		document.getElementById(id).style.display = "none";
		document.getElementById('frame__'+id).style.display="none";
	}
}


//Funcion para registrar un abuso de ip por medio de AJAX...
function RegistraAbusoIP(mail,lugar){
	ajax=objetoAjax();		
	////////////////////////////////////////////////////////////////
	//prototipo que sirve para tratar la respuesta que recibes de AJAX
	String.prototype.tratarResponseText = function() {		
		var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
		var pat2=/\b\s+src=[^>\s]+\b/g;
		var elementos = this.match(pat) || [];		
		for (i = 0; i < elementos.length; i++) {			
			var nuevoScript = document.createElement('script');
			nuevoScript.type = 'text/javascript';
			var tienesrc=elementos[i].match(pat2) || [];			
			if (tienesrc.length) 
				nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
			else {				
				var elemento = elementos[i].replace(pat,'$1');
				nuevoScript.text = elemento;				
			}			
			document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
		}		
		return this.replace(pat,'');
	} 
	///////////////////////////////////////////////////////////////		
	archPhp = 'SSN/Funciones_bloqueo.php';
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {
			 //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,' Verificando Datos ', 'amarillo')
		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX
				//divE.innerHTML = ajax.responseText.tratarResponseText();				
		 }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=AbusoIP&mail=" + mail + "&lug=" + lugar);	
}

/********************************************************************************************************
Funcion:		ValidaCaptcha
Descripcion:	Valida cuantas veces se ha accedido en la pagina de inicio de sesion neubox, si es necesario muestra el div que 
				control captcha y deshabilita el boton 'entrar' de login para que sea accedido solo por medio del control captcha.
Entradas:		<< ninguna >>
Salidas:		<< ninguna >>
********************************************************************************************************/
function ValidaCaptcha(idEntrar,idDivCaptcha){
	ajax=objetoAjax();		
	////////////////////////////////////////////////////////////////
	//prototipo que sirve para tratar la respuesta que recibes de AJAX
	String.prototype.tratarResponseText = function() {		
		var pat=/<script[^>]*>([\S\s]*?)<\/script[^>]*>/ig;
		var pat2=/\b\s+src=[^>\s]+\b/g;
		var elementos = this.match(pat) || [];		
		for (i = 0; i < elementos.length; i++) {			
			var nuevoScript = document.createElement('script');
			nuevoScript.type = 'text/javascript';
			var tienesrc=elementos[i].match(pat2) || [];			
			if (tienesrc.length) 
				nuevoScript.src=tienesrc[0].split("'").join('').split('"').join('').split('src=').join('').split(' ').join('');			
			else {				
				var elemento = elementos[i].replace(pat,'$1');
				nuevoScript.text = elemento;				
			}			
			document.getElementsByTagName('body')[0].appendChild(nuevoScript);			
		}		
		return this.replace(pat,'');
	} 
	///////////////////////////////////////////////////////////////		
	archPhp = 'SSN/Funciones_bloqueo.php';
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {
			 //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,' Verificando Datos ', 'amarillo')
		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX
		 		if(ajax.responseText == 'si'){
					suplantar(idEntrar);//deshabilita el boton de entrar para que se ejecute con el captcha
					document.getElementById(idDivCaptcha).style.display = 'block';//muestra el captcha
				}			
		 }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=accesos_conteo_validacion_ajax");	
}


/*****************************************************************************************************************************
//Limpia los controles de inicio de sesion y pone el focus en usuario
*****************************************************************************************************************************/
function LimpiaForma(){		
	//document.getElementById('tMail').value = '';
	document.getElementById('tPass').value = '';
	document.getElementById('tPass').focus();
}


function HayCaptcha(re_ruta){		
	if(document.getElementById('captcha').style.display == 'none')
		ValidaForma(re_ruta);
	else
		document.getElementById('recaptcha_response_field').focus();		
}

/*
  *realiza una determinda peticion con GetTransfer a este u otro dominio, dicha peticion sera atendida por GetTransfer y procesada para redireccionar al lugar que sea necesario
*/
function RedirectServer(dominio,destino,accion){
	ajax=objetoAjax();
	
	archPhp = 'SetTransfer.php';
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {//mientras recibe respuesta de AJAX	 
		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX		 		
		 	if(ajax.responseText != null)
				location.href = 'http://www.neubox.' + dominio+ '/GetTransfer.php' + ajax.responseText;
				
		 }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=RedirectServer&local=" + dominio + "&destino=" + destino + "&accion=" + accion);
}



/*Bloquea el poder utilizar ctrl + c y ctrl + v en alguna caja de texto*/
function EvitaCtrlCV(e) {  
  //list all CTRL + key combinations you want to disable
	var forbiddenKeys = new Array('a', 'n', 'c', 'x', 'v', 'j');
	var key;
	var isCtrl;
	if(window.event){
		key = window.event.keyCode;     //IE
		if(window.event.ctrlKey)
			isCtrl = true;
		else
			isCtrl = false;
  		}
  	else{
		key = e.which;     //firefox
	  	if(e.ctrlKey)
	  		isCtrl = true;
	  	else
			isCtrl = false;
	}
        //if ctrl is pressed check if other key is in forbidenKeys array
	if(isCtrl){
		for(i=0; i < forbiddenKeys.length; i++){
			//case-insensitive comparation
			if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()){
				//alert('Key combination CTRL + '	+ String.fromCharCode(key) + ' has been disabled.');
				return false;
			}
	  	}
  	}
  	return true;
}




function DesSubscribirPromos(mail,phpArch,div,es_cliente,la_razon,txt_razon){
	ajax=objetoAjax();		
	var divE = document.getElementById(div);
	////////////////////////////////////////////////////////////////	
	archPhp = phpArch;
	email = mail;
	
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {
			 //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,' Verificando Datos ', 'amarillo')			 
		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX		 		
			divE.innerHTML = ajax.responseText;
			if(ajax.responseText == 'baja_correcta'){
		 		divE.innerHTML = '<img src="includes/titulos.php?titulo=A partir de este momento no recibiras mas promociones de Neubox" alt="A partir de este momento no recibiras mas promociones de Neubox" title="A partir de este momento no recibiras mas promociones de Neubox" />';
			}
		 }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=DesSubscribirPromos&mail="+email+"&esCliente="+ es_cliente+"&razon="+la_razon+"&otra="+txt_razon);
}

function ReenviarMailConfirmacion(mail,div){
	ajax=objetoAjax();		
	var divResp = document.getElementById(div);
	////////////////////////////////////////////////////////////////	
	archPhp = 'includes/Login/Funciones_Login.php';
	email = mail;
	
	ajax.open("POST",archPhp,true);
	ajax.onreadystatechange = function() {
		 if (ajax.readyState==1) {
			 //divE.innerHTML = "Verificando Datos ... ... ...";
			 //escribir_mensaje(div,' Verificando Datos ', 'amarillo')			 
			 divResp.innerHTML = "Cargando...";
		 }
		 else if(ajax.readyState==4){//si se recibe respuesta de AJAX		 		
			switch(ajax.responseText){
				case 'mail_enviado':
					divResp.innerHTML = '<img src="includes/titulos.php?titulo=El correo ha sido enviado a tu correo" title="El correo ha sido enviado a tu correo" alt="Enviado" />';
				break;
				case 'cuenta_ya_verificada':
					divResp.innerHTML = '<img src="includes/titulos.php?titulo=Tu cuenta ya esta verificada" title="Tu cuenta ya esta verificada" alt="Enviado" />';
				break;
				case 'mail_incorrecto':
					divResp.innerHTML = '<img src="includes/titulos.php?titulo=El mail que proporcionaste es incorrecto" title="El mail que proporcionaste es incorrecto" alt="Enviado" />';
				break;
				case 'error_datos':
					divResp.innerHTML = '<img src="includes/titulos.php?titulo=Ha ocurrido un error al procesar la petici&oacute;n" title="Ha ocurrido un error al procesar la petici&oacute;n" alt="Enviado" />';
				break;				
			}
		 }
	}
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("funcion=ReenviarMailConfirm&mail="+email);
}


function CambiarEstados(idPais,idComboEdo,divResp){
	if ( document.getElementById(idPais).value ) {
		codigo_pais = document.getElementById(idPais).value;
		var divR = document.getElementById(divResp);
		////////////////////////////////////////////////////////////////	
		archPhp = 'includes/Login/Funciones_Login.php';		
		
		ajax.open("POST",archPhp,true);
		ajax.onreadystatechange = function() {
			 if (ajax.readyState==1) {				 
				 divR.innerHTML = "Cargando...";
			 }
			 else if(ajax.readyState==4){//si se recibe respuesta de AJAX		 							
				divR.innerHTML = ajax.responseText;
			 }
		}
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		//Se deben de enviar los parametros de pais_cod, id_combo_edo.
		//Son opcionales los parametros selecc, clas, acc, habil
		ajax.send("funcion=MakeStatesCombo&pais_cod="+codigo_pais+"&id_combo_edo="+idComboEdo);
	}	
}