// JavaScript Document
/* Variáveis Globais */
var codSort = 0;
var mostrar = 0;
var n = 0;
var Amigo = false;
var FF = (navigator.userAgent.indexOf("Firefox") != -1);

function Ano() {
	var hoje, ano;
	
	hoje = new Date();
	ano = String(hoje.getFullYear());
	ano = ano.substr(2,2);
	
	return ano;
}

function Mes() {
	var hoje, mes;
	
	hoje = new Date();
	mes  = hoje.getMonth()+1;
	if (mes < 10) mes = "0" + String(mes);
	else mes = String(mes);

	return mes;
}

function Dia() {
	var hoje, dia;

	hoje = new Date();
	dia  = hoje.getDate();
	if (dia < 10) dia = "0" + String(dia);
	else dia = String(dia);
	
	return dia;
}

function Round5(valor) {
	var valorabaixo, valoracima;
	
	if ((valor % 5) != 0) {
		valorabaixo = valor;
		valoracima = valor;

		while(valorabaixo % 5 != 0 )
			valorabaixo--;
	
		while(valoracima % 5 != 0)
			valoracima++;
	
		if (valoracima - valor > valor - valorabaixo) return valorabaixo;
		else return valoracima;
	}
	else return valor;
}

function NumRandom() {
	return Math.ceil(Math.random() * 9);
}

function ConcatOne() {
	mostrar++;
}

function Trim(value) {
	var len = value.length;
	
	while(value.substr(0,1) == " ") {
		value = value.substr(1, len); len--;
	}

	while(value.substr(len - 1, 1) == " ") {
		value = value.substr(0, len - 1); len--;
	}
	
	return value;
}

/***/
function preencheDDD(campo, destino) {
	if(campo.value.length == 2) destino.focus();
}

function preencheFone2(campo) {
	if(campo.value.length == 4) campo.value += "-";
}
/***/

// Função para validar todos os  campos do formulario
function validar() {
	var campos = Array("input", "select", "textarea");
	for (var u = 0; u < campos.length; u++) {
		var e = document.form.getElementsByTagName(campos[u]);
		for (var i=0; i<e.length; i++) {
			if (e[i].title != "" && e[i].title.indexOf("Google") == -1) {
				if (e[i].title.indexOf("Nome Completo") != -1) {
					if(validaNome(e[i]) === false) return false;
				} else if (e[i].title.indexOf("Email") != -1) {
					if(validaEmail(e[i]) === false) return false;
				} else {
					if (e[i].value == "") {
						alert("O campo " + e[i].title + " não pode permanecer em branco.");
						e[i].focus();
						return false;
					}
				}
			}
		}
	}
	return true;
}

function validaNome(campo) {
	var nome = Trim(campo.value);
	var arNomes = nome.split(" ");
	
	if (nome == "") {
		alert("Preencha o campo Nome Completo corretamente. (sem abreviações)");
		campo.focus();
		return false;
	}
	
	for (var i = 0; i <= arNomes.length-1; i++) {
		if (arNomes[i] != "") {
			if (i == 0) campo.value = arNomes[i];
			else campo.value += " " + arNomes[i];
		}
	}
	
	if (nome.indexOf(".") != -1) {
		alert("Preencha o nome completo, sem abreviações.");
		campo.focus();
		return false;
	}
	
	nome = Trim(campo.value);
	arNomes = nome.split(" ");
	
	if (arNomes.length == 1) {
		alert("Preencha o nome completo, sem abreviações.");
		campo.focus();
		return false;
	}
	
	for(var j in arNomes) {
		if (arNomes[j].length == 1) {
			if (arNomes[j] == arNomes[j].toUpperCase()) {
				alert("Preencha o nome completo, sem abreviações.");
				campo.focus();
				return false;
			}
		}
	}
	return true;
}

// Função que valida o email digitado
function validaEmail(email) {
	var e   = email.value;
	var a   = e.indexOf("@");
	var la  = e.lastIndexOf("@");
	var p   = e.indexOf(".");
	var lp  = e.lastIndexOf(".");
	var sp  = e.indexOf(" ");
	var len = e.length - 1;
	if (e == "") {
		alert("Por favor preencha o campo de Email corretamente.");
		email.focus();
		return false;
	} else {
		if (a == -1 || p == -1 || a != la || p == a+1 || a == p+1 || a == len || p == len || la == len || lp == len || sp != -1) {
			alert("Email Inválido! Por favor verifique o email digitado.");
			email.focus();
			return false;
		}
	}
}

function MakeXmlHttp() {
	var xmlhttp;
	
	try {
		xmlhttp = new XMLHttpRequest();
	} catch(e) {
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e1) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e2) {
				alert("Desculpe, mas seu navegador de internet não aceita todas as funcionalidades deste site.\nNão foi possível realizar a operação desejada.");
				xmlhttp = false;
			}
		}
	}
	return xmlhttp;
}

function Stop() {
	clearInterval(iPrincipal);
	clearTimeout(iMostrar);
	ShowResult();
	// Habilitar Sessão envie para um amigo
	if(!Amigo) ShowSendFriend();
}

function ShowResult() {
	var desconto, msg;

	desconto = document.form.txtResult.value.substr(8, 2);

	if (Amigo) {
		msg =  "Parab&eacute;ns, seu amigo ganhou " + desconto + "% de desconto no curso onLine ";
		msg += "para T&eacute;cnicas em Vendas de Cons&oacute;rcios.<br /><br /> J&aacute; enviamos um email para o seu amigo ";
		msg += "com todas as informa&ccedil;&otilde;es necess&aacute;rias para efetuar a inscri&ccedil;&atilde;o no curso.<br /><br />"
		msg += "<a href=\"../ecommerce/cadastro.asp?codSort=" + document.form.txtMeuCodDesconto.value + "\">Clique aqui para se inscrever no curso</a><br /><br />"
		msg += "<a href=\"javascript:sendAgain();\">Clique aqui para enviar para outro amigo</a>"
	} else {
		document.form.txtMeuCodDesconto.value = codSort;
		msg  = "Parab&eacute;ns, voc&ecirc; ganhou " + desconto + "% de desconto no curso onLine para T&eacute;cnicas ";
		msg += "em Vendas de Cons&oacute;rcios.<br /><br />";
		msg += "<a href=\"../ecommerce/cadastro.asp?codSort=" + codSort + "\">Clique aqui para se inscrever no curso</a>";
	}
	// Exibe Div com o resultado do Sorteio
	document.getElementById("div_desconto").style.display = "";
	Escreve("div_desconto", msg);
	StatusBT(false, true);
}

function sendAgain() {
	with(document.form)	 {
		txtNomeAmigo.value = "";
		txtEmailAmigo.value = "";
		txtDDDAmigo.value = "";
		txtFoneAmigo.value = "";
		txtNomeAmigo.focus();
	}
}

function ShowSendFriend() {
	document.form.txtNomeAmigo.title  = "Nome Completo do(a) Amigo(a)";
	document.form.txtEmailAmigo.title = "Email do(a) Amigo(a)";
	document.form.txtDDDAmigo.title   = "DDD do(a) Amigo(a)";
	document.form.txtFoneAmigo.title  = "Telefone do(a) Amigo(a)";
	document.getElementById("SendFriend").style.display = "";
}

function JogaNums(result) {
	iMostrar = setTimeout("ConcatOne()", 3000 * (++n));
	
	document.form.txtResult.value = result.substr(0, mostrar);
	for(var i = 1; i <= (14 - mostrar); i++) {
		document.form.txtResult.value += "" + NumRandom();
	}
	
	if (mostrar == 14) Stop();
}

function GeraDesconto() {
	var num = Math.ceil(Math.random() * 30) + 10;
	return Round5(num);
}

function numSort(cod) {
	if(cod < 10) 	  return "00000" + cod;
	else if(cod < 100) return "0000" + cod;
	else if(cod < 1000) return "000" + cod;
	else if(cod < 10000) return "00" + cod;
	else if(cod < 100000) return "0" + cod;
	else return cod;
}

function Sorteio(Desconto, vCod) {
	var result;
	result = vCod + Dia() + Desconto + Mes() + Ano();
	// Inicia Animação
	iPrincipal = setInterval("JogaNums('" + result + "')", 50);
}

function Escreve(div, texto) {
	document.getElementById(div).innerHTML = texto;
}

function StatusBT(btSort, btSortAmigo) {
	var off = "<img src=\"../../img/btSortearOff.gif\" alt=\"Sortear\" title=\"Sortear\" />";
	var on  = "<input type=\"image\" src=\"../../img/btSortear.gif\" name=\"btSort\" alt=\"Sortear\" onfocus=\"this.blur()\" />"
	var on2  = "<img src=\"../../img/btSortear.gif\" alt=\"Sortear\" title=\"Sortear\" onclick=\"SendToFriend()\" onfocus=\"this.blur()\" style=\"cursor:hand;\" />";
	
	if (btSort) Escreve("btSort", on);
	else Escreve("btSort", off);
	
	if (btSortAmigo) Escreve("btSortAmigo", on2);
	else Escreve("btSortAmigo", off);
}

function SendToFriend() {
	var xmlhttp, desconto, url, q;
	var nome, email, fone;
	var nomeAmigo, emailAmigo, foneAmigo;
	
	if (validar()) {
		// Desabilita o botão de sorteio
		StatusBT(false, false);
		Escreve("div_desconto", "");
		document.form.txtResult.value = "00000000000000";
		
		// Cria obj do Ajax
		xmlhttp = MakeXmlHttp();
		
		if(xmlhttp) {
			
			nome  	   = document.form.txtNome.value;
			email 	   = document.form.txtEmail.value;
			fone  	   = document.form.txtDDD.value + " - ";
			fone 	  += document.form.txtFone.value;
			nomeAmigo  = document.form.txtNomeAmigo.value;
			emailAmigo = document.form.txtEmailAmigo.value;
			foneAmigo  = document.form.txtDDDAmigo.value + " - ";
			foneAmigo += document.form.txtFoneAmigo.value;
			desconto   = GeraDesconto();
			
			url = "retornoEnviarAmigo.asp";
			q =  "?n=" + nome + "&e=" + email + "&f=" + fone + "&d=" + desconto;
			q += "&na=" + nomeAmigo + "&ea=" + emailAmigo + "&fa=" + foneAmigo;

			xmlhttp.open("GET", url + q, true);
			xmlhttp.onreadystatechange = function () {
				if(xmlhttp.readyState == 4) {
					switch (xmlhttp.status) {
						case 200: 
							// Resgata Texto da página retornoSorteio.asp
							var msg = unescape(xmlhttp.responseText.replace(/\+/g," "));
							codSort = parseInt(msg);
							if(!isNaN(codSort)) {
								mostrar = 0; n = 0;
								Amigo = true;
								Sorteio(desconto, numSort(codSort));
							} else {
								document.getElementById("div_desconto").style.display = "none";
								document.form.txtResult.value = "00000000000000"; alert(msg);
								StatusBT(false, true);
							}
							break;
						case 404: alert("Página não encontrada."); break;
						case 500: err = prompt("Internal Server Error", "http://www.netconsorcio.com.br/elearning/" + url + q);  break;
					}
				}
			}
			xmlhttp.send(null);
		}
		
	}
	
	return false;
}

function verifDesconto() {
	var xmlhttp, url, msg;
	var nome, email, ddd, fone;
	var nomeB, emailB, dddB, foneB;

	if (validar()) {
		
		nome = Trim(document.form.txtNome.value);
		email = Trim(document.form.txtEmail.value);
		ddd = Trim(document.form.txtDDD.value);
		fone = Trim(document.form.txtFone.value);
		
		nomeB = Trim(document.form.txtNomeB.value);
		emailB = Trim(document.form.txtEmailB.value);
		dddB = Trim(document.form.txtDDDB.value);
		foneB = Trim(document.form.txtFoneB.value);

		url  = "preAvaliacao4.asp";
		url += "?n=" + nome + "&e=" + email + "&d=" + ddd + "&f=" + fone;
		url += "&nb="+ nomeB +"&eb="+ emailB +"&db=" + dddB + "&fb=" + foneB;
		if(FF) location.href = url + "&nav=Firefox";
		
		// Cria obj do Ajax
		xmlhttp = MakeXmlHttp();
			
		if(xmlhttp) {
			xmlhttp.open("GET", url, false);
			xmlhttp.onreadystatechange = function () {
				if(xmlhttp.readyState == 4) {
					// Resgata Texto da página retornoSorteio.asp
					msg = unescape(xmlhttp.responseText.replace(/\+/g," "));
					if (msg.length > 0) alert(msg);
				}
			}
			xmlhttp.send(null);
			return (msg == "");
		} else return false;
	}
	return false;
}

function main() {
	var xmlhttp, nome, email, fone, desconto, url, q;
	
	if (validar()) {
		// Desabilita o botão de sorteio
		StatusBT(false, true);
		document.form.txtResult.value = "";
		
		// Cria obj do Ajax
		xmlhttp = MakeXmlHttp();
		
		if(xmlhttp) {
			
			nome  = document.form.txtNome.value;
			email = document.form.txtEmail.value;
			fone  = document.form.txtDDD.value + " - ";
			fone += document.form.txtFone.value;
			desconto = GeraDesconto();
			
			url = "retornoSorteio.asp";
			q = "?n=" + nome + "&e=" + email + "&f=" + fone + "&d=" + desconto;

			xmlhttp.open("GET", url + q, true);
			xmlhttp.onreadystatechange = function () {
				if(xmlhttp.readyState == 4) {
					switch (xmlhttp.status) {
						case 200: 
							// Resgata Texto da página retornoSorteio.asp
							var msg = unescape(xmlhttp.responseText.replace(/\+/g," "));
							codSort = parseInt(msg);
							if(!isNaN(codSort)) {
								Sorteio(desconto, numSort(codSort));
							} else {
								document.form.txtResult.value = "00000000000000"; alert(msg);
								ShowSendFriend(); /* Habilitar Sessão envie para um amigo */
							}
							break;
						case 404: alert("Página não encontrada."); break;
						case 500: err = prompt("Internal Server Error", "http://www.netconsorcio.com.br/elearning/" + url + q);  break;
					}
				}
			}
			xmlhttp.send(null);
		}
		
	}
	
	return false;
}


/* Parte de Questionário */

function CopiarDados() {
	with(document.form) {
		txtNomeB.value = txtNome.value;
		txtEmailB.value = txtEmail.value;
		txtDDDB.value = txtDDD.value;
		txtFoneB.value = txtFone.value;
	}
}

function LimparDados() {
	with(document.form) {
		if(txtNomeB.value  == txtNome.value)   txtNomeB.value  = "";
		if(txtEmailB.value == txtEmail.value) txtEmailB.value = "";
		if(txtDDDB.value   == txtDDD.value)    txtDDDB.value   = "";
		if(txtFoneB.value  == txtFone.value)  txtFoneB.value  = "";
	}
}

function ChkCopiar() {
	with(document.form) {
		if(chkBene.checked) CopiarDados();
		else LimparDados();
	}
}

