// JavaScript Document

/**
*	Variável que armazena os campos e se os mesmo estão validados
*/
arrCamposCadastro = [ 
					 { nome: "txtLogin", ativo: false }, 
					 { nome: "txtSenha", ativo: false }, 
					 { nome: "txtSenha1", ativo: false }, 
					 { nome: "txtNome", ativo: false }, 
					 { nome: "txtEmail", ativo: false }, 
					 { nome: "chkTermoUso", ativo: false } 
					 ];

arrFuncoesCadastro = [ "doRequestLogin( objCampo )", "doVerificaSenha()", "doVerificaRepetirSenha()", "doVerificaNome()", "doVerificaEmail()", "doVerificaTermoUso( objCampo )" ];
	

/**
*	Função que valida o formulário de cadastro
*
*/
function validaFormCadastro( tipoChamada )
{
	envio = tipoChamada == 'submit' ? 1 : 0;
	errado = false;
	
	if( envio )
	{
		clearInterval( intervaloId );	
	}
	
	for( var i = 0; i < arrCamposCadastro.length ; i++ )
	{
		objCampo = document.getElementById( 'formCadastro' )[ arrCamposCadastro[ i ].nome ];
		//document.getElementById( 'debug' ).innerHTML += 'Envio: ' + arrCamposCadastro[ i ].ativo  + '<br />';
		if( envio || arrCamposCadastro[ i ].ativo )
			eval( arrFuncoesCadastro[ i ] );
		
		objStatus = document.getElementById( objCampo.name + 'Status' );
		
		if( objStatus.className.indexOf( 'statusErrado' ) != -1 )
		{
			errado = true;
		}
	}
	
	if( envio )
	{
		if( errado )
			return false;
			
		return true;
	}
	
}

/**
*	Variáveis de controle do loop e do campo
*/
intervaloId = null;
objCampo = null;


/**
*	Variáveis de controle das requisicoes ao servidor na verificação do login
*/
carregando = false;
contador = 0;
idReq = 0;
idResp = 1;
arrValores = new Array();
idInt = 0;
arrIntervalos = new Array();

/**
*	Função que inicia a validacao do login
*
*	@param object campo Campo a ser validado
*	@param function rotina Rotina a ser rodada no loop
*/
function verificaCampoLoop( campo, rotina )
{
		//clearInterval( intervaloId );
		for( var i = 0 ; i < arrCamposCadastro.length ; i++ )
		{
			if( campo.name == arrCamposCadastro[ i ].nome )
			{
				arrCamposCadastro[ i ].ativo = true;
			}
		}
		objCampo = campo;
		valor = objCampo.value;
		if( !intervaloId )
			intervaloId = setInterval( validaFormCadastro, 200 );
}

function validarLogin( nome )
{
	objCampo = document.formCadastro[ nome ];
	
	doRequestLogin( objCampo );
	
	
}

/**
*	Função que realiza a verificação da existência do login digitado na base de dados
*
*/
function doRequestLogin( objCampo )
{
	if( (/\W/).test( objCampo.value ) )
	{
		mostrarStatus( objCampo.name, 'Somente letras e números', 0 );
		return;
	}
	
	if( objCampo.value.length < 3 )
	{
		mostrarStatus( objCampo.name, 'No mínimo 3 caracteres', 0 );
	}
	
	if( arrValores[ arrValores.length - 1 ] == objCampo.value )
	{
		if( contador >= 5 )
		{
			//document.getElementById( 'debug' ).innerHTML += 'Parou: ' + objCampo + '<br />';
			return;
		}
			contador ++;
	}
	else
	{
		contador = 0;
	}
	
	
	arrValores[ idReq ] = objCampo.value;	
	
	this.onVerificaLoginComplete = function( resposta )
	{
		carregando = false;
		//document.getElementById( 'debug' ).innerHTML += 'Resposta: ' + idResp + ' Valor: ' + resposta + ' Campo: ' + objCampo.value + 'ValorAnt: ' + arrValores[ idResp ] + '<br />';

		if( arrValores[ idResp ] == objCampo.value || true )
		{
			if( resposta == '1' )
			{
				//strStatus = 'O login ' + objCampo.value + ' está indisponível';
				strStatus = 'está indisponível';
				mostrarStatus( objCampo.name, strStatus, 0 );
			}
			else if( resposta == '0' )
			{
				//strStatus = 'O login ' + objCampo.value + ' está disponível';
				strStatus = 'está disponível';
				mostrarStatus( objCampo.name, strStatus, 1 );
			}
			else
			{
				strStatus = "No mínimo 3 caracteres";
				mostrarStatus( objCampo.name, strStatus, 0 );
			}
		}
		idResp++;			
	}
	
	callbacks = 
	{
		onloadcomplete: this.onVerificaLoginComplete,
		onloading: function()
		{
			carregando = true;
		},
		onloaded: function()
		{
			carregando = false;	
		}
	};
	parametros =
	[
		{ name: objCampo.name, value: objCampo.value }
	]
	objConfiguracao = 
	{
		url: '/Usuario/verificarLogin',
		metodo: 'POST',
		callbacks: callbacks,
		tipoResposta: 'texto',
		parametros: parametros,
		enctype: 'application/x-www-form-urlencoded',
		bAssincrono: 1
	};
	
	//if( ! carregando )
	//{
		//document.getElementById( 'debug' ).innerHTML += 'Requisicao: ' + idReq + '<br />';
		objAjax.enviaRequisicao( objConfiguracao );
		
	//	idReq++;
	//}
}

/**
*	Função que verifica se a senha é válida
*
*/
function doVerificaSenha()
{
	if( (/\W/).test( objCampo.value ) )
	{
		mostrarStatus( objCampo.name, 'Somente letras e números', 0 );
	}
	else if( objCampo.value.length < 4 )
	{
		mostrarStatus( objCampo.name, 'No mínimo 4 caracteres', 0 );	
	}
	else
	{
		mostrarStatus( objCampo.name, '', 1 );
		objForm = document.getElementById( 'formCadastro' )
		campoRepetirSenha = objForm.txtSenha1.value;
		if( campoRepetirSenha != '' && campoRepetirSenha.length >= 4 && campoRepetirSenha != objCampo.value )
		{
			mostrarStatus( 'txtSenha1', 'As senhas não estão iguais', 0 );
		}
	}
}

/**
*	Função que verifica se as senhas são iguais
*
*/
function doVerificaRepetirSenha()
{
	objForm = document.getElementById( 'formCadastro' )
	campoSenha = objForm.txtSenha.value;
	if( (/\W/).test( objCampo.value ) )
	{
		mostrarStatus( objCampo.name, 'Somente letras e números', 0 );
	}
	else if( objCampo.value.length < 4 )
	{
		mostrarStatus( objCampo.name, 'No mínimo 4 caracteres', 0 );	
	}
	else if( objCampo.value == campoSenha )
	{
		mostrarStatus( objCampo.name, '', 1 );	
	}
	else
	{
		mostrarStatus( objCampo.name, 'As senhas não estão iguais', 0 );
	}
}

/**
*	Função que valida o nome
*
*/
function doVerificaNome()
{
	if( objCampo.value != '' )
	{
		mostrarStatus( objCampo.name, '', 1 );
	}
	else
	{
		mostrarStatus( objCampo.name, '', 0 );
	}
}

/**
*	Função que valida o e-mail
*
*/
contEmail = 0;
function doVerificaEmail()
{
		
	if( isValidEmail( objCampo.value ) )
	{
		mostrarStatus( objCampo.name, 'E-mail válido', 1 );
	}
	else
	{
		mostrarStatus( objCampo.name, 'E-mail inválido', 0 );	
	}
	
}

/*	Função que valida a seleção do termo de uso
*
*/
function doVerificaTermoUso( campo )
{
	if( campo.checked )
	{
		mostrarStatus( campo.name, '', 1 );
	}
	else
	{
		mostrarStatus( campo.name, '', 0 );
	}
}




/*
Copyright 2005, 4word systems
All rights reserved.

This software may not be reproduced or distributed in any form without the express 
written consent of 4word systems or it's designee.

Revision 1.1:  20050729 Added underscore to list of valid characters
*/
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}