// JavaScript Document
onload=function() 
{
 divTransparente=document.getElementById("transparencia");
 divMensaje=document.getElementById("transparenciaMensaje");
 /*divpago_tarjeta=document.getElementById("pago_tarjeta");*/
 form=document.getElementById("registro_agencia");
 urlDestino="reg_agencia.php";
 
 claseNormal="input";
 claseError="inputError";
}
function getPageScroll()
{

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
function validarBotonRadio(pago)
{
var s = "no";
var a="";

	 for ( var i = 0; i < pago.length; i++ )
	 {
	   if ( pago[i].checked )
	   { 
        s= "si";
		a=pago[i].value; 
        break; 
      } 
     } 
	 
     if ( s == "no" )
     { 
	  a="Debe seleccionar algun tipo de pago" ;
	  error=2;
     } 
return a;
}
function nuevoAjax()
{ 
	var xmlhttp=false; 
	try 
	{ 
		// No IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!="undefined") { xmlhttp=new XMLHttpRequest(); } 
	return xmlhttp; 
}
function campoError(campo)
{
	campo.className=claseError;
	error=1;
}
function campoError_email(campo)
{
	campo.className=claseError;
	error=2;
}
function campoError_telefono(campo)
{
 campo.className=claseError;
 error=3;
}
function campoError_cPostal(campo)
{
 campo.className=claseError;
 error=4;
}
function campoError_Password(campo)
{
 campo.className=claseError;
 error=5;
}
function ocultaMensaje()
{
	divTransparente.style.display="none";
}
function muestraMensaje(mensaje)
{
	divMensaje.innerHTML=mensaje;
	divTransparente.style.display="block";
}
function eliminaEspacios(cadena)
{
	// Funcion para eliminar espacios delante y detras de cada cadena
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}
function validaLongitud(valor, permiteVacio, minimo, maximo)
{
	var cantCar=valor.length;
	if(valor=="")
	{
		if(permiteVacio) return true;
		else return false;
	}
	else
	{
		if(cantCar>=minimo && cantCar<=maximo) return true;
		else return false;
	}
}
function limpiaForm()
{
	for(i=0; i<=14; i++)
	{
		form.elements[i].className=claseNormal;
	}
	document.getElementById("code_s").className=claseNormal;
}
function validaCorreo(valor)
{
	var reg=/(^[a-zA-Z0-9._-]{1,30})@([a-zA-Z0-9.-]{1,30}$)/;
	if(reg.test(valor)) return true;
	else return false;
}
function validaTelefono(tel)
{
 reg=/^\d{3}-\d{3}-\d{4}\+\(\d{3,4}\)$/;
 if(reg.test(tel)) return true;
	else return false;
}
function valida_codigoP(cod)
{
 reg=/^\d{5}$/;
 if(reg.test(cod)) return true;
	else return false;
}
function validaPassword(pass,re_pass)
{
 if(pass==re_pass) return true;
  else return false;
}
function validaForm()
{

limpiaForm();
error=0;
  
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();
  divTransparente.onclick = function () {ocultaMensaje(); return false;}
  divTransparente.style.width=arrayPageSize[0]+'px';
  divTransparente.style.height=arrayPageSize[1]+'px';
    
  var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - 32) / 2);
  var lightboxLeft = ((arrayPageSize[0] - 20 - 32) / 2);
	
  divMensaje.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
  divMensaje.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
	
 /****************Datos Agencia***************************/
  var agencia=eliminaEspacios(form.agencia.value);  
  var pais=eliminaEspacios(form.pais.value);
  var estado=eliminaEspacios(form.estado.value);
  var ciudad=eliminaEspacios(form.ciudad.value);
  var direccion=eliminaEspacios(form.direccion.value);
  var cod_postal=eliminaEspacios(form.cod_postal.value);
  var tel_agencia=eliminaEspacios(form.tel_ext.value);
  var pag_web=eliminaEspacios(form.pag_web.value);
  
  var usuario=eliminaEspacios(form.usuario.value);
  var password=eliminaEspacios(form.password.value);
  var conf_password=eliminaEspacios(form.re_password.value);
  
  /****************Datos Gerente***************************/
  var nom_gerente=eliminaEspacios(form.nom_direc.value);
  var tel_gerente=eliminaEspacios(form.tel_direc.value);
  var email_gerente=eliminaEspacios(form.email_direc.value);

  /****************Codigo de Seguridad***************************/
  var codigo_seguridad=eliminaEspacios(form.code_s.value);  
  	
  /************************************************************
  *                                                           * 
  *                Validar los Datos                          *
  *                                                           *
  ************************************************************/
  /***************************************************************/
  if(!validaCorreo(email_gerente)) campoError_email(form.email_direc);
  if(!validaTelefono(tel_gerente)) campoError_telefono(form.tel_direc);
  var tel1=encodeURIComponent(tel_gerente);
  if(!validaTelefono(tel_agencia)) campoError_telefono(form.tel_ext);
  var tel=encodeURIComponent(tel_agencia);
  if(!valida_codigoP(cod_postal)) campoError_cPostal(form.cod_postal);
  //if(!validaCorreo(email_agen)) campoError_email(form.email_agen);
  if(!validaPassword(password,conf_password)) campoError_Password(form.re_password);

  /*******************Validando codigo de seguridad****************/
  if(!validaLongitud(codigo_seguridad, 0, 1, 50)) campoError(form.code_s);
  
  /*******************Datos Gerente****************************/
  if(!validaLongitud(nom_gerente, 0, 1, 50)) campoError(form.nom_direc);  
    
  /*******************Datos Agencia****************************/
   if(!validaLongitud(conf_password, 0, 1, 50)) campoError(form.re_password);
   if(!validaLongitud(password, 0, 1, 50)) campoError(form.password);
   if(!validaLongitud(usuario, 0, 1, 50)) campoError(form.usuario);
   if(!validaLongitud(pag_web, 1, 1, 50)) campoError(form.pag_web);
   if(!validaLongitud(direccion, 0, 1, 50)) campoError(form.direccion);
   if(!validaLongitud(ciudad, 0, 1, 50)) campoError(form.ciudad);
   if(!validaLongitud(estado, 0, 1, 50)) campoError(form.estado);
   if(!validaLongitud(pais, 0, 1, 50)) campoError(form.pais);
   if(!validaLongitud(agencia, 0, 1, 50)) campoError(form.agencia);
   
    if(error==1)
	{
		var texto="<img src='images/error.gif' alt='Error'><br><br>Error: check the red fields.<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
		
	}else
      if(error==0)
	  {
	    var texto="<img src='images/loading.gif' alt='Error'><br>Sending. Please wait ...<br>";
		muestraMensaje(texto);
	   
	   
		var ajax=nuevoAjax();

		ajax.open("POST", urlDestino, true);
     	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("agencia="+agencia+"&pais="+pais+"&estado="+estado+"&ciudad="+ciudad+"&direccion="+direccion+"&cod_postal="+cod_postal+"&tel_agen="+tel+"&pag_web="+pag_web+"&usuario="+usuario+"&password="+password+"&nom_gerente="+nom_gerente+"&tel_gerente="+tel1+"&email_gerente="+email_gerente+"&codigo_seguridad="+codigo_seguridad);
				
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
				var respuesta=ajax.responseText;
				if(respuesta=="OK")
				{
				 pag_php("index.php?registro=true");
				}
				else
				 if(respuesta=="E1")
				 {
				  var texto="<img src='images/error.gif'><br><br>Error: Verify the security code ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				   muestraMensaje(texto);
				 }
				 else
				 if(respuesta=="E2")
				 {
				  var texto="<img src='images/error.gif'><br><br>Error: The agency has been registered ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				   muestraMensaje(texto);
				 }
				 else
				 {
					 var texto="<img src='images/error.gif'><br><br>Error: Try again later ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				muestraMensaje(texto); 
				 }
			}
		}
	  }
	  else
	   if(error==2)
	   {
	    var texto="<img src='images/error.gif' alt='Error'><br><br>Error: Any of your email is not valid ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
	   }
	   else
	    if(error==3)
		{
		 var texto="<img src='images/error.gif' alt='Error'><br><br>Error: Any of your phone is invalid ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
		}
		else
		 if(error==4)
		 {
		  var texto="<img src='images/error.gif' alt='Error'><br><br>Error: Check your Postcode ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
		 }
		 else
		  if(error==5)
		  {
		    var texto="<img src='images/error.gif' alt='Error'><br><br>Error: The Password does not match ...<br><br><button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
		  }	   
}
function pag_php(pag)
{
 document.location.href=pag;
}
