//Declarando variáveis para controlar a versão do navegador.
var ie4=document.all&&navigator.userAgent.indexOf("Opera")==-1;
var ns6=document.getElementById&&!document.all;
var ns4=document.layers;

//Valida se o campo é numérico
function ValidaNum(Campo, carac) {
	var valid = "0123456789" + '' + carac;
	var ok = "yes";
	var temp;
	for (var i=0; i< Campo.value.length; i++) {
		temp = "" + Campo.value.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
		Campo.value = '';
		Campo.focus();
   }
   return true;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//Abre janela centralizada
function openCenterWin(url,nome,largura,altura, propriedades){
	var Top=(screen.height/2)-(altura/2);
	var Left=(screen.width/2)-(largura/2);
	var features='height='+altura+',width='+largura+',top='+Top+',left='+Left+','+propriedades;	
	janela=window.open(url,nome,features);
	return janela;
}

// Mostra / esconde gráfico
function f_grafico(objClique, objManipulado){

	if (objManipulado.style.visibility=='hidden'){
		objManipulado.style.visibility='';
		objManipulado.style.position = '';
		objClique.innerText='Esconder gráfico'; 
	} else { 
		objManipulado.style.visibility='hidden' ; 
		objManipulado.style.postition = 'absolute';
		objClique.innerText='Visualizar gráfico'; 
	}
}

function Obj(obj){
	if (ie4)
		return document.all[obj];
	else if (ns6)
		return document.getElementById(""+obj+"");
	else if (ns4)
		return document[obj];
	else
		return document.getElementById(""+obj+"");
}

function getTecla(e){
	if (ie4)
		return e.keyCode;
	else
		return e.which;
}
// Essa função recebe um valor e qtd de casas decimais e faz a arredondacêra
function formatCurrency(number,X) {
    X = (!X ? 2 : X);

	var retorno = new String(Math.round(number*Math.pow(10,X))/Math.pow(10,X));
	retorno = retorno.replace('.',',');	
	return retorno;
}

//função que formata hora com ou sem SEGUNDOS
// campo - obj do campo de hora
// segundos [true/false] - se é pra validar com segundos ou sem
// pra q campo vai depois de terminar de digitar
function formataHora(campo, segundos, proximo_campo, e) {
	tecla = getTecla(e);

	if ((tecla != 8) && (tecla != 37 )&&(tecla != 39)) {
		obj = Obj(campo.id); // obj passa a conter a referência do campo, em qq bráuzer
		hora = new String(obj.value); // conteúdo do campo, no formato String
		tam_completo = hora.length;  // tamanho com dois pontos
		hora = hora.replace(':',''); // conteúdo do campo sem dois pontos
		tamanho = hora.length;  // tamanho sem dois pontos

		if (segundos){
//			Obj(campo.id).maxLength = 8;
			if (tam_completo == 8){
				//document.focus();
				if (proximo_campo){
					Obj(proximo_campo).focus();
					return false;
				}
			}
		}else{
//			Obj(campo.id).maxLength = 5;
			if (tam_completo >= 5){
				//document.focus();
				if (proximo_campo){
					Obj(proximo_campo).focus();
					return false;
				}
			}
		}
		if (tamanho == 2 || tamanho == 3){ // verifica se hora foi digitada
			//alert('hora formatada: ' +hora.substring(0,2) + ":" + hora.substring(2,6));
			obj.value = hora.substring(0,2) + ":" + hora.substring(2,4) ;
		}else if(tamanho == 4){  // verifica se minutos foi digitado
			if (segundos){
				obj.value = hora.substring(0,2) + ":" + hora.substring(2,4) + ":";// + hora.substring(6,8);
			}else{
				obj.value = hora.substring(0,2) + ":" + hora.substring(2,4);// + hora.substring(6,8);
			}			
		}else if (tamanho== 5 && segundos){
			obj.value = hora.substring(0,2) + ":" + hora.substring(2,4) + ":" + hora.substring(4,8);// + hora.substring(6,8);
		}
	} 	
} 

function apenasInt(e) {
	if (ie4) {
		return ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 13 || e.keyCode == 46));
	} else {
		return ((e.which >= 48 && e.which <= 57) || (e.which == 8 || e.which == 9 || e.wich == 13 || e.wich == 46));
	}
}

function stripTags(str){	
	var expreg = /<\S[^>]*>/g; // expressão regular que identifica uma tab <xxx>
	var txt = new String(str);
	txt = txt.replace(expreg,""); // retira todas as tags

	// a variável txt tava retornando com uns 'enters' e uns 'tabs' no final
	// o for abaixo substitui esses caracteres do final por ''
	// substitui só do final, pois se realmente tiver enter ou tab no meio do texto, não pode substituir
	for (i=txt.length-1; i >= 0; i--){
		if (txt.charCodeAt(i) == 9 || txt.charCodeAt(i) == 10 || txt.charCodeAt(i) == 13){
			txt = txt.replace(txt.charAt(i), '');
		}else{
			return txt;
		}
	}		
	return txt;	
}


function formataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

/*############################################################################################
	INICIO FUNÇÕES PARA VALIDAÇÃO CNPJ
#############################################################################################*/
function VerificaCPF_CNPJ_INT(cnpj){
	return ConfereCIC(cnpj)			
}

//Função para Cálculo do Digito do CPF/CNPJ
function DigitoCPFCNPJ(numCIC) {
	var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
	var novoCIC = numCIC.substring(0, numCIC.length-2);
	switch (numCIC.length){
		case 11 :
			numLim = 11;
			break;
		case 14 :
			numLim = 9;
			break;
		default : return false;
	}
	//
	var numSoma = 0;
	var Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
		Fator = Fator + 1;
		if (Fator > numLim) {
			Fator = 2;
		}
		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	numSoma = numSoma/11;
	var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
    if (numResto > 1) {
		numResto = 11 - numResto;
    }
    else {
		numResto = 0;
    }
    //-- Primeiro dígito calculado.  Fará parte do novo cálculo.
    //--
    var numDigito = String(numResto);
    novoCIC = novoCIC.concat(numResto);
    //--
	numSoma = 0;
	Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
		Fator = Fator + 1;
		if (Fator > numLim) {
			Fator = 2;
		}
		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	numSoma = numSoma/11;
	numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
    if (numResto > 1) {
		numResto = 11 - numResto;
    }
    else {
		numResto = 0;
    }
	//-- Segundo dígito calculado.
	numDigito = numDigito.concat(numResto);
	//
	if (numDigito == numDois) {
		return true;
	}
	else {
		return false;
	}
}
//--< Fim da Função >--

//-- Retorna uma string apenas com os números da string enviada
function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	for (var i=0; i < strParm.length; i++) {
		chrPrt = strParm.substring(i, i+1);
		if ( chrPrt.match(/\d/) ) {
			if (j==0) {
				strRet = chrPrt;
				j=1;
			}
			else {
				strRet = strRet.concat(chrPrt);
			}
		}
	}
	return strRet;
}
//--< Fim da Função >--

//-- Somente aceita os caracteres válidos para CPF e CNPJ.
function PreencheCIC(objCIC) {
	var chrP = objCIC.value.substring(objCIC.value.length-1, objCIC.value.length);
	
	if ( !chrP.match(/[0-9]/) && !chrP.match(/[\/.-]/) ) {
		objCIC.value = objCIC.value.substring(0, objCIC.value.length-1);
		return false;
	}
	return true;
}
//--< Fim da Função >--

function FormataCIC (numCIC) {
	numCIC = String(numCIC);
	switch (numCIC.length){
	case 11 :
		return numCIC.substring(0,3) + "." + numCIC.substring(3,6) + "." + numCIC.substring(6,9) + "-" + numCIC.substring(9,11);
	case 14 :
		return numCIC.substring(0,2) + "." + numCIC.substring(2,5) + "." + numCIC.substring(5,8) + "/" + numCIC.substring(8,12) + "-" + numCIC.substring(12,14);
	default : 
		alert("Tamanho incorreto do  CNPJ!");
		document.form1[objCIC.name].focus();
		return "";
	}
}

//-- Remove os sinais, deixando apenas os números e reconstroi o CPF ou CNPJ, verificando a validade
//-- Recebe como parâmetros o número do CPF ou CNPJ, com ou sem sinais e o atualiza com sinais é validado.
function ConfereCIC(objCIC) {
	if (objCIC.value.length == 0) {
		alert("Preenchimento obrigatório CNPJ");
		objCIC.focus();
		return false;
	}
	var strCPFPat  = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
	var strCNPJPat = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;
	
	numCPFCNPJ = ApenasNum(objCIC.value);

	if (!DigitoCPFCNPJ(numCPFCNPJ)) {
		alert("Atenção o Dígito verificador do CNPJ é inválido!");
		document.form1[objCIC.name].focus();
		return false;
	}
	
	objCIC.value = FormataCIC(numCPFCNPJ);

	if (objCIC.value.match(strCNPJPat)) {
		return true;
	}
	else if (objCIC.value.match(strCPFPat)) {
		return true;
	}
	else {
		alert("Digite um  CNPJ válido!");
		return false;
	}
	return true; 
}

//abre um popup, clicando com o botao direito do mouse sobre um elemento html qualquer
//ex: onmouseup = "clickR(event, 'about:blank', 'nome', 400, 300)"
function clickR(e, url, name, w, h) {
	if (e.button == 2 || e.button == 3) {
		openCenterWin(url, name, w, h);
		document.oncontextmenu = new Function("return false")
	}
}

/*#############################################################################################
		FIM FUNÇÕES PARA VALIDAÇÃO CNPJ
#############################################################################################*/

function html2xls() {
	_html = document.getElementById('_excel_html');
	_form = document.getElementById('_excel_form');
	if (_html) {
		_form._excel_input.value = _html.innerHTML; 
		_form.submit();
	} else {
		alert("Pesquise algo antes");
	}
}

/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Robert Nyman | http://robertnyman.com/ */
function removeHTMLTags(content){
 		//var strInputCode = document.getElementById("input-code").innerHTML;
		var strInputCode = content;
 		/* 
  			This line is optional, it replaces escaped brackets with real ones, 
  			i.e. < is replaced with < and > is replaced with >
 		*/	
 	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
 		 	return (p1 == "lt")? "<" : ">";
 		});
 		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		
 		return strTagStrippedText;
}

function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}
