var strAlertPopup, localeFacebook, localeGoogle;
if (document.location.pathname.match(/Ingles/i)) {
	strAlertPopup = "Please enable the display of pop-up in your browser to continue.";
	localeFacebook = "en_US";
	localeGoogle = "en-US"; //padrão: ''
} else if (document.location.pathname.match(/Espanhol/i)) {
	strAlertPopup = "Por favor, activa la pantalla de pop-up en su navegador para continuar.";
	localeFacebook = "es_ES";
	localeGoogle = "es-ES"; //es
} else {
	strAlertPopup = "Por favor habilite a exibição de pop-up no seu navegador para continuar.";
	localeFacebook = "pt_BR";
	localeGoogle = "pt-BR";
}

function getLinkRelativo() {
	var i;
	var link = document.location.pathname.replace(/^\/Site[0-9]{1,4}[a-zA-Z]*/i, "");
	var qtde = link.split("/");
	var str = "";
	for (i=1; i<qtde.length-1; ++i) {
		str += "../";
	}
	if (!str)
		str = "./";
	return str;
}

function getLinkPath() {
	var i, path;
	i = document.location.pathname.lastIndexOf("/");
	path = document.location.pathname.substr(0, i+1);
	return path;
}
// location.host => nome servidor + porta
// location.hostname => nome servidor
function isIntranet() {
	if (document.location.hostname.match(/192\.168\.0\.[0-9]{1,3}/) || document.location.hostname == "127.0.0.1" || document.location.hostname == "localhost") {
		return true;
	} else {
		return false;
	}
}
function isOnline() {
	if (isIntranet() || document.location.hostname == "intranet.icos.com.br" || document.location.hostname == "icos.no-ip.org" || document.location.hostname == "icos.servehttp.com" || document.location.hostname.match(/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/)) {
		return false;
	} else {
		return true;
	}
}
function getHostInicial() {
	var host = (document.location.pathname.search(/^\/Site[0-9]{1,4}[a-zA-Z]*\//i) != -1)?document.location.pathname.match(/^\/Site[0-9]{1,4}[a-zA-Z]*\//i)[0]:"/";
	return host;
}

function getHostHTTP() {
	var host = document.location.protocol + "//" + document.location.host;
	return host;
}

function getHostSeguro(https) {
	var host = (https || isOnline())?'https://icos.websiteseguro.com':getHostHTTP();
	return host;
}
//retorna um requisicao XMLHttpRequest
function getXMLHTTPRequest() {
	var xRequest = null;
	if (window.XMLHttpRequest) {
		xRequest = new XMLHttpRequest();
		if(xRequest.overrideMimeType) {
			xRequest.overrideMimeType('text/xml');
		}
	}
	else if(window.ActiveXObject) {
		try {
			xRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {

			}
		}
	}

	return xRequest;
}

//retorna string somente numeros
function extrairNumero(txt) {
	var numero = "";
	for (var i=0; i<txt.length; i++) {
		if (!isNaN(parseInt(txt.charAt(i)))) {
			numero += txt.charAt(i);
		}
	}
	return numero;
}

//detectar o browser(eh usado para emitir os sons)
function getBrowser() {
	var ie = document.all != undefined;
	var opera = window.opera != undefined;

	if (opera) return "opera";
	if (ie) return "ie";
	if ((window)&&(window.netscape)&&(window.netscape.security)) {
		if (window.XML) {
			return "firefox"; //versao 1.5+
		}
		else return "firefox"; //antes 1.5
	}
	else {
		var ua = navigator.userAgent.toLowerCase();
		if (ua.indexOf("safari") != -1 && ua.indexOf("chrome") == -1) {
			return "safari";
		} else if (ua.indexOf("chrome") != -1) {
			return "chrome";
		}
	}
	return "outro";
}

function ativaMenuLadoEsq(menu, e, nome, offset, x, y) {
	if (!e) e = window.event;
	var dv = document.getElementById(menu);
	if (dv != null) {
		dv.style.visibility = "visible";
		var imagem = document.getElementById("img_mini");
		if (typeof(offset)=="object") {
			var left = getLeftPosition(offset)-5;
			var top = getTopPosition(offset);
		}
		else {
			var left = (x==null)?(e.clientX + document.body.scrollLeft-10):x;
			var top = (y==null)?(e.clientY + document.body.scrollTop+2):y;
		}
		if (imagem.src.match(nome+"$")) {
			dv.style.left = (left-dv.clientWidth) + "px";
			dv.style.top = top + "px";
		}
		else {
			imagem.onload = function() {
				this.onload = null;
				this.parentNode.style.top = top + "px";
				this.parentNode.style.left = (left - this.parentNode.clientWidth) + "px";
			}
			imagem.src = nome;
		}
	}
}

function ativaMenuLadoDir(menu, e, nome, offset, x, y) {
	if (!e) e = window.event;
	var dv = document.getElementById(menu);
	if (dv != null) {
		dv.style.visibility = "visible";
		var imagem = document.getElementById("img_mini");
		if (typeof(offset)=="object") {
			var left = getLeftPosition(offset)+offset.offsetWidth;
			var top = getTopPosition(offset);
		}
		else {
			var left = (x==null)?(e.clientX + document.body.scrollLeft + 5):x;
			var top = (y==null)?(e.clientY + document.body.scrollTop+2):y;
		}
		if (imagem.src.match(nome+"$")) {
			dv.style.left = left + "px";
			dv.style.top = top + "px";
		}
		else {
			imagem.onload = function() {
				this.onload = null;
				this.parentNode.style.left = left + "px";
				this.parentNode.style.top = top + "px";
			}
			imagem.src = nome;
		}
	}
}

//esconder objeto
function desativaMenu(menu) {
	var dv = document.getElementById(menu);
	if (dv != null)
		dv.style.visibility = "hidden";
}

//retorna posicao y do objeto no documento
function getTopPosition( objeto ) {
	if (objeto.offsetParent!=null)
		return objeto.offsetTop + getTopPosition( objeto.offsetParent );
	else
		return objeto.offsetTop;
}

//retorna posicao x do objeto no documento
function getLeftPosition( objeto ) {
	if (objeto.offsetParent!=null)
		return objeto.offsetLeft + getLeftPosition( objeto.offsetParent );
	else
		return objeto.offsetLeft;
}
function getWindowWidth() {
	if (window.self && self.innerWidth) {
		return self.innerWidth;
	}
	if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	}
	return 0;
}
function getWindowHeight() {
	if (window.self && self.innerHeight) {
		return self.innerHeight;
	}
	if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	}
	return 0;
}

//funcao formata a exibicao do campo/textobox
//usado no evento onkeyup para todos navegadores, recebe 3 parametros
// 1- a referencia do campo,
// 2- formato da formatacao: ##/##/#### para data, ###.###.###-## para CPF
// 3- objeto evento;
function mascararCampo(campo, mascara, e) {
	if (campo.readOnly || campo.desabled)
		return false;
	if (!e) e = window.event;
	var num = extrairNumero(campo.value);
	var formatoFinal = "";
	var i, j;
	var reg = mascara.substr(0, campo.value.length);
	reg = reg.replace(/\\/g, "\\\\");
	reg = reg.replace(/\*/g, "\\\*");
	reg = reg.replace(/\./g, "\\\.");
	reg = reg.replace(/\(/g, "\\\(");
	reg = reg.replace(/\)/g, "\\\)");
	reg = reg.replace(/\+/g, "\\\+");
	reg = reg.replace(/#/g, "[0-9]");
	reg = "^" + reg + "$";
	if (!campo.value.match(reg)) {
		for (i=j=0; i<num.length && j<mascara.length; j++) {
			if (mascara.charAt(j) == "#") {
				formatoFinal += num.charAt(i++);
			}
			else {
				if (i<num.length || e.keyCode != 8)
				formatoFinal += mascara.charAt(j);
			}
		}

		if (campo.value != formatoFinal) {
			campo.value = formatoFinal;
		}
	}
	e.returnValue = true;
	return true;
}

function mascararCPFCNPJ(campo, e) {
	if (!e) e = window.event;
	var num = extrairNumero(campo.value);
	if (num.length < 11) {
		if (campo.value.match(/^\d\d\./)) {
			mascararCampo(campo, "##.###.###/####-##", e);
		}
		else {
			mascararCampo(campo, "###.###.###-##", e);
		}
	}
	else if (num.length == 11) {
		mascararCampo(campo, "###.###.###-##", e);
	}
	else {
		mascararCampo(campo, "##.###.###/####-##", e);
	}
}

function mascararFone(campo, e) {
	if (!e) e = window.event;
	var num = extrairNumero(campo.value);

	if (campo.value.match(/^\+/)) {
		mascararCampo(campo, "+###############", e);
	}
	else if (num.match(/^0800/)) {
		if (num.length<11)
			mascararCampo(campo, "#### ## ####", e);
		else
			mascararCampo(campo, "#### ### ####", e);
	}
	else if (num.match(/^0[1-9]{2}/)) {
		campo.value= ""+num.substr(1);
		mascararCampo(campo, "(##) #### ####", e);
	}else if (num.match(/^00[1-9]/)) {
		campo.value= "+"+num.substr(2);
		mascararCampo(campo, "+###############", e);
	}
	else {
		if (num.match(/^119/) && num.length>10)
			mascararCampo(campo, "(##) # #### ####", e);
		else
			mascararCampo(campo, "(##) #### ####", e);
	}

}
function mascararValor(campo, mascara, e) {
	if (!e) e = window.event;
	var num = parseInt(extrairNumero(campo.value), 10);
	if (isNaN(num)) {
		campo.value = "";
		e.returnValue = true;
		return true;
	}
	else {
		num = num.toString();
	}
	var formatoFinal = "";
	var i, j;
	for (i=num.length-1, j=mascara.length-1; j>=0; --j) {
		if (i<0) {
			if (mascara.charAt(j) != "#") {
				formatoFinal = mascara.charAt(j) + formatoFinal;
			}
			else {
				break;
			}
		}
		else {
			if (mascara.charAt(j) == "#") {
				formatoFinal = num.charAt(i--) + formatoFinal;
			}
			else if (!isNaN(parseInt(mascara.charAt(j)))){
				//if (e.keyCode != 8)
					formatoFinal = num.charAt(i--) + formatoFinal;
			}
			else {
				formatoFinal = mascara.charAt(j) + formatoFinal;
			}
		}
	}

	if (campo.value != formatoFinal) {
		campo.value = formatoFinal;
	}
	e.returnValue = true;
	return true;
}

function addCotado(cod) {
	document.location = getLinkRelativo()+"Cotacao/inter_cotados.php?cod="+cod;
}

function verCotacao() {
	document.location = getLinkRelativo()+"Cotacao/inter_cotados.php";
}
function verCotAntiga(cod) {
	document.location="cotacao_antiga.php?cod="+cod;
}
function parentVerCotAntiga(cod) {
	parent.location = getHostSeguro() + getHostInicial() + "Cotacao/cotacao_antiga.php?cod="+cod;
}
function cotarMaisProduto(cm) {
	if (cm) {
		if (cm.match(/fluxo/))
			document.location = getLinkRelativo()+"Fluxo/fluxo.php";
		else if (cm.match(/nivel/))
			document.location = getLinkRelativo()+"Nivel/nivel.php";
		else
			document.location = getLinkRelativo()+"Filtro/filtro.php";
	}
	else {
		goHostInicial();
	}
}

// esta funcao depende validacao.js
function consultarCPFCNPJ(campo) {
	var ref, ref2;
	ref2 = document.getElementById("msgErroCPFCNPJ");
	try {
		if (typeof(campo)=="object")
			ref = campo;
		else
			ref = document.getElementById(campo);
		if (ref.value.length > 0) {
			var numero = extrairNumero(ref.value);
			if (validarCPF(numero) || validarCNPJ(numero)) {
				ref2.innerHTML = "&nbsp;";
				abrirMeuHistorico();
			}
			else {
				ref2.innerHTML = ((numero.length<11)?"CPF/CNPJ":((numero.length==11)?"CPF":"CNPJ"))+ " inválido!";
				ref.focus();
			}
		} else {
			ref2.innerHTML = "Informe CPF/CNPJ!";
		}
	} catch (e) {
		if (ref2 != null)
			ref2.innerHTML = e.toString();
	}
}

function abrirMeuHistorico() {
	var frm = document.getElementById("frmCNPJ");
	if (frm != null) {
		try {
			frm.action = getHostSeguro() + getHostInicial() + "Cotacao/meu_historico.php";
			if (getHostHTTP() != getHostSeguro() && isOnline()) {
				pageTracker._linkByPost(frm); // Google Analytics
				frm.submit();
			}
			else {
				frm.submit();
			}
		}
		catch (e) {
			frm.submit();
		}
	}
	else {
		try {
			var link = getHostSeguro() + getHostInicial() + "Cotacao/meu_historico.php";
			if (getHostHTTP() != getHostSeguro() && isOnline()) {
				//pageTracker._link(link); // Google Analytics
				goComReferrer_GA_link(link);
			}
			else {
				//document.location = link;
				goComReferrer(link);
			}
		}
		catch (e) {
			//document.location = link;
			goComReferrer(link);
		}
	}
}
function parentAbrirMeuHistorico() {
	var link = getHostSeguro() + getHostInicial() + "Cotacao/meu_historico.php";
	parent.location = link;
}
function abrirMeuCadastro() {
	try {
		var link = getHostSeguro() + getHostInicial() + "Cotacao/cad_cliente.php";
		if (getHostHTTP() != getHostSeguro() && isOnline()) {
			//pageTracker._link(link); // Google Analytics
			goComReferrer_GA_link(link);
		}
		else {
			goComReferrer(link);
		}
	}
	catch (e) {
		goComReferrer(link);
	}
}

function logoff() {
	try {
		if (getHostHTTP() != getHostSeguro() && isOnline()) {
			goComReferrer_GA_link(getHostInicial() + "Cotacao/login_cliente.php?logout=logout");
		}
		else {
			goComReferrer(getHostInicial()+"Cotacao/login_cliente.php?logout=logout");
		}
	}
	catch (e) {
		goComReferrer(getHostInicial()+"Cotacao/login_cliente.php?logout=logout");
	}
}

// funcao para quando precisar do document.referrer na pagina seguinte
// IE nao envia cabecalho document.referrer quando usa document.location/window.location
function goComReferrer(link) {
	var frm = document.createElement("form");
	var body = document.getElementsByTagName("body");
	body[0].appendChild(frm);
	frm.action = link;
	frm.name = "_formularioReferrer_";
	frm.method = "post";
	frm.submit();
}

function goHostInicial() {
	// document.location = getLinkRelativo();
	document.location = getHostInicial();
}

function focarComponente(nome) {
	var comp = document.getElementById(nome);
	if(comp != null)
		comp.focus();
}

function escapeSinalPositivo(str) {
	return str.replace(/\+/g,"%2B");
}

function textoIsVazio(txt) {
	if (txt) {
		return (txt.match(/\S/))?false:true;
	} else {
		return true;
	}
}
//use no evento onchange, recebe a reference do caixa de texto
function somenteMaiusculo(ref) {
	if (ref != null)
		ref.value = ref.value.toUpperCase();
}

function somenteMinusculo(ref) {
	if (ref != null)
		ref.value = ref.value.toLowerCase();
}
function somenteNumero(e) {
	if (!e) e = window.event;
	var objExpressaoRegular = /^(8|9|35|36|37|39)$/;

	if (e.keyCode) {
		var code = e.keyCode;
		if (e.charCode != null)
			objExpressaoRegular = /^(8|9|35|36|37|39|46)$/;
	} else if (e.which) {
		var code = e.which;
	} else if (e.charCode) {
		var code = e.charCode;
	}
	else {
		//var code = void(0);
		e.returnValue=true;
		return true;
	}

	if (code>57) {
		e.returnValue=false;
		return false;
	} else if ((code>=48 && code<=57) || objExpressaoRegular.test(code)) {
		e.returnValue=true;
		return true;
	} else {
		e.returnValue=false;
		return false;
	}
}
//validar 1 email
function validarEmail(txt) {
	if (textoIsVazio(txt))
		return false;
	var emailValido = /^[a-z0-9-]+(\.[a-z0-9-]+|_[a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i;
	var emailValidoICOSSERVER = /^[a-z0-9-]+(\.[a-z0-9-]+|_[a-z0-9-]+)*@s.icoserver$/i;
	return (emailValido.test(txt) || emailValidoICOSSERVER.test(txt))?true:false;
}
//validar vários e-mails
function validarEmails(txt) {
	if (textoIsVazio(txt))
		return false;
	var emails = txt.replace(/[,;\s]+/g, " ").split(" ");
	var emailValido = /^[a-z0-9-]+(\.[a-z0-9-]+|_[a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i;
	var emailValidoICOSSERVER = /^[a-z0-9-]+(\.[a-z0-9-]+|_[a-z0-9-]+)*@s.icoserver$/i;
	var i;
	
	for (i = 0; i < emails.length; i++) {
		if (textoIsVazio(emails[i]))
			continue;
		if (!emailValido.test(emails[i]) && !emailValidoICOSSERVER.test(emails[i]))
			return false;
	}
	return true;
}

function validarURL(link) {
	if (link.match(/^[a-z]+:\/\//i)) {
		if(link.match(/^[a-z]+:\/\/[a-z0-9-]{3,}/i)) {
			return 1;
		}
	}
	else if (link.match(/^www/)) {
		if(link.match(/^www[a-z0-9]*\.[a-z0-9-]+(\.[a-z0-9]+)*(\.[a-z]{2,4})$/i)) {
			return 2;
		}
		else if(link.match(/^www[a-z0-9]*\.[a-z0-9-]+(\.[a-z0-9]+)*(\.[a-z]{2,4})\/[.]*/i)) {
			return 3;
		}
	}
	else if(link.match(/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i)) {
		return 4;
	}
	else if(link.match(/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})\/[.]*/i)) {
		return 5;
	}
	
	return 0;
}

function tratarSite(link) {
	var pos = link.search("://");
	pos = (pos == -1)?0:pos+3;
	pos = link.indexOf("/", pos);
	if (pos == -1) {
		return link.toLowerCase();
	}
	else {
		return link.substr(0, pos).toLowerCase() + link.substr(pos);
	}
}

function linhaOver(ref, cor, chk) {
	if (typeof(ref)!="object")
		ref = document.getElementById(ref);
	if (ref != null) {
		if (!cor)
			cor = "#FFF8DC";
		if (chk == null) {
			ref.style.backgroundColor = cor;
		}
		else {
			if (typeof(chk)!="object")
				chk = document.getElementById(chk);
			if (!chk || chk.checked == false) {
				ref.style.backgroundColor = cor;
			}
		}
	}
}

function linhaOut(ref, cor, chk) {
	if (typeof(ref)!="object")
		ref = document.getElementById(ref);
	if (ref != null) {
		if (!cor)
			cor = "#FFFFFF";
		if (chk == null) {
			ref.style.backgroundColor = cor;
		}
		else {
			if (typeof(chk)!="object")
				chk = document.getElementById(chk);
			if (!chk || chk.checked == false) {
				ref.style.backgroundColor = cor;
			}
		}
	}
}

function pintarLinha(ref, cor) {
	if (!cor)
		cor = "#FFF8DC";
	if (typeof(ref)=="object") {
		ref.style.backgroundColor = cor;
	}
	else {
		ref = document.getElementById(ref);
		if (ref != null)
			ref.style.backgroundColor = cor;
	}
}

function pintarLinhaClick(ref, cor, chk) {
	if (typeof(ref)!="object")
		ref = document.getElementById(ref);
	if (ref != null) {
		if (!cor)
			cor = "#FFF8DC";
		if (chk == null) {
			ref.style.backgroundColor = cor;
		}
		else {
			if (typeof(chk)!="object")
				chk = document.getElementById(chk);
			if (!chk) {
				ref.style.backgroundColor = cor;
			}
			else if (chk.checked == false) {
				ref.style.backgroundColor = "#FFFFFF";
			}
			else {
				ref.style.backgroundColor = cor;
			}
		}
	}
}

function preChat() {
	// document.location = getLinkRelativo()+"Faq/faq.php?chat=sim";
	document.location = getLinkRelativo()+"Faq/pre_chat.php";
}

function iniciarChat(tipo, clique) {
	var link;
	if (tipo!=null) {
		if (tipo==2)
			link = getLinkRelativo()+"Chat/index.php?tipo=2"+((clique!=null)?"&clique="+clique:"");
		else
			link = getLinkRelativo()+"Chat/index.php?tipo=1"+((clique!=null)?"&clique="+clique:"");
	}
	else {
		link = getLinkRelativo()+"Chat/index.php";
	}
	var cht = window.open(link, "chat", "toolbar=no, status=yes, scrollbars=yes, location=no, menubar=no, directories=no, width=650, height=550");
	if (cht == null)
		alert(strAlertPopup);
	else
		cht.focus();
}
//Sedex
function rastrearSedex(codigo) {
	var sedex = window.open("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=" + codigo, "Correios", "top=0, left=0, height=400, width=540, resizable=yes, status=no, scrollbars=yes, toolbar=yes, menubar=no, location=no");
	if (sedex != null) {
		sedex.focus();
	}
	else {
		alert(strAlertPopup);
	}
}
function reloadPagina() {
	document.location = document.location.href;
}
function limitarTextarea(obj, max) {
	if (!max || isNaN(parseInt(max)))
		max = 200;
	if (typeof(obj)!='object') {
		obj = document.getElementById(obj);
	}
	if (obj != null) {
		if (obj.value.length>max)
			obj.value = obj.value.substr(0, max);
	}
}
function bloquearVoltar(e) {
	if (!e) e=window.event;
	if (e.altKey && e.keyCode == 37) {
		e.returnValue = false;
		return false;
	}
	else if (e.shiftKey && e.keyCode == 8) {
		e.returnValue = true;
		return true;
	}
	/* //problema com edicao
	else if (e.keyCode == 8) {
		e.returnValue = false;
		return false;
	}*/
	else {
		e.returnValue = true;
		return true;
	}
}
function goPagina(pg) {
	var frm = document.getElementById("formularioPaginada");
	if (frm) {
		frm.reset();
		frm.pagina.value = pg;
		frm.submit();
	}
}
function proximaPagina() {
	var frm = document.getElementById("formularioPaginada");
	if (frm) {
		frm.reset();
		frm.pagina.value = parseInt(frm.pagina.value)+1;
		frm.submit();
	}
}
function anteriorPagina() {
	var frm = document.getElementById("formularioPaginada");
	if (frm) {
		frm.reset();
		frm.pagina.value = parseInt(frm.pagina.value)-1;
		frm.submit();
	}
}

function isEnabledFlashPlayer() {
	var UNDEF = "undefined",
	OBJECT = "object",
	SHOCKWAVE_FLASH = "Shockwave Flash",
	SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
	FLASH_MIME_TYPE = "application/x-shockwave-flash";
	if (typeof navigator.plugins != UNDEF && typeof navigator.plugins[SHOCKWAVE_FLASH] == OBJECT) {
		if (navigator.plugins[SHOCKWAVE_FLASH].description && !(typeof navigator.mimeTypes != UNDEF && navigator.mimeTypes[FLASH_MIME_TYPE] && !navigator.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) {
		// navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
			return true;
		}
	}
	else if (typeof window.ActiveXObject != UNDEF) {
		try {
			var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
			if (a) { // a will return null when ActiveX is disabled
				return true;
			}
		}
		catch(e) {}
	}
	return false;
}

