// Name: createXMLDocument
// Input: String
// Output: XML Document
var createXMLDocument = function(string)
{
var browserName = navigator.appName;
var doc;
if (browserName == 'Microsoft Internet Explorer')
{
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false'
doc.loadXML(string);
} else {
doc = (new DOMParser()).parseFromString(string, 'text/xml');
}
return doc;
}

function usuario() {
	this.enviando = false;
	this.Nome = "";
	this.Email = "";
	this.Senha = "";
	this.Senha1 = "";
	this.Cpf = "";
	this.Nascimento = "";
	this.Sexo = "";

	var usr = this;


	this.efetuarLogin = function() {
		try {
			if (this.enviando)
				return;
			this.enviando = true;
			var dados = {
				secao: "usuario",
				acao: "efetuarlogin",
				Email: $("#email_login").attr("value"),
				Senha: $("#senha_login").attr("value")
			};
			$.post("./",dados,onLoginEnviado,"txt");
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	var onLoginEnviado = function(text) {
		try {
			xml = createXMLDocument(text);
			usr.enviando = false;
			if (xml.getElementsByTagName("Sucesso").length > 0)
			{
				nav.navegar("usuario&acao=logado");
			} else {
				
				$("#erro_login").fadeIn("slow");
			}
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.cadastrar = function()
	{
		if (this.enviando)
			return;
		try {
			this.enviando = true;
			this.Nome = document.getElementById("txtNome").value;
			this.Email = document.getElementById("txtEmail").value;
			this.Senha = document.getElementById("txtSenha").value;
			this.Senha1 = document.getElementById("txtSenha1").value;
			this.Cpf = document.getElementById("txtCpf").value;
			this.Nascimento = document.getElementById("txtNascimento").value;
			this.Sexo = $("#sexo_m").attr("checked") ? "M" : "F";

			if (this.validarForm()) {
				this.enviarCadastro();
			} else {
				this.enviando = false;
			}
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.enviarCadastro = function() {
		try {
			$("#bt_enviar").hide();
			var dados =
			{
				secao: "usuario",
				acao: "enviar",
				Nome: this.Nome,
				Email: this.Email,
				Senha: this.Senha,
				Cpf: this.Cpf,
				Nascimento: this.Nascimento,
				Sexo: this.Sexo
			};
			if (document.getElementById("chkOptIn1") != null) {
				dados["OptIn"] = document.getElementById("chkOptIn1").checked ? "1" : "0";
				var id = location.href.toString();
				id = document.forms["frmUsuario"].Id.value;
				dados["Id"] = id;
			}

			$.post("./", dados, onCadastroEnviado,"xml");
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	var onCadastroEnviado = function(xml) {
		try {
			usr.enviando = false;
			$("#bt_enviar").show();
			if (xml.getElementsByTagName("Erro").length > 0)
			{
				usr.MostrarErro(null,xml.getElementsByTagName("Erro")[0].childNodes[0].nodeValue);
				nav.ContabilizarVisita("vw_hotsite_tribodogol_carteirinha_erro");
			} else {
				if (document.getElementById("chkOptIn1") == null) {
					document.getElementById("frmUsuario").Id.value = xml.getElementsByTagName("Sucesso")[0].childNodes[0].nodeValue;
					document.getElementById("dados_pessoais").style.display = "none";
					document.getElementById("upload").style.display = "inline";
					nav.ContabilizarVisita("vw_hotsite_tribodogol_carteirinha_foto");
				} else {
					usr.mostrarSucesso();
				}
			}
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.enviarFoto = function() {
		try {
			var form = document.getElementById("frmUsuario");
			form.target = "frameUpload";
			form.acao.value = "form_upload";
			form.submit();
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.abrirCarteirinha = function() {
		try {
			this.popup('carteirinha.html','carteirinha','width=496, height=600, resizable=no, location=no');
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.marcarOptIn = function() {
		var dados = {
			secao: "usuario", 
			acao: "optin",
			"OptInInformacoes": $("#chkOptIn").attr("checked") ? "1" : "0",
			Id: document.forms["frmUsuario"].Id.value
		}
		$.post("./",dados);
		this.mostrarSucesso()
	}

	this.mostrarSucesso = function() {
		try {
			document.getElementById("upload").style.display = "none";
			document.getElementById("dados_pessoais").style.display = "none";
			document.getElementById("sucesso").style.display = "inline";
			nav.ContabilizarVisita("vw_hotsite_tribodogol_carteirinha_sucesso");
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.mostrarErroUpload = function(msg) {
		try {
			document.getElementById("erroUpload").style.display = "inline";
			document.getElementById("erroUpload").innerHTML = msg;
			nav.ContabilizarVisita("vw_hotsite_tribodogol_carteirinha_erro_foto");
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.lembrarSenha = function() {
		try
		{
			var dados = {
				secao: "usuario",
				acao: "enviar_lembrarsenha",
				Email: document.getElementById("txtEmail").value
			};

			if (dados.Email == "") {
				this.MostrarErro("txtEmail","Preencha o campo Email");
				return;
			} else if (!this.isEmail(dados.Email)) {
				this.MostrarErro("txtEmail","Email inválido");
				return;
			}

			$.post("./",dados,onLembrarSenhaEnviado,"xml");
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	var onLembrarSenhaEnviado = function(xml) {
		try {
			if (xml.getElementsByTagName("Erro").length > 0)
				msg = xml.getElementsByTagName("Erro")[0].childNodes[0].nodeValue;
			else
				msg = xml.getElementsByTagName("Sucesso")[0].childNodes[0].nodeValue;

			document.getElementById("erro").innerHTML = msg;
			//alert(msg);
		} catch(e) 
		{
			nav.Exc(e);
		}
	}

	this.validarForm = function() {
		try {
			var valido = true;
			if (this.Nome.length == 0) {
				this.MostrarErro("txtNome");
				valido = false;
			} else
				this.OcultarErro("txtNome");

			if (this.Email.length == 0) {
				this.MostrarErro("txtEmail");
				valido = false;
			} else
				this.OcultarErro("txtEmail");

			if (this.Senha.length == 0) {
				this.MostrarErro("txtSenha");
				valido = false;
			} else
				this.OcultarErro("txtSenha");

			if (this.Senha1.length == 0) {
				this.MostrarErro("txtSenha1");
				valido = false;
			} else
				this.OcultarErro("txtSenha1");

			if (this.Cpf.length == 0) {
				this.MostrarErro("txtCpf");
				valido = false;
			} else
				this.OcultarErro("txtCpf");

			if (this.Nascimento.length == 0) {
				this.MostrarErro("txtNascimento");
				valido = false;
			} else
				this.OcultarErro("txtNascimento");

			if (valido) {
				if (!this.isEmail(this.Email))
				{
					this.MostrarErro("txtEmail","E-mail inválido.");
					valido = false;
				}
				else if (!this.isCPF(this.Cpf))
				{
					this.MostrarErro("txtCpf","CPF inválido.");
					valido = false;
				}
				else if (!/(\d{2}\/){2}\d{4}/.test(this.Nascimento))
				{
					this.MostrarErro("txtNascimento","Nascimento inválido.");
					valido = false;
				}
				else if (this.Senha != this.Senha1)
				{
					this.MostrarErro("txtSenha1","As senhas digitadas não são iguais.");
					valido = false;
				}
			}

			if (!document.getElementById("sexo_m").checked && !document.getElementById("sexo_f").checked) {
				if (!valido)
					this.MostrarErro("sexo_m");
				else
					this.MostrarErro("sexo_m","Selecione o seu sexo.");
				valido = false;
			} else
				this.OcultarErro("sexo_m");


			if (valido)
				document.getElementById("erro").style.display = "none";
			else
				nav.ContabilizarVisita("vw_hotsite_tribodogol_carteirinha_erro");
			return valido;
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.MostrarErro = function(obj,msgErro) {
		try {
			obj = document.getElementById(obj);
			if (obj != null)
			{
				obj.style.backgroundColor = "#CC3333";
				obj.style.marginTop = "3px";
			}

			var pErro = document.getElementById("erro")
			pErro.style.display = "inline";
			if (msgErro == undefined)
				pErro.innerHTML = "Preencha corretamente os campos obrigatórios.";
			else
				pErro.innerHTML = msgErro;
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.OcultarErro = function(obj) {
		try {
			obj = document.getElementById(obj);
			obj.style.backgroundColor = "#FFFFFF";
			obj.style.marginTop = "7px";
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.mascaraData = function(obj,evento) {
		try {
			ascii = (evento.keyCode) ? evento.keyCode : evento.which;

			if(ascii == 8 || ascii == 9 || ascii == 13 || ascii == 116 || ascii == 37 || ascii == 39 || ascii == 36 || ascii == 35)
				return true;

			str = obj.value.replace(/\D/g,"");
			if (str.length >= 4)
				str = str.substring(0,2) +"/"+ str.substring(2,4) +"/"+ str.substring(4);
			else if (str.length >= 2)
				str = str.substring(0,2) +"/"+ str.substring(2);
			obj.value = str;
			return this.mascara(/\d/,evento);
		}
		catch (e)
		{
			nav.Exc(e);
			return true;
		}
	}

	this.mascara = function(expressao, evento) {
		try {
			var e = evento;
			var ascii;

			if (e.keyCode)
				ascii = e.keyCode;
			else if (e.which)
				ascii = e.which;
			chr = String.fromCharCode(ascii);
			if(ascii == 8 || ascii == 9 || ascii == 13 || ascii == 116 || ascii == 37 || ascii == 39 || ascii == 36 || ascii == 35){
				return true;
			}
			var regx = new RegExp(expressao);
			return (regx.test(chr));
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.kpress = function (evt) {
		try {
			if(evt.which == 13) { 
				usr.cadastrar()
			}
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.isCPF = function(cpf){
		try {
			var cpf_limpo = cpf.replace(/\D/g,"");
			if (cpf_limpo.length !=11)
				return false;

			var soma = 0;
			for (var i=0; i<9; i++)
				soma += parseInt(cpf_limpo.charAt(i)) * (10-i);

			if (soma == 0)
				return false;

			primeiro_digito = 11 - soma % 11;
			if (primeiro_digito > 9)
				primeiro_digito = 0;

			if (cpf_limpo.substr(9,1) != primeiro_digito)
				return false;

			var soma = 0;
			for (var i=0; i<10; i++)
				soma += parseInt(cpf_limpo.charAt(i)) * (11-i);

			var segundo_digito = 11 - soma % 11;

			if (segundo_digito > 9)
				segundo_digito = 0;
			if (cpf_limpo.substr(10,1) != segundo_digito)
				return false;

			return true;
		}
		catch (e)
		{
			nav.Exc(e);
			return true;
		}
	}

	this.popup = function(url, name, features) {
		try {
			// Tamanho da janela
			var width = /width=(\d+)/i.exec(features);
			wwidth = width[1];
			var height = /height=(\d+)/i.exec(features);
			wheight = height[1];

			// Tamanho da tela
			swidth = screen.availWidth;
			sheight = screen.availHeight;

			// Distância do topo esquerdo
			_left = parseInt((swidth / 2) - (wwidth / 2));
			_top = parseInt((sheight / 2) - (wheight / 2));

			features.replace("/top=\d+,?/", "");
			features.replace("/left=\d+,?/", "");

			features += ',top=' + _top + ',left=' + _left;


			//Abre a Janela
			jan = window.open(url, name, features);
			jan.focus();
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

	this.isEmail = function(email){
			try {
			var suportado = 0;
			EmailInv = false;

			if (window.RegExp) {
				var tempReg = /a/;
				if (tempReg.test("a")){
					suportado = 1;
				}
			}

			if (!suportado){
				if(((email.indexOf(".") <= 0) || (email.indexOf("@") <= 0)) || ((email.lastIndexOf(".") == (email.length - 1)) || (email.lastIndexOf("@") == (email.length -1)))){
					EmailInv = true;
				}
			}else{
				var tmp1 = /(@.*@)|(\.\.)|(@\.)|(^\.)/;
				var tmp2 = /^.+@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
				if(tmp1.test(email) || !tmp2.test(email)){
					EmailInv = true;
				}
			}

			return !EmailInv;
		}
		catch (e)
		{
			nav.Exc(e);
		}
	}

}

var usr = new usuario();

var init = function() {
	if (document.getElementById("fUpload") == null)
		return;
	if (/MSIE/.test(navigator.appVersion))
		document.getElementById("fUpload").style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
	else {
		document.getElementById("fUpload").style.opacity = "0";
	}
	try
	{
		SI.Files.stylizeById("fUpload");
	}
	catch (e)
	{
	}
}


if (window.addEventListener)
	window.addEventListener("load", init, false);
else
	window.attachEvent("onload", init);

try
{
	init();
}
catch (e)
{
}