var isIE = (navigator.userAgent.toUpperCase().indexOf("MSIE") > 0 ? true : false);
/*
var intervaloVerMudancaLink = 0;
var bFrm;
var mnu_sel;
var mnu_dsel;
/////////////////////////////
//Funções para usar o AJAX

var arAx = Array("Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
var ajax = false;
var er = true;

try{
	ajax = new XMLHttpRequest();
}catch(e){
		for (var i = 0; i < arAx.length && er == true; i++){
			try{
				er = false;
				ajax = new ActiveXObject(arAx[i]);
			}catch(e){
				er = true;
			}
		}
}

if (ajax){
	if(window.document.location.href.indexOf('#sec:') < 0){
		if(window.document.location.href.indexOf('?sec=') >= 0){
			window.document.location.href = window.document.location.href.replace('?sec=', '#sec:');
		}
	}
}

function carregaAjax(url, metodo, obj_ret, url_sub){
	ajax.open(metodo, url,true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState == 4){
			if (ajax.status == 200){
				var texto = ajax.responseText;
				obj_ret.innerHTML = texto;
				if (typeof(mnu_sel) == 'object') mnu_sel.className = 'menu_sel';
				if (typeof(mnu_dsel) == 'object') mnu_dsel.className = '';
				var url_hash = url_sub.replace('?sec=','#sec:');
				window.document.location.href = url_hash;
				if (navigator.appName.indexOf('Netscape') < 0){
					bFrm.src = 'http://www.homecam.com.br/novo/ajax_frame.asp?loc=' + escape('#' + url_hash.split('#')[1]);
				}
				ultUrl = window.document.location.href;
				intervaloVerMudancaLink = setInterval('verMundancaLink()', 100);
				trocaLinksAjax_cont();
				criaEventosIe();
				window.document.getElementById('carregando').style.display = 'none';
			}else{
				alert("Houve um problema ao obter os dados:\n" + ajax.statusText);
				window.document.location.href = url_sub;
			}
		}
	}
	ajax.send(null);
}


var isIE = (window.document.all && navigator.appName.indexOf('Opera') == -1) ? true:false;

function trocaLinksAjax(){
	var lks = window.document.getElementById('menu').getElementsByTagName('a');
	for(var i = 0; i < lks.length; i++){
		lks[i].onclick = function(){
			carregaMenu(this);
			return false;
		}
	}
	
	window.document.getElementById('index').getElementsByTagName('a')[0].onclick = function(){
		carregaMenu(this);
		return false;
	}
}

function trocaLinksAjax_cont(){
	lks = window.document.getElementById('conteudo').getElementsByTagName('a');
	var lh = window.document.location.href;
	lh = lh.split('?')[0];
	lh = lh.split('#')[0];
	
	for(i = 0;i < lks.length; i++){
		if ((lks[i].href.substr(0,lh.length) == lh) && (lks[i].href.indexOf('?sec=') >= 0)){
			lks[i].onclick = function(){
				carregaMenu(this);
				return false;
			}
		}
	}
	
}

function carregaMenu(lk){
	var cont = window. winment.getElementById('conteudo');
	//cont.innerHTML = "<div style='height:" + (screen.height - 100) + "px'></div>";
	
	window.document.getElementById('carregando').style.display = 'block';
	
	Topo();
	
	var lks = window.document.getElementById('menu').getElementsByTagName('a');
	var secLk = lk.href.split('?sec=')[1];
	secLk = secLk.split('&')[0];
	secLk = secLk.split('#')[0];
	
	var secA = '';
	for(var i = 0; i < lks.length; i++){
		secA = lks[i].href.split('?sec=')[1];
		secA = secA.split('&')[0];
		secA = secA.split('#')[0];
		
		if ((secA != secLk) && (lks[i].className == 'menu_sel')) mnu_dsel = lks[i];
		else if(secA == secLk) mnu_sel = lks[i]; // = 'menu_sel';
		//if (lks[i].href != lk.href) lks[i].className = '';
	}
	if (navigator.appName.indexOf('Netscape') >= 0){
		window.document.getElementById('pgtopo').focus();
		//if (cont.getElementsByTagName('a')[0]) cont.getElementsByTagName('a')[0].focus;
		//else window.document.getElementsByTagName('a')[0].focus();
	}
	carregaAjax(lk.href + '&a=s', 'GET', cont, lk.href);
}
*/

//Função para criar um abbr válido para IE
//fonte: http://www.sovavsiti.cz/css/abbr.html
function styleAbbr() {
	var oldBodyText, newBodyText, reg
	if (isIE) {
		oldBodyText = document.body.innerHTML;
		reg = /<ABBR([^>]*)>([^<]*)<\/ABBR>/g;
		newBodyText = oldBodyText.replace(reg, '<ABBR $1><SPAN class=\"abbr\" $1>$2</SPAN></ABBR>');
		document.body.innerHTML = newBodyText;
	}
}

function scrollPos(){
	if (window.scrollY){
		var Y = window.scrollY;
		var X = window.scrollX;
	}else if(document.documentElement.scrollTop){
		var Y = document.documentElement.scrollTop;
		var X = document.documentElement.scrollLeft;
	}else{
		var Y = document.body.scrollTop;
		var X = document.body.scrollLeft;
	}
	return {left:X, top:Y}
}

var i = 5;
function Topo(){
	var sp = scrollPos();
	var Y = sp.top, X = sp.left;
	
	Y = Y - 50;
	if (i < 50){
		i = i + 5;
	}
	if (Y >= 0){
		window.scrollTo(X, Y);
		setTimeout("Topo()", (i == 50? 1 : 10));
	}else{
		window.scrollTo(X, 0);
		i = 5;
	}
	return false;
}

function vaiConteudo(){
	var cont = window.document.getElementById("conteudo");
	window.scrollTo(cont.offsetLeft, cont.offsetTop);
	return false;
}

function Favoritos(){
//Baseado no link: http://www.roccofroes.com/materia_descricao.asp?materia_codigo=189
	var url      = window.document.location.href;
	var title    = window.document.title;
	var msg = "Seu browser não permite este mecanismo automático!\nPor favor, pressione Ctrl+D para adicionar a página aos favoritos, ou faça o processo manualmente!" ;
	try{
		if (window.sidebar){ //Firefox e Netscape
			window.sidebar.addPanel(title, url,"");
		}else if(window.opera && window.print){ //Opera
				var mbm = document.createElement('a');
				mbm.setAttribute('rel','sidebar');
				mbm.setAttribute('href',url);
				mbm.setAttribute('title',title);
				mbm.click();
		}else if(document.all){ //Internet Explorer
			window.external.AddFavorite(url, title);
		}else{ //Segurança nunca é demais...^^ (no Safari - testei para Windows - não funfa, ainda não descobri como adicionar nele)
			alert(msg);
		}
	}catch(e){
		alert(msg);
	}
}

function Imprimir(){
	Janela('imprimir.asp', 600, 800);
	return false;
}

function Mapa(){
	Janela('inc/mapa.asp', 600, 800);
	return false;
}

function Torpedo(){
	if (isIE){
		Janela('inc/torpedo.asp', 216, 260);
	}else{
		Janela('inc/torpedo.asp', 200, 240);
	}
	return false;
}

function Janela(url,iHeight,iWidth)
{
	iTop = (screen.height - iHeight) / 2;
	iLeft = (screen.width - iWidth) / 2;
	popupWin = window.open(url,'NPag'+iHeight+''+iWidth,'toolbar=no,location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, left=' + iLeft + ', top=' + iTop + ', height=' + iHeight + ',width=' + iWidth + '');
	if (!popupWin.opener) popupWin.opener = self;
	popupWin.focus();
}

function Pg2Mail(){
	if(mail = prompt("Informe o e-mail de seu amigo!", "")){
		window.document.location = "mailto:" + mail + "?Subject=Link%20Interessante&Body=Vistei%20esta%20pagina%20da%20HomeCAM%20e%20achei%20interessante:%20%20" + window.document.location;
	}
}

function CriaOpcoesJS(){
	var lblOp = window.document.getElementById('lbl_opcoes');
	lblOp.style.cursor = 'pointer';
	
	var pos = document.createElement("span");
	
	if (document.cookie.indexOf('opcao=me') >= 0){
		pos.appendChild(document.createTextNode("+ "));
		var disp_opcoes = 'none';
	}else{
		pos.appendChild(document.createTextNode("- "));
		var disp_opcoes = 'block';
	}
	lblOp.insertBefore(pos, lblOp.firstChild);
	
	lblOp.onclick = function(){
		if (document.getElementById("cont_opcoes").style.display == "none"){
			//if (this.firstChild.firstChild.nodeValue.indexOf("+") == 0){
			this.firstChild.firstChild.nodeValue = "- ";
			document.getElementById("cont_opcoes").style.display = "block";
			document.cookie = "opcao=";
		}else{
			this.firstChild.firstChild.nodeValue = "+ ";
			document.getElementById("cont_opcoes").style.display = "none";
			document.cookie = "opcao=me";
		}
	}
	var topo = document.getElementById("ir_topo");
	topo.parentNode.removeChild(topo);
	var opcoes = document.createElement("opcoes");
	opcoes.setAttribute("id", "cont_opcoes");
	opcoes.style.display = disp_opcoes;
	
	var imp = document.createElement("a");
	imp.setAttribute("href", "#imprimir");
	imp.setAttribute("title", "Imprimir o conteúdo da página atual");
	var img = document.createElement("img");
	img.setAttribute("src", "imgs/imprimir.jpg");
	img.setAttribute("alt", "Imprimir");
	imp.onclick = function(){ Imprimir(); return false; }
	imp.appendChild(img);
	//document.getElementById("opcoes").appendChild(imp);
	
	var fav = document.createElement("a");
	fav.setAttribute("href", "#adicionar_aos_favoritos");
	fav.setAttribute("title", "Adicionar página atual aos favoritos");
	img = document.createElement("img");
	img.setAttribute("src", "imgs/favoritos.jpg");
	img.setAttribute("alt", "Favoritos");
	fav.onclick = function(){ Favoritos(); return false; }
	fav.appendChild(img);
	//document.getElementById("opcoes").appendChild(fav);
	opcoes.appendChild(topo);
	opcoes.appendChild(imp);
	opcoes.appendChild(fav);
	document.getElementById("opcoes").appendChild(opcoes);
}

function AcertaOpcoes(){
	if (window.document.all && navigator.appName.indexOf('Opera') == -1 && navigator.userAgent.indexOf("MSIE 7") < 0){
		try{
			var div_op = window.document.getElementById("opcoes");
			div_op.style.position = 'absolute';
			div_op.style.top = document.documentElement.clientHeight + document.documentElement.scrollTop - (div_op.offsetHeight - 1);
			MoveOpcoes();
		}catch(e){
			alert("Erro: " + e.name + "\n" + e.message);
		}
	}
}

function getOffsetHeight(obj){
	if (!obj.offsetParent) return obj.offsetHeight;
	else return (obj.offsetHeight + getOffsetHeight(obj.offsetParent));
}

function MoveOpcoes(){
	try{
		var op = window.document.getElementById("opcoes");
		var T = (document.documentElement.clientHeight + scrollPos().top - (op.offsetHeight));
		var O = parseInt(op.style.top.replace('px', ''));
		
		if ((O - T) > -5 && (O - T) < 5){
			if (op.style.top != T) op.style.top = T + 'px';
		}else if (O > T){
			op.style.top = (O - 5) + 'px';
		}else if(O < T){
			op.style.top = (O + 5) + 'px';
		}
		setTimeout('MoveOpcoes()', 1);
	}catch(e){
		alert("Erro ao mover opções: " + e.name + "\n" + e.message);
	}
}

/*function overTables(){
	var tbls = document.getElementsByTagName('table');
	var trs = Array();
	var i, j;
	for(i = 0; i < tbls.length; i++){
		trs = tbls[i].getElementsByTagName('tr');
		for(j = 0; j < trs.length; j++){
			trs[j].onmouseover = function(){
				this.className += " over ";
			}
			trs[j].onmouseout = function(){
				this.className = this.className.replace(" over ", "");
			}
		}
	}
}*/

function cliqueLegend(){
	var legs = document.getElementsByTagName('fieldset'), i;
	for (i = 0; i < legs.length; i++){
		if (legs[i].getElementsByTagName('legend')[0]){
			legs[i].getElementsByTagName('legend')[0].onclick = function(){
				if (this.parentNode.tagName.toLowerCase() != "fieldset") return false; // Se o parente não for um fieldset, cai fora
				var elementos = this.parentNode.getElementsByTagName('*'); // Pega todos elementos filhos do fieldset parente
				// São pegos todos os elementos, pois nem sempre um input é o primeiro, e nem sempre este input não é oculto
				var i = 0; // Conta as iterações
				var form_elementos = /^(select|input|textarea)$/ig; // Expressão regular para elementos válidos para foco
				
				for (i = 0; i < elementos.length; i++)
					// Testa a expressão regular e verifica se não é um campo escondido
					if ((form_elementos.test(elementos[i].tagName.toString())) && (elementos[i].type.toLowerCase() != "hidden")) {
						// Dá o foco ao elemento e sai do loop
						elementos[i].focus();
						break;
					}
			}
		}
	}
}

function $(id){
	return document.getElementById(id);
}

function defineEventos(){
	if ($('vai_conteudo')){
		$('vai_conteudo').onclick = function(){
			return vaiConteudo();
		}
	}
	
	if ($('ir_topo')){
		$('ir_topo').onclick = function(){
			return Topo();
		}
	}
	
	var menus = $('menu').getElementsByTagName('a');
	for (var i = 0; i < menus.length; i++)
		menus[i].onclick = function(){
			var menus = $('menu').getElementsByTagName('a');
			for (var i = 0; i < menus.length; i++)
				if (menus[i] != this)
					menus[i].className = "";
				else
					menus[i].className = "menu_sel";
			
			window.scrollTo(0, 0);
			return true;
		}
	
	var links = document.getElementsByTagName('*');
	window.status = "  HomeCAM Tecnologia & Informática";
	for(i = 0; i < links.length; i++){
		if (links[i].title){
			links[i].onmouseover = function(){
				window.status = "  " + this.title;
				return true;
			}
			links[i].onmouseout = function(){
				window.status = "  HomeCAM Tecnologia & Informática";
				return true;
			}
		}
	}
}

function NPag(tag_a){
	window.open(tag_a.href);
	return false;
}

window.onload = function(){
	//styleAbbr();
	defineEventos();
	AcertaOpcoes();
	//if (isIE) overTables();
	cliqueLegend();
	CriaOpcoesJS();
	/*
	trocaLinksAjax_cont();
	
	if (ajax){
		var tb = window.document.getElementsByTagName('body')[0];
		var car = window.document.createElement('div');
		
		car.setAttribute('id', 'carregando');
		car.setAttribute('style', 'display:none');
		car.innerHTML = 'CARREGANDO...';
		tb.appendChild(car);
		
		if (navigator.appName.indexOf('Netscape') < 0){
			bFrm = window.document.createElement('iframe');
			bFrm.setAttribute('height', '0');
			bFrm.setAttribute('width', '0');
			bFrm.setAttribute('style', 'display:none');
			bFrm.setAttribute('src', 'http://www.homecam.com.br/novo/ajax_frame.asp?loc=' + escape(a_hash()));
			tb.appendChild(bFrm);
		}
		
		PegaLink(window.document.location.href);
		trocaLinksAjax();
		intervaloVerMudancaLink = setInterval('verMundancaLink()', 100);
	}
	*/
	
	/*
	if (navigator.appName.indexOf('Netscape') >= 0){
		var st = window.document.getElementsByTagName('style')[0];
		st.innerHTML = st.innerHTML + '\n*::-moz-selection{	background-color:#446FBD;color:#FFFFFF;}html{overflow: -moz-scrollbars-vertical;}';
	}
	*/
	
	/*
	carregaImagens('imgs/carregando.gif');
	*/
}

function criaEventosIe(){
if (isIE){
	var inp = window.document.getElementsByTagName('input');
	var i;
	for(i = 0; i < inp.length; i++){
		if (inp[i].className == 'botao'){
			inp[i].onmouseover = function(){
				this.className = 'botao_hover';
			}
			inp[i].onmouseout = function(){
				this.className = 'botao';
			}
		}
	}
}
}

//Preload imagens
function carregaImagens(){
	if(window.document.images){
		var imgs = carregaImagens.arguments;
		if(!window.document.imagens) window.document.imagens=new Array();
			var j=window.document.imagens.length;
			for(i=0;i<imgs.length;i++){
				window.document.imagens[j]=new Image;
				window.document.imagens[j++].src = imgs[i];
			}
	}
}

function PegaLink(aUrl){
	if (aUrl.indexOf('#sec:') != -1){
		var sec = aUrl.substr(aUrl.indexOf('#sec:') + 5);
		var lks = window.document.getElementById('menu').getElementsByTagName('a');
		var achou = false;
		
		for(var i=0;i<lks.length && achou == false;i++){
			if (lks[i].href.indexOf('?sec=' + sec) != -1){
				carregaMenu(lks[i]);
				achou = true;
			}
		}
	}
}

var ultUrl = window.document.location.href;

function verMundancaLink(){
	if (window.document.location.href != ultUrl){
		clearInterval(intervaloVerMudancaLink);
		ultUrl = window.document.location.href;
		PegaLink(window.document.location.href);
	}
}

function a_hash(){
	var lh = window.document.location.href;
	if (lh.indexOf('#') >= 0){
		return '#' + lh.split('#')[1];
	}else{
		return '#sec:home';
	}
}