//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;
}

//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'; 
	}
}

//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;

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 (window.event){
		return e.keyCode;
	} else {
		return e.which;
	}
	
	/*else if (ns6) {
		return document.getElementById(""+obj+"");
	} else if (ns4) { 
		return document[obj];
	} else {
		return document.getElementById(""+obj+"") ;
	}*/
}
// 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 = 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 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; 
}

/*#############################################################################################
		FIM FUNÇÕES PARA VALIDAÇÃO CNPJ
#############################################################################################*/

//mascarar a placa do carro, 
function mascara_placa(campo, evt){

 //se for um backspace ou o direcional para a esquerda
  if(evt.keyCode == 8 || evt.keyCode == 37)
    return false;
	
  var comprimento = campo.value.length;

  //checa os caracteres
  var placa = /[a-z0-9]/ ;
      
  if(!placa.test(campo.value)){	  	

	  campo.value = campo.value.substr(0, comprimento);	  
	  return false;  
  }  
   
  //limite de caracteres
  if(comprimento >= 8){
    campo.value = campo.value.substr(0, 8);
	return false;
  }	

  //primeiras letras em uppercase
  if(comprimento == 1 || comprimento == 2 || comprimento == 3)
	campo.value = campo.value.toUpperCase();
	
  //adciona o ífen
  if(campo.value.length == 3)
	  campo.value += "-";
	  
  return true;

}
//#########

//Retorna mensagem para o usuário,seta o foco no campo e retorna false se existir um ou mais horários com problema 
function checa_form_horarios(){

	if(horaErrada.length > 0){
		alert("Você não pode ter horários iniciais maiores do que o respectivo horário final.\n Por favor confira o(s) "+horaErrada.length+" par(es) de horários inconsistente(s)");
		horaErrada[0].focus();		
		return false;
	}
}

/**
	FUNÇÃO RESPOSÁVEL POR FAZER A CHECAGEM DOS HORÁRIOS DE TRABALHO SELECIONADOS NA PARTE DE CONFIGURAÇÃO E NO MÓDULO DE PROJETOS
	É CHAMADO A CADA EVENTO "onChange" DOS SELECTS E FAZ A VERIFICAÇÃO DOS VALORES. 
	DEPENDE DE UMA VARIÁVEL GLOBAL "horaErrada" DO TIPO ARRAY. ELA GUARDARÁ UMA REFERÊNCIA A TODOS OS CAMPOS CUJOS PARES DE HORÁRIOS 
	SÃO INCONSISTENTES.
	CHAMADO A FUNÇÃO ACIMA NO EVENTO "onSubmit" DO FORMULÁRIO ESSA ARRAY SERÁ TESTADO.
*/
var horaErrada = new Array();
function verifica_horario(campo){

		var hrOuMin     = (campo.name.indexOf("HOR") != -1) ? "HOR" : "MIN"; 
		var hrOuMinRev  = (campo.name.indexOf("HOR") != -1) ? "MIN" : "HOR"; 
		var iniOuFin    = (campo.name.indexOf("INI") != -1) ? "INI" : "FIN"; 
		var iniOuFinRev = (campo.name.indexOf("INI") != -1) ? "FIN" : "INI"; 

		var cp1ini = campo;
		var cp1fin = document.getElementById(campo.name.replace(hrOuMin, hrOuMinRev));
		var cp2ini = document.getElementById(cp1ini.name.replace(iniOuFin, iniOuFinRev));
		var cp2fin = document.getElementById(cp1fin.name.replace(iniOuFin, iniOuFinRev));
		
		// remove os do array de campos com problemas os que estão sendo testados, pois se passar agora, estão liberdaos,
		// se não passar um deles acabará sendo inserido denovo e esse teste será refeito até que todos passem
		for(i in horaErrada){
			if(horaErrada[i] == campo)
				horaErrada.splice(i, 1);
			if(horaErrada[i] == cp1ini)
				horaErrada.splice(i, 1);	
			if(horaErrada[i] == cp1fin)
				horaErrada.splice(i, 1);					
			if(horaErrada[i] == cp2ini)
				horaErrada.splice(i, 1);					
			if(horaErrada[i] == cp2fin)
				horaErrada.splice(i, 1);									
		}

		if(hrOuMin == "HOR"){//se mexeu num select de horas
		
			if(iniOuFin == "INI"){//se era de hora inical
				var inicio = cp1ini.value+":"+cp1fin.value+":00";
				var oFinal  = cp2ini.value+":"+cp2fin.value+":00";
				//var str = "Hora inicial é "+cp1ini.value+":"+cp1fin.value+" \n Final é "+cp2ini.value+":"+cp2fin.value;
			}	
			else{
				var inicio = cp2ini.value+":"+cp2fin.value+":00";
				var oFinal  = cp1ini.value+":"+cp1fin.value+":00";				
				//var str = "Hora inicial é "+cp2ini.value+":"+cp2fin.value+" \n Final é "+cp1ini.value+":"+cp1fin.value;
			}	
		}	
		else{
			if(iniOuFin == "INI"){
				var inicio = cp1fin.value+":"+cp1ini.value+":00";
				var oFinal  = cp2fin.value+":"+cp2ini.value+":00";
				//var str = "Hora inicial é "+cp1fin.value+":"+cp1ini.value+" \n Final é "+cp2fin.value+":"+cp2ini.value;
			}	
			else{
				var inicio = cp2fin.value+":"+cp2ini.value+":00";
				var oFinal  = cp1fin.value+":"+cp1ini.value+":00";
				//var str = "Hora inicial é "+cp2fin.value+":"+cp2ini.value+" \n Final é "+cp1fin.value+":"+cp1ini.value;
			}	
		}	

		var horaInicio = new Date("Nov 29, 1984 "+ inicio);
		var horaFinal  = new Date("Nov 29, 1984 "+ oFinal);
		if(horaInicio.getTime() > horaFinal.getTime()){
			
			alert("O horário de início "+ inicio.substr(0, 5) +" é maior do que o de término "+ oFinal.substr(0, 5));
			for(i in horaErrada){
				if(horaErrada[i] == campo)
					var jaEsta = true;
			}
			if(!jaEsta){
				horaErrada.push(campo); 
			}

			return false;
		}		

}//function

function replicar(){
	
	if(horaErrada.length > 0){
		alert("Você tem horários inconsistentes na primeira linha.\nAcerte-os antes de replicar os horários");
		return false;
	}
	
	var modelo1 = document.getElementById('HOR_INI_MANHA_1');
	var modelo2 = document.getElementById('HOR_FIN_MANHA_1');
	var modelo3 = document.getElementById('HOR_INI_TARDE_1');
	var modelo4 = document.getElementById('HOR_FIN_TARDE_1');	
	var modelo5 = document.getElementById('MIN_INI_MANHA_1');
	var modelo6 = document.getElementById('MIN_FIN_MANHA_1');
	var modelo7 = document.getElementById('MIN_INI_TARDE_1');
	var modelo8 = document.getElementById('MIN_FIN_TARDE_1');		
	
	for(var i=0; i<7; i++){		
		document.getElementById(modelo1.id.replace("1", i)).value = document.getElementById('HOR_INI_MANHA_0').value;		
		document.getElementById(modelo2.id.replace("1", i)).value = document.getElementById('HOR_FIN_MANHA_0').value;		
		document.getElementById(modelo3.id.replace("1", i)).value = document.getElementById('HOR_INI_TARDE_0').value;		
		document.getElementById(modelo4.id.replace("1", i)).value = document.getElementById('HOR_FIN_TARDE_0').value;				
		document.getElementById(modelo5.id.replace("1", i)).value = document.getElementById('MIN_INI_MANHA_0').value;		
		document.getElementById(modelo6.id.replace("1", i)).value = document.getElementById('MIN_FIN_MANHA_0').value;		
		document.getElementById(modelo7.id.replace("1", i)).value = document.getElementById('MIN_INI_TARDE_0').value;		
		document.getElementById(modelo8.id.replace("1", i)).value = document.getElementById('MIN_FIN_TARDE_0').value;						
	}
}

function formata_data_hora(data){
	
	if(!data || typeof(data) == "undefined"){
		var data = new Date;		
	}
	
	var dia = data.getDate();
	var mes = data.getMonth();
	var ano = data.getFullYear();
	var hora = data.getHours();
	var minutos = data.getMinutes();

	dia = (dia < 10) ? "0"+dia : dia;
	mes = (mes < 10) ? "0"+ parseInt(mes+1) : parseInt(mes+1); //mes de janeiro é zero no JS, por isso o (+1)
	var data_hora = dia + "/" + mes + "/" + ano + " " + hora + ":" + minutos;
	alert(data_hora);
	return data_hora;
}

function mostraEsconde(elementoId, estado){
	
	if(!document.getElementById(elementoId))	
		return false;

	document.getElementById(elementoId).style.display = estado;	
		return true;
}
//essa função vai buscar o elemento (um select) com o id informado 
//e incluir a lista de options do mesmo, um novo option tento como 
//valor o parametro valor e como texto o parametro texto passados.
//Caso não encontre elemento com o id informado nessa página, irá
//se esta for um popup tentará achar na página "opener", por fim
//irá tentar achar em algum possível iframe

function add_options_select(id_select, valor, texto, showAlert){
	
	var gotcha = getElementAnyWhere(id_select);
	if(gotcha){
		var oSelect = gotcha[0];
		var where = gotcha[1];
	}
	else{
		return false;
	}
	
	var newElem   = where.createElement("OPTION");
	newElem.text  = texto;
	newElem.value = valor;
	oSelect.options.add(newElem);		
	oSelect.value = newElem.value;
	
	return true;
}//funciton

function remover_options_select(id_select, valor, texto){

	var gotcha = getElementAnyWhere(id_select);
	if(gotcha){
		var oSelect = gotcha[0];
	}
	else{
		return false;
	}	

	for(var x = 0; x < oSelect.options.length; x++){
		
		if(oSelect.options[x].value == valor && oSelect.options[x].text == texto){
			oSelect.removeChild(oSelect.options[x]);
			return true;
		}
	}	
	
	//alert('Não consegui encontrar o "option" informado');
	return false;	
}//function

function alterar_options_select(id_select, valor, texto, novo_valor, novo_texto){

	var gotcha = getElementAnyWhere(id_select, true);
	if(gotcha){
		var oSelect = gotcha[0];
	}
	else{
		return false;
	}	

	for(var x = 0; x < oSelect.options.length; x++){
		
		if(oSelect.options[x].value == valor && oSelect.options[x].text == texto){
			oSelect.options[x].value = novo_valor;
			oSelect.options[x].text = novo_texto;
			return true;
		}
	}	
	
	alert('Não consegui encontrar o "option" informado');
	return false;	
}//function


function getElementAnyWhere(id_elemento, showAlert){
	
	if(showAlert == undefined){
		showAlert = true;
	}
	var oElemento = false;
	var where  	  = false;
	var isPopup   = (window.opener) ? true : false;
	var osIframes = (document.getElementsByTagName('iframe')) ? document.getElementsByTagName('iframe') : false;
	
	if(document.getElementById(id_elemento)){
		var oElemento = document.getElementById(id_elemento);
		where = document;
	}	
	else{
		if(isPopup){
			if(window.opener.document.getElementById(id_elemento)){
				oElemento = window.opener.document.getElementById(id_elemento);
				where = window.opener.document;
			} 
		}
		
		if(!oElemento && osIframes != false){
			for (var x in osIframes){

				var iDocument = osIframes[x].contentWindow || osIframes[x].contentDocument;
				if(iDocument.document.getElementById(id_elemento)){
					oElemento = iDocument.document.getElementById(id_elemento);
					where = iDocument.document;
				}				
			}//for
		}//if
	}//else
	
	if(oElemento == false){

		if(showAlert == true){
			alert("Não pude localizar o elemento a partir com id "+id_elemento);
		}
		return false;
	}
	
	var retorno = new Array(oElemento, where);

	return retorno;
}//funciton
