var tentConta = 0;

function getInternetExplorerVersion()
{
    var rv = -1; // Return value assumes failure.
    if(navigator.appName == "Microsoft Internet Explorer")
	{
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function checkPhone(phone)
{
	for (a = 0; a < phone.length; a++)
		if((phone.charCodeAt(a) < 48)||(phone.charCodeAt(a) > 57)) 
			return true;
	return false;
}

function apresentarRegisto(salesID)
{
	document.getElementById('minhaContaTitulo').innerHTML = 'Registo';
	document.getElementById('minhaContaTexto').innerHTML = '';
	document.getElementById('minhaContaTexto').style.paddingLeft = 0+'px';
	document.getElementById('minhaContaTexto').style.paddingRight = 0+'px';
	document.getElementById('minhaContaTexto').style.textAlign = 'left';
	document.getElementById('minhaContaTexto2').innerHTML = '';
	
	var success = '';
	var newopt;
	success += '<p class="text" style="text-align:left;font-size: 12px;">&nbsp Os campos assinalados com asterisco &nbsp<font style="color:#FF0000">(*)</font>&nbsp são de preenchimento obrigatório.</p>';
	success += '<p style="font:15px Arial;font-weight:bold;color:#000000;padding-top:10px">&nbsp Detalhes do Utilizador</p>';
	success += '<form name="register" action="" id="formregister" method="post" enctype="multipart/form-data">';
	success += '<table id="registerTable" border=0 align="center" width="530px" style="font:11px Arial;color:#000000;">';
	
	success += '<tr>';
	success += '<td width=41%><span class="textRegister" id="campoNome">Nome<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="text" id="nomeRegisto" name="nome"/></td>';
	success += '<td><span class="textRegister" id="campoApelido">Apelido<font style="color:#FF0000">*</span><br/>';
	success += '<input class="textInput" size="30" type="text" id="apelidoRegisto" name="apelido"/></td>';
	success += '</tr>';
	
	success += '<tr>';
	success += '<td colspan="2" style="padding-top:10px"><span class="textRegister" id="campoUsername">Username<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="text" id="usernameRegisto" name="username"/></td>';
	success += '</tr>';
	
	success += '<tr>';
	success += '<td width=41% style="padding-top:10px"><span class="textRegister" id="campoPass">Password<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="password" id="passwordRegisto" name="password"/></td>';
	success += '<td style="padding-top:10px"><span class="textRegister" id="campoVPass">Repetir Password<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="password" id="vpasswordRegisto" name="vpassword"/></td>';	
	success += '</tr>';
	
	success += '<tr>';
	success += '<td width=41% style="padding-top:10px"><span class="textRegister" id="campoEmail">E-mail<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="email" id="emailRegisto" name="email"/></td>';
	success += '<td style="padding-top:10px"><span class="textRegister" id="campoVEmail">Repetir E-mail<font style="color:#FF0000">*</font></span><br/>';
	success += '<input class="textInput" size="30" type="vemail" id="vemailRegisto" name="vemail"/></td>';
	success += '</tr>';
	success += '</table>';
	success += '</form>';	
		
	success += '<p style="font:15px Arial;font-weight:bold;color:#000000;padding-top:20px">&nbsp Informação Pessoal</p>';
	
	success += '<form name="pInfo" action="" id="pInfoRegister" method="post" enctype="multipart/form-data">';	
	success += '<table class="tableRegister" id="pInfoTable" border=0 align="center" width="530px">';	
	success += '<tr>';
	success += '<td width=41%><span class="textRegister" id="campoDesporto">Desporto</span><br/>';
	success += '<input class="textInput" size="30" type="text" id="desportoRegisto" name="desporto"/></td>';
	success += '<td><span class="textRegister" id="campoPraia">Praia de eleição</span><br/>';
	success += '<input class="textInput" size="35" type="text" id="praiaRegisto" name="praia"/></td>';
	success += '</tr></table>';
	
	success += '<table class="tableRegister" id="pInfoTable2" border=0 align="center" width="530px">';	
	success += '<tr>';
	success += '<td width=33% style="padding-top:10px"><span class="textRegister" id="campoDataNasc">Data de Nascimento</span><br/>';
	success += '<input class="textInput" maxlength="2" type="text" style="width:25px;text-align:center" id="diaNascRegisto" name="diaNasc"/>&nbsp - &nbsp';
	success += '<input class="textInput" maxlength="2" type="text" style="width:25px;text-align:center" id="mesNascRegisto" name="mesNasc"/>&nbsp - &nbsp';
	success += '<input class="textInput" maxlength="4" type="text" style="width:55px;text-align:center" id="anoNascRegisto" name="anoNasc"/>';
	success += '</td>';
	success += '<td style="padding-top:10px"><span class="textRegister" id="campoOcup">Ocupação</span><br/>';
	success += '<input class="textInput" size="35" type="text" id="ocupRegisto" name="ocup"/></td>';
	success += '</tr></table>';
	
	success += '<table class="tableRegister" id="pInfoTable3" border=0 align="center" width="530px">';
	success += '<tr>';
	success += '<td width=71% style="padding-top:10px"><span class="textRegister" id="campoMorada">Endereço</span><br/>';
	success += '<input class="textInput" size="62" type="text" id="moradaRegisto" name="morada"/>';
	success += '</br><small>&nbsp[Para envio de informação]</small></td>';		
	success += '<td style="padding-bottom:5px"><span class="textRegister" id="campoCodPost">Código Postal</span><br/>';
	success += '<input class="textInput" maxlength="4" type="text" style="width:45px;text-align:center" id="cod1CodPost" name="cod1Post"/>&nbsp - &nbsp';
	success += '<input class="textInput" maxlength="3" type="text" style="width:35px;text-align:center" id="cod2CodPost" name="cod2Post"/>';
	success += '</td>';
	success += '</tr></table>';
	
	success += '<table class="tableRegister" id="pInfoTable4" border=0 align="center" width="530px">';
	success += '<tr>';
	success += '<td colspan="2" style="padding-top:10px"><span class="textRegister" id="campoMovel">Telemóvel</span><br/>';
	success += '<input class="textInput" size="23" maxlength="15" type="text" id="movelRegisto" name="movel" style="text-align:right"/><br/>&nbsp<small>[Para receber notícias]</small></td>';
	success += '</tr></table>';	
	success += '</form>';	
	
	success += '<p class="text" style="text-align:left;font-size: 12px;">&nbsp Antes de proceder ao registo, leia atentamente a <a href="privacidade.php">política de privacidade</a></p>';
	success += '<br/><a href="javascript:registarConta('+salesID+')" style="padding-top:20px;padding-left:10px"><img src="../common/images/minhacontaButton.png" border="0"/></a>';
	
	if (navigator.appName == "Microsoft Internet Explorer") 
		success += '<div id="registerErrors" style="position:relative;left:140px;bottom:50px;line-height:1.3"></div>';
	else
		success += '<div id="registerErrors" style="position:relative;left:100px;bottom:40px"></div>';
	
	document.getElementById('minhaContaTexto').innerHTML = success;
}

function registarConta(saleID)
{
	// Obrigatorios
	var nome = document.getElementById('nomeRegisto').value;
	var apelido = document.getElementById('apelidoRegisto').value;
	var username = document.getElementById('usernameRegisto').value;
	var password = document.getElementById('passwordRegisto').value;
	var vpassword = document.getElementById('vpasswordRegisto').value;
	var email = document.getElementById('emailRegisto').value;
	var vemail = document.getElementById('vemailRegisto').value;
	
	// Opcionais	
	var desporto = document.getElementById('desportoRegisto').value;
	var praia = document.getElementById('praiaRegisto').value;
	var dia = document.getElementById('diaNascRegisto').value;
	var mes = document.getElementById('mesNascRegisto').value;
	var ano = document.getElementById('anoNascRegisto').value;
	var ocup = document.getElementById('ocupRegisto').value;
	var morada = document.getElementById('moradaRegisto').value;
	var codP1 = document.getElementById('cod1CodPost').value;
	var codP2 = document.getElementById('cod2CodPost').value;
	var telemovel = document.getElementById('movelRegisto').value;
	
	var htmlError = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'>";
	
	if( (checkPhone(telemovel)&&(telemovel.length>0))||(nome=='')||(username=='')||(password=='')||(vpassword=='')||(email=='')||(vemail=='') )
	{
		if (nome == '') 
			htmlError += "<li>Falta preencher o Nome</li>";
			
		if (apelido == '') 
			htmlError += "<li>Falta preencher o Apelido</li>";
			
		if (username == '') 
			htmlError += "<li>Falta preencher o Username</li>";	
			
		if (password == '') 
			htmlError += "<li>Falta preencher o Password</li>";
					
		if (vpassword == '') 
			htmlError += "<li>Falta preencher o Repetir Password</li>";
		
		if (email == '') 
			htmlError += "<li>Falta preencher o E-mail</li>";
			
		if (vemail == '') 
			htmlError += "<li>Falta preencher o Repetir E-mail</li>";
			
		if( checkPhone(telemovel)&&(telemovel.length>0) )
			htmlError += "<li>Telemóvel inválido</li>";
			
		htmlError += "<ul>";
		document.getElementById('registerErrors').innerHTML = htmlError;
	}
	else 
		if( (username==password)||( password.length<4 )||(email.search(/@/)==-1)||(email.search(/@/)==0)||(email.search(/@/)==(email.length-1))||(password!=vpassword)||(email!=vemail) )
		{
			if( username==password )
				htmlError += "<li>Nome e Password iguais</li>";
				
			if( password.length<4 )
				htmlError += "<li>Password demasiado pequena</li>";
				
			if( (email.search(/@/)==-1)||(email.search(/@/)==0)||(email.search(/@/)==(email.length-1)) )
				htmlError += "<li>E-mail Inválido</li>";
			
			if( password!=vpassword )
				htmlError += "<li>Password e Repetir Password diferentes</li>";

			if( email!=vemail )
				htmlError += "<li>E-mail e Repetir E-mail diferentes</li>";
			
			htmlError += "<ul>";
			document.getElementById('registerErrors').innerHTML = htmlError;
		}
		else
		{			
			var req = 'minhaconta/pedidosConta.php?tipo=3';
			req += '&nome='+encodeURIComponent(nome);
			req += '&username='+encodeURIComponent(username);
			req += '&password='+encodeURIComponent(password);
			req += '&email='+encodeURIComponent(email);
			if( apelido!='' )
				req += '&apelido='+encodeURIComponent(apelido);
			if( desporto!='' )
				req += '&desporto='+encodeURIComponent(desporto);
			if( praia!='' )
				req += '&praia='+encodeURIComponent(praia);
			if( (dia!='')&&(mes!='')&&(ano!=''))
				req += '&dia='+dia+'&mes='+mes+'&ano='+ano;
			if( ocup!='' )
				req += '&ocup='+encodeURIComponent(ocup);
			if( morada!='' )
				req += '&morada='+encodeURIComponent(morada);
			if( (codP1!='')&&(codP2!='') )
				req += '&codp1='+codP1+'&codp2='+codP2;
			if( telemovel!='' )
				req += '&telemovel='+encodeURIComponent(telemovel);
			
			req += '&sale='+saleID;
			
			//alert(req);
			new Ajax.Request(req, {method: 'get',onSuccess: function(transport)
			{
					var find = transport.responseText;					
					switch(find)
					{
						case 'ok':
							document.getElementById('minhaContaTexto').innerHTML = '';
							document.getElementById('minhaContaTexto2').innerHTML = '';
							var success = '<p class="text" style="text-align:left;">O registo da sua conta foi feita com sucesso!</p>';
							success += '<p class="text" style="text-align:left;">A confirmação do seu registo será enviada por e-mail. Proceda à sua activação!</p>';
							success += '<p class="text" style="text-align:left;">Keep Surfing,<cite><br/><b>1oo%surF team</b></cite><br/></p>';
							success += '<p class="text" style="text-align:left;">Para mais informação: <a href="mailto:info@100surf.pt">info@100surf.pt</a></p>';
							document.getElementById('minhaContaTexto').innerHTML = success;
							break;
							
						case 'userrep':
							document.getElementById('registerErrors').innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>Username já existente</li></ul>";
							break;
							
						case 'mailrep':
							document.getElementById('registerErrors').innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>E-mail já existente</li></ul>";
							break;
							
						default: break;
					}
				}
			});	
		}
}

function entrarConta()
{
	var username = document.getElementById('usernameLogin').value;
	var password = document.getElementById('passwordLogin').value;
	
	if((username=='')||(password=='')) 
	{
		document.getElementById('erroLogin').innerHTML = 'Insira os dados!';
		document.getElementById('erroLogin').style.visibility = 'visible';
	}
	else 
	{
		new Ajax.Request('minhaconta/pedidosConta.php?tipo=1&user=' + username + '&pass=' + password, {
			method: 'get', onSuccess: function(transport)
			{
				var find = transport.responseText;

				switch(find)
				{
					case 'er':
						tentConta++;
						document.getElementById('erroLogin').innerHTML = 'Username ou Password errada!';
						document.getElementById('erroLogin').style.visibility = 'visible';
						
						if( tentConta == 3)
							document.getElementById('minhaContaTexto2').style.visibility = 'visible';
						break;
					
					case 'ac':
						document.getElementById('erroLogin').innerHTML = 'Confirme o seu registo!';
						document.getElementById('erroLogin').style.visibility = 'visible';						
						break;
						
					default:
						tentConta = 0;
						window.location = "conta.php?first=1";
						break;						
				}
			}
		});
	}	
}

function pedirPassword()
{
	var email = document.getElementById('emailLogin').value;
	
	new Ajax.Request('minhaconta/pedidosConta.php?tipo=2&mail='+email, {
		method: 'get',
		onSuccess: function(transport){
			var find = transport.responseText;
			
			if (find == 'ok') 
			{
				var success = '';
				success += '<p class="text" style="text-align:left;"> A sua password e user name de acesso foram enviados com sucesso para o seu endereço de correio electrónico</p>';
				success += '<p class="text" style="text-align:left;"><strong>Verifique o seu E-mail!</strong></p>';
				document.getElementById('minhaContaTexto').innerHTML = '';		
				document.getElementById('minhaContaTexto2').innerHTML = '';
				
				document.getElementById('minhaContaTexto').innerHTML = success;	
			}
			else
				document.getElementById('erroMail').style.visibility = 'visible';
		}
	});
}

function alterarConta(oldnick,oldmail)
{
	// Obrigatorios
	var nome = document.getElementById('nomeRegisto').value;
	var apelido = document.getElementById('apelidoRegisto').value;
	//var username = document.getElementById('usernameRegisto').value;
	var oldpassword = document.getElementById('oldpassRegisto').value;
	var password = document.getElementById('passwordRegisto').value;
	var vpassword = document.getElementById('vpasswordRegisto').value;
	var email = document.getElementById('emailRegisto').value;
	
	// Opcionais	
	var desporto = document.getElementById('desportoRegisto').value;
	var praia = document.getElementById('praiaRegisto').value;
	var dia = document.getElementById('diaNascRegisto').value;
	var mes = document.getElementById('mesNascRegisto').value;
	var ano = document.getElementById('anoNascRegisto').value;
	var ocup = document.getElementById('ocupRegisto').value;
	var morada = document.getElementById('moradaRegisto').value;
	var codP1 = document.getElementById('cod1CodPost').value;
	var codP2 = document.getElementById('cod2CodPost').value;
	var telemovel = document.getElementById('movelRegisto').value.split(' ').join('');	
	var htmlError = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'>";
		
	if((checkPhone(telemovel))||(email.search(/@/)==-1)||(email.search(/@/)==0)||(email.search(/@/)==(email.length-1))||(nome == '')/*||(username == '')*/||(((oldpassword!='')||(password!='')||(vpassword!=''))&&(!((oldpassword!='')&&(password!='')&&(vpassword!=''))))||(email == '')) 
	{
		if (nome == '') 
			htmlError += "<li>Falta preencher o Nome</li>";
		
		if (apelido == '') 
			htmlError += "<li>Falta preencher o Apelido</li>";
		
		//if (username == '') 
		//		htmlError += "<li>Falta preencher o Username</li>";
				
		if ( (oldpassword!='')||(password!='')||(vpassword!='') )
		{		
			if (oldpassword == '') 
				htmlError += "<li>Falta preencher o Password Antiga</li>";
				
			if (password == '') 
				htmlError += "<li>Falta preencher o Password Nova</li>";
			
			if (vpassword == '') 
				htmlError += "<li>Falta preencher o Repetir Password Nova</li>";
		}		
		
		if (email == '') 
			htmlError += "<li>Falta preencher o E-mail</li>";
			
		if( (email.search(/@/)==-1)||(email.search(/@/)==0)||(email.search(/@/)==(email.length-1)) )
				htmlError += "<li>E-mail Inválido</li>";
		
		if(checkPhone(telemovel))
			htmlError += "<li>Telemóvel inválido</li>";
		
		htmlError += "<ul>";
		document.getElementById('registerErrors').innerHTML = htmlError;
		
	}
	else 
		if ( (password!=vpassword) ) 
		{
			htmlError += "<li>Password Nova e Repetir Password Nova diferentes</li>";				
			htmlError += "<ul>";
			document.getElementById('registerErrors').innerHTML = htmlError;
		}
		else
		{		
			document.getElementById('registerErrors').innerHTML = '';
			var req = 'minhaconta/pedidosConta.php?tipo=4';
			req += '&nome='+encodeURIComponent(nome);
			
			//if( oldnick != username)
			//	req += '&username='+encodeURIComponent(username);
						
			if( (oldpassword!='')&&(password!='') )
			{
				req += '&password='+encodeURIComponent(password);
				req += '&oldpass='+encodeURIComponent(oldpassword);
			}	
							
			if( oldmail != email)	
				req += '&email='+encodeURIComponent(email);			
			if( apelido!='' )
				req += '&apelido='+encodeURIComponent(apelido);
			if( desporto!='' )
				req += '&desporto='+encodeURIComponent(desporto);
			if( praia!='' )
				req += '&praia='+encodeURIComponent(praia);
			if( (dia!='')&&(mes!='')&&(ano!=''))
				req += '&dia='+dia+'&mes='+mes+'&ano='+ano;
			if( ocup!='' )
				req += '&ocup='+encodeURIComponent(ocup);
			if( morada!='' )
				req += '&morada='+encodeURIComponent(morada);
			if( (codP1!='')&&(codP2!='') )
				req += '&codp1='+codP1+'&codp2='+codP2;
			if( telemovel!='' )
				req += '&telemovel='+encodeURIComponent(telemovel);
			
			new Ajax.Request(req, {method: 'get',onSuccess: function(transport)
			{
					var find = transport.responseText;					
					switch(find)
					{
						case 'ok':
							alert("Dados alterados com sucesso");
							document.getElementById('oldpassRegisto').value ="";
							document.getElementById('passwordRegisto').value="";
							document.getElementById('vpasswordRegisto').value="";
							break;
							
						/*case 'userrep':
							document.getElementById('registerErrors').innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>Username já existente</li></ul>";
							break;*/
							
						case 'mailrep':
							document.getElementById('registerErrors').innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>E-mail já existente</li></ul>";
							break;
							
						case 'passwrong':
							document.getElementById('registerErrors').innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>Password Antiga Errada</li></ul>";
							break;
							
						default:
							alert("Erro na alteração de dados");
							break;
					}
				}
			});	
		}
}

function getPate(pateID)
{
	var req = 'minhaconta/pedidosConta.php?tipo=5&pate_chav='+pateID;
	new Ajax.Request(req, {method: 'get',onSuccess: function(transport)
		{
			var find = transport.responseText;					
			document.getElementById('minhaContaTexto').innerHTML = find;
			
			if (navigator.appName == "Microsoft Internet Explorer") 
			{
				document.getElementById('aceitarTermos').style.marginTop = '15px';
				document.getElementById('enviarButton').style.padding = '0px';
				document.getElementById('enviarButton').style.marginTop = '20px';
			}
			else
			{
				document.getElementById('enviarButton').style.paddingTop = '0px';
				document.getElementById('enviarButton').style.paddingBottom = '15px';
				document.getElementById('tabelaNext').style.marginBottom = '50px';								
			}			
		}
	});	
}

function pateSubmit(pateID,number)
{

	if (document.pateForm.aceitarTermos.checked)
	{
		document.getElementById("pateForm").action = 'minhaconta/pedidosConta.php?tipo=6&pate_chav='+pateID+'&number='+number;
		document.getElementById("pateForm").submit();		
	}
	else
	{
		document.getElementById("debug").innerHTML = "<ul class='attr' style='font-size:11px;font-weight:lighter;color:#FF0000;'><li>Tem que aceitar as condições deste concurso</li><ul>"
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			document.getElementById("debug").style.left = "110px";
			document.getElementById("debug").style.bottom = "40px";
			document.getElementById("debug").style.lineHeight = "1.3";
		}
		else
		{
			document.getElementById("debug").style.left = "110px";
			document.getElementById("debug").style.bottom = "45px";
		}
	}		
}

