/**
* @author Heber
*/
/**********************************************************************
* Framework Javascript                                                *
* Desenvolvimento : Heber Aragão 									  			 *
* Data : 23/01/2008													  				 *
* Objetivo : Esta Biblioteca tem por Objetivo a disponibilização de   *
* diversas ferramentas                                                *	
* 																	  						 *
* Biblioteca de Funções -  Tools                  					  		 *
***********************************************************************/

/*************************** Trabalhando com os objetos - Get e Set ********************/

// retorna o Objeto 
function getObj(id)
{
	var obj = document.getElementById(id);
	return obj;
}


// retorna um array com os elementos que tem aquele nome "TAG"
function getTagName(tagName,obj)
{
	if(!obj) 
		obj=document;
	if(typeof obj=="string") 
		obj=getObj(obj);
	return obj.getElementsByTagName(tagName);
}

// retorna o valor 
function getValue(id)
{
	var valor = document.getElementById(id).value;
	return valor;
}

// retorna o tamannho(comprimento) 
function getLength()
{
	var tam = document.getElementById(id).value.length;
	return tam;
}

// seta o foco em algum objeto
function setFocus(obj)
{
	getObj(obj).focus();
}

// habilita objetos do form
function setEnabled(obj)
{
	getObj(obj).disabled = false;				
}

// desabilita objetos do form
function setDisabled(obj)
{	
	getObj(obj).disabled = true;		
}

// limpa a div de status
function limpaDiv(id)
{
	getObj(id).innerHTML = "";
}

// torna o objeto visivel
function setVisible(obj)
{
	getObj(obj).style.visibility = "visible";
}

// torna o objeto invisivel
function setHidden(obj)
{
	getObj(obj).style.visibility = "hidden";
}


/* exclui o objeto passado */
function delObj(obj)
{
	obj.parentNode.removeChild(obj);
}

/* insere um obj [n] antes de outro objeto [o] */
function insertBefore(n,o)
{
	o.parentNode.insertBefore(n,o);
}

/* substitui o obj [o] pelo obj [n] */
function replaceObj(n,o)
{
	o.parentNode.replaceChild(n,o);
}

/* cria um novo elemento e aplica um texto [innerHTML] */
function newObj(tagName,innerHTML)
{
	var novo=document.createElement(tagName);
	if(innerHTML)
		novo.innerHTML=innerHTML;
	return novo;
}

// cria um evento na página -- obj = onde será executado o evento, evType = o evento, fn = Função que será executada 
function createEvent(obj,evType,fn)
{
	try
	{
   		obj.addEventListener(evType,fn,true);
   	}
   	catch(e)
   	{
   		obj.attachEvent("on"+evType,fn);
  	}
}

// Cancela um evento na página
function cancelEvent(e)
{
	if(e.preventDefault)
  		e.preventDefault();
  	return false;
}

/************************************ Formatando Campos de Form *******************************/


// formata a data enquanto digita
function formataData(id)
{	
	var data = getObj(id);
	if ((data.value.length == 2)||(data.value.length == 5))
	{					
		data.value = data.value+"/";							
	}		
}

// função js que formata um cep enquanto um usuario digita
function formataCep(id)
{
	var obj = getObj(id);
	if(obj.value.length == 5)
	{
		obj.value = obj.value+"-";
	}
}

// função js que formata um valor R$ 
function formataValor(id)
{
	var obj = getObj(id);
	if(obj.value != "")
	{
		obj.value = arredonda(obj.value);
	}
}

// arredonda o numero para duas casas decimais
function arredonda(num)
{
	return Math.round(num*100)/100; 
}

// formata fone ao digitar
function formataFone(id)
{ 
	var nome = getObj(id);
	if (nome.value.length == 1)
	{
		nome.value = "("+nome.value;
	}
	if (nome.value.length == 3)
	{
		nome.value = nome.value+")";
	}
	if (nome.value.length == 8)
	{					
		nome.value = nome.value+"-";							
	}			
}

// validação de CPF
function validaCPF(id) 
{
		 var cpf = getValue(id);
		 var erro = new String;
		 if (cpf.length < 11) 
		 	erro += "Sao necessarios 11 digitos para verificacao do CPF! "; 
		 var nonNumbers = /\D/;
		 if (nonNumbers.test(cpf)) 
		 	erro += "A verificacao de CPF suporta apenas numeros! "; 
		 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
		 {
		 	erro += "Numero de CPF invalido!"
		 }
		 var a = [];
		 var b = new Number;
		 var c = 11;
		 for (i=0; i<11; i++)
		 {
		 	a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] * --c);
		 }
		 if ((x = b % 11) < 2) 
		 { 
		 	a[9] = 0 
		 } 
		 else 
		 { 
		 	a[9] = 11-x 
		 }
		 b = 0;
		 c = 11;
		 for (y=0; y<10; y++) 
		 	b += (a[y] * c--); 
		 if ((x = b % 11) < 2) 
		 { 
		 	a[10] = 0; 
		 } 
		 else 
		 { 
		 	a[10] = 11-x; 
		 }
		 if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
		 {
		 	erro +="Digito verificador com problema!";
		 }
		 if (erro.length > 0)
		 {
		  	   alert(erro);
			   document.getElementById(id).focus();
			   return false;
		 }
		 return true;
}

// validação de CNPJ
function validaCNPJ(val) 
{  
	var cnpj = document.getElementById(val).value;  
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;  
	digitos_iguais = 1;  
	for (var i=0; i < cnpj.length - 1; i++)  
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)) 
		{  
			digitos_iguais = 0;  
			break;  
		}  
	if (!digitos_iguais) 
	{  
		tamanho = cnpj.length - 2  
		numeros = cnpj.substring(0,tamanho);  
		digitos = cnpj.substring(tamanho);  
		soma = 0;  
		pos = tamanho - 7;  
		for (var i=tamanho; i >= 1; i--) 
		{  
			soma += numeros.charAt(tamanho - i) * pos--;  
			if (pos < 2) 
			{  
				pos = 9;  
			}  
		}  
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;  
		if (resultado != digitos.charAt(0)) 
		{  
	   		return false;  
		}  
		tamanho = tamanho + 1;  
		numeros = cnpj.substring(0,tamanho);  
		soma = 0;  
		pos = tamanho - 7;  
		for (i = tamanho; i >= 1; i--) 
		{  
	    	soma += numeros.charAt(tamanho - i) * pos--;  
			if (pos < 2) 
			{  
	   			pos = 9;  
			}  
		}  
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;  
		if (resultado != digitos.charAt(1)) 
		{  
	   		return false;  
		}  
		return true;  
	}  
	else  
	return false;  
}  

// retira caracteres invalidos da string
function Limpar(valor, validos) 
{
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) 
	{
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) 
		{
			result += aux;
		}
	}
	return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function formataMoeda(campo,tammax,teclapres,decimal) 
{
	var tecla = teclapres.keyCode;
	vr = Limpar(campo.value,"0123456789");
	tam = vr.length;
	dec=decimal

	if (tam < tammax && tecla != 8)
	{ 
		tam = vr.length + 1 ; 
	}
	if (tecla == 8)
	{ 
		tam = tam - 1 ; 
	}
	if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
	{
		if (tam <= dec)
		{ 
			campo.value = vr ; 
		}
		if ((tam > dec) && (tam <= 5))
		{
			campo.value = vr.substr(0, tam - 2) + "," + vr.substr(tam - dec, tam) ; 
		}
		if ((tam >= 6) && (tam <= 8))
		{
			campo.value = vr.substr(0, tam - 5) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam) ; 
		}
		if ((tam >= 9) && (tam <= 11))
		{
			campo.value = vr.substr(0, tam - 8) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam) ; 
		}
		if ((tam >= 12) && (tam <= 14))
		{
			campo.value = vr.substr(0, tam - 11) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - dec, tam) ; 
		}
		if ((tam >= 15) && (tam <= 17))
		{
			campo.value = vr.substr(0, tam - 14) + "." + vr.substr(tam - 14, 3) + "." + vr.substr(tam - 11, 3) + "." + vr.substr(tam - 8, 3) + "." + vr.substr(tam - 5, 3) + "," + vr.substr(tam - 2, tam) ;
		}
	} 
}


/******************************* Trabalhando com Forms e PopUp ************************/


// seta a variável de popUp
var popUpWin = 0;

// carrega uma página
function carregaPagina(url,div)
{
	// div que exibirá o resultado
	var divResult = getObj(div); 
			
	// Instancia o Ajax. 
	var ajx = new ajax("POST",url,"application/x-www-form-urlencoded",divResult); 
		
	// abre o ajax chamando o arquivo
	ajx.openAjax(1,"","");		
	
	// envia os parametros
	ajx.envia("","Carregando...");
}


// carrega uma página e executa a função
function carregaPaginaExec(url,div,cod_exec)
{
	// div que exibirá o resultado
	var divResult = getObj(div); 
			
	// Instancia o Ajax. 
	var ajx = new ajax("POST",url,"application/x-www-form-urlencoded",divResult); 
		
	// abre o ajax chamando o arquivo
	ajx.openAjax(1,"","");		
	
	// envia os parametros
	ajx.enviaExecuta("","Carregando...",cod_exec);
}

// chama uma página como popup
function abrePopup(url,left,top,width,height)
{
	if(popUpWin)
	{
		if(!popUpWin.closed) 
			popUpWin.close();
	}	
  	popUpWin = open(url, 'popUpWin','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}


// abre um relatório 
function abreRel(url,ar,width,height)
{	
	var pagina = url+"?"+montaUrl(ar);	
	abrePopup(pagina,200,100,width,height);
}

// função que limpa o formulário
function limpaForm(array)
{
	for(i = 0; i < array.length;i++)
	{			
		var obj = getObj(array[i]);				
		obj.value = "";				
	}		
}


// função que identifica quando pressionar o ENTER
function enter(event,funcao)
{
	var	tecla = event.keyCode;		
	if(tecla == 13)
	{		
		eval(funcao);		
	}
}

// marca uma linha selecionada
function marcaSelecao(id,cor1,cor2)
{
	if(ifIsSet(lista)) // se já está selecionado
	{			
		getObj(lista.pop()).style.backgroundColor = cor1; // desmarca a linha					
		lista.push(id);			
		getObj(id).style.backgroundColor = cor2;		
	}
	else // se não esta selecionado
	{		
		getObj(id).style.backgroundColor = cor2;
		lista.push(id);		
	}	
}

// pega os valores de um formulário pelo array
function montaParam(array)
{
	var param = "";
	for(i = 0; i < array.length; i++)
	{
		if((array.length > 1)&&(i < array.length)&&(i > 0))			
			param = param+"&";
		param = param+array[i]+"="+getValue(array[i]);						
	}
	return param;
}

// pega os valores de um formulário pelo array
function montaParamVal(ar_campo,ar_val)
{
	var param = "";
	for(i = 0; i < ar_campo.length; i++)
	{
		if((ar_campo.length > 1)&&(i < ar_campo.length)&&(i > 0))			
			param = param+"&";
		param = param+ar_campo[i]+"="+ar_val[i];				
	}
	return param;
}

// limpa o valor dos campos do formulário
function limpaCampos(array)
{
	for(i = 0; i < array.length; i++)
	{
		getObj(array[i]).value = "";				
	}
}

// função js genérica que valida um formulário, para utilizar basta informar no array os campos a serem validados
function validaForm(form,campos)	
{		 
	for(i = 0; i <= campos.length - 1; i++)
	{				
		if((getValue(campos[i]) == "")||(getValue(campos[i]) == "#"))
		{
			alert("Você deve preencher o campo "+campos[i]);
			getObj(campos[i]).focus();
			return false;
		}			
	}	
	//getObj(form).submit();
	return true;
			
}

// captura os elementos do form que tem um valor e transforma em um array com os nomes dos elementos
function FormArray(frm)
{		
	var ar = new Array();
	var cont = 0;
	for(var i = 0; i < frm.length; i++)
	{			
		var elem = frm.elements[i];			
		if(elem.type == "text")
		{
			if((elem.value != null)&&(elem.value != "")&&(!isBlank(elem.value))&&(elem.value != "NaN"))
			{
				if(elem.name.substr(0,1) == "1")
				{
					ar[cont]= elem.name;
					cont++;
				}
			}
		}
	}
	return ar;
}

//
function loadCheckbox(qtde,prefix)
{
	var ar = new Array();
	var cont = 0;	
	for(i = 1; i <= qtde; i++)
	{			
		var nome  = getObj(prefix+i);		
		if(nome.checked)
		{
			ar[cont] = nome.value;
			cont++;
		}		
	}
	return ar;
}

/******************************  Trabalhando com Strings  *******************************/

// verifica se uma string só contem espaços vazios
function isBlank(str)
{
	for(var i = 0; i < str.length; i++)
	{
		var caract = str.charAt(i);
		if((caract != ' ')&&(caract != '\n')&&(caract != ''))
			return false;
	}
	return true;
}


// busca um valor dentro de um texto
function buscaParcial(texto,valor)
{
	var ret = texto.search(valor);	
	if(ret > -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}


/*****************************  Trabalhando com Arrays **********************************/

// monta uma url com o array passado por parametro
function montaUrl(ar)
{		
	var url = "";
	for(i=0;i<=ar.length-1;i++)
	{		
		url = url+ar[i]+"="+getValue(ar[i])+"&";
	}
	return url;
}

// verifica se já existe algum elemento no array
function ifIsSet(array)
{
	num = array.length;	
	if(num > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// retorna a resoluão da tela
function heightPagina()
{
	var xScroll, yScroll;
	if(window.innerHeight && window.scrollMaxY) 
	{
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight) // todos os navegadores
	{
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} 
	else 
	{ // Para Mac...trabalha também com Explorer 6, Mozilla e Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) 	// todos exceto Explorer
	{
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 
	{
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} 
	else if (document.body)  // outros navegadores
	{
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	// para páginas pequenas com altura total menos a altura do viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	} 
	else 
	{
		pageHeight = yScroll;
	}
	return pageHeight;
}

// retorna a posição do elemento
function getTopElement(compId)
{
	var offsetTrail = document.getElementById(compId);
	var offsetTop = 0;
	while (offsetTrail) 
	{
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
	{
		offsetTop += document.body.topMargin;
	}
	return offsetTop;
}
// retona a posição do elemento coordenada X e Y
function getPosicaoElemento(elemID)
{
    var elemento = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (elemento) 
    {
        offsetLeft += elemento.offsetLeft;
        offsetTop += elemento.offsetTop;
        elemento = elemento.offsetParent;
    }
    // para IE6
    if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
    {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function formata_fone(nome)
{ 
	if (nome.value.length == 1)
	{
		nome.value = "("+nome.value;
	}
	if (nome.value.length == 3)
	{
		nome.value = nome.value+")";
	}
	if (nome.value.length == 8)
	{					
		nome.value = nome.value+"-";							
	}			
}

function VerificaCaracteres(caracter){
	if(window.event) { // Internet Explorer
	var tecla = event.keyCode;
	}
	else { // Firefox
	var tecla = caracter.which;
	}
	if (tecla >= 48 && tecla <= 57){
		return true;
	} else	if (tecla >= 65 && tecla <= 90){
		return true;
	} else if (tecla >= 97 && tecla <= 122){
		return true;
	} else {
		if (tecla != 0 && tecla != 13 && tecla != 8 && tecla != 95){
			alert('Caracter inválido');
			return false;
		}
	}
}
