onerror=handleErr;
var txt="";

function handleErr(msg,url,l){
	txt="Ocorreu um erro na execução do JavaScript.\n\n";
	txt+="Erro: " + msg + "\n";
	txt+="URL: " + url + "\n";
	txt+="Linha: " + l + "\n\n";
	txt+="Click OK para Continuar.\n\n\n\n";
	txt+="Virtualiza - Comunicação Virtual";
	alert(txt);
	return false;
}

/**
 * Exibe ou esconde todos os selects
 * 
 * @param {Boolean} -> true para esconder e false para aparecer
 */
function mDisplaySelect(p_param) {
	var els = document.getElementsByTagName("select");
	var checar = 0;
	
	for(var i = 0; i < els.length; i++){
		element = els[i];

		if (p_param == "true") {
			element.style.display = "none";
		} else {
			element.style.display = "";
		}
	}
}

// depois de um valor X de caracteres vai para o proximo campo automaticamente
// se usa assim: onkeyup="proxCampo(this.id,2,'nomeIdDestino');"
function proxCampo(id,qtde,idDestino) {
	if (document.getElementById(id).value.length == qtde) {
		document.getElementById(idDestino).focus();
	}
}

// maximiza a janela
function mMaximizarJanela() {
	window.moveTo(0, 0);
	if (document.all) {
		top.window.resizeTo(screen.availWidth, screen.availHeight);
	}else if (document.layers||document.getElementById) {
		if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth) {
			top.window.outerHeight = screen.availHeight;
			top.window.outerWidth  = screen.availWidth;
		}
	}
}
// Limpa campo q tenha id= id do objeto e valor=valor atual do campo
function mLimpaCampo(id, valor){
	var txtNews = document.getElementById(id).value;
	if(txtNews == valor){ document.getElementById(id).value = "";}
}
// Valida Email, param = id do email e retorna boolean
function mValidaEmail(id){
	var email = document.getElementById(id).value;
	var erro = 0;
	
	if (typeof(email) != "string") erro++;
    else if (!email.match(/^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}$/)) erro++;

	if(erro != 0){
		if (document.getElementById(id).value != "") {
			alert ("E-mail tem que ser válido!");
			document.getElementById(id).focus();
		}
		return false;
	}else return true;
}
// Limpa espacos em branco da direita
function rtrim(string){ 
	while(string.charAt((string.length -1))==" "){ 
		string = string.substring(0,string.length-1); 
	} 
	return string; 
}
//	Limpa espacos em branco a esquerda
function ltrim(string){
	while(string.charAt(0)==" "){
		string = string.replace(string.charAt(0),"");
	}
	return string;
}
// Limpa espacos em branco do inico e do final
function trim(string){
	string = ltrim(string);
	return rtrim(string);
}
// Abre pop up onclick="abreJanela(Url, NomeJanela, width, height, status, extras);"
function mAbreJanela(Url, NomeJanela, width, height, status, extras) {
	var largura = width;
	var altura = height;
	var adicionais= extras;
	var topo = (screen.height-altura)/2;
	var esquerda = (screen.width-largura)/2;

	novaJanela = window.open(''+ Url +'', ''+ NomeJanela +'', 'width='+ largura +', height='+ altura +', top='+ topo +', left='+ esquerda +', status='+ status +', features='+ adicionais +'');
	novaJanela.focus();
}
// Marca ou Descamrca todos os checkbox: onclick="checkAllCheckbox(this.check, 'selecionados[]');"
function mCheckAllCheckbox(check, nameInput){
	var els = document.getElementsByTagName("input");
	
	for(var i = 0; i < els.length; i++){
		element = els[i];
	
		if((element.type == "checkbox") && (element.name == nameInput)){
			 if(check == true) element.checked = true;
			 else element.checked = false;
		}
	}
}
// verficica se checck foi marcado, e pergunta se deseja mesmo excluir, nameInput: nome do input, msg1: pergunta, msg2: nada foi selecionado
function mConfirmaExcluir(nameInput, msg1, msg2){
	
	if(msg1 == undefined) msg1 = "Tem certeza que deseja excluir?";
	if(msg2 == undefined) msg2 = "Nenhum item foi selecionado!";
	
	var els = document.getElementsByTagName("input");
	var checar = 0;
	
	for(var i = 0; i < els.length; i++){
		element = els[i];
		
		if((element.type == "checkbox") && (element.name == nameInput) && (element.checked == true)){
			++checar;
		}
	}
	
	if(checar > 0) return confirm(msg1);
	else { alert(msg2); return false; }
}
// Numero máximo, id do campo e o nº max que vc pretende liberar	
function mMaxNumero(id, nMax){
	form = document.getElementById(id);
	expr = form.value;
	Max = nMax;
	
	if(expr > Max) form.value = "";
}
// Máscara de cep, onkeypress="return('mMascaraCep', event);"  
function mMascaraCep(Campo, e) { 
    var key = ""; 
    var len = 0; 
    var strCheck = "0123456789"; 
    var aux = ""; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0) return true; 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1) return false;  
    
    aux =  Cep_Remove_Format(Campo.value); 
    
    len = aux.length; 
    if(len >= 8) return false;
    aux += key; 
     
    Campo.value = Cep_Mont_Format(aux); 
    return false; 
} 
// Utilizada pela mascara do cep
function Cep_Mont_Format(Cep){ 
    var aux = len = ""; 
 						    
    len = Cep.length; 
    if(len <= 9) tmp = 5;
	else tmp = 5; 
    
    aux = ""; 
    for(i = 0; i < len; i++){ 
        aux += Cep.charAt(i); 
        if(i+1 == tmp) aux += "-"; 
    } 
    return aux ; 
} 
// Utilizado pela mascara de cep
function Cep_Remove_Format(Cep){ 
    var strCheck = "0123456789"; 
    var len = i = aux = ""; 
    len = Cep.length; 
    for(i = 0; i < len; i++){ 
        if (strCheck.indexOf(Cep.charAt(i))!= -1) aux += Cep.charAt(i);
    } 
    return aux; 
}
// Máscara de Moeda, onkeypress="return(mMascaraMoeda(this, '.', ',', event));"
function mMascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){ 
    var sep = 0; 
    var key = ""; 
    var i = j = 0; 
    var len = len2 = 0; 
    var strCheck = "0123456789"; 
    var aux = aux2 = ""; 
    var whichCode = (window.Event) ? e.which : e.keyCode;
     
    if (whichCode == 13) return true;
    if (whichCode == 8) return true;
    if (whichCode == 0) return true;
    
    key = String.fromCharCode(whichCode);
    if (strCheck.indexOf(key) == -1) return false;
    len = objTextBox.value.length; 
    
    for(i = 0; i < len; i++) 
        if ((objTextBox.value.charAt(i) != "0") && (objTextBox.value.charAt(i) != SeparadorDecimal)) break; 
	aux = ""; 
    for(; i < len; i++) 
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i); 
    aux += key; 
    len = aux.length; 
    if (len == 0) objTextBox.value = ""; 
    if (len == 1) objTextBox.value = "0"+ SeparadorDecimal + "0" + aux; 
    if (len == 2) objTextBox.value = "0"+ SeparadorDecimal + aux; 
   
    if (len > 2) { 
        aux2 = ""; 
        for (j = 0, i = len - 3; i >= 0; i--) { 
            if (j == 3) { 
                aux2 += SeparadorMilesimo; 
                j = 0; 
            } 
            aux2 += aux.charAt(i); 
            j++; 
        } 
        objTextBox.value = ""; 
        len2 = aux2.length; 
       
        for (i = len2 - 1; i >= 0; i--) 
        objTextBox.value += aux2.charAt(i); 
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len); 
    } 
    return false;
}
//Máscara de hora, onkeypress="return(mascaraHora(this, event));"
function mMascaraHora(Campo, e) { 
    var key = ''; 
    var len = 0; 
    var strCheck = '0123456789'; 
    var aux = ''; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)return true;
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1) return false;
    
    aux =  hora_remove_format(Campo.value); 
    
    len = aux.length; 
    if(len>=4) return false; 
    aux += key; 
    Campo.value = hora_mont_format(aux); 
    return false; 
} 
//Utilizado pela hora
function hora_mont_format(Data){ 
    var aux = len = ''; 
 						    
    len = Data.length; 
    if(len<=9) tmp = 5; 
    else tmp = 5;

    aux = ''; 
    for(i = 0; i < len; i++){ 
        if(i==0) aux = '';
        aux += Data.charAt(i); 
        if(i+1==2) aux += ':';
    } 
    return aux ; 
} 
// Utilizada pela hora
function hora_remove_format(Data){ 
    var strCheck = '0123456789'; 
    var len = i = aux = ''; 
    len = Data.length; 
    for(i = 0; i < len; i++){ 
        if (strCheck.indexOf(Data.charAt(i))!=-1) aux += Data.charAt(i);
    } 
    return aux; 
}
// Aceita Campos numéricos apenas, onkeypress="return(campoNumerico(this,event));"
function mCampoNumerico(Campo, e){ 
 	var key = ''; 
    var len = 0;  
    var strCheck = '0123456789'; 
    var aux = Campo; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0) return true; 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1) return false; 
    return aux; 
}

// Recebe o tipo de campo, 'num' -> numero, 'cep' -> cep, 'data' -> Data, 'hora' -> Hora
// 'fone' -> Telefone, 'cpfcnpj' -> Cpf/CNPJ, 'letra' -> Letras, onkeyup="tipoCampo('num', this);
function mTipoCampo(tipo, obj){
    var str;

    if(tipo == 'num') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*.,;:~!?/|\\'\\\"<>()[]{}&%#-_=+"; 
    if(tipo == 'hora') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*.,;~!?/|\\'\\\"<>()[]{}&%#-_=+"; 
    if(tipo == 'numd') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*;:~!?/|\\'\\\"<>()[]{}&%#-_=+"; 
    else if(tipo == 'data') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*.,;:~!?|\\'\\\"<>()[]{}&%#-_=+"; 
    else if(tipo == 'cep') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*,;:~!?/|\\'\\\"<>()[]{}&%#_=+"; 
    else if(tipo == 'cpfcnpj') str = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*,;:~!?|\\'\\\"<>()[]{}&%#_=+"; 
    else if(tipo == 'fone') str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZçÇáéíóúÁÉÍÓÚàÀâêîôûÂÊÎÔÛãõÃÕäëïöüÄËÏÖÜ@*.,;:~!?/|\\'\\\"<>[]{}&%#_=+"; 
    else if(tipo == 'letra') str = "1234567890"; 

    if(obj.value != ''){ 
        tam = str.length; 
        for(x=0;x<tam;x++){ 
            if(obj.value.indexOf(str.substr(x,1)) != -1){ 
                obj.value = obj.value.substr(0,obj.value = '') 
                break; 
            } 
        } 
    } 
}
// Máscara de telefone, onkeypress="return mMascaraTelefone(this, event);" 
function mMascaraTelefone(Campo, e) {
    var key = "";
    var len = 0;
    var strCheck = "0123456789";
    var aux = "";
    var whichCode = (window.Event) ? e.which : e.keyCode;
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0) return true; 
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1) return false;
    
    aux =  Telefone_Remove_Format(Campo.value); 
    
    len = aux.length; 
    if(len >= 10) return false;
    aux += key; 
     
    Campo.value = Telefone_Mont_Format(aux); 
    return false; 
} 

function formataTel(evt) {
var obj;
    if (navigator.appName.indexOf("Netscape") != -1) obj = evt.target;
    else obj = evt.srcElement;
    qtd = obj.value.length;
    if (qtd == 2) obj.value = "("+obj.value+")";
    if (qtd == 7) obj.value = obj.value+"-";
    if (qtd == 12 && evt.keyCode == 8) {
    character = tiraChar(obj.value, "-");
        obj.value = character.substring(0,7)+"-"+character.substring(7,12);
    }
    if (qtd == 13) {
    character = tiraChar(obj.value, "-");
    obj.value = character.substring(0,8)+"-"+character.substring(8,12);
	}
}
function tiraChar(texto, caracter) {
var ret;
    for (i=0; i < texto.length; i++) {
    if (texto.substring(i, i+1) == caracter)
            ret = texto.substring(0, i)+texto.substring(i+1, texto.length);
    }
    return ret;
}

// Utilizada pela mascara telefone
function Telefone_Mont_Format(Telefone){ 
    var aux = len = ""; 
    len = Telefone.length; 
    
    if(len <= 9) tmp = 6; 
    else tmp = 6;
    
    aux = ""; 
    for(i = 0; i < len; i++){ 
        if(i == 0)aux = "("; 
        aux += Telefone.charAt(i); 
        if(i+1 == 2) aux += ") "; 
        
        if(i+1==tmp) aux += "-";
    } 
    return aux ; 
} 
// Utilizado pela mascara telefone
function Telefone_Remove_Format(Telefone){ 
    var strCheck = "0123456789"; 
    var len = i = aux = ""; 
    len = Telefone.length; 
    for(i = 0; i < len; i++){ 
        if (strCheck.indexOf(Telefone.charAt(i))!= -1) aux += Telefone.charAt(i);
    } 
    return aux; 
}
// Máscara de data, onkeypress="return(mascaraData(this,event));"
function mMascaraData(Campo, e) { 
    var key = ''; 
    var len = 0; 
    var strCheck = '0123456789'; 
    var aux = ''; 
    var whichCode = (window.Event) ? e.which : e.keyCode; 
    
    if (whichCode == 13 || whichCode == 8 || whichCode == 0) return true;
    key = String.fromCharCode(whichCode); 
    if (strCheck.indexOf(key) == -1) return false;    
    aux =  data_remove_format(Campo.value); 
    
    len = aux.length; 
    if(len>=8) return false;
    aux += key; 
     
    Campo.value = data_mont_format(aux); 
    return false; 
} 
// Utilizada pela data
function data_mont_format(Data){ 
    var aux = len = ''; 
    len = Data.length; 
    
    if(len<=9) tmp = 5; 
	else tmp = 5;
    
    aux = ''; 
    for(i = 0; i < len; i++){ 
        if(i==0) aux = '';
        aux += Data.charAt(i); 
        if(i+1==2) aux += '/';
        
        if(i+2==tmp) aux += '/';
    } 
    return aux ; 
} 
// Utilizada pela data
function data_remove_format(Data){ 
    var strCheck = '0123456789'; 
    var len = i = aux = ''; 
    len = Data.length; 
    for(i = 0; i < len; i++){ 
        if (strCheck.indexOf(Data.charAt(i))!=-1) aux += Data.charAt(i);
    } 
    return aux; 
} 

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

    var nTecla = evtKeyPress.keyCode ? evtKeyPress.keyCode : evtKeyPress.which ? evtKeyPress.which : evtKeyPress.charCode;
	
    sValue = document.getElementById(strField).value;

    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) == "/"))
      	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++;
    }

    document.getElementById(strField).value = sCod;

	if (nTecla != 8) {
		if (sMask.charAt(i-1) == "9") return ((nTecla > 47) && (nTecla < 58) || (nTecla == 8) || (nTecla == 46));
		else return true;
	}else return true;
}
// validação de cnpj
function mValidaCNPJ(id) {
	CNPJ = document.getElementById(id).value;
	erro = new String;
	
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x;
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
	
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i = 0; i < 12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }

	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) erro +="Dígito verificador com problema!";
	if (erro.length > 0){
		if(document.getElementById(id).value != "") {
			alert("CNPJ está inválido!");
			document.getElementById(id).focus();
			document.getElementById(id).select();
		}
		return false;
	}
	return true;
}
// Adicionar ao favoritos
function addfav(){
	var browsName = navigator.appName;
	var URLSite   = window.location.href;
	var TituloSite = document.title;

	if ((browsName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
		window.external.AddFavorite(URLSite,TituloSite);
	}else if(browsName == "Netscape"){
		alert ("\nPara adicionar ao Favoritos aperte CTRL+D");
	}
}

/*
* Função para abrir janela
*/
function mOpenWindow(url, width, height) {
	var largura = width;
	var altura = height;
	var topo = (screen.height-altura)/2;
	var esquerda = (screen.width-largura)/2;

	window.open(url, "", "width="+largura+",height="+altura+",top="+topo+",left="+esquerda+",scrollbars=yes");
}

/*
* Função para abrir janelas no meio da tela
*/
function mWindowOpen(url, width, height) {
	var topo = (screen.height - height) / 2;
	var esquerda = (screen.width - width) / 2;

	janela = window.open(url,"","width="+width+",height="+height+",top="+topo+",left="+esquerda+",scrollbars=yes");
	janela.focus();
}

/*
* Função para abrir janela
*/
function mOpenWindow(url, width, height) {
	var largura = width;
	var altura = height;
	var topo = (screen.height-altura)/2;
	var esquerda = (screen.width-largura)/2;

	window.open(url, "", "width="+largura+",height="+altura+",top="+topo+",left="+esquerda+",scrollbars=yes");
}

/*
* Altera tamanho da fonte do texto
*/
function alteraFonte(id, param) {
	tamanho = document.getElementById(id).style.fontSize.substr(0,2);
	
	if (param == "aumenta") {		
		tamanho = parseInt(tamanho) + 2;
		
		if (tamanho < 17) document.getElementById(id).style.fontSize = tamanho + "px";
	} else {
		tamanho = parseInt(tamanho) - 2;
		
		if (tamanho > 8) document.getElementById(id).style.fontSize = tamanho + "px";
	}
}

/*
* Função para enviar fale conosco
*/
function mEnviaFaleConosco() {
	if (mValidaForm()) {
		if (mValidaEmail("email")) {
			ajaxForm("ajaxFaleConosco","formFaleConosco");
		}
	}
	return false;
}

/*
* informativo
*/
function mEnviaEmail() {
	if (mValidaEmail("emailEmail")) {
		ajaxForm("cadastro","formEmails");
	}
	return false;
}

/*
* informativo
*/
function confere(id,param,valor) {
	if (param == 1) {
		if (document.getElementById(id).value == valor) document.getElementById(id).value = "";
	} else {
		if (document.getElementById(id).value == "") document.getElementById(id).value = valor;
	}
}

/*
* Função para abrir o formulario de indique
*/
function abreIndique(id) {
	//Ajusta posição na tela
	document.getElementById("envolvePopup").style.left = ((screen.width - 450) / 2) + "px";
	document.getElementById("envolvePopup").style.top = ((screen.height - 450) / 2) + "px";
	
	//Ajusta tamanhos css
	document.getElementById("envolvePopup").style.width = 475 + "px";
	document.getElementById("envolvePopup").style.height = 393 + "px";
	document.getElementById("popup").style.width = 475 + "px";
	document.getElementById("popup").style.height = 393 + "px";
	
	//Carrega formulario de indique com ajax
	ajaxLink("popup","index.php?link=indique&cd_produto="+id);
	
	document.getElementById("seguraFundo").style.display = "";
	document.getElementById("envolvePopup").style.display = "";
}

/*
* Função para fechar a popup flutuante do indique
*/
function fechaPopup() {
	document.getElementById("seguraFundo").style.display = "none";
	document.getElementById("envolvePopup").style.display = "none";
	
	//Limpa a foto
	document.getElementById("popup").innerHTML = "<a href=\"#1\" onclick=\"fechaPopup();\" title=\"Fechar\"><img id=\"imgPopup\" src=\"imagens/aguardeCarregando.jpg\" alt=\"Fechar\" /></a>";
}
/*
* Função para o formulario de indique
*/
function mEnviaIndique() {
	if (mValidaForm()) {
		if ((mValidaEmail("email")) && (mValidaEmail("email_para"))) {
			ajaxForm("indiqueForm","formIndique");
		}
	}
	return false;
}
/*
* Função para o cadastro de usuário
*/
function mCadastraUser() {
	if (mValidaFormUser()) {
		if (mValidaEmail("email")) {
			ajaxForm("boxCadastro","formCad");
		}
	}
	return false;
}

/*
* Função para alternar style.diplay
*/
function mDisplay(id) {
	if (document.getElementById(id).style.display == "none") {
		document.getElementById(id).style.display = "";
	} else {
		document.getElementById(id).style.display = "none";
	}
}


/*
 Função para hover no background
*/

function Go(m){
m.style.backgroundPosition='right';

}

function Back(m){
m.style.backgroundPosition='left';

}

function Stop(m){
m.className='menuOn';

}

/***********************************************
* AnyLink Drop Down Menu- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
var menu=new Array()
menu[2]='<a href=\"?link=inst_sobre\">Sobre a CMC<\/a>'
menu[3]='<a href=\"?link=inst_qualid\">Politíca de Qualidade<\/a>'
menu[4]='<a href=\"?link=inst_local\">Localização<\/a>'

var menuEn=new Array()
menuEn[2]='<a href=\"?link=inst_sobre\">About the CMC<\/a>'
menuEn[3]='<a href=\"?link=inst_qualid\">Quality Politics<\/a>'
menuEn[4]='<a href=\"?link=inst_local\">Localization<\/a>'

var menuEs=new Array()
menuEs[2]='<a href=\"?link=inst_sobre\">Sobre la CMC<\/a>'
menuEs[3]='<a href=\"?link=inst_qualid\">Política de Cualidad<\/a>'
menuEs[4]='<a href=\"?link=inst_local\">Localización<\/a>'


//menu1[5]='<a href=\"?link=inst_seto\">Setores Internos<\/a>'

var menu2=new Array()
menu2[2]='<a href=\"?link=produtos&cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu2[3]='<a href=\"?link=produtos&cd_categoria=29\">CMC Tecnologia<\/a>'
menu2[4]='<a href=\"?link=produtos&cd_categoria=26\">CMC Cerâmica Técnica<\/a>'
menu2[5]='<a href=\"?link=produtos&cd_categoria=28\">CMC OFF SHORE<\/a>'
menu2[6]='<a href=\"?link=prod_obras\">Projetos Executados<\/a>'

var menu2Es=new Array()
menu2Es[2]='<a href=\"?link=produtos&cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu2Es[3]='<a href=\"?link=produtos&cd_categoria=29\">CMC Tecnologia<\/a>'
menu2Es[4]='<a href=\"?link=produtos&cd_categoria=26\">CMC Cerámica Técnica<\/a>'
menu2Es[5]='<a href=\"?link=produtos&cd_categoria=28\">CMC OFF SHORE<\/a>'
menu2Es[6]='<a href=\"?link=prod_obras\">Proyecto Exceptuado<\/a>'

var menu2En=new Array()
menu2En[2]='<a href=\"?link=produtos&cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu2En[3]='<a href=\"?link=produtos&cd_categoria=29\">CMC Tecnologia<\/a>'
menu2En[4]='<a href=\"?link=produtos&cd_categoria=26\">CMC Cerâmica Técnica<\/a>'
menu2En[5]='<a href=\"?link=produtos&cd_categoria=28\">CMC OFF SHORE<\/a>'
menu2En[6]='<a href=\"?link=prod_obras\">Executed Projects<\/a>'


var menu3=new Array()
menu3[2]='<a href=\"?link=faleconosco\">Clientes<\/a>'
menu3[3]='<a href=\"?link=representantes\">Distribuidores / Representantes<\/a>'
menu3[4]='<a href=\"?link=trabalhe\">Trabalhe Conosco<\/a>'

var menu3En=new Array()
menu3En[2]='<a href=\"?link=faleconosco\">Customer<\/a>'
menu3En[3]='<a href=\"?link=representantes\">Distributer / Representative<\/a>'
menu3En[4]='<a href=\"?link=trabalhe\">Work with us<\/a>'

var menu3Es=new Array()
menu3Es[2]='<a href=\"?link=faleconosco\">Cliente<\/a>'
menu3Es[3]='<a href=\"?link=representantes\">Distribuidor / Representante<\/a>'
menu3Es[4]='<a href=\"?link=trabalhe\">Trabaje conosco<\/a>'


var menu4=new Array()
menu4[3]='<a href=\"?link=prod_manuais&amp;cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu4[4]='<a href=\"?link=prod_manuais&amp;cd_categoria=29\">CMC Tecnologia<\/a>'
menu4[5]='<a href=\"?link=prod_manuais&amp;cd_categoria=26\">CMC Cerâmica Técnica<\/a>'
menu4[6]='<a href=\"?link=prod_manuais&amp;cd_categoria=28\">CMC OFF SHORE<\/a>'

var menu4En=new Array()
menu4En[3]='<a href=\"?link=prod_manuais&amp;cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu4En[4]='<a href=\"?link=prod_manuais&amp;cd_categoria=29\">CMC Tecnologia<\/a>'
menu4En[5]='<a href=\"?link=prod_manuais&amp;cd_categoria=26\">CMC Cerâmica Técnica<\/a>'
menu4En[6]='<a href=\"?link=prod_manuais&amp;cd_categoria=28\">CMC OFF SHORE<\/a>'

var menu4Es=new Array()
menu4Es[3]='<a href=\"?link=prod_manuais&amp;cd_categoria=27\">CMC Construções Mecânicas Cocal<\/a>'
menu4Es[4]='<a href=\"?link=prod_manuais&amp;cd_categoria=29\">CMC Tecnologia<\/a>'
menu4Es[5]='<a href=\"?link=prod_manuais&amp;cd_categoria=26\">CMC Cerâmica Técnica<\/a>'
menu4Es[6]='<a href=\"?link=prod_manuais&amp;cd_categoria=28\">CMC OFF SHORE<\/a>'


var menuwidth='200px' //default menu width
var menubgcolor='#CCCCCC'  //menu bgcolor
var disappeardelay=250  //menu disappear speed onMouseout (in miliseconds)
var hidemenu_onclick="yes" //hide menu when user clicks within menu?

/////No further editting needed

var ie4=document.all
var ns6=document.getElementById&&!document.all

if (ie4||ns6)
document.write('<div id=\"dropmenudiv\" style=\"visibility:hidden;width:'+menuwidth+';background-color:'+menubgcolor+'\" onMouseover=\"clearhidemenu()\" onMouseout=\"dynamichide(event)\"><\/div>')

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}


function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top="-500px"
if (menuwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
}
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}


function dropdownmenu(obj, e, menucontents, menuwidth){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("dropmenudiv") : dropmenudiv
populatemenu(menucontents)

if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)

dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}

return clickreturnvalue()
}

function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}

function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

if (hidemenu_onclick=="yes")
document.onclick=hidemenu

/*************************** SCRIPT DA NOTICIA ***********************************/
var dhtmlgoodies_slideSpeed = 16;	// Higher value = faster
var dhtmlgoodies_timer = 5;	// Lower value = faster

var objectIdToSlideDown = false;
var dhtmlgoodies_activeId = false;
var dhtmlgoodies_slideInProgress = false;
function showHideContent(e,inputId)
{
	if(dhtmlgoodies_slideInProgress)return;
	dhtmlgoodies_slideInProgress = true;
	if(!inputId)inputId = this.id;
	inputId = inputId + '';
	var numericId = inputId.replace(/[^0-9]/g,'');
	var answerDiv = document.getElementById('dhtmlgoodies_a' + numericId);

	objectIdToSlideDown = false;
	
	if(!answerDiv.style.display || answerDiv.style.display=='none'){		
		if(dhtmlgoodies_activeId &&  dhtmlgoodies_activeId!=numericId){			
			objectIdToSlideDown = numericId;
			slideContent(dhtmlgoodies_activeId,(dhtmlgoodies_slideSpeed*-1));
		}else{
			
			answerDiv.style.display='block';
			answerDiv.style.visibility = 'visible';
			
			slideContent(numericId,dhtmlgoodies_slideSpeed);
		}
	}else{
		slideContent(numericId,(dhtmlgoodies_slideSpeed*-1));
		dhtmlgoodies_activeId = false;
	}	
}

function slideContent(inputId,direction)
{
	
	var obj = document.getElementById('dhtmlgoodies_a' + inputId);
	var contentObj = document.getElementById('dhtmlgoodies_ac' + inputId);
	height = obj.clientHeight;
	if(height==0)height = obj.offsetHeight;
	height = height + direction;
	rerunFunction = true;
	if(height>contentObj.offsetHeight){
		height = contentObj.offsetHeight;
		rerunFunction = false;
	}
	if(height<=1){
		height = 1;
		rerunFunction = false;
	}

	obj.style.height = height + 'px';
	var topPos = height - contentObj.offsetHeight;
	if(topPos>0)topPos=0;
	contentObj.style.top = topPos + 'px';
	if(rerunFunction){
		setTimeout('slideContent(' + inputId + ',' + direction + ')',dhtmlgoodies_timer);
	}else{
		if(height<=1){
			obj.style.display='none'; 
			if(objectIdToSlideDown && objectIdToSlideDown!=inputId){
				document.getElementById('dhtmlgoodies_a' + objectIdToSlideDown).style.display='block';
				document.getElementById('dhtmlgoodies_a' + objectIdToSlideDown).style.visibility='visible';
				slideContent(objectIdToSlideDown,dhtmlgoodies_slideSpeed);				
			}else{
				dhtmlgoodies_slideInProgress = false;
			}
		}else{
			dhtmlgoodies_activeId = inputId;
			dhtmlgoodies_slideInProgress = false;
		}
	}
}



function initShowHideDivs()
{
	var divs = document.getElementsByTagName('DIV');
	var divCounter = 1;
	for(var no=0;no<divs.length;no++){
		if(divs[no].className=='dhtmlgoodies_question'){
			divs[no].onclick = showHideContent;
			divs[no].id = 'dhtmlgoodies_q'+divCounter;
			var answer = divs[no].nextSibling;
			while(answer && answer.tagName!='DIV'){
				answer = answer.nextSibling;
			}
			answer.id = 'dhtmlgoodies_a'+divCounter;	
			contentDiv = answer.getElementsByTagName('DIV')[0];
			contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px'; 	
			contentDiv.className='dhtmlgoodies_answer_content';
			contentDiv.id = 'dhtmlgoodies_ac' + divCounter;
			answer.style.display='none';
			answer.style.height='1px';
			divCounter++;
		}		
	}	
}
window.onload = initShowHideDivs;

function mAtendimento(){
	
	var inputAtend			= "inputAtend";
	var nm_atendimento 		= document.getElementById("nm_atendimento");
	var emailEmail			= document.getElementById("emailEmail");
	var fone_atendimento	= document.getElementById("fone_atendimento");
	var erro				= document.getElementById("msgErroAtend");
	
	// Valida campo nome
	if( (nm_atendimento.value == "") || (nm_atendimento.value == "Nome") || (nm_atendimento.value == "Name") ){
		nm_atendimento.style.border = "1px solid #990000";
		nm_atendimento.style.background = "#FFF0F8";
		nm_atendimento.focus();
		erro.innerHTML = "<img src='imagens/btError.gif' style='float:left' />&nbsp;<strong>Preencha o Nome corretamente.</strong>";
		return false;
	} else {
		nm_atendimento.style.border = "1px solid #CCCCCC";
		nm_atendimento.style.background = "#FFF";
		erro.innerHTML = "Solicite atendimento de um de nossos consultores através deste canal";
}
	// Valida campo email
	if( (emailEmail.value == "") || (emailEmail.value == "Seu e-mail") || (emailEmail.value == "E-mail") || (!mValidaEmail("emailEmail")) ){
		emailEmail.style.border = "1px solid #990000";
		emailEmail.style.background = "#FFF0F8";
		emailEmail.focus();
		erro.innerHTML = "<img src='imagens/btError.gif' style='float:left' />&nbsp;<strong>Preencha seu Email corretamente.</strong>";
		return false;
	} else {
		emailEmail.style.border = "1px solid #CCCCCC";
		emailEmail.style.background = "#FFF";
		erro.innerHTML = "Solicite atendimento de um de nossos consultores através deste canal";
	}
	// Valida campo fone
	if( (fone_atendimento.value == "") || (fone_atendimento.value == "DDD + Telefone") ){
		fone_atendimento.style.border = "1px solid #990000";
		fone_atendimento.style.background = "#FFF0F8";
		fone_atendimento.focus();
		erro.innerHTML = "<img src='imagens/btError.gif' style='float:left' />&nbsp;<strong>Preencha o Telefone corretamente.</strong>";
		return false;
	} else {
		fone_atendimento.style.border = "1px solid #CCCCCC";
		fone_atendimento.style.background = "#FFF";
		erro.innerHTML = "Solicite atendimento de um de nossos consultores através deste canal";
	}
	return true;
}

messageObj = new DHTML_modalMessage();	// We only create one object of this class
messageObj.setShadowOffset(5);	// Large shadow

function displayMessage(url){
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(404,240);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}

function closeMessage(){
	messageObj.close();
	window.location = ''+document.location+'';
}
