var browser = navigator.appName;
var browserVersion  = parseInt(navigator.appVersion);

function dataHora(){
	var now = new Date();
	var hora = now.getHours();
	var minuto = now.getMinutes();
	var segundo = now.getSeconds();
	var mes = now.getMonth();
	var dia = now.getDate();
	var ano = now.getFullYear();
	var semana = new Array("Domingo","Segunda-Feira","Terça-Feira","Quarta-Feira","Quinta-Feira","Sexta-Feira","Sábado");
	var mesesAno = new Array("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");
	var nomeMes = mesesAno[mes];
	var diaSemana = semana[now.getDay()];
	
	//Rotina para adicionar '0' á horas, minutos e segundos de um só algarismo
	if (String(segundo).length == 1){
		segundo = "0" + segundo;
	}
	if (String(minuto).length == 1){
		minuto = "0" + minuto;
	}	
	if (String(hora).length == 1){
		hora = "0" + hora;
	}
	
	//Rotina para saudação
	if ((hora >= 6) && (hora < 12)){
		var saudacao = "Bom dia";
	}
	else if ((hora >= 12) && (hora < 18)){
		saudacao = "Boa tarde";
	}
	else if (hora >= 18){
		saudacao = "Boa noite";
	}
	else if (hora >= 0){
		saudacao = "Boa noite";
	}
	
	var horaAtual = hora + ":" + minuto + ":" + segundo;
	
	//Atualiza valor do relógio
	document.getElementById("relogio").firstChild.nodeValue = saudacao + "! São " + horaAtual;
	//Atualiza valor da data
	if(dia == 1){
		document.getElementById("data").firstChild.nodeValue = diaSemana + ", " + dia + "º de " + nomeMes + " de " + ano;
	}
	else{
		document.getElementById("data").firstChild.nodeValue = diaSemana + ", " + dia + " de " + nomeMes + " de " + ano;
	}
}

function formatTel(objeto, sMask, evtKeyPress){
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all){ //Internet Explorer
		nTecla = evtKeyPress.keyCode;
	}
	else if(document.layers){ //Netscape
		nTecla = evtKeyPress.which;
	}
	else{
		nTecla = evtKeyPress.which;
		if (nTecla == 8){
			return true;
		}
	}

    sValue = objeto.value;

    //Limpa todos os caracteres de formatação que já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen){
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      	bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      	if (bolMask){
			sCod += sMask.charAt(i);
			mskLen++;
		}
      	else {
			sCod += sValue.charAt(nCount);
			nCount++;
      	}

      	i++;
    }

    objeto.value = sCod;

    if (nTecla != 8){ //backspace
    	if (sMask.charAt(i-1) == "9"){ //apenas números...
        	return ((nTecla > 47) && (nTecla < 58));
		} 
      	else{ //qualquer caracter...
        	return true;
      	} 
    }
    else{
      	return true;
    }
}

function somenteNumero(e, param, valor){ //Função para aceitar apenas digitação de valores numericos
	// <input type='text' size='10' value='' onkeypress='return SomenteNumero(event)'>
	var tecla = (window.event)?event.keyCode:e.which;
	
	if ((tecla > 47 && tecla < 58)) 
	{
		return true;
    }
	else if (tecla == 8) 
	{
		return true;
	}
	else if (tecla == 0)	
	{	
		return true;
	}
	else if (tecla == 44){
		if (param != null){
			if(valor == ""){
				return false;
			}			
			else if(valor.match(",") == ","){
				return false;
			}
			
			return true;
		}
		else
			return false;
	}
	else
	{
		return false; 	
	}
}

function openWindowContato(){
	window.open("contato.php", "Contato", "height=450, width=500, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
}

function openWindowComoAnunciar(param){
	if(param != null){
		window.open("../comoAnunciar.php", "Anunciar", "height=300, width=500, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	}
	else{
		window.open("comoAnunciar.php", "Anunciar", "height=300, width=500, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	}
}

function popup_galeria(){
	window.open("http://www.falconi.com.br/fotos.asp", "Galeria", "height=600px,width=850px,status=no,menubar=no,toolbar=no,titlebar=no");
}

/*function openWindowPalestra(idPalestra){
	window.open("verPalestra.php?id=" + idPalestra, "Palestra", "height=475, width=700, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}*/

function openWindowPalestra(idUsuarioPalestra, pasta){
	if(navigator.appName.indexOf('Internet Explorer') < 0){
		alert('É necessário utilizar o navegador Internet Explorer para visualizar as palestras.');
		return false;
	}
	//window.open("../palestras/"+pasta+"/web/default.php?id=" + idPalestra, "Palestra", "height=475, width=700, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	window.open("prePalestra.php?idup=" + idUsuarioPalestra, "Palestra", "height=600, width=800, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function openWindowForum(){
	window.open("../forum/", "Forum");
}

function mostraTiposCurso(){
	var tiposCurso = document.getElementById('tiposCurso');
	
	if(tiposCurso.style.display != 'none'){
		tiposCurso.style.display = 'none';
	}
	else{
		tiposCurso.style.display = 'block';
	}
}

//FUNÇÕES PARA O CARREGAMENTO DINÂMICO DE ESTADOS E CIDADES

function buscaEstados(param) //PARAM PARA ADMIN
{
	var estadoSelecionado = param;
	var uf = document.getElementById('uf');
	var loading = document.getElementById('loadingEstado');
	
	var op = document.createElement('option');
    op.setAttribute('value', '');
    op.appendChild(document.createTextNode("Carregando..."));
	loading.style.visibility = 'visible';
    uf.appendChild(op);
	
	var ajax = openAjax();
	
	if(param != null)
		ajax.open('GET', '../includes/funcoes.php?acao=buscaEstados', true);
	else
		ajax.open('GET', 'includes/funcoes.php?acao=buscaEstados', true);
	
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.status == 200)
			{
				uf.innerHTML = '';
				
				var opcao = document.createElement('option');
				opcao.setAttribute('value', '');
				opcao.appendChild(document.createTextNode('Selecione'));
				uf.appendChild(opcao);
				
				var xml = ajax.responseXML;
				var estado = xml.getElementsByTagName('estado');
				
				for (var i = 0; i < estado.length; i++)
				{
					var idEstado = estado[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					var siglaEstado = estado[i].getElementsByTagName('sigla')[0].firstChild.nodeValue;
					var nomeEstado = estado[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
					
					var opcao = document.createElement('option');
					if(estadoSelecionado == idEstado){
						opcao.setAttribute('selected', 'true');
					}
					opcao.setAttribute('value', idEstado);
					opcao.appendChild(document.createTextNode(nomeEstado));
					loading.style.visibility = 'hidden';
					uf.appendChild(opcao);					
				}
			}
		}
	}
    ajax.send(null);
    
}

function buscaCidades(uf, param) //PARAM PARA ADMIN
{
	if (uf == 0)
	{
		limpaCidades();
		return true;
	}

	var cidades = document.getElementById('cidade');
	var loading = document.getElementById('loadingCidade');

	cidades.innerHTML = '';
	var op = document.createElement('option');
    op.setAttribute('value', '');
    op.appendChild(document.createTextNode("Carregando..."));
	loading.style.visibility = 'visible';
    cidades.appendChild(op);
	
	if(param != null)
		var url = '../includes/funcoes.php?acao=buscaCidades&uf=' + uf;
	else
		var url = 'includes/funcoes.php?acao=buscaCidades&uf=' + uf;
		
	var ajax = openAjax();
	
	ajax.open('GET', url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.status == 200)
			{
				cidades.innerHTML = '';
				
				var xml = ajax.responseXML;
				var cidade = xml.getElementsByTagName('cidade');
				
				//alert(param);
				
				for (var i = 0; i < cidade.length; i++)
				{
					var idCidade = cidade[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					var nomeCidade = cidade[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
					
					var opcao = document.createElement('option');
					if(param == idCidade){
						opcao.setAttribute('selected', 'true');
					}
					opcao.setAttribute('value', idCidade);
					opcao.appendChild(document.createTextNode(nomeCidade));
					loading.style.visibility = 'hidden';
					cidades.appendChild(opcao);
				}
			}
		}
	}
	ajax.send(null);
}

function limpaCidades(){
	var cidades = document.getElementById('cidade');
	var loading = document.getElementById('loadingCidade');

	cidades.innerHTML = 'Selecione um estado';
	var op = document.createElement('option');
	loading.style.visibility = 'hidden';
    op.setAttribute('value', '');
	op.appendChild(document.createTextNode("Selecione um estado"));
	cidades.appendChild(op);
}

//FIM DAS FUNÇÕES DE ESTADOS E CIDADES



//FUNÇÕES TEMPORÁRIAS PARA ATUALIZAÇÃO DE CADASTRO
//------------------------------
//------------------------------
//------------------------------

function buscaEstados2(param) //PARAM PARA ADMIN
{
	var estadoSelecionado = param;
	var uf = document.getElementById('uf');
	var loading = document.getElementById('loadingEstado');
	
	var op = document.createElement('option');
    op.setAttribute('value', '');
    op.appendChild(document.createTextNode("Carregando..."));
	loading.style.visibility = 'visible';
    uf.appendChild(op);
	
	var ajax = openAjax();
	
	ajax.open('GET', 'includes/funcoes.php?acao=buscaEstados', true);
	
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.status == 200)
			{
				uf.innerHTML = '';
				
				var opcao = document.createElement('option');
				opcao.setAttribute('value', '');
				opcao.appendChild(document.createTextNode('Selecione'));
				uf.appendChild(opcao);
				
				var xml = ajax.responseXML;
				var estado = xml.getElementsByTagName('estado');
				
				for (var i = 0; i < estado.length; i++)
				{
					var idEstado = estado[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					var siglaEstado = estado[i].getElementsByTagName('sigla')[0].firstChild.nodeValue;
					var nomeEstado = estado[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
					
					var opcao = document.createElement('option');
					if(estadoSelecionado == idEstado){
						opcao.setAttribute('selected', 'true');
					}
					opcao.setAttribute('value', idEstado);
					opcao.appendChild(document.createTextNode(nomeEstado));
					loading.style.visibility = 'hidden';
					uf.appendChild(opcao);					
				}
			}
		}
	}
    ajax.send(null);
    
}

function buscaCidades2(uf, param) //PARAM PARA ADMIN
{
	if (uf == 0)
	{
		limpaCidades();
		return true;
	}

	var cidades = document.getElementById('cidade');
	var loading = document.getElementById('loadingCidade');

	cidades.innerHTML = '';
	var op = document.createElement('option');
    op.setAttribute('value', '');
    op.appendChild(document.createTextNode("Carregando..."));
	loading.style.visibility = 'visible';
    cidades.appendChild(op);
	
	var url = 'includes/funcoes.php?acao=buscaCidades&uf=' + uf;
		
	var ajax = openAjax();
	
	ajax.open('GET', url, true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
			if (ajax.status == 200)
			{
				cidades.innerHTML = '';
				
				var xml = ajax.responseXML;
				var cidade = xml.getElementsByTagName('cidade');
				
				//alert(param);
				
				for (var i = 0; i < cidade.length; i++)
				{
					var idCidade = cidade[i].getElementsByTagName('id')[0].firstChild.nodeValue;
					var nomeCidade = cidade[i].getElementsByTagName('nome')[0].firstChild.nodeValue;
					
					var opcao = document.createElement('option');
					if(param == idCidade){
						opcao.setAttribute('selected', 'true');
					}
					opcao.setAttribute('value', idCidade);
					opcao.appendChild(document.createTextNode(nomeCidade));
					loading.style.visibility = 'hidden';
					cidades.appendChild(opcao);
				}
			}
		}
	}
	ajax.send(null);
}
//FUNÇÕES TEMPORÁRIAS PARA ATUALIZAÇÃO DE CADASTRO
//------------------------------
//------------------------------
//------------------------------



// INÍCIO DAS FUNÇÕES DA LOJA

function insereProduto(idProduto, categoria){
	
	var tbody = document.createElement("TBODY");

	if((categoria != 1) && (categoria != 2)){
		var quantidade = document.getElementById('qtd').value;
	}
	else{
		var quantidade = 1;
	}
	var lista = document.getElementById('listaItens');
	var qtdItens = document.getElementById('qtdItens');
	var totalCompra = document.getElementById('totalCompra');
	var tdComprar = document.getElementById('tdComprar');
	
	var tdNenhum = document.getElementById('tdNenhum');
	var trNenhum = document.getElementById('trNenhum');
	
	var tdNovaQuantidade = document.getElementById(idProduto);
	
	var tr = document.createElement('tr');
	var tdQtd = document.createElement('td');
	var tdProduto = document.createElement('td');
	
	tr.setAttribute('id', 'tr' + idProduto);
    tdQtd.setAttribute('align', 'right');
	tdQtd.setAttribute('valign', 'top');
	tdQtd.setAttribute('id', idProduto);
	tdProduto.setAttribute('align', 'center');
	
    //tdProduto.appendChild(document.createTextNode("Carregando..."));
	
	if(tdNenhum != null){
		//lista.removeChild(trNenhum);
		trNenhum.removeChild(tdNenhum);
	}
	
	var ajax = openAjax();
	var url = 'insereProduto.php';
	
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;');
	ajax.send('produto=' + idProduto + '&quantidade=' + quantidade);
	if(ajax.status == 200){
		//alert(ajax.reponseText);
		document.getElementById('itens').value = 1;
		var resultado = ajax.responseText.split(" ; ");
		
		if((resultado[1].charAt(0) == "1") && (resultado[1].length == 1))
			qtdItens.innerHTML = resultado[1] + " Item";
		else
			qtdItens.innerHTML = resultado[1] + " Itens";
		
		if(resultado[4] == "insert"){
			lista.appendChild(tbody)
			tbody.appendChild(tr);
			tr.appendChild(tdQtd);
			tr.appendChild(tdProduto);
			
			tdQtd.innerHTML = "<b>" + quantidade + "x</b>";
			tdProduto.innerHTML = "<a href='index.php?act=1&produto=" + resultado[3] + "'>" + resultado[0] + "</a>";
		}
		else if(resultado[4] == "update"){
			tdNovaQuantidade.innerHTML = "<b>" + resultado[5] + "x</b>";
		}
		
		totalCompra.innerHTML = 'R$ ' + resultado[2];
		
		if(categoria == 1){
			tdComprar.innerHTML = "<img src='../img/comprar_disabled.gif' title='Este curso já está no carrinho'>";
		}
		else if(categoria == 2){
			tdComprar.innerHTML = "<img src='../img/comprar_disabled.gif' title='Esta palestra já está no carrinho'>";
		}
		
		//pergunta...
		if(confirm("Deseja ver o carrinho de compras ou continuar comprando?\n\n- \"OK\" para ver o carrinho\n- \"Cancelar\" para continuar comprando")){
			window.location.href = "index.php?act=4";
		}
	}
	else{
		tdProduto.appendChild(document.createTextNode("Carregando..."));
	}
}

function alteraProduto(idProduto){
	var novaQuantidade = document.getElementById('novaQuantidade' + idProduto);
	var qtdItens = document.getElementById('qtdItens');
	var tdQtd = document.getElementById(idProduto);
	var totalCompra = document.getElementById('totalCompra');
	var totalCarrinho = document.getElementById('totalCarrinho');
	var totalPontos = document.getElementById('totalPontos');
	
	var ajax = openAjax();
	var url = 'insereProduto.php';
	
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1');
	ajax.send('produto=' + idProduto + '&novaQuantidade=' + novaQuantidade.value);
	if(ajax.status == 200){
		//alert(ajax.responseText);
		var resultado = ajax.responseText.split(" ; ");
		if((resultado[0].charAt(0) == "1") && (resultado[0].length == 1))
			qtdItens.innerHTML = resultado[0] + " Item";
		else
			qtdItens.innerHTML = resultado[0] + " Itens";
			
		tdQtd.innerHTML = "<b>" + resultado[1] + "x</b>";
		totalCompra.innerHTML = "R$ " + resultado[2];
		totalCarrinho.innerHTML = "R$ " + resultado[2];
		totalPontos.innerHTML = resultado[3];
		//novaQuantidade.onblur = "'javascript:if((this.value == \"\") || (this.value == \"0\")){this.value = \"" + resultado[1] + "\"}'";
	}
}

function removeProduto(idProduto){
	
	var tableProduto = document.getElementById('table' + idProduto);
	var lista = document.getElementById('listaItens');
	
	var qtdItens = document.getElementById('qtdItens');
	var totalCompra = document.getElementById('totalCompra');
	var totalCarrinho = document.getElementById('totalCarrinho');
	var totalPontos = document.getElementById('totalPontos');
	
	var trProduto = document.getElementById('tr' + idProduto);
	var tdQtd = document.getElementById(idProduto);
			
	//tdNenhum.appendChild(document.createTextNode("Carregando..."));
			
	var ajax = openAjax();
	var url = 'removeProduto.php';
	
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=iso-8859-1'); 
	ajax.send('produto=' + idProduto);
	if(ajax.status == 200){
		var resultado = ajax.responseText.split(" ; ");
		if(resultado[3] == 1){
			document.getElementById('itens').value = 0;
			window.location.href = "index.php";
		}
		
		if((resultado[2].charAt(0) == "1") && (resultado[2].length == 1))
			qtdItens.innerHTML = resultado[2] + " Item";
		else
			qtdItens.innerHTML = resultado[2] + " Itens";
				
		totalPontos.innerHTML = resultado[1];
		totalCompra.innerHTML = 'R$ ' + resultado[0];
		totalCarrinho.innerHTML = 'R$ ' + resultado[0];
			
		tableProduto.style.display = 'none';
		trProduto.style.display = 'none';
	}
}

function verificaPreRequisito(idUsuario, preRequisito, idProduto){
	if(idUsuario != ''){	
		var ajax = openAjax();
		var url = 'verificaPreRequisito.php?pre=' + preRequisito + '&id=' + idUsuario;
			
		ajax.open('GET', url, false);
		ajax.send(null);
		if(ajax.status == 200){
			if(ajax.responseText == 1){
				insereProduto(idProduto, 1);
			}
			else{
				alert("Você não possui o pré-requisito necessário para comprar este produto.\nVerifique e adquira o curso indicado em nossa loja.");
			}
		}
	}
	else{
		openWindowLogin();
	}
}

function openWindowLogin(){
	window.open("janelaLogin.php", "Login", "width=300, height=290, top="+(screen.height/5)+", left="+(screen.width/5)+", menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=no")
}

function efetuaLogin(param){
	var login = document.getElementById('login');
	var senha = document.getElementById('senha');
	
	var formLogin = document.getElementById('formLogin');
	var formLogado = document.getElementById('formLogado');
	var erroLogin = document.getElementById('erroLogin');
	var textoErroLogin = document.getElementById('textoErroLogin');
		
	var nomeUsuario = document.getElementById('nomeUsuario');
	var tipoCliente = document.getElementById('tipoCliente');
	var pontosAcumulados = document.getElementById('pontosAcumulados');
	var ultimoAcesso = document.getElementById('ultimoAcesso');
	var editarDados = document.getElementById('editarDados');
	var th = document.getElementById('th');
	
	//tdProduto.appendChild(document.createTextNode("Carregando..."));
		
	var ajax = openAjax();
	if(param != null)
		var url = 'loja/login.php';
	else
		var url = 'login.php';
		
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
	ajax.send('login=' + login.value + '&senha=' + senha.value);
	if(ajax.status == 200){
		login.value = "";
		senha.value = "";
		//alert(ajax.responseText);
		if(ajax.responseText == "null"){
			textoErroLogin.innerHTML = "Usuario ou senha incorretos!";
			erroLogin.style.display = "block";
			login.focus();
			return false;
		}
		else if(ajax.responseText == "log"){
			textoErroLogin.innerHTML = "Este usuário já está logado!";
			erroLogin.style.display = "block";
			login.focus();
			return false;
		}
		else{
			var resultado = ajax.responseText.split(" ; ");
			var resultadoNome = resultado[0].split(" ");
			//alert(ajax.reponseText);
			formLogin.style.display = "none";
			erroLogin.style.display = "none";
			formLogado.style.display = "block";
			
			nomeUsuario.innerHTML = resultado[0];
			tipoCliente.innerHTML = resultado[4];
			pontosAcumulados.innerHTML = resultado[5];
			ultimoAcesso.innerHTML = resultado[1];
			
			if(resultado[6] == 1){
				th.style.display = 'block';
			}
			//editarDados.href = "edit.php?edt=" + resultado[3] + "&key=" + resultado[4];
		}
	}
}

function efetuaLoginDireto(login, senha, area){
	var erroLogin = document.getElementById("erroLogin");
	var textoErroLogin = document.getElementById("textoErroLogin");
	
	var ajax = openAjax();
	if(area == "loja")
		var url = 'login.php';
	else
		var url = 'efetuaLogin.php';
		
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
	ajax.send('login=' + login + '&senha=' + senha);
	if(ajax.status == 200){
		if(ajax.responseText == "null"){
			textoErroLogin.innerHTML = "Usuário ou senha incorretos!";
			if(browser == "Netscape")
				erroLogin.style.display = "table";
			else
				erroLogin.style.display = "block";
			document.form_login.login.value = "";
			document.form_login.senha.value = "";
			document.form_login.login.focus();
			//alert("Não foi possível completar a operação! Tente novamente mais tarde.");
			//window.location.href = "index.php";
		}
		else if(ajax.responseText == "log"){
			textoErroLogin.innerHTML = "Este usuário já está logado!";
			if(browser == "Netscape")
				erroLogin.style.display = "table";
			else
				erroLogin.style.display = "block";
			document.form_login.login.value = "";
			document.form_login.senha.value = "";
			document.form_login.login.focus();
		}
		else{
			if(area == "loja")
				window.location.href = "finalizaCompra2.php";
			else if(area == "home")
				window.location.href = "index.php?act=6";
			else
				window.location.href = "index.php";
		}
	}
}

function logout(param){	
	var formLogin = document.getElementById('formLogin');
	var formLogado = document.getElementById('formLogado');
	var erroLogin = document.getElementById('erroLogin');
	
	var login = document.getElementById('login');
	
	var ajax = openAjax();
	var url = 'logout.php';
		
	ajax.open('GET', url, false);
	ajax.send(null);
	if(ajax.status == 200){
		if(param != null){
			window.location.href = "index.php";
		}
		else{
			formLogado.style.display = "none";
			formLogin.style.display = "block";
			erroLogin.style.display = "none";
			login.focus();
		}
	}
}

function verificaLogin(login, loginCarregado){
	var tdLogin = document.getElementById("tdLogin");
	var button = document.getElementById("enviar");
	
	if((login != '') && (login != loginCarregado)){
		
		var ajax = openAjax();
		var url = 'verificaLogin.php';
		
		tdLogin.style.color = "#000000";
		tdLogin.innerHTML = "Carregando...";
			
		ajax.open('POST', url, false);
		ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
		ajax.send('login=' + login);
		
		if(ajax.status == 200){
			if(ajax.responseText != "ok"){
				tdLogin.style.color = "#FF0000";
				tdLogin.innerHTML = ajax.responseText;
				button.disabled = true;
			}
			else{
				tdLogin.style.color = "#009900";
				tdLogin.innerHTML = "Login disponível!";
				button.disabled = false;
			}
		}
	}
	else{
		tdLogin.innerHTML = "";
		button.disabled = false;
	}
}

function verificaEmail(email, emailCarregado){
	var button = document.getElementById("enviar");
	
	if((email != '') && (email != emailCarregado)){
		
		var ajax = openAjax();
		var url = 'verificaEmail.php';
				
		ajax.open('POST', url, false);
		ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
		ajax.send('email=' + email);
			
		if(ajax.status == 200){
			if(ajax.responseText != "ok"){
				alert(ajax.responseText);
				document.form_cadastro.email.value = "";
				document.form_cadastro.email.focus();
				button.disabled = true;
			}
			else{
				button.disabled = false;
			}
		}
	}
	else{
		button.disabled = false;
	}
}

/*function calculaFrete(){
	var frete = document.getElementById("frete");
	var totalCompra = document.getElementById("totalCompra");
	var cepOrigem = document.getElementById("cepOrigem").value;
	var cepDestino = document.getElementById("cepDestino").value;
	var servico = document.getElementById("servico").value;
	var pesoTotal = document.getElementById("pesoTotal").value;
	var pesoCubicoTotal = document.getElementById("pesoCubicoTotal").value;
	
	var ajax = openAjax();
	var url = 'calculaFrete.php?cep1=' + cepOrigem + 'cep2=' + cepDestino + 'massa=' + pesoTotal + 'pesoCubico=' + pesoCubicoTotal + 'servicoEntrega=' + servico;
		
	ajax.open('GET', url, false);
	ajax.send(null);
	if(ajax.status == 200){
		alert(ajax.responseText);
	}
}*/

/*function calculaFrete(){
	var cepOrigem = document.getElementById("cepOrigem").value;
	var cepDestino = document.getElementById("cepDestino").value;
	var servico = document.getElementById("servico").value;
	var peso = document.getElementById("pesoTotal").value;
	var pesoCubicoTotal = document.getElementById("pesoCubicoTotal").value;
	
	window.location.href = "http://www.correios.com.br/encomendas/precos/calculo.cfm?Servico=" + servico + "&cepOrigem=" + cepOrigem + "&cepDestino=" + cepDestino + "&peso=" + peso + "&resposta=http://localhost/oriente-ocidente/loja/finalizaCompra2.php";
}*/

function cadastraNewsletter(id, email, nome, tipo){
	var url = 'cadastraNewsletter.php?id=' + id + '&email=' + email + '&nome=' + nome + '&tipo=' + tipo;
	var ajax = openAjax();
	
	ajax.open('GET', url, false);
	//ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;'); 
	//ajax.send('id=' + id + '&email=' + email + '&nome=' + nome);
	ajax.send(null);
	if(ajax.status == 200){
		alert("Operação realizada com sucesso!");
		window.location.href = "index.php";
	}
}

function esvaziaCarrinho(param){
	if(param == 'cancelaCompra'){
		window.location.href = "esvaziaCarrinho.php";
		return;
	}
	
	//alert(param.substr(0, 5));
	
	if(document.getElementById('itens').value == 1){
		if(confirm('Tem certeza que deseja esvaziar seu carrinho de compras?')){
			
			if(param != null){
				if(param == 1){
					window.location.href = "esvaziaCarrinho.php";
				}
				
				if((param.substr(0, 5) != "curso") && (param.substr(0, 8) != "palestra")){
					window.location.href = "esvaziaCarrinho.php";
				}
				else{
					var tdComprar = document.getElementById('tdComprar');
				}
			}
			
			var tbody = document.createElement("TBODY");
			var lista = document.getElementById('listaItens');
			
			var qtdItens = document.getElementById('qtdItens');
			var totalCompra = document.getElementById('totalCompra');
			
			var trNenhum = document.createElement('tr');
			var tdNenhum = document.createElement('td');
			
			trNenhum.setAttribute('id', 'trNenhum');
			tdNenhum.setAttribute('align', 'center');
			tdNenhum.setAttribute('id', 'tdNenhum');
			
			tdNenhum.appendChild(document.createTextNode("Carregando..."));
			
			var ajax = openAjax();
			var url = 'esvaziaCarrinho.php';
			
			ajax.open('GET', url, false);
			ajax.send(null);
			if(ajax.status == 200){
				document.getElementById('itens').value = 0;
				
				while(lista.childNodes[0]){
					lista.removeChild(lista.childNodes[0]);
				}
				
				lista.appendChild(tbody);
				tbody.appendChild(trNenhum);
				trNenhum.appendChild(tdNenhum);
				tdNenhum.innerHTML = "Nenhum produto";

				qtdItens.innerHTML = "0 Itens";
				totalCompra.innerHTML = 'R$ 0,00';
				
				if(param != null){
					if(param.substr(0, 5) == "curso"){
						var result = param.split(" - ");
						tdComprar.innerHTML = "<a href='javascript:void(0)'><img src='../img/comprar.gif' title='Colocar no carrinho' onclick=\"insereProduto(" + result[1] + ", 1)\" border='0'></a>";
					}
					
					if(param.substr(0, 8) == "palestra"){
						var result = param.split(" - ");
						tdComprar.innerHTML = "<a href='javascript:void(0)'><img src='../img/comprar.gif' title='Colocar no carrinho' onclick=\"insereProduto(" + result[1] + ", 2)\" border='0'></a>";
					}
				}
			}
		}
	}
	else{
		alert("O carrinho já está vazio!");
	}
}

function verificaCarrinho(){
	if(document.getElementById('itens').value == 1){
		window.location.href = 'index.php?act=4';
	}
	else{
		alert("Seu carrinho está vazio!\nPara adicionar um item ao carrinho, escolha o produto e clique no botão Comprar");
	}
}

function openWindowComoComprar(){
	window.open("comoComprar.php", "Comprar", "height=550, width=700, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

// FIM DAS FUNÇÕES DA LOJA

// INÍCIO DAS FUNÇÕES DA ÁREA DE ADMINISTRAÇÃO

function excluiRegistro(idRegistro, tabela){
	if(tabela == "modulo"){
		var confirmacao = "Todas as aulas e páginas deste módulo serão perdidas ao excluir o registro.\nDeseja continuar?";
	}
	else if(tabela == "aula"){
		var confirmacao = "Todas as páginas desta aula serão perdidas ao excluir o registro.\nDeseja continuar?";
	}
	else{
		var confirmacao = "Tem certeza que deseja excluir esse registro?";
	}
	
	if(confirm(confirmacao)){
		window.location.href = "confirmaExclusao.php?id=" + idRegistro + "&tabela=" + tabela;
	}
}

function openWindowJustificativa(tipo, idItemCompra, idCompra, acao){ //tipo: 1 = compra inteira ou 0 = item específico | acao: 1 = gravar ou 0 = visualizar
	if(tipo == 0)
		window.open("justificativa.php?type=0&id=" + idItemCompra + "&action=" + acao,"Justificativa","height=320, width=500, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
	else if(tipo == 1)
		window.open("justificativa.php?type=1&id=" + idCompra + "&action=" + acao,"Justificativa","height=320, width=500, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
}

function gravaJustificativa(id, tipo){
	var justificativa = document.getElementById("textArea").value;
	
	if(tipo == 0)
		var canceladoItem = opener.document.getElementById("canceladoItem" + id);
	else
		var canceladoCompra = opener.document.getElementById("canceladoCompra" + id);
	
	var url = "gravaJustificativa.php?justificativa=" + justificativa + "&id=" + id + "&tipo=" + tipo;
	var ajax = openAjax();
	
	ajax.open('GET', url, false);
	//ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;'); 
	//ajax.send('id=' + id + '&email=' + email + '&nome=' + nome);
	ajax.send(null);
	if(ajax.status == 200){
		alert("Justificativa gravada com sucesso!");
		//window.opener.location = "index.php";
		if(tipo == 0){
			canceladoItem.innerHTML = "<span style='color:#FF0000;font-size:10px;font-weight:bold'>Cancelado</span>";
			//alert(ajax.responseText);
			if(ajax.responseText != "ok"){
				opener.document.getElementById("canceladoCompra" + ajax.responseText).innerHTML = "<span style='color:#FF0000;font-size:12px;font-weight:bold'>Cancelada</span>";
			}
		}
		else{
			canceladoCompra.innerHTML = "<span style='color:#FF0000;font-size:12px;font-weight:bold'>Cancelada</span>";
			responseText = ajax.responseText.substring(0, (ajax.responseText.length - 1));
			//alert(responseText);
			var itens = responseText.split("/");
			//alert(itens.length);
			for(i = 0; i < itens.length; i++){
				opener.document.getElementById("canceladoItem" + itens[i]).innerHTML = "<span style='color:#FF0000;font-size:10px;font-weight:bold'>Cancelado</span>";
			}
		}
		window.close();
	}
}

function mudaVisivel(visivel){
	var visivelPadrao = document.getElementById("visivelPadrao").value;
	var buttonAlterar = document.getElementById("buttonAlterar");
	
	if(visivel != visivelPadrao){
		buttonAlterar.disabled = false;
	}
	else{
		buttonAlterar.disabled = true;
	}
}

function confirmaAlteracaoEnquete(){
	var visivelPadrao = document.getElementById("visivelPadrao").value;
	
	if(visivelPadrao == 0){
		if(confirm("Ao alterar a propriedade 'visível' de uma enquete para 'Sim', todas as outras serão automaticamente configuradas para 'Não'.\nDeseja continuar?")){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return true;
	}
}

function openWindowModulo(idCurso, idModulo, acao){ //acao: 1 = inserção ou 0 = edição
	if(acao == 0)
		window.open("modulo.php?id=" + idModulo + "&action=" + acao,"modulo","height=320, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
	else if(acao == 1)
		window.open("modulo.php?&id=" + idCurso + "&action=" + acao,"modulo","height=320, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
}

function openWindowAula(idModulo, idAula, acao){ //acao: 1 = inserção ou 0 = edição
	if(acao == 0)
		window.open("aula.php?id=" + idAula + "&action=" + acao,"aula","height=170, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	else if(acao == 1)
		window.open("aula.php?&id=" + idModulo + "&action=" + acao,"aula","height=170, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function openWindowAulaVideo(idCurso, idAula, acao){ //acao: 1 = inserção ou 0 = edição
	if(acao == 0)
		window.open("aulavideo.php?id=" + idAula + "&action=" + acao,"aula","height=200, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	else if(acao == 1)
		window.open("aulavideo.php?&id=" + idCurso + "&action=" + acao,"aula","height=200, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function visualizarAula(idAula ,contadorAula, contadorModulo){
	window.open("verAula.php?id=" + idAula + "&a=" + contadorAula + "&cm=" + contadorModulo + "&page=1", "verAula","height=500, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function openWindowPagina(idAula, idPagina, acao){ //acao: 1 = inserção ou 0 = edição
	if(acao == 0)
		window.open("paginaAula.php?id=" + idPagina + "&action=" + acao,"pagina","height=720, width=720, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
	else if(acao == 1)
		window.open("paginaAula.php?&id=" + idAula + "&action=" + acao,"pagina","height=510, width=720, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function openWindowAvaliacao(idCurso, idModulo, idAvaliacao, idPergunta, acao){ //acao: 0 = avaliação do curso, 1 = avaliação no módulo, 2 = inserir questão e 3 = editar questão
	if(acao == 0)
		window.open("avaliacao.php?id=" + idCurso + "&action=" + acao,"avaliacao","height=330, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
	if(acao == 1)
		window.open("avaliacao.php?id=" + idModulo + "&action=" + acao,"avaliacao","height=330, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
	if(acao == 2)
		window.open("avaliacao.php?id=" + idAvaliacao + "&action=" + acao,"avaliacao","height=330, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
	if(acao == 3)
		window.open("avaliacao.php?id=" + idPergunta + "&action=" + acao,"avaliacao","height=330, width=580, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
}

function mostraListaModulos(idCurso){
	var listaModulos = document.getElementById('listaModulos' + idCurso);
	var expandLink = document.getElementById('expandLinkModulos' + idCurso);
	var expandImg = document.getElementById('expandImgModulos' + idCurso);
	var expandText = document.getElementById('expandTextModulos' + idCurso);
	var expandOrCollapse = document.getElementById('expandOrCollapseModulos' + idCurso);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		expandText.innerHTML = "Esconder módulos";
		expandLink.title = "Recolher módulos";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaModulos.style.display = 'table';
		}
		else{
			listaModulos.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		expandText.innerHTML = "Ver módulos";
		expandLink.title = "Expandir módulos";
		listaModulos.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaAulas(idModulo){
	var listaAulas = document.getElementById('listaAulas' + idModulo);
	var expandLink = document.getElementById('expandLinkAulas' + idModulo);
	var expandImg = document.getElementById('expandImgAulas' + idModulo);
	var expandText = document.getElementById('expandTextAulas' + idModulo);
	var expandOrCollapse = document.getElementById('expandOrCollapseAulas' + idModulo);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		//expandText.innerHTML = "Esconder módulos";
		expandLink.title = "Esconder aulas deste módulo";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaAulas.style.display = 'table';
		}
		else{
			listaAulas.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		//expandText.innerHTML = "Ver módulos";
		expandLink.title = "Ver aulas deste módulo";
		listaAulas.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaPaginas(idAula){
	var listaPaginasAula = document.getElementById('listaPaginasAula' + idAula);
	var expandLink = document.getElementById('expandLinkPaginas' + idAula);
	var expandImg = document.getElementById('expandImgPaginas' + idAula);
	var expandText = document.getElementById('expandTextPaginas' + idAula);
	var expandOrCollapse = document.getElementById('expandOrCollapsePaginas' + idAula);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		//expandText.innerHTML = "Esconder módulos";
		expandLink.title = "Esconder páginas desta aula";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaPaginasAula.style.display = 'table';
		}
		else{
			listaPaginasAula.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		//expandText.innerHTML = "Ver módulos";
		expandLink.title = "Ver páginas desta aula";
		listaPaginasAula.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaQuestoesAvaliacaoCurso(idAvaliacao){
	var listaQuestoesAvaliacaoCurso = document.getElementById('listaQuestoesAvaliacaoCurso' + idAvaliacao);
	var expandLink = document.getElementById('expandLinkAvaliacaoCurso' + idAvaliacao);
	var expandImg = document.getElementById('expandImgAvaliacaoCurso' + idAvaliacao);
	var expandText = document.getElementById('expandTextAvaliacaoCurso' + idAvaliacao);
	var expandOrCollapse = document.getElementById('expandOrCollapseAvaliacaoCurso' + idAvaliacao);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		expandLink.title = "Esconder questões desta avaliação";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaQuestoesAvaliacaoCurso.style.display = 'table';
		}
		else{
			listaQuestoesAvaliacaoCurso.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		expandLink.title = "Ver questões desta avaliação";
		listaQuestoesAvaliacaoCurso.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaQuestoesAvaliacaoModulo(idAvaliacao){
	var listaQuestoesAvaliacaoModulo = document.getElementById('listaQuestoesAvaliacaoModulo' + idAvaliacao);
	var expandLink = document.getElementById('expandLinkAvaliacaoModulo' + idAvaliacao);
	var expandImg = document.getElementById('expandImgAvaliacaoModulo' + idAvaliacao);
	var expandText = document.getElementById('expandTextAvaliacaoModulo' + idAvaliacao);
	var expandOrCollapse = document.getElementById('expandOrCollapseAvaliacaoModulo' + idAvaliacao);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		expandLink.title = "Esconder questões desta avaliação";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaQuestoesAvaliacaoModulo.style.display = 'table';
		}
		else{
			listaQuestoesAvaliacaoModulo.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		expandLink.title = "Ver questões desta avaliação";
		listaQuestoesAvaliacaoModulo.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function gravaNumeroVisualizacoes(idAula, idUsuarioCurso){
	var qtd = document.getElementById("qtdVisualizacoes" + idAula).value;
	
	var ajax = openAjax();
	var url = 'gravaVisualizacoes.php';
			
	ajax.open('POST', url, false);
	ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
	ajax.send("qtd=" + qtd + "&id=" + idAula + "&idUsuarioCurso=" + idUsuarioCurso);
		
	if(ajax.status == 200){
		if(ajax.responseText != "ok"){
			alert("Falha ao gravar número de visualizações! Tente novamente mais tarde.");
		}
		else{
			alert("Número de visualizações atualizado com sucesso!");
		}
	}
}

function openWindowDetalhesCompra(idCompra){
	window.open("detalhesCompra.php?id=" + idCompra,"compra","height=500, width=620, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=yes");
}

function openWindowRastreio(idItemCompra){
	window.open("rastreio.php?id=" + idItemCompra,"rastreio","height=100, width=300, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no, scrollbars=auto");
}

// FIM DAS FUNÇÕES DA ÁREA DE ADMINISTRAÇÃO

function Security(val, tamanho) {
 	
 	document.getElementById('d_baixa').style.background = 'white';
 	document.getElementById('d_media').style.background = 'white';
 	document.getElementById('d_alta').style.background = 'white';
	
	if(val == "")
	{
		document.getElementById('d_baixa').style.background = 'white';
		document.getElementById('d_media').style.background = 'white';
		document.getElementById('d_alta').style.background = 'white';
	 	return;   
	}
	
	if(val.length < tamanho )
	{
		document.getElementById('d_baixa').style.background = 'white';
		document.getElementById('d_media').style.background = 'white';
		document.getElementById('d_alta').style.background = 'white'; 
	  	return;   
	}
  
	if( val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) != -1 
		||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) 
		||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1 && val.search(/[0-9]/) 
		||val.length >= tamanho  && val.search(/[@!#$%&*+=?|-]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) )
		{
  			document.getElementById('d_baixa').style.background = "url('../img/pass_green.gif')";
 			document.getElementById('d_media').style.background = "url('../img/pass_green.gif')";
 			document.getElementById('d_alta').style.background = "url('../img/pass_green.gif')";
  		}
		
		else{
  		if( val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 
  			||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[0-9]/) != -1 
  			||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1
				||val.length >= tamanho && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) != -1
				||val.length >= tamanho && val.search(/[A-Z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1
				||val.length >= tamanho && val.search(/[0-9]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1)
		{
  			document.getElementById('d_baixa').style.background = "url('../img/pass_yellow.gif')";
 			document.getElementById('d_media').style.background = "url('../img/pass_yellow.gif')";
 			document.getElementById('d_alta').style.background = 'white';
  		}
		
  		else {
  		if(val.length >= tamanho)
  		{
  			document.getElementById('d_baixa').style.background = "url('../img/pass_red.gif')";
 			document.getElementById('d_media').style.background = 'white';
 			document.getElementById('d_alta').style.background = 'white';
		}
  	}
}
}



//TEMPORÁRIO
//-----------------------------------------------------------
//-----------------------------------------------------------
function Security2(val, tamanho) {
 	
 	document.getElementById('d_baixa').style.background = 'white';
 	document.getElementById('d_media').style.background = 'white';
 	document.getElementById('d_alta').style.background = 'white';
	
	if(val == "")
	{
		document.getElementById('d_baixa').style.background = 'white';
		document.getElementById('d_media').style.background = 'white';
		document.getElementById('d_alta').style.background = 'white';
	 	return;   
	}
	
	if(val.length < tamanho )
	{
		document.getElementById('d_baixa').style.background = 'white';
		document.getElementById('d_media').style.background = 'white';
		document.getElementById('d_alta').style.background = 'white'; 
	  	return;   
	}
  
	if( val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) != -1 
		||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) 
		||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1 && val.search(/[0-9]/) 
		||val.length >= tamanho  && val.search(/[@!#$%&*+=?|-]/) != -1 && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) )
		{
  			document.getElementById('d_baixa').style.background = "url('img/pass_green.gif')";
 			document.getElementById('d_media').style.background = "url('img/pass_green.gif')";
 			document.getElementById('d_alta').style.background = "url('img/pass_green.gif')";
  		}
		
		else{
  		if( val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[A-Z]/) != -1 
  			||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[0-9]/) != -1 
  			||val.length >= tamanho && val.search(/[a-z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1
				||val.length >= tamanho && val.search(/[A-Z]/) != -1 && val.search(/[0-9]/) != -1
				||val.length >= tamanho && val.search(/[A-Z]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1
				||val.length >= tamanho && val.search(/[0-9]/) != -1 && val.search(/[@!#$%&*+=?|-]/) != -1)
		{
  			document.getElementById('d_baixa').style.background = "url('img/pass_yellow.gif')";
 			document.getElementById('d_media').style.background = "url('img/pass_yellow.gif')";
 			document.getElementById('d_alta').style.background = 'white';
  		}
		
  		else {
  		if(val.length >= tamanho)
  		{
  			document.getElementById('d_baixa').style.background = "url('img/pass_red.gif')";
 			document.getElementById('d_media').style.background = 'white';
 			document.getElementById('d_alta').style.background = 'white';
		}
  	}
}
}
//-----------------------------------------------------------
//-----------------------------------------------------------



function trocaPesoFrete(servico){
	var pesoEnvio = document.getElementById("pesoEnvio").value;
	var pesoEnvioPAC = document.getElementById("pesoEnvioPAC").value;
	
	if(servico == 41106){
		document.form_frete.peso.value = pesoEnvioPAC;
	}
	else{
		document.form_frete.peso.value = pesoEnvio;
	}
}

function mostraDadosBancarios(formaPagamento){
	var dadosBancarios = document.getElementById('dadosBancarios');
	var atencaoBoleto = document.getElementById('atencaoBoleto');
	var dadosMilhagem = document.getElementById('dadosMilhagem');
	var proximaEtapa = document.getElementById('proximaEtapa');
	var buttonConcluir = document.getElementById("buttonConcluir");
	
	var pontosDinheiro = document.getElementById("pontosDinheiro").value;
	var valorTotal = document.getElementById("valorTotal").value;
	
	var i = 0;
	
	if(formaPagamento == "deposito"){
		dadosBancarios.style.display = 'block';
		atencaoBoleto.style.display = 'none';
		dadosMilhagem.style.display = 'none';
		i++;
	}
	else if(formaPagamento == "boleto"){
		dadosBancarios.style.display = 'none';
		atencaoBoleto.style.display = 'block';
		dadosMilhagem.style.display = 'none';
		i++;
	}
	else{
		dadosMilhagem.style.display = 'block';
		dadosBancarios.style.display = 'none';
		atencaoBoleto.style.display = 'none';
		if(parseFloat(pontosDinheiro) >= parseFloat(valorTotal)){
			i++;
		}
		else{
			i = 0;
		}
	}
	
	if(i > 0){
		buttonConcluir.disabled = false;
		buttonConcluir.src = "../img/concluir.gif";
		buttonConcluir.title = "Concluir compra";
	}
	else{
		buttonConcluir.disabled = true;
		buttonConcluir.src = "../img/concluir_disabled.gif";
	}
}

function cancelaCompra(){
	if(confirm("Tem certeza que deseja cancelar essa compra?\nSeu carrinho será esvaziado!")){
		esvaziaCarrinho('cancelaCompra');
		//window.location.href = "index.php";
	}
}

function mostraListaCompra(param, idCompra){
	var listaCompra = document.getElementById('listaCompra' + idCompra);
	var expandCollapse = document.getElementById('expandCollapse' + idCompra);
	var expandCollapseText = document.getElementById('expandCollapseText' + idCompra);
	var expandCollapseLink = document.getElementById('expandCollapseLink' + idCompra);
	var expandOrCollapse = document.getElementById('expandOrCollapse' + idCompra);
	
	if(expandOrCollapse.value == 1){
		expandCollapse.src = "../img/collapse.gif";
		expandCollapseText.innerHTML = "Esconder itens da compra";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaCompra.style.display = 'table';
		}
		else{
			listaCompra.style.display = 'block';
		}
	}
	else{
		expandCollapse.src = "../img/expand.gif";
		expandCollapseText.innerHTML = "Ver itens da compra";
		listaCompra.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaAulasLoja(idModulo){
	var listaAulas = document.getElementById('listaAulas' + idModulo);
	var expandLink = document.getElementById('expandLinkAulas' + idModulo);
	var expandImg = document.getElementById('expandImgAulas' + idModulo);
	//var expandText = document.getElementById('expandTextAulas' + idModulo);
	var expandOrCollapse = document.getElementById('expandOrCollapseAulas' + idModulo);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/collapse.gif";
		//expandText.innerHTML = "Esconder módulos";
		expandLink.title = "Esconder conteúdo deste módulo";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaAulas.style.display = 'table';
		}
		else{
			listaAulas.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/expand.gif";
		//expandText.innerHTML = "Ver módulos";
		expandLink.title = "Ver conteúdo deste módulo";
		listaAulas.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function enviaMail(usuario){
	var url = "enviaMail.php?id=" + usuario;
	var ajax = openAjax();
	
	ajax.open('GET', url, false);
	ajax.send(null);
	if(ajax.status == 200){
		if(ajax.responseText == "1")
			alert("E-mail com os dados bancários enviado com sucesso!");
		else
			alert("Falha ao enviar e-mail! Tente novamente mais tarde.");
	}
}

function mudaVoto(opcao){
	var alternativa = document.getElementById("alternativa");
	alternativa.value = opcao;
}

function votar(enquete, votar){
	var alternativa = document.getElementById("alternativa").value;
	
	window.open("enquete.php?o=" + alternativa + "&e=" + enquete + "&v=" + votar,"enquete","height=270, width=450, left=300, top=200, menubar=no, titlebar=no, status=no, menubar=no, toolbar=no, location=no");
}

// INÍCIO DAS FUNÇÕES DO ENSINO À DISTÂNCIA

function mostraListaAulasEad(idModulo){
	var listaAulas = document.getElementById('listaAulas' + idModulo);
	var expandLink = document.getElementById('expandLinkAulas' + idModulo);
	var expandImg = document.getElementById('expandImgAulas' + idModulo);
	//var expandText = document.getElementById('expandTextAulas' + idModulo);
	var expandOrCollapse = document.getElementById('expandOrCollapseAulas' + idModulo);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/arrow_collapse.gif";
		//expandText.innerHTML = "Esconder módulos";
		expandLink.title = "Esconder aulas deste módulo";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaAulas.style.display = 'table';
		}
		else{
			listaAulas.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/arrow_expand.gif";
		//expandText.innerHTML = "Ver módulos";
		expandLink.title = "Ver aulas deste módulo";
		listaAulas.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraListaResultados(idUsuarioCurso){
	var listaResultados = document.getElementById('listaResultados' + idUsuarioCurso);
	var expandLink = document.getElementById('expandLinkResultados' + idUsuarioCurso);
	var expandImg = document.getElementById('expandImgResultados' + idUsuarioCurso);
	var expandOrCollapse = document.getElementById('expandOrCollapseResultados' + idUsuarioCurso);
	
	if(expandOrCollapse.value == 1){
		expandImg.src = "../img/arrow_collapse.gif";
		expandLink.title = "Esconder resultados das avaliações";
		expandOrCollapse.value = 0;
		if(browser == "Netscape"){
			listaResultados.style.display = 'table';
		}
		else{
			listaResultados.style.display = 'block';
		}
	}
	else{
		expandImg.src = "../img/arrow_expand.gif";
		expandLink.title = "Exibir resultados das avaliações";
		listaResultados.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function mostraAnotacao(idAnotacao){
	var anotacao = document.getElementById('anotacao' + idAnotacao);
	var expandLink = document.getElementById('expandLinkAnotacao' + idAnotacao);
	var expandOrCollapse = document.getElementById('expandOrCollapse' + idAnotacao);
	
	if(expandOrCollapse.value == 1){
		expandLink.title = "Esconder anotação completa";
		expandOrCollapse.value = 0;
		anotacao.style.display = 'block';
	}
	else{
		expandLink.title = "Ver anotação completa";
		anotacao.style.display = 'none';
		expandOrCollapse.value = 1;
	}
}

function openWindowAulaEad(idAula, contadorAula, idModulo, contadorModulo, idUsuarioCurso){
	window.open("aula.php?id=" + idAula + "&a=" + contadorAula + "&m=" + idModulo + "&uc=" + idUsuarioCurso + "&cm=" + contadorModulo + "&page=" + 1 + "&deleteSession=" + 1, "aula", "menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=yes");
}

function openWindowAulaEadVideo(idAula, contadorAula, idUsuarioCurso, pasta){
	if(navigator.appName.indexOf('Internet Explorer') < 0){
		alert('É necessário utilizar o navegador Internet Explorer para visualizar os cursos.');
		return false;
	}
	
	window.open("../cursos/"+pasta+"/web/default.php?id=" + idAula + "&a=" + contadorAula + "&uc=" + idUsuarioCurso, "aulavideo", "menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=yes,resizable=yes");
}

function openWindowAvaliacaoModuloEad(idAvaliacao, idModulo, contadorModulo, idUsuarioCurso, tipo){ //tipo: 0 = módulo ou 1 = curso
	window.open("avaliacao.php?id=" + idAvaliacao + "&m=" + idModulo + "&uc=" + idUsuarioCurso + "&cm=" + contadorModulo + "&tipo=" + tipo + "&corrigida=0", "avaliacao", "menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=yes");
}

function fullscreen(){
	window.moveTo(0,0);
	window.resizeTo(screen.width,screen.height);
}

function gravaAnotacao(idUsuarioCurso){
	var button = document.getElementById("buttonSalvar");
	
	if(button.disabled == false){
		var anotacao = document.getElementById("anotacoes");		
		var url = "gravaAnotacao.php";
		var ajax = openAjax();
		
		ajax.open('POST', url, false);
		ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
		ajax.send('a=' + anotacao.value + '&id=' + idUsuarioCurso);
		
		if(ajax.status == 200){
			if(ajax.responseText == "1"){
				//alert("Anotação gravada com sucesso!");
				anotacao.value = "";
				button.disabled = true;
				anotacao.focus();
			}				
			else{
				alert("Falha ao gravar anotação!");
			}
		}
	}
}

function finalizaCurso(){
	alert("Parabéns!\n\nO curso foi concluído com sucesso.\nVá até \"Cursos concluídos\" e clique em \"Exibir certificado\" para visualizar seu certificado de conclusão do curso.");
	window.close();
}

function exibeCertificado(idCurso){
	window.open("../certificadopdf.php?id=" + idCurso, "Certificado", "width=810, height=640, top="+(screen.height/5)+", left="+(screen.width/5)+", menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=no");
}

function openWindowGlossario(){
	var palavra = document.getElementById("palavra");
	window.open("glossario.php?p=" + palavra.value, "Glossario", "width=600, height=500, top="+(screen.height/5)+", left="+(screen.width/5)+", menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=auto");
	palavra.value = "";
}

function openWindowNoticia(idNoticia){
	window.open("noticia.php?id=" + idNoticia, "Noticia", "width=700, height=600, top="+(screen.height/5)+", left="+(screen.width/5)+", menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=yes");
}

function disableSelect(){
	var element = document.getElementById('content');
	var element2 = document.getElementById('fixedtopbox');
	var element3 = document.getElementById('fixedbottombox');
	
	if(browser != "Netscape"){
		element.onselectstart = function (){
			return false;
		}
		
		element2.onselectstart = function (){
			return false;
		}
		
		element3.onselectstart = function (){
			return false;
		}
	}
	else{
		element.onmousedown = function (){
			return false;
		}
		
		element2.onmousedown = function (){
			return false;
		}
		
		element3.onmousedown = function (){
			return false;
		}
	}
}

function submitEnter(evt){
	if(evt.keyCode == 13){
		if(document.getElementById('palavra').value.length != 0){
			openWindowGlossario();
		}
		else{
			alert('Digite uma palavra.');
			document.getElementById('palavra').focus();
		}
	}
}

function excluiAnotacao(idAnotacao){
	if(confirm("Tem certeza que deseja excluir essa anotação?")){
		window.location.href = "excluiAnotacao.php?id=" + idAnotacao;
	}
}

function selecionaFaq(id){
	if(id != "")
		window.location.href = "index.php?act=3&id=" + id;
}

function openWindowChat(idUsuario, key){
	window.open("../chat/index.php?uid=" + idUsuario + "&key=" + key, "Chat", "width=500, height=260, top="+(screen.height/5)+", left="+(screen.width/5)+", menubar=no,titlebar=no,status=no,toolbar=no,location=no,scrollbars=yes");
}

function mostraFormUpload(){
	var element = document.getElementById("formUpload");
	
	if(element.style.display != "none"){
		element.style.display = "none";
	}
	else{
		if(browser != "Netscape")
			element.style.display = "block";
		else
			element.style.display = "table";
	}
}

// FIM DAS FUNÇÕES DO ENSINO À DISTÂNCIA

// CONTROLE DE ACESSO SIMULTÂNEO

function loga(){
	var ajax = openAjax();
	var url = 'loga.php';
	
	ajax.open('GET', url, false);
	//ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
	ajax.send(null);
}

function desloga(){
	var ajax = openAjax();
	var url = 'desloga.php';
	
	ajax.open('GET', url, false);
	//ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=iso-8859-1;');
	ajax.send(null);
	if(ajax.status == 200){
		if(ajax.responseText != 0){
			return false;
		}
		else{
			return true;
		}
	}
}

function bodyOnReady(func){
	//call the function 'func' when DOM loaded
	//Version 2.0 - 03/03/2008 - based on Jquery bindReady
	//by Micox - www.elmicox.com - elmicox.blogspot.com - webly.com.br
	//http://www.elmicox.com/2007/evento-body-onready-sem-o-uso-de-libs/
	
	if(document.addEventListener && navigator.appName.indexOf('Opera') < 0){ //FF
		document.addEventListener("DOMContentLoaded", func, false);
	}
	else if(navigator.appName.indexOf('Internet Explorer') >= 0){ //IE
		try{ // by Diego Perini - http://javascript.nwbox.com/IEContentLoaded/
			document.documentElement.doScroll("left");
			func();
		}
		catch(error){
			setTimeout( arguments.callee, 20 );
			return
		}	
	}
	else if(navigator.appName.indexOf('Opera') >= 0){
		document.addEventListener("DOMContentLoaded", function (){
			for (var i = 0; i < document.styleSheets.length; i++){
				if (document.styleSheets[i].disabled){
					setTimeout(arguments.callee, 0);
					return;
				}
			}
		func();
		}, false);
	}
}


