/**
 * 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; 
} 
// 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 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();
}

/*
* 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 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";
	}
}