/***************************************************************************************************************
CONECTT MARKETING INTERATIVO - 2005
Programador...: Marcelo Correia Pinheiro
E-mail........: salizzar@gmail.com
Descrição.....: arquivo com as funções JavaScript utilizadas pelo sistema.
***************************************************************************************************************/

//--------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------
// COMANDOS QUE BLOQUEIAM BOTAO DIREITO NA TELA
// Alterado por Marcelo Allievi em 24/11/2005 Motivo: Em ambiente de desenvolvimento é desnecessário este bloqueio
if (location.host=='utrsa.com.br')
{
	document.oncontextmenu = function(){ return false };
	document.ondragstart   = function(){ return false };
	document.onselectstart = function(){ return false };
}

//--------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------


//--------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------
// DEMAIS FUNÇÕES
function cpfValido(cpf)
{
	// remove pontos e traços
	cpf = cpf.replace(/\D/g, '');
	
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	digitos_iguais = 1;
	if (cpf.length < 11)
		return false;
	for (i = 0; i < cpf.length - 1; i++)
		if (cpf.charAt(i) != cpf.charAt(i + 1))
			  {
			  digitos_iguais = 0;
			  break;
			  }
	if (!digitos_iguais)
		{
		numeros = cpf.substring(0,9);
		digitos = cpf.substring(9);
		soma = 0;
		for (i = 10; i > 1; i--)
			  soma += numeros.charAt(10 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
			  return false;
		numeros = cpf.substring(0,10);
		soma = 0;
		for (i = 11; i > 1; i--)
			  soma += numeros.charAt(11 - i) * i;
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
			  return false;
		return true;
		}
	else
		return false;
} 

// função pra tratar navegadores mozilla
function ehTeclaValida(prmTecla){
	return (prmTecla == 8 || prmTecla == 46 || prmTecla == 37 || prmTecla == 39 || prmTecla == 35 || prmTecla == 36 || prmTecla == 9);
}

/*****************************************************************************
* Verifica se os valores informados para os números são válidos				 *
* By Régis Gabineski Rodrigues												 *
* Data 22/07/2004															 *
******************************************************************************/

function EhNumero( e ) 
{
	if( e.keyCode )					// Internet Explorer
	{ 	var sTecla = e.keyCode;	}
	else 
	{	if( e.which )			// Nestcape
		{ 	var sTecla = e.which;	}
	}

	if ( sTecla > 47 && sTecla < 58 )	// numeros de 0 a 9
	{ 	return true;	}
	else 
	{	if ( !ehTeclaValida(sTecla) )				// backspace
		{ 	return false;	}
		else 
		{	return true;	}
	}
}

/*****************************************************************************
* Monta a mascara para os formatos especificados							 *
* By Régis Gabineski Rodrigues												 *
* Data 22/07/2004															 *
******************************************************************************/
function Mascara( sFormato, e, oObjeto )
{
	if ( EhNumero( e ) )	//Só processa as mascaras se a tecla for numérica
	{
		campo = oObjeto; //eval( oObjeto );
	
		// *** Mascara para o formato CEP ***
		// Formato: XX.XXX/XXX
		if ( sFormato == 'CEP' )
		{
			if ( campo.value.length == 2 )
			{	campo.value = campo.value + ".";	}
			if ( campo.value.length == 6 )
			{	campo.value = campo.value + "/";	}
		}
		
		// *** Mascara para o formato CPF ***
		// Formato: XXX.XXX.XX-XX
		if ( sFormato == 'CPF' )
		{
			if ( campo.value.length == 3 )
			{	campo.value = campo.value + ".";	}
			if ( campo.value.length == 7 )
			{	campo.value = campo.value + ".";	}
			if ( campo.value.length == 11 )
			{	campo.value = campo.value + "-";	}
		}
		
		// *** Mascara para o formato CNPJ ***
		// Formato: XX.XXX.XXX/XXXX-XX
		if ( sFormato == 'CNPJ' )
		{
			if ( campo.value.length == 2 )
			{	campo.value = campo.value + ".";	}
			if ( campo.value.length == 6 )
			{	campo.value = campo.value + ".";	}
			if ( campo.value.length == 10 )
			{	campo.value = campo.value + "/";	}
			if ( campo.value.length == 15 )
			{	campo.value = campo.value + "-";	}
		}
		
		// *** Mascara para o formato data ***
		// Formato: DD/MM/YYYY
		if ( sFormato == 'DATA' )
		{
			tam = campo.value.length;
			if ((tam==2) || (tam==5)) campo.value = campo.value + "/";
		}
		
		// *** Mascara para o formato data ***
		// Formato: DD/MM/YYYY
		if ( sFormato == 'HORA' )
		{
			tam = campo.value.length;
			if (tam == 2 || tam == 5) campo.value = campo.value + ":";
		}
	}
	else	//Se não for numérico, retorna false e não insere as teclas no campo
	{	return false;	}
}

function abreJanela(I, W, H){
	lpos = (screen.availWidth/2) - (W/2);
	tpos = (screen.availHeight/2) - (H/2);
	window.open(I,'janfoto','scrollbars=no,left='+lpos+',top='+tpos+',width='+W+',height='+H).focus();
}

function emailValido(src) {
	emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[a-zA-Z]$"
	var regex = new RegExp(emailReg);
	return regex.test(src);	
}

//valida a data
function isDate(prmData){
	var boolOK  = false;
	var intMaxDias = 0;
	var arrData = prmData.split('/'); // quebra num array
	
	// se for array
	if (!isNaN(arrData.length)){
		// se todos os dados são numéricos
		if ((!isNaN(arrData[0])) && (!isNaN(arrData[1])) && (!isNaN(arrData[2]))){
			// converte valores em inteiros
			arrData[0] = Number(arrData[0]);
			arrData[1] = Number(arrData[1]);
			arrData[2] = Number(arrData[2]);
			
			//se ano válido
			if (arrData[2] < 1900) {
				return false;
			}

			// se dia válido
			if (arrData[0] > 0 && arrData[0] <= 31){
				//alert(arrData[1]);
				// faz tratamento de mês
				switch (arrData[1]){
					// meses com total de 31 dias
					case 1: case 3: case 5: case 7: case 8: case 10: case 12: {
						intMaxDias = 31;
						break;
					}
					// meses com total de 30 dias
					case 4: case 6: case 9: case 11: {
						intMaxDias = 30;
						break;
					}
					// tratamento para fevereiro
					case 2: {
						// se divisível por quatro é 29 dias
						if (arrData[2] % 4 == 0){
/*							// se for divisível por 100 e 400 é ano bissexto
							if (arrData[2] % 100 == 0 && arrData[2] % 400 == 0){
								intMaxDias = 29;
							} else {// não é ano bissexto e o total é de 28 dias
								intMaxDias = 28;
							}*/
							// se for divisível por 4 é ano bissexto
							if (arrData[2] % 4 == 0 ){
								intMaxDias = 29;
							} else {// não é ano bissexto e o total é de 28 dias
								intMaxDias = 28;
							}
						} else {
							intMaxDias = 28;
						}
						
						break;
					}
				}
				//alert(intMaxDias);
				// se data igual ou menor ao total de dias no mês temos uma data válida
				boolOK = (arrData[0] <= intMaxDias);
			}
		}
	}
	
	return boolOK;
	/*
	var dma = -1;
	var data = Array(3);
	var ch = Data.charAt(0); 
	for (i=0; i < Data.length && ((ch >= '0' && ch <= '9' || (ch == '/' && i != 0))); i++){
		data[++dma] = '';
		
		if(ch!='/' && i != 0) return false;
		if(i != 0 ) ch = Data.charAt(++i);
		if(ch=='0') ch = Data.charAt(++i);
		
		while( ch >= '0' && ch <= '9' ){
			data[dma] += ch;
			ch = Data.charAt(++i);
		} 
	}
	
	if(ch!='') return false;
	if(data[0] == '' || isNaN(data[0]) || parseInt(data[0]) < 1) return false;
	if(data[1] == '' || isNaN(data[1]) || parseInt(data[1]) < 1 || parseInt(data[1]) > 12) return false;
	if(data[2] == '' || isNaN(data[2]) || ((parseInt(data[2]) < 0 || parseInt(data[2]) > 99 ) && (parseInt(data[2]) < 1900 || parseInt(data[2]) > 9999))) return false;
	if(data[2] < 50) data[2] = parseInt(data[2]) + 2000;
	else
		if(data[2] < 100) data[2] = parseInt(data[2]) + 1900;
	
	switch(parseInt(data[1])){
		case 2:
		{
			if(((parseInt(data[2])%4!=0 || (parseInt(data[2])%100==0 && parseInt(data[2])%400!=0)) && parseInt(data[0]) > 28) || parseInt(data[0]) > 29 ) return false;
			break;
		}
		
		case 4: case 6: case 9: case 11:
		{
			if(parseInt(data[0]) > 30) return false;
			break;
		}
		default:
		{
			if(parseInt(data[0]) > 31) return false;
		}
	}
	
	return true;
	*/
}

function isHour(prmHora){
	var boolOK = false;
	
	// SE STRING EM FORMATO HH:MM:SS
	if (prmHora.length == 8){
		// QUEBRA NUM ARRAY
		var arrHora = prmHora.split(':');
		
		// SE ARRAY POSSUI TRES VALORES
		if (arrHora.length == 3){
			// RETORNA TRUE SE OS VALORES SAO NUMERICOS E MINUTO/SEGUNDO NAO SUPERAR 60
			boolOK = (!isNaN(arrHora[0]) && (!isNaN(arrHora[1]) && arrHora[1] < 60) && (!isNaN(arrHora[2]) && arrHora[2] < 60));
		}
	}
	
	return boolOK;
}

//somente números são desbloqueados
function digitaNumeros(digit){
	var intTecla;
	
	if (digit.keyCode){ // IE
		intTecla = digit.keyCode;
	} else if (digit.which){ // MOZILLA
		intTecla = digit.which;
	} else {
		return true;
	}
	
	return !((intTecla < 48 || intTecla > 57) && !ehTeclaValida(intTecla));
}

//somente dígitos e vírgula são aceitos
function digitaValores(digit){
	var intTecla;
	
	if (digit.keyCode){ // IE
		intTecla = digit.keyCode;
	} else if (digit.which){ // MOZILLA
		intTecla = digit.which;
	} else {
		return true;
	}
	
	return !((intTecla < 48 || intTecla > 57) && !ehTeclaValida(intTecla));
}

//somente dígitos e barra são aceitos
function digitaDatas(digit){
	var intTecla;
	
	if (digit.keyCode){ // IE
		intTecla = digit.keyCode;
	} else if (digit.which){ // MOZILLA
		intTecla = digit.which;
	} else {
		return true;
	}
	
	return !((intTecla < 47 || intTecla > 57) && !ehTeclaValida(intTecla));
}


//vê se tem algum checkbox marcado
function marcouCheckBox(checkitem){
	selecionou = false;
	
	if (checkitem){
		if (isNaN(checkitem.length)){
			selecionou = checkitem.checked;
		} else {
			i = 0;
			
			while ((i <= (checkitem.length -1)) && (!selecionou)){
				selecionou = checkitem[i].checked;
				i++;
			}
		}
	} else {
		selecionou = false;
	}
	
	return selecionou;
}

function getData(ano, mes, dia){
	var now = new Date();
	var data = new Date(ano, mes, dia, now.getHours(),now.getMinutes(), now.getSeconds());
	return data;
}

//cria um objeto do tipo date
function createDate(dia, mesano){
	mes = mesano;
	ano = mesano;
	
	mes = mes.substring(0, 2) - 1;
	ano = ano.substring(3, ano.length);
	
	var data = getData(ano, mes, dia);//, now.getMilliseconds());
	return data;
}

//converte uma string de data no formato brasileiro em um objeto do tipo date;
function cDate(strdata){
	strdata = strdata.split('/');
	datacv  = getData(strdata[2], strdata[1] - 1, strdata[0]);
	return datacv;
}

//verifica se é numérico

function isNumeric(str){
	if (str.length == 0) {
		return false;
	} else {
		//return !isNaN(String(str.replace('.', '')).replace(',', '.'))
		return !isNaN(str.replace(',', '.'))
	}
}

//pôe o cursor no objeto e seleciona o conteúdo
function setFocus(obj){
	obj.focus();
	
	if (obj.type == 'text' || obj.type == 'textarea')
		obj.select();
}

// função para selecionar checkboxes
function marcaCheckBox(prmChk){
	if (prmChk){
		if (isNaN(prmChk.length)){
			prmChk.checked = true;
		} else {
			for (var i = 0; i < prmChk.length; i++){
				prmChk[i].checked = true;
			}
		}
	}
}

// verifica se um radio button foi selecionado
function marcouOption(prmOption){
	var i = 0;
	
	// se for somente um item (meio ilógico, mas tudo bem)
	if (isNaN(prmOption.length)){
		return prmOption.checked
	// caso contrário temos dois ou mais itens
	} else {
		// varre o array de radios até achar o primeiro selecionado
		while (i < prmOption.length && !prmOption[i].checked){
			i++;
		}
		
		// retorna valor
		return (i < prmOption.length);
	}
}

// completa valor de horas com zero à direita
function completaHora(prmCampo){
	var strAux = prmCampo.value.replace(/\D/g, '');
	var intTam = strAux.length;
	
	if (strAux != ''){
		for (var i = intTam; i <= 6; i++){
			strAux += '0';
		}
		
		prmCampo.value = strAux.substr(0, 2) + ':' + strAux.substr(2, 2) + ':' + strAux.substr(4, 2);
	}
}

// retorna uma data a partir de uma hora
function geraDataHora(prmHora){
	var dtaNow  = new Date();
	var arrHora = prmHora.split(':');
	return new Date(dtaNow.getYear(), dtaNow.getMonth(), dtaNow.getDate(), arrHora[0], arrHora[1], arrHora[2]);
}

// insere zero à esquerda caso o número seja menor que 10
function getNumeroFormatado(prmNumero){
	return ((prmNumero < 10) ? '0' : '') + prmNumero;
}

// retorna hora resultante da diferença entre hora inicial e hora final
function getDuracao(prmHoraIni, prmHoraFim){
	var lngDiferenca;
	var dtaDiferenca;
	var strResultado = '';
	
	// se ambas as horas são válidas
	if (isHour(prmHoraIni) && isHour(prmHoraFim)){
		var dtaHoraIni = geraDataHora(prmHoraIni);
		var dtaHoraFim = geraDataHora(prmHoraFim);
		
		// se hora final menor que hora inicial acrescenta um dia
		if (dtaHoraFim < dtaHoraIni)
			dtaHoraFim.setDate(dtaHoraFim.getDate() + 1);
		
		// calcula a diferença em segundos (por isso divide por 1000, já que JavaScript trabalha com milissegundos)
		lngDiferenca = (dtaHoraFim - dtaHoraIni) / 1000;
		
		// gera data a partir da diferença em segundos
		dtaDiferenca = new Date(1970, 1, 1, 0, 0, lngDiferenca);
		
		// retorna mensagem formatada ao usuário
		strResultado = getNumeroFormatado(dtaDiferenca.getHours())   + ':' + 
					   getNumeroFormatado(dtaDiferenca.getMinutes()) + ':' + 
					   getNumeroFormatado(dtaDiferenca.getSeconds());
	}
	
	return strResultado;
}

// retorna um numero formatado com tres casas decimais
function getValorToneladaFormatado(prmValor){
	return prmValor.toFixed(3);
}