var req;
var idsel;
var timeID;
var div_photo;
var imgDivPhoto = '';
var parametro = '';

var strEnts = 'AElig Aacute Acirc Agrave Aring Atilde Auml Ccedil ETH Eacute Ecirc Egrave Euml Iacute Icirc Igrave Iuml Ntilde Oacute Ocirc Ograve Oslash Otilde Ouml Uacute Ucirc Ugrave Uuml Yacute aacute acirc aelig agrave aring atilde auml ccedil eacute ecirc egrave eth euml iacute icirc igrave iuml ntilde oacute ocirc ograve oslash otilde ouml szlig thorn uacute ucirc ugrave uuml yacute yuml copy para pound reg sup1 sup2 sup3';
var strChars = 'Æ Á Â À Å Ã Ä Ç Ð É Ê È Ë Í Î Ì Ï Ñ Ó Ô Ò Ø Õ Ö Ú Û Ù Ü Ý á â æ à å ã ä ç é ê è ð ë í î ì ï ñ ó ô ò ø õ ö ß þ ú û ù ü ý ÿ © ¶ £ ® ¹ ² ³';
var arrEnts = strEnts.split(" ");
var arrChars = strChars.split(" ");

function getHTTPObject() {
  var xmlhttp;
	
   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) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function loadDoc(url,p){
	if(p){
		parametro=p;
	}
	div_photo.style.display = 'none';
	idsel = 'conteudo';
	req = new getHTTPObject();
	req.onreadystatechange = processReqChange;
	req.open("GET", url, true);
	req.send(null);	
}


function processReqChange(){
    if (req.readyState == 1) {
			//timeID = window.setTimeout("pageTimeOut()",10000);
			document.getElementById(idsel).innerHTML = "<div id='carregando_pagina"+timeID+"' style='background-color:#4F7EBE; color:#FFFFFF; width: 70px; padding: 3px 5px;'>Carregando...</div>";
		}

    // only if req shows "complete"
    if (req.readyState == 4) {
				//window.clearTimeout(timeID);
        if (req.status == 200) {
						montaPagina(req.responseText);
						if(idsel=='conteudo'){ 
							if(window.pageYOffset>230){
								try{scroll(0,195);}
								catch(e){}
							}
						}
        } else {
						document.getElementById(idsel).innerHTML = "<span class='erro_carregamento'>Erro ao carregar o conte&uacute;do!</span>";
        }
    }
}

function pageTimeOut(){
	if (document.getElementById('carregando_pagina'+timeID)){
		document.getElementById(idsel).innerHTML = "<span class='erro_carregamento'>Esgotado o tempo para carregar a pagina!</span>";
		window.clearTimeout(timeID);
	}
}

function montaPagina(aJSONtext){
	var myObject = JSON.parse(aJSONtext);
	var rs = myObject.pagina;
	var conteudo = document.getElementById(idsel);
	var html='';
	
	if(rs.Titulo)
		document.title = uncodeEC(rs.Titulo);

	if(rs.Html)
		html = rs.Html;
	
	if(rs.bloco){
		for(k=0;k<rs.bloco.length;k++){
			html += header(rs.bloco[k].Titulo);
			
			if(rs.bloco[k].Html)
				html += "<div class=\"txt_intro\">" + rs.bloco[k].Html + "</div>";
			
			if(rs.bloco[k].subbloco){
				for(w=0;w<rs.bloco[k].subbloco.length;w++){
					var subbloco = rs.bloco[k].subbloco;
					var titulo = '';
					if (subbloco[w].Titulo){titulo = "<span>" + subbloco[w].Titulo + "</span>" }
					html += "<div class=\"cont_bloco\">" + titulo + "<div>"
					if (subbloco[w].Html){html += "<table><tr><td>" + subbloco[w].Html + "</td></tr></table>"}
					html += "</div></div>";
				}
			}
		}
	}
	
	conteudo.innerHTML = html;
	if(rs.Script)
		eval(rs.Script);

	urchinTracker(document.title);
}

function header(t){

	h = "		<table class=\"titulo\">"
	h+= "				<tr>"
	h+= "					<td class=\"seta_tit\"><img src=\"imagens/titulo/seta_titulo.gif\" alt=\"\" /></td>"
	h+= "					<td>" + t + "</td>"
	h+= "				</tr>"
	h+= "				<tr>"
	h+= "					<td colspan=\"2\" class=\"back_titulo\"><img src=\"imagens/titulo/spacer.gif\" alt=\"\" /></td>"
	h+= "				</tr>"
	h+= "			</table>"
	return h;
}

function procura(){
	if (document.f.inputtext.value!=''){
		loadDoc('procura.asp?search=' + document.f.inputtext.value);
	}
}

function showBloco(id){
	div_photo.style.display = 'none';
	var d = document.getElementById(id);
	if (d.className=='desc_item_on'){
		d.className = 'desc_item';
	}
	else{
		d.className = 'desc_item_on';
		if (d.innerHTML=='' || d.innerHTML.match("erro_carregamento>") || d.innerHTML.match("carregando_pagina")){
			loadBloco(id);
		}
	}
}

function loadBloco(id){
	idsel = id;
	var f = id + '.json';
	if(id.indexOf('.')!=-1) f=id;
	req = new getHTTPObject();
	req.onreadystatechange = processReqChange;
  req.open("GET", f, true);
  req.send(null);
}

//Aumenta ou diminui o tamanho das fontes no conteudo da pagina
function fontmaior(){
	document.getElementById('conteudo').style.fontSize="120%"
}
function fontmenor(){
	document.getElementById('conteudo').style.fontSize="100%"
}

//Alterna as imagens (+) da area de destaque para onmouseover e onmouseout
function changeimg(elemento,acao) {
	var elementoid = document.getElementById(elemento);
	if (acao=='on') 
	elementoid.innerHTML='<img src="imagens/destaque/mais_destaque_on.gif" width="19" height="81" alt="" />';
	if (acao=='off') 
	elementoid.innerHTML='<img src="imagens/destaque/mais_destaque_off.gif" width="19" height="81" alt="" />';
}

//Alterna cor de linhas de uma tabela
function alternate(id){
	if(document.getElementsByTagName){  
		if(document.getElementById(id)){
			var table = document.getElementById(id);  
			var rows = table.getElementsByTagName("tr");  
			for(i = 0; i < rows.length; i++){          
				if(i % 2 == 0){
					rows[i].className = "even";
				}else{
					rows[i].className = "odd";
				}      
			}
		}
	}
}

var jsEmailErrado = "O endereço de email informado aparenta estar errado (verifique se possui o '@' e os '.')";
var jsEmailUsuarioInvalido = "Caracteres inválidos no nome do usuário.";
var jsEmailDominioInvalido = "Caracteres inválidos no nome do domínio.";
var jsEmailAparentaInvalido = "O nome do usuário não aparenta ser valido.";
var jsEmailIPInvalido = "IP de destino inválido!";

function emailCheck (emailStr) {
var checkTLD=1;
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert(jsEmailErrado);
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert(jsEmailUsuarioInvalido);
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert(jsEmailDominioInvalido);
return false;
   }
}
if (user.match(userPat)==null) {
alert(jsEmailAparentaInvalido);
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert(jsEmailIPInvalido);
return false;
   }
}
return true;
}
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("O nome do dominio não aparenta ser válido.");
return false;
   }
}
if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("O endereço deve finalizar em um dominio conhecido ou duas letras '+' país.");
return false;
}
if (len<2) {
alert("O endereço não tem o hostname!");
return false;
}
return true;
}


//Exibe ou nao o campo do formulario dependente de outro campo (form contato > assunto)
function displayOutro(t){
	if (t.value=='Outros'){
		if(document.all)
			document.getElementById('espec_outros').style.display = 'block';
		else
			document.getElementById('espec_outros').style.display = 'table-row';
		document.contato.outro.focus();
	}
	else{
		document.getElementById('espec_outros').style.display = 'none';
		document.contato.outro.value = '';
	}
}

//Exibe ou esconde o popup de imagens maiores
function photostyle(param,imagem,origem){
	if (param=='') {
		if (imgDivPhoto == imagem && div_photo.style.display == 'block') { 
			div_photo.style.display = 'none';
		}
		else {
			var obj = document.getElementById(origem);
			setPos(obj,div_photo);
			div_photo.innerHTML = "<p onmousedown=\"dragStart(event, 'photo')\"><a href=\"javascript:photostyle('fechar','','');\">fechar</a></p><div><img onmousedown=\"dragStart(event, 'photo')\" width='300' height='225' src='imagens/" +imagem+ "' alt='' /></div>"
			div_photo.style.display = 'block';
		}
		imgDivPhoto = imagem;
	} else {
		div_photo.style.display = 'none';
	}
}

function setPos(obj,lyr)
{
	var newX = findPosX(obj);
	var newY = findPosY(obj);
	var x = lyr;
	x.style.top = newY + 'px';
	x.style.left = newX + 'px';
}
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;
}

// Determine browser and version.

function Browser() {
  var ua, s, i;
  this.isIE    = false;
  this.isNS    = false;
  this.version = null;
  ua = navigator.userAgent;
  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
  // Treat any other "Gecko" browser as NS 6.1.
  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();
// Global object to hold drag information.
var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {
  var el;
  var x, y;
  // If an element id was given, find it. Otherwise use the element being
  // clicked on.
  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;
    // If this is a text node, use its parent element.
    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }
  // Get cursor position with respect to the page.
  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  // Save starting positions of cursor and element.
  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);
  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;
  // Update element's z-index.
  dragObj.elNode.style.zIndex = ++dragObj.zIndex;
  // Capture mousemove and mouseup events on the page.
  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {
  var x, y;
  // Get cursor position with respect to the page.
  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  // Move drag element by the same amount the cursor has moved.
  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {
  // Stop capturing mousemove and mouseup events.
  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

var jsFormNome =     'Preencha o seu nome';
var jsFormUF =       'Selecione o seu estado';
var jsFormAssunto =  'Informe o assunto';
var jsFormOutro =    'Especifique o assunto';
var jsFormMensagem = 'Digite a sua mensagem';
var jsFormEnviando = 'Enviando';
var jsFormDDD = 'Entre com o DDD do seu telefone';
var jsFormTEL = 'Entre com o seu telefone';

var jsFormBase = 'Entre com sua base';
var jsFormMatricula = 'Entre com sua matricula';
var jsFormCPF = 'Entre com seu CPF';

function marcaObrigatorio(t){
	if(t.value==3){
		document.getElementById("trBase").style.display="none";
		document.getElementById("trMatricula").style.display="none";
		document.getElementById("trCPF").style.display="none";
	} else {
		var display="table-row";
		if(document.all)
			display= "inline";
		document.getElementById("trBase").style.display=display;
		document.getElementById("trMatricula").style.display=display;
		document.getElementById("trCPF").style.display=display;
	}
}

var telObrigatorio = 0;
function enviarForm(){
	var checkExtraFields = false;
	var f = document.contato;
	
		if(f.classe){
			if(f.classe.value==1){
				checkExtraFields = true;
			}
		}
		if(f.nome.value==''){
			alert(jsFormNome);
			f.nome.focus();
			return false;
		}
		
		if (!emailCheck (f.email.value)){
			f.email.focus();
			return false;
		}
		
		if(f.base && checkExtraFields){
		if(f.base.value==''){
			alert(jsFormBase);
			f.base.focus();
			return false;
		}
		}
		if(f.matricula && checkExtraFields){
		if(f.matricula.value==''){
			alert(jsFormMatricula);
			f.matricula.focus();
			return false;
		}
		}
		if(f.cpf && checkExtraFields){
		if(f.cpf.value==''){
			alert(jsFormCPF);
			f.cpf.focus();
			return false;
		}
		}
		
		if(f.uf.selectedIndex==0){
			alert(jsFormUF);
			f.uf.focus();
			return false;
		}
		
		if(telObrigatorio){
			if(f.ddd.value==''){
				alert(jsFormDDD);
				f.ddd.focus();
				return false;
			}
			if(f.telefone.value==''){
				alert(jsFormTEL);
				f.telefone.focus();
				return false;
			}
		}

		if (document.getElementById('blocoAssunto').style.display!='none'){
			if(f.assunto.selectedIndex==0){
				alert(jsFormAssunto);
				f.assunto.focus();
				return false;
			}
			
			if(f.assunto.value=='Outros' && f.outro.value==''){
				alert(jsFormOutro);
				f.outro.focus();
				return false;
			}
		}

		if(f.mensagem.value==''){
			alert(jsFormMensagem);
			f.mensagem.focus();
			return false;
		}
		document.getElementById('btnform').disabled=true;
		document.getElementById('btnform').value=jsFormEnviando + '...';
		f.submit();
}

function enviarIncricao(){
	var f = document.inscricao;
	var c, h1,h2;
	
		if(f.nome.value==''){
			alert('Preencha o seu nome');
			f.nome.focus();
			return false;
		}
		

		if (!emailCheck (f.email_part.value)){
			f.email.focus();
			return false;
		}
		
		if(f.com.value=='' && f.res.value=='' && f.cel.value==''){
			alert('Informe pelo menos um telefone de contato');
			f.res.focus();
			return false;
		}

		c=0;
		for(var k=0;k<f.local_curso.length;k++){
			if(f.local_curso[k].checked ) c=1;
		}
		if(!c){
			alert('Escolha o local para realização do curso');
			f.local_curso[0].focus();
			return false;
		}
		
		c=0;
		for(var k=0;k<f.horario_curso.length;k++){
			if(f.horario_curso[k].checked ){
				c=1;
				h1=k;
			}
		}
		if(!c){
			alert('Escolha a 1ª opção de horário');
			f.horario_curso[0].focus();
			return false;
		}
		
		
		c=0;
		for(var k=0;k<f.horario_curso_2.length;k++){
			if(f.horario_curso_2[k].checked ){
				c=1;
				h2=k;
			}
		}
		if(!c){
			alert('Escolha a 2ª opção de horário');
			f.horario_curso_2[0].focus();
			return false;
		}
		
		if(h1==h2){
			alert('A 1ª opção e a 2ª opção de horario não podem ser iquais');
			f.horario_curso_2[0].focus();
			return false;
		}		
		
		c=0;
		for(var k=0;k<f.opcao.length;k++){
			if(f.opcao[k].checked ) c=1;
		}
		if(!c){
			alert('Indique de que modo você ficou sabendo do curso');
			f.opcao[0].focus();
			return false;
		}
		
		/*
		
		if(f.uf.selectedIndex==0){
			alert('Selecione o seu estado');
			f.uf.focus();
			return false;
		}

		*/
		
		//document.getElementById('btnform').disabled=true;
		//document.getElementById('btnform').value='Enviando...';
		f.submit();
}

function ajustaInscricao(){
	if(parametro == 1){
		document.getElementById('uniforme').style.display = 'none';
	}
	//alternate('tbl_incricao');
	/* depois de usar reseta o parametro, para não interferir em outros pontos*/
	parametro='';
}

function ajustaForm(){
	if(parametro == 1){
		document.getElementById('blocoAssunto').style.display = 'none';
		document.contato.assuntoFixo.value = 'Piloto de jato';
	}
	/* depois de usar reseta o parametro, para não interferir em outros pontos*/
	parametro='';
}


function uncodeEC(s){
	for (var counter = 0; counter < arrEnts.length; counter++) {
			var strToFind = "&" + arrEnts[counter] + ';';
			var strReplacement = arrChars[counter];
			eval ("var reToFind = /" + strToFind + "/g");
			s = s.replace(reToFind, strReplacement);
	}
	return s;
}

function validarIncricaoex(){
	var f = document.inscricaoex;
	if(f.matricula.value==''){
		alert('Preencha o sua matricula');
		f.matricula.focus();
		return false;
	}
	if(f.nascimento.value==''){
		alert('Preencha o sua data de nascimento');
		f.nascimento.focus();
		return false;
	}
	f.validar.value='Validando...';
	contatoServer.location="validaInscricaoex.asp?m=" + f.matricula.value + "&d=" +f.nascimento.value;
	
}

function enviarCV(){
	var f = document.cvporemail;
	if(f.nome.value==''){
		alert('Preencha o seu nome');
		f.nome.focus();
		return false;
	}
	if (!emailCheck (f.email.value)){
		f.email.focus();
		return false;
	}
	if(f.cpf.value==''){
		alert('Preencha o seu CPF');
		f.cpf.focus();
		return false;
	}
	if(f.anexo.value==''){
		alert('Entre com seu curriculo');
		f.anexo.focus();
		return false;
	}
	//f.btnform.disabled = true;
	f.btnform.value='Enviando...';
	f.submit();
}

function enviarIncricaoex(){
	var f = document.inscricaoex;
	if(f.nome.value==''){
		alert('Preencha o seu nome');
		f.nome.focus();
		return false;
	}

	if (!emailCheck (f.email_part.value)){
		f.email_part.focus();
		return false;
	}
	
	if(f.base.value==''){
		alert('Preencha o sua base');
		f.base.focus();
		return false;
	}

	if(f.situacao.selectedIndex==0){
		alert('Selecione sua situação');
		f.situacao.focus();
		return false;
	}

	if(f.res.value=='' && f.cel.value==''){
		alert('Informe pelo menos um telefone de contato');
		f.res.focus();
		return false;
	}

	if(f.endereco.value==''){
		alert('Preencha o seu endereço');
		f.endereco.focus();
		return false;
	}

	if(f.cidade.value==''){
		alert('Preencha a cidade do seu endereço');
		f.cidade.focus();
		return false;
	}

	if(f.uf.selectedIndex==0){
		alert('Selecione o estado do seu endereço');
		f.uf.focus();
		return false;
	}

	if(f.cep.value==''){
		alert('Preencha o CEP do seu endereço');
		f.cep.focus();
		return false;
	}

	if(f.senha1.value!='' && (f.senha1.value!=f.senha2.value)){
		alert('Senhas não conferem');
		f.senha1.focus();
		return false;
	}
	if(f.senha1.value!='' && (f.senha1.value.length<6)){
		alert('Senhas tem que ter pelo menos 6 caracteres');
		f.senha1.focus();
		return false;
	}
	 

	f.matricula.disabled = false;
	f.nascimento.disabled = false;
	f.enviar.disabled = true;
	f.enviar.value='Enviando...';
	f.submit();
}

