// global variables
var host = "http://www.jmobi.com.br";

function getXmlHttp() {
	var xmlhttp = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) { xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try { xmlhttp = new XMLHttpRequest();
		} catch (e) { alert('Seu browser não suporta a tecnologia AJAX.'); 
		}
	}
	return xmlhttp;
}
function setHeaders(httpRequest) {
	httpRequest.setRequestHeader("Pragma", "no-cache");
	httpRequest.setRequestHeader("Content-Type", "charset=UTF-8");	
	httpRequest.setRequestHeader("Cache-Control", "no-store, no-cache, max-age=1, post-check=0, pre-check=0, must-revalidate");
}
function openDesc(page) {
//para manuais gprs
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", page+".xml", true);
	setHeaders(xmlhttp);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
    		var listItens = document.getElementsByTagName('li');
    		for( var x=0; x<listItens.length; x++) {
    			if (listItens[x].className == "ativo") {
					listItens[x].className = ""; }
    		}
    		content = writeTitle(xmlhttp.responseText);
    		document.getElementById("subTitulo").innerHTML = content;		
   			content = writeContent(xmlhttp.responseText);
   			document.getElementById("descricaoAssunto").innerHTML = content;
 		}
 	}
 	xmlhttp.send(null);
}
function openContent(page, elementId) {
//para conteudos em geral
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", page+".xml", true);
	setHeaders(xmlhttp);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
    		var listItens = document.getElementsByTagName('li');
    		for( var x=0; x<listItens.length; x++) {
    			if (listItens[x].className == "ativo") {
					listItens[x].className = ""; }
    		}
    		var title = writeTitle(xmlhttp.responseText);
    		altClass(elementId, 'ativo');
    		document.getElementById("subTitulo").innerHTML = title;
			if ((page == 'sobre' && elementId == 'm1') || (page == 'esqueci_senha' && elementId == 'm3')) {
				document.getElementById("sm3").style.background= "#e3e3e3";
				document.getElementById("sm3").style.color= "gray";
			} else if (page == 'cadastro' && elementId == 'm2') {
				document.getElementById("sm3").style.color= "gray";
			} else if (page == 'ajuda_como' && elementId == 'm2') {	showSubFaqMenu(); }
			var content = writeContent(xmlhttp.responseText);
			if (document.getElementById("descricaoConteudo")) {
				document.getElementById("descricaoConteudo").innerHTML = content;
			} else { document.getElementById("conteudoGeral").innerHTML = content; }
			acertarMenuLateral();
   		}
   	}
   	xmlhttp.send(null);
}
function getConfGPRS() {
	window.open("/jmobi-gprs/config_gprs", "config_gprs", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=790px, height=570px");
}
function openContentFromUrl(page){
	var url = window.location + "$";
	var contentIndex = url.indexOf('#') + 1;
	var contentMenuId = url.indexOf(';');
	var pointer = url.indexOf('$');
	if (contentIndex > 0) {
		page = url.substring(contentIndex,contentMenuId);
		var elementId = url.substring(contentMenuId+1,pointer);
	} else { var elementId = "m1"; }
	openContent(page, elementId);
}
function writeTitle(ajaxResponse){
	var contentBegin = ajaxResponse.indexOf('<title>') + 7;
	var contentEnd = ajaxResponse.indexOf('</title>',contentBegin);
	var content = ajaxResponse.substring(contentBegin,contentEnd);
	return content;
}
function writeContent(ajaxResponse){
	var contentBegin = ajaxResponse.indexOf('<texto>') + 7;
	var contentEnd = ajaxResponse.indexOf('</texto>',contentBegin);
	var content = ajaxResponse.substring(contentBegin,contentEnd);
	return content;
}
function writeConfGPRS(ajaxResponse){
	var contentBegin = ajaxResponse.indexOf('<div id="descricaoServico">');
	var contentEnd = ajaxResponse.indexOf('<div id="lateralDireita">',contentBegin) - 12;
	var content = ajaxResponse.substring(contentBegin,contentEnd);
	return content;
}
function carregarManual() {
    var endereco = window.location;
    modelo = String(endereco+".xml");
    var posicaoCaracter = modelo.indexOf("?");
    var arquivo = modelo.slice(posicaoCaracter+1);
    this.carregarConteudo("/website/manuais/"+arquivo);
}
function carregarConteudo(page) {
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", page, true);
	setHeaders(xmlhttp);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
    		if (xmlhttp.responseText.indexOf('Error report')==-1) {
		   		var content = writeContent(xmlhttp.responseText);
		   		document.getElementById("conteudo").innerHTML = content;
		}	}
   	 }
   	 xmlhttp.send(null);
}
function carregarTermo() {
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", "termoUso.xml", true);
	setHeaders(xmlhttp);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
	   		var content = writeContent(xmlhttp.responseText);
	   		document.getElementById("termoUso").innerHTML = content; }
   	 }
   	 xmlhttp.send(null);
}
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;	}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;	}
	} else if (obj.y)
		curtop += obj.y;
	return curtop;
}
function loadingImageAt(elementId) {
	var loadImage = '<center><img class="loading" src="/website/imagens/carregando.gif" /></center>';
	document.getElementById(elementId).innerHTML = loadImage;
}
function acertarMenuLateral() {
	var obj = document.getElementById("rodape");
	var tam = 0;
	tam = findPosY(obj);
	tam = tam - 242;
	document.getElementById("lateralEsquerda").style.height= tam;
}
function abrirManual(manual) {
	window.open("/website/manualgprs.html?"+manual, "manual" ,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600px, height=570px");
}
function cadastrar() {
	if (loggedin()) { alert("Não é possível efetuar um novo cadastro\nestando logado.");
	} else { window.open("cadastrar.html", "system" ,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600px, height=570px"); }
}
function entrarDadosUsuario() {
	window.location="/system/signup.html";
}
function editarPerfil() {
	window.open("/system/editProfile.html", "system" ,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600px, height=570px");
}
function verTermoUso() {
	window.open("/website/termouso.html", "system" ,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600px, height=570px");
}
function showSubMenu() {
	if (loggedin()) {
		document.getElementById("sm3").style.background= "#fae3d1";
		showMe("sm3"); }
}
function showSubFaqMenu() {
	document.getElementById("sm0").style.background= "#fae3d1";
	showMe("sm0");
	document.getElementById("sm1").style.background= "#fae3d1";
	showMe("sm1");
	document.getElementById("sm2").style.background= "#fae3d1";
	showMe("sm2");
	document.getElementById("sm4").style.background= "#fae3d1";
	showMe("sm4");
	document.getElementById("sm5").style.background= "#fae3d1";
	showMe("sm5");
	document.getElementById("sm6").style.background= "#fae3d1";
	showMe("sm6");
}
function hideSubFaqMenu() {
	document.getElementById("sm0").style.color= "gray";
	hideMe("sm0");
	document.getElementById("sm1").style.color= "gray";
	hideMe("sm1");
	document.getElementById("sm2").style.color= "gray";
	hideMe("sm2");
	document.getElementById("sm4").style.color= "gray";
	hideMe("sm4");
	document.getElementById("sm5").style.color= "gray";
	hideMe("sm5");
	document.getElementById("sm6").style.color= "gray";
	hideMe("sm6");
}
function subFaqMenuAcessado(elementId) {
	document.getElementById("sm0").style.color= "gray";
	document.getElementById("sm1").style.color= "gray";
	document.getElementById("sm2").style.color= "gray";
	document.getElementById("sm4").style.color= "gray";
	document.getElementById("sm5").style.color= "gray";
	document.getElementById("sm6").style.color= "gray";
	document.getElementById(elementId).style.color= "#701000";
	document.getElementById(elementId).style.background= "#fae3d1";
}
function subMenuAcessado(elementId) {
	document.getElementById(elementId).style.color= "#701000";
	document.getElementById(elementId).style.background= "#fae3d1";
}
function showMe(elementId) {
	document.getElementById(elementId).style.display= "block";
}
function hideMe(elementId) {
	document.getElementById(elementId).style.display= "none";
}
function altClass(elementId, classe) {
	document.getElementById(elementId).className= classe;
}
function passwordHint() {
	var linkVoltar = '<br /><p><a href="javascript:openContent(\'esqueci_senha\', \'m3\');">Voltar</a></p>';
	if (document.getElementById("j_password") == null) {
		alert("Você não pode requisitar sua dica de senha \nenquanto estiver logado!");
	} else {
	if ((document.getElementById("usernameHint").value.length == 0) || (document.getElementById("usernameHint").value == "usuário")) {
		alert("O campo 'Usuário' tem que estar completo para sua dica \nde senha ser enviada ao seu e-mail!");
		document.getElementById("usernameHint").focus();
	} else {
		var username = "";
		username = document.getElementById("usernameHint").value;
		loadingImageAt("hintArea");
		var redirectUrl = "/system/passwordHint.html?username=" + username;
		var messageText = "Sua senha foi enviada ao seu e-mail cadastrado.";
		var xmlhttp = getXmlHttp();
		xmlhttp.open("GET", redirectUrl, true);
		setHeaders(xmlhttp);
		xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState == 4) {
    		var messageBegin = xmlhttp.responseText.indexOf('<div id="content">') + 65;
			var messageEnd = xmlhttp.responseText.indexOf('<div id="loginTable">') - 80;
			messageText = xmlhttp.responseText.substring(messageBegin,messageEnd);
			var messageStatus = messageText.indexOf('successMessages');
			if (messageStatus == '-1') {
				document.getElementById("hintArea").innerHTML = "Não foi encontrado o usuário " + username + linkVoltar;
			} else {
				document.getElementById("hintArea").innerHTML = messageText + linkVoltar; }
    	} }
		xmlhttp.send(null);
	} }
}
function segurar() {
	document.getElementById("proximo").disabled=true;
}
function liberar() {
	document.getElementById("proximo").disabled=false;
}
function validate() {
	if (yes) { return true; } else { return false; }
}
function validateInvite() {
	var nome = document.getElementById("nome").value;
	var userEmail = document.getElementById("email").value;
	var emailAmigo = document.getElementById("emailAmigo1").value;
	if (emailAmigo == "") {
		emailAmigo = document.getElementById("emailAmigo2").value;
		if (emailAmigo == "") {
			emailAmigo = document.getElementById("emailAmigo3").value;
			if (emailAmigo == "") {
				emailAmigo = document.getElementById("emailAmigo4").value; }
	}	}
	if ((nome == "") && (userEmail == "") && (emailAmigo == "")) {
		alert("Por favor, entre com todos os dados.");
		return false;
	} else if ((nome == "") && (userEmail == "")) {
		alert("Por favor, entre com seu nome e e-mail.");
		return false;
	} else if (nome == "") {
		alert("Por favor, entre com seu nome.");
		return false;
	} else if (userEmail == "") {
		alert("Por favor, entre com seu e-mail.");
		return false;
	} else if (emailAmigo == "") {
		alert("Por favor, entre com pelo menos um e-mail de amigo.");
		return false;
	} else if (userEmail.indexOf("@") == -1) {
		alert("E-mail inválido!\nPor favor, entre com seu e-mail corretamente.");
		return false;
	} else if (emailAmigo.indexOf("@") == -1) {
		alert("E-mail amigo inválido!\nPor favor, entre com e-mail de seu amigo corretamente.");
		return false;
	} else {
		return true; }
}
function convidarAmigos() {
	var nome = document.getElementById("nome").value;
	nome = encodeURIComponent(nome);
	var email = document.getElementById("email").value;
	email = encodeURIComponent(email);
	var servico = document.getElementById("nomeServico").value;
	servico = encodeURIComponent(servico);
	var emailAmigo1 = document.getElementById("emailAmigo1").value;
	emailAmigo1 = encodeURIComponent(emailAmigo1);
	var emailAmigo2 = document.getElementById("emailAmigo2").value;
	emailAmigo2 = encodeURIComponent(emailAmigo2);
	var emailAmigo3 = document.getElementById("emailAmigo3").value;
	emailAmigo3 = encodeURIComponent(emailAmigo3);
	var emailAmigo4 = document.getElementById("emailAmigo4").value;
	emailAmigo4 = encodeURIComponent(emailAmigo4);
	var loadImage = '<img src="/website/imagens/carregando.gif" />';
	document.getElementById("loadImage").innerHTML = loadImage;
	var xmlhttp = getXmlHttp();
	xmlhttp.open("POST", "/system/convidar", true);
	setHeaders(xmlhttp);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	xmlhttp.send("nome="+nome+"&email="+email+"&emailAmigo1="+emailAmigo1+"&emailAmigo2="+emailAmigo2+"&emailAmigo3="+emailAmigo3+"&emailAmigo4="+emailAmigo4+"&nomeServico="+servico);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				alert("Mensagem enviada!");
				openContent(servico, 'm1');
			} else if (xmlhttp.status == 500) {
				alert("Problemas no envio da mensagem. Provavelmente endereço de e-mail está errado.");
				document.getElementById("loadImage").innerHTML = "";
			} else if (xmlhttp.status == 400) {
				alert("Problemas no envio da mensagem. Provavelmente alguma informação está errada.");
				document.getElementById("loadImage").innerHTML = "";
			} else {
				alert("Problemas no serviço. Tente novamente mais tarde.");
				document.getElementById("loadImage").innerHTML = ""; }
	}	}
}
function validateContact() {
	var nome = document.getElementById("nome").value;
	var userEmail = document.getElementById("email").value.indexOf("@");
	var assunto = document.getElementById("subject").value;
	var mensagem = document.getElementById("textareaContato").value;
	if (nome == "") {
		alert("Por favor, entre com seu nome.");
		return false;
	} else if (userEmail == -1) {
		alert("E-mail inválido!\nPor favor, entre com seu e-mail corretamente.");
		return false;
	} else if (assunto == "") {
		alert("Por favor, escreva um tópico para assunto.");
		return false;
	} else if (mensagem == "") {
		alert("Por favor, escreva sua mensagem ou comentário.");
		return false;
	} else {
		return true; }
}
function contactUs() {
	var nome = document.getElementById("nome").value;
	nome = encodeURIComponent(nome);
	var email = document.getElementById("email").value;
	email = encodeURIComponent(email);
	var subject = document.getElementById("subject").value;
	subject = encodeURIComponent(subject);
	var mensagem = document.getElementById("textareaContato").value;
	mensagem = encodeURIComponent(mensagem);
	document.getElementById("contactForm").style.display= "none";
	loadingImageAt("loadingSpace");
	acertarMenuLateral();
	var xmlhttp = getXmlHttp();
	xmlhttp.open("POST", "/system/contactar", true);
	setHeaders(xmlhttp);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	xmlhttp.send("nome="+nome+"&email="+email+"&subject="+subject+"&comentario="+mensagem);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				alert("Mensagem enviada!");
				openContent('contato', 'm1');
			} else if (xmlhttp.status == 500) {
				alert("Problemas no envio da mensagem. Provavelmente endereço de e-mail está errado.");
				document.getElementById("loadingSpace").innerHTML = "";
				document.getElementById("contactForm").style.display= "block";
				acertarMenuLateral();
			} else if (xmlhttp.status == 400) {
				alert("Problemas no envio da mensagem. Provavelmente alguma informação está errada.");
				document.getElementById("loadingSpace").innerHTML = "";
				document.getElementById("contactForm").style.display= "block";
				acertarMenuLateral();
			} else {
				alert("Problemas no serviço. Tente novamente mais tarde.");
				document.getElementById("loadingSpace").innerHTML = "";
				document.getElementById("contactForm").style.display= "block";
				acertarMenuLateral(); }			
	}	}
}
function bannerAction() {
	window.location="contato.html";
}
function downloadJarApp(appName) {
	if (loggedin()) {
		var username = document.getElementById('jmobi-username').innerHTML;
		var appUrl = "/jar-generator/jar/" + appName + "?jmobiuser=" + username;
		window.open(appUrl, "application" , "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=120px, height=20px");
	} else {
		alert("Você precisa estar logado para baixar nossas aplicações.\nSe você não tem uma conta JMobi, entre na \nseção \"Meu JMobi\" e se cadastre."); }
}
function downloadJadApp(appName) {
	if (loggedin()) {
		var username = document.getElementById('jmobi-username').innerHTML;
		var appUrl = "/jar-generator/jad/" + appName + "?jmobiuser=" + username;
		window.open(appUrl, "application" , "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=120px, height=20px");
	} else {
		alert("Você precisa estar logado para baixar nossas aplicações.\nSe você não tem uma conta JMobi, entre na \nseção \"Meu JMobi\" e se cadastre."); }
}
function underConstruction() {
	alert("O Portal JMobi está em construção. Disponibilizamos por enquanto,\napenas os serviços mKut, Fotolog Mobile, eMSN e mFut para testes.\nVolte em breve!");
}
function openJarJadHelp() {
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", "/website/sobre_jar-jad.xml", true);
	setHeaders(xmlhttp);
	xmlhttp.onreadystatechange=function() {
    	if (xmlhttp.readyState==4) {
	   		var content = writeContent(xmlhttp.responseText);
	   		document.getElementById("jar-jad").style.backgroundColor= '#e5e5e5';
	   		new fx.Height('jar-jad', {duration:500, onComplete: function(){
	   		document.getElementById("jar-jad").innerHTML = content;
	   		}}).custom(0,120);
	   	}
   	 }
   	 xmlhttp.send(null);
}
function closeJarJadHelp() {
	new fx.Height('jar-jad', {duration:500, onComplete: function(){
	document.getElementById("jar-jad").style.backgroundColor= 'transparent';
	}}).custom(120,0);
	document.getElementById("jar-jad").innerHTML = "";
}
function getDateFromRSS(date) {
	var newDate = date.substring(date.indexOf(', ')+2, date.indexOf('GMT')-1);
	return formatDate(new Date(getDateFromFormat(newDate,"d MMM y k:m:s")),"dd/MM/y");
}


