function registo() {
	var erro= new Array();
	var msg_erro="";
	
	i=0;
	var username = document.getElementById('username').value;
	if(username.length < 5) {erro[i] = 'O username tem que ter mais que 5 caracteres.'; i++;}
	if(document.getElementById('password').value.length < 5) {erro[i] = 'A palavra passe tem que ter mas que 5 caracteres.'; i++;}
	if(document.getElementById('password').value !== document.getElementById('password_confirma').value) {erro[i] = 'Palavra passe não coincide.'; i++;}
	var checkEmail = document.getElementById('email').value;
	if((checkEmail.indexOf('@') < 0) || ((checkEmail.charAt(checkEmail.length-4) != '.') && (checkEmail.charAt(checkEmail.length-3) != '.'))) {erro[i] = 'E-mail inválido.'; i++;}
	if(document.getElementById('nome').value.length < 2) {erro[i] = 'Tem que preencher o campo nome.'; i++;}
	if(document.getElementById('nif').value.length < 9) {erro[i] = 'Tem que preencher o campo numero de contribuinte.'; i++;}
	if(document.getElementById('morada').value.length < 2) {erro[i] = 'Tem que preencher o campo morada.'; i++;}
	if(document.getElementById('cp1').value.length < 4) {erro[i] = 'Código postal incorrecto.'; i++;}
	if(document.getElementById('localidade').value.length < 2) {erro[i] = 'Tem que preencher o campo localidade.'; i++;}
	if(document.getElementById('telef').value.length < 9) {erro[i] = 'Tem que preencher o campo telefone.'; i++;}
	
	
	for (i=0;i < erro.length ;i++) {
	msg_erro += erro[i]+'<br />';
	}
	msg_erro += '<br />';
	
	if(erro.length>0) {
		document.getElementById('msg').innerHTML = msg_erro;
	}
	else {
		document.getElementById('msg').innerHTML = '';
		verifica_username('confirma_username_ajax.php?username=' + username);
		
	}
}

function envia() {
		f = document.getElementById('form_registo');
		f.action = 'submit_registo.php';
		f.submit();
}


var xmlhttp;
function verifica_username(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for Firefox, Opera, IE7, etc.
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=state_Change;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
  	{
		if(xmlhttp.responseText) {
			document.getElementById('msg').innerHTML = 'Esse username já existe.';
		}
		else
		{
			envia();
		}
	}
    
  else
    {
    alert("Problem retrieving data:" + xmlhttp.statusText);
    }
  }
}
