// valida_form_entidade.js

/*  This page does all the magic for applying
 *  Ajax to an "add an employee" form.
 *  The form data is sent to a PHP 
 *  script using the POST method.
 *  The PHP script sends back a response in XML format.
 */
 
// Have a function run after the page loads:
window.onload = init;
//window.onload = showOptions;

// Function that adds the Ajax layer:
function init()
	{
		// Get an XMLHttpRequest object:
		var ajax_form = getXMLHttpRequestObject();
  
		// Attach the function call to the form submission, if supported:
		if (ajax_form)
			{
				// Check for DOM support:
				if (document.getElementById('resultado'))
					{
						// Add an onsubmit event handler to the form:
						document.getElementById('formEntidade').onsubmit = function()
							{
								// Call the PHP script.
								// Use the POST method.
						        // Open the connection:
								ajax_form.open('POST', 'xmlphp/add_entidade_xml.php');
        
								// Function that handles the response:
								ajax_form.onreadystatechange = function()
									{
										// Pass it this request object:
										handleResponse(ajax_form);
									}

								// Assemble all the form data:
								var fields = ['tipoEntidade', 
								'Especificar', 
								'Entidade', 
								'Morada', 
								'Distrito', 
								'Concelho', 
								'Freguesia', 
								'codigoPostal', 
								'Email', 
								'Telefone'];
								for (var i = 0; i < fields.length; i++)
									{
										fields[i] = fields[i] + '=' + encodeURIComponent(document.getElementById(fields[i]).value); 
									}
								var values = fields.join('&');
								// Set the request headers:
								ajax_form.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        
								// Send the request along with the data:
								ajax_form.send(values);
      
								return false; // So form isn't submitted.

							} // End of anonymous function.
					} // End of DOM check.
			} // End of ajax IF.
	
	} // End of init() function.

// Function that handles the response from the PHP script:
function handleResponse(ajax_form)
	{
		// Check that the transaction is complete:
		if (ajax_form.readyState == 4)
			{
				// Check for a valid HTTP status code:
				if ((ajax_form.status == 200) || (ajax_form.status == 304) )
					{
						var results = document.getElementById('resultado');
						// Reset all the labels:
						document.getElementById('tipoEntidade_label').className = 'label';
						document.getElementById('Especificar_label').className = 'label';
						document.getElementById('Entidade_label').className = 'label';
						document.getElementById('Morada_label').className = 'label';
						document.getElementById('Distrito_label').className = 'label';
						document.getElementById('Concelho_label').className = 'label';
						document.getElementById('Freguesia_label').className = 'label';
						document.getElementById('codigoPostal_label').className = 'label';
						document.getElementById('Email_label').className = 'label';
						document.getElementById('Telefone_label').className = 'label';

						//alert(ajax_form.responseText);
						//alert(ajax_form.responseXML);

						// Get the XML data:
						var data_form = ajax_form.responseXML;
      
						// Get the main response:
						var message = data_form.getElementsByTagName('resultado');
      
						// Get all the errors:
						var errors = data_form.getElementsByTagName('error');

						// Verify erros
						if (errors.length > 0)
							{
								// Temp variable to use in the loop:
								var temp = false;
		      
								// Loop through each error:
								for (var i = 0; i < errors.length; i++)
									{
										// Get the error value:
										temp = errors[i].firstChild.nodeValue;
										// Change the class:
										document.getElementById(temp + '_label').className = 'error';
		        
									} // End of FOR loop.
		  
								// Put the received response in the DOM:
								results.innerHTML = message[0].firstChild.nodeValue;
		      
								// Make the results box visible:
								results.style.display = 'block';
							}
						else
							{
								document.getElementById('formEntidade').submit();							
							}
					}
				else
					{ // Bad status code, alert user.
						alert('Problema na comunicação com o servidor. Por favor, tente mais tarde');
						//return false;
					}
    
  			} // End of readyState IF.
  
	} // End of handleResponse() function.


function focusElement(formName, elemName)
	{
		var elem = document.forms[formName].elements[elemName];
		elem.focus();
		elem.select();
	}
	
function validarEmail(form)
	{	
		var email = form.email.value;
		email = email.toLowerCase();
		if	(email.indexOf("@") > 1)
			{
				var nome		= email.substring(0, email.indexOf("@"));
				var operador	= email.substring(email.indexOf("@") + 1, email.length);
				var dominio		= email.substring(email.lastIndexOf(".") + 1, email.length);
				//pelo menos um operador de email necessario
				if	(operador.indexOf(".") == -1)
					{
						alert("Verifique o nome do seu operador de email no endereço de email.");
						setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
						return false;
					}
				//verificar o nome do email caracter a caracter
				for (var i = 0; i < nome.length; i++)
					{
						umChar = nome.charAt(i).charCodeAt(0);
						//ponto ou ifen nao permitidos na primeira posicao ponto no fim
						if	((i == 0 && (umChar == 45 || umChar == 46)) || (i == nome.length - 1 && umChar == 46))
							{
								alert("Verifique a parte do nome: " + nome + " no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
						//verificar caracacteres aceitaveis 
						if	( umChar == 45 || umChar == 46 || umChar == 95 || (umChar > 47 && umChar < 58) || (umChar > 96 && umChar < 123))
							{
								continue;
							}
						else
							{
								alert("Verifique a parte do nome no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
					}
				//verificar o operador do email caracter a caracter
				for (i = 0; i < operador.length; i++)
					{
						umChar = operador.charAt(i).charCodeAt(0);
						if ((i == 0 && (umChar == 45 || umChar == 46)) || ((i == operador.length - 1 || i == operador.length - 2) &&  umChar == 46))
							{
								alert("Verifique o nome do seu operador de email no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
						//verificar caracacteres aceitaveis 
						if	( umChar == 45 || umChar == 46 || umChar == 95 || (umChar > 47 && umChar < 58) || (umChar > 96 && umChar < 123))
							{
								continue;
							}
						else
							{
								alert("Verifique o nome do seu operador de email no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
					}
				//verificar o dominio do email para evitar caracteres numericos
				for (i = 0; i < dominio.length; i++)
					{
						umChar = dominio.charAt(i).charCodeAt(0);
						//ponto ou ifen nao permitidos na primeira posicao ponto no fim
						if ((i == 0 && (umChar == 45 || umChar == 46)) || ((i == dominio.length - 1 || i == dominio.length - 2) &&  umChar == 46))
							{
								alert("Verifique o domínio: " + dominio + " do seu operador de email no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
						//verificar caracacteres aceitaveis e existencia de numeros
						if	( umChar == 45 || umChar == 46 || umChar == 95 || (umChar > 96 && umChar < 123))
							{
								continue;
							}
						else
							{
								alert("Verifique o domínio: " + dominio + " do seu operador de email no endereço de email.");
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							}
					}
				verificar_email(email, form);
				return true;
			}
		else
			{
				if	(email !='')
					{
						alert("O endereço de email poderá não estar formatado correctamente. Por favor verifique.");
						setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
						return false;
					}
			}

		verificar_email(email, form);
		return true;
	}


function verificar_email(email, form)
	{
		var entidadeID = form.entidadeID.value;

		// Attach the function call to the form submission, if supported:
		if (email)
			{
				// Get an XMLHttpRequest Object
				var ajax_email = getXMLHttpRequestObject();
				if (!ajax_email)
					{
						alert('Ajax inoperacional');
						return;	
					}
					
				// Check for DOM support:
				if (document.getElementById('resultado_email'))
					{
						ajax_email.onreadystatechange = function()
							{
								verifica_email(ajax_email, form);
							}
						if (entidadeID)
							{
								ajax_email.open('GET', 'xmlphp/verifica_email_xml.php?email=' + email + '&entidadeID=' + entidadeID, true);
								// alert('GET, xmlphp/verifica_email_xml.php?email=' + email + '&entidadeID=' + entidadeID +', true');							
							}
						else
							{
								ajax_email.open('GET', 'xmlphp/verifica_email_xml.php?email=' + email, true);
								// alert('GET, xmlphp/verifica_email_xml.php?email=' + email +', true');							
							}
						ajax_email.send(null);
					}
			}
	}
	
// Function that handles the response from the PHP script:
function verifica_email(ajax_email, form)
	{
		// Check that the transaction is complete:
		if (ajax_email.readyState == 4)
			{
				// Check for a valid HTTP status code:
				if ((ajax_email.status == 200) || (ajax_email.status == 304) )
					{
						var results = document.getElementById('resultado_email');

						// Get the XML data:
						var data_email = ajax_email.responseXML;
      
						// Get the main response:
						var message = data_email.getElementsByTagName('resultado_email');
      
						// Put the received response in the DOM:
						results.innerHTML = message[0].firstChild.nodeValue;
      
						// Make the results box visible:
						results.style.display = 'block';
						
						// If email exists then focus field email
						if (results.innerHTML != ' ')
							{
								alert('Tem de substituir o endereço de email, para poder registar/editar a presente entidade');
								setTimeout("focusElement('" + form.name + "', '" + form.email.name + "')", 0);
								return false;
							} 
					}
				else
					{ // Bad status code, alert user.
						alert('Problema na comunicação com o servidor. Por favor, tente mais tarde');
						return;
					}
    
  			} // End of readyState IF.
	} // End of verifica_email() function.

	
