
/******************************************************************************/
/*	UTILS.JS
Responsavel: Jefferson José Gomes
Setor: Informática
Ultima Atualizacao: 27/11/2006
*/
/******************************************************************************/

// Removes leading whitespaces
function LTrim( value ) {

	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim( value ) {

	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trimALL( value ) {

	return LTrim(RTrim(value));

}

/**
*Função que anula o efeito da tecla F5, se colocada no body não atualiza, porém, em campos de
*texto ela funciona. Para que ela não funcione em campos de texto, deve-se colocar em seus
*respectivos eventos.
*
*@autor: desconhecido (descoberta por Giovani Marin)
*@date: 07/07/2007 - 15:35:00
*/
function anulaTeclaF5() {

	var tecla=window.event.keyCode;

	if (tecla==116) {
		event.keyCode=0;
		event.returnValue=false;
	}
}

//String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };




/******************************************************************************/
/*	Funcoes: w(<texto>) e wln(<texto>)
Parametros:
- texto: Texto html a ser inserido na pagina
Retorno: nenhum
Descricao: Simplificam a sintaxe no codigo javascript*/
/******************************************************************************/
function w( texto)
{
	document.write( texto);
}

function wln( texto)
{
	document.writeln( texto);
}

/******************************************************************************/
/*	Funcao: popup(<url>, <nome_janela>[,atributos])
Parametros:
- url: Url a ser aberta na nova janela
- janela: Nome da janela que sera' criada
- atributos: Caracteristicas da janela, que devem ser seguir a sintaxe da
funcao padrao window.open
Retorno: O objeto correspondente a janela criada.
*/
/******************************************************************************/
function popup(url,janela,atributos)
{
	var WinPop =  window.open(url, janela, atributos);
	WinPop.focus();
}

function popupRandom(url,janela,atributos)
{
	if (parent.getRandomPopupName) {
		janela = parent.getRandomPopupName();
	}
	
	var WinPop =  window.open(url, janela, atributos);
	WinPop.focus();
}

/******************************************************************************/
/*	Funcao: random(n1, n2)
Parametros:
- n1: intervalo inferior
- n2: intervalo superior
Retorno: Inteiro
Descricao: Retorna um valor inteiro randomico entre os valores especificados.
*/
/******************************************************************************/
function random(r1, r2) {
	if (r2 > r1) return (Math.round(Math.random()*(r2-r1))+r1);
	else return (Math.round(Math.random()*(r1-r2))+r2);
}

function copiaArray(baseArray)
{
	var novoArray = new Array();
	for(var i=0; i < baseArray.length; i++)
	{
		novoArray[i] = new String (baseArray[i]);
	}
	return novoArray;
}


function isSelect( campo, arraySelects) {
	if( arraySelects == null) return false;
	for( var i=0; i< arraySelects.length; i++)
	{
		if( arraySelects[i] == campo)
		{
			return true;
		}
	}
	return false;
}


function isNull(checkString)
{
	var nulo=true,
	ch,
	str= new String(checkString);
	if(str.length == 0)
	return true;
	else
	{
		for (i=0; i<str.length; i++)
		{
			ch=str.substring(i,i+1);
			if (ch!='\r' && ch!='\n' && ch!=' ')
			return false;
		}
		return true;
	}
}

/******************************************************************************/
/*        Funcao: isValidEmail(s)
Parametros:
- s: string contendo o email a ser verificado
Retorno: boolean
Descricao: Retorna um valor booleano se o email está dentro dos padrões
*/
/******************************************************************************/
function isValidEmail(s) {


		if (s == '') return true;
		if (s.indexOf("@") == -1) return false;
		if (s.indexOf(".") == -1) return false;
		at=false;
		dot=false;
		if (s.charAt(s.length-1) == '.'){
			return false;
		}
		for (var i = 0; i < s.length; i++) {
			ch = s.substring(i, i + 1)
			if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z")
			|| (ch == "@") || (ch == ".") || (ch == "_")
			|| (ch == "-") || (ch >= "0" && ch <= "9")) {
				if (ch == "@"){
					if (at) return false;
					else at=true;
				}
				if ((ch==".") && at)
				dot=true;
			}
			else return false;
		}

	return dot;
}


/******************************************************************************/
/*      Funcao: verificaDatas(dataI, dataF )
Parametros:
- dataI: string contendo a data inicial
- dataF: string contendo a data final
Retorno: boolean
Descricao: Retorna um valor booleano se a data final é maior q a data inicial
*/
/******************************************************************************/
function verificaDatas(dataI, dataF )  {
	var dataInicial = dataI.split("/");
	dataInicial = new Date(dataInicial[2], ( parseInt(dataInicial[1]) -1 ), dataInicial[0],0,0,0);

	var dataFinal = dataF.split("/");
	dataFinal = new Date(dataFinal[2], ( parseInt(dataFinal[1]) -1 ), dataFinal[0],0,0,0);
	if (dataFinal >= dataInicial) {
		return true;
	} else {
		return false;
	}
}


function ConSeCart(text){
	var nrLetras = '';
	for (i=0; i<text.length; i++){
		nrLetras = nrLetras + ((i+2) * text.charCodeAt(i));
	}
	return nrLetras;
}


function valCart(txt, campo, nrBinConvenio)
{
	if (txt.substring(0, 8) == nrBinConvenio) {
		return valCartConvenio(txt, campo);
	} else {
		if (txt != '') {
			var dv = getDigControle( txt.substr( 0, (txt.length-1) ) );
			if ( txt.substr( 0, (txt.length-1) ) + dv  != txt ) {
				alert('O Número do cartão não é válido...');
				if (campo != undefined){
					campo.focus();
				}
				return false;
			} else {
				return true;
			}
		}
	}
}

function valCartConvenio(txt, campo)
{
	if (txt.length > 0) {
		if (txt.length == 16) {
			if (valor_cartao_nexxera < txt) {
				var dv = getDigControle(txt.substr(0, (txt.length-1)));
				if (txt.substr(0, (txt.length-1)) + dv  != txt ) {
					alert('O Número do cartão não é válido...');
					if (campo != undefined){
						campo.focus();
					}
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		} else {
			alert("O número do cartão precisa ser digitado com 16 dígitos numéricos");
			campo.focus();
			campo.value = '';
			return false;
		}
	}
}

function getDigControle(txt)
{
	var soma = 0;
	var multI = 0;
	var multS = '';

	for (var i = 0; i < txt.length; i++) {
		multI = fator_dig_controle_cartoes[i] * txt.charAt(i);
		multS = new String(multI)

		for (var j = 0; j < multS.length; j++) {
			soma = soma + parseInt(multS.charAt(j));
		}
	}

	var dv = 10 - (soma % 10);

	if (dv > 9) {
		return 1;
	} else {
		return dv;
	}
}


/**************************************************************************************************/
/*      Funcao: getExtensaoArq(CampoPath, ArrayExtensao){
Parametros:
- CampoPath: caminho do arquivo que vai ser enviado
- ArrayExtensao: array com as extensoes que são aceitas pelo campo do arquivo
Retorno: nenhum
Descricao: Exibe uma mensagem se o arquivo não for do tipo
*/
/**************************************************************************************************/

function getExtensaoArq(CampoPath, ArrayExtensao){
	if (CampoPath.value != "") {
		var extArquivo = CampoPath.value.substr(CampoPath.value.length - 3, CampoPath.value.length);
		extArquivo = extArquivo;
		var extensaoValida = false;
		var strListaExtensao = '';



		for (var i=0; i<ArrayExtensao.length; i++ ) {
			strListaExtensao = strListaExtensao + "   - " + ArrayExtensao[i] + "\n";
			if ( ArrayExtensao[i] == extArquivo.toUpperCase() ) {
				extensaoValida = true;
			}
		}

		if (! extensaoValida ) {
			alert('O arquivo selecionado precisa ser de um desses tipos:    \n \n' + strListaExtensao );
			CampoPath.select();
			CampoPath.focus();
		}
	}
}



/******************************************************************************/
/* Funcao: adicionaCaracter(string, charAdd, qtd , posicao)
Parametros:
- string: valor original da string
- charAdd  : string a ser adicionada a string original
- qtd     : quantidade maxima que deve ter a string no retorno
- posicao : se a string sera adicionada a direita ou a esquerda (D - E)
Retorno: string original com a adicao das strings solicitadas.
*/
/******************************************************************************/
function adicionaCaracter(string, charAdd, qtd , posicao){
	var adicionar = "";
	for( i=string.length; i < qtd; i++ ) {
		adicionar += charAdd;
	}
	if (posicao == "D") {
		return string + adicionar;
	} else if (posicao == "E")  {
		return adicionar + string;
	} else {
		return string;
	}
}




/**************************************************************************************************/
/*      Funcao: imgDbManager(acao, NmeCampo, TituloCampo, tamCampo, extAceitas){
Parametros:
- acao: string contendo a descrição da ação que vai ser executada
- NmeCampo: string contendo o nome do campo
- TituloCampo: string contendo o título do campo
- tamCampo: numerico contendo o tamanho do campo para alteração do arquivo
- extAceitas: array com as extensoes que são aceitas pelo campo do arquivo
Retorno: nenhum
Descricao: Exibe ferramentas pra manipular imagens como cadastro, alteração e exclusão
*/
/**************************************************************************************************/
function imgDbManager(acao, NmeCampo, TituloCampo, tamCampo, arrayExtAceitas, path){
	layer = document.getElementById('LAYER_'+NmeCampo);
	var arrayExtAceitasOrig = arrayExtAceitas;

	var auxExt = '';
	for(var i=0; i<arrayExtAceitas.length; i++){
		if ( ( i > 0 ) && ( arrayExtAceitas.charAt(i) == "'" ) ) {
			if ( arrayExtAceitas.charAt(i-1) == "\\" ) {
				auxExt = auxExt + arrayExtAceitas.charAt(i);
			} else {
				auxExt = auxExt + "\\\'";
			}
		} else {
			auxExt = auxExt + arrayExtAceitas.charAt(i);
		}
	}

	arrayExtAceitas = auxExt;

	eval("var imagem = IMAGEM_"+NmeCampo+";");
	if ( acao == 'troca_imagem' ) {
		layer.innerHTML = '    <div id="div_Img_'+NmeCampo+'"><input class="formulario" type="file" name="'+NmeCampo+'" size="'+tamCampo+'" onblur="getExtensaoArq(this, '+arrayExtAceitasOrig+')"><br>'+
		'     <a href="javascript:void(0)" onclick="imgDbManager(\'\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\', \''+path+'\')"><span class="fonte_formato">não alterar imagem</span></a></div>';
	} else if ( acao == 'exclui_imagem' ) {
		layer.innerHTML = ' <table border=\"0\" cellpadding=\"0\" cellspacing=\"3\">'+
		'   <tr>'+
		'     <td>'+
		'       <table border=\"0\" class=\"bordaImg\" cellpadding=\"0\" cellspacing=\"3\">'+
		'         <tr>'+
		'            <td align=\"center\" valign=\"middle\"><img src=\"'+path+'imagens/sem_imagem.gif\"><input type=\"hidden\" name=\"'+NmeCampo+'\"></td>'+
		'         </tr>'+
		'       </table>'+
		'     </td>'+
		'     <td>'+
		'       <div id="div_Img_'+NmeCampo+'">'+
		'       <table border=\"0\" cellpadding=\"0\" cellspacing=\"5\">'+
		'         <tr>'+
		'            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\', \''+path+'\')\"><span class=\"fonte_normal\">não excluir imagem</a></span></td>'+
		'         </tr>'+
		'       </table>'+
		'       </div>'+
		'     </td>'+
		'   </tr>'+
		' </table>';
	} else {
		layer.innerHTML = ' <table border=\"0\" cellpadding=\"0\" cellspacing=\"3\">'+
		'   <tr>'+
		'     <td>'+
		'       <table border=\"0\" class=\"bordaImg\" cellpadding=\"0\" cellspacing=\"3\">'+
		'         <tr>'+
		'            <td>'+imagem+'</a></td>'+
		'         </tr>'+
		'       </table>'+
		'     </td>'+
		'     <td>'+
		'       <div id="div_Img_'+NmeCampo+'"> '+
		'       <table border=\"0\" cellpadding=\"0\" cellspacing=\"5\">'+
		'         <tr>'+
		'            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'troca_imagem\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\', \''+path+'\')\"><span class=\"fonte_normal\">alterar imagem</span></a></td>'+
		'         </tr>'+
		'         <tr>'+
		'            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'exclui_imagem\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\', \''+path+'\')\"><span class=\"fonte_normal\">excluir imagem</a></span></td>'+
		'         </tr>'+
		'       </table>'+
		'       </div> '+
		'     </td>'+
		'   </tr>'+
		' </table>';
	}
}

var nmeCampoDivImg = new Array();

function trataTravamentoImagens(){
	for (var i=0; i<nmeCampoDivImg.length; i++) {
		div = document.getElementById('div_Img_'+nmeCampoDivImg[i]);
		if (div != null) {
			if ( div.style.display == '' ) {
				div.style.display = 'none';
			} else {
				div.style.display = '';
			}
		}
	}
}



/**************************************************************************************************/
/*      Funcao: retiraAcentos(texto){
Parametros:
- texto: campo string com o conteúdo a ser verificado
Retorno: string convertida em sem acentuação
Descricao: Converte uma string para maiúsculo e remove acentuações e caracteres delimitadores de String
*/
/**************************************************************************************************/
function retiraAcentos(texto){
	texto = texto.toUpperCase();
	var novoTexto = '';
	for (i=0; i<texto.length; i++) {
		switch (texto.charAt(i)) {
			case "Á" : novoTexto = novoTexto + 'A'; break;
			case "É" : novoTexto = novoTexto + 'E'; break;
			case "Í" : novoTexto = novoTexto + 'I'; break;
			case "Ó" : novoTexto = novoTexto + 'O'; break;
			case "Ú" : novoTexto = novoTexto + 'U'; break;
			case "Ý" : novoTexto = novoTexto + 'Y'; break;

			case "Ä" : novoTexto = novoTexto + 'A'; break;
			case "Ë" : novoTexto = novoTexto + 'E'; break;
			case "Ï" : novoTexto = novoTexto + 'I'; break;
			case "Ö" : novoTexto = novoTexto + 'O'; break;
			case "Ü" : novoTexto = novoTexto + 'U'; break;
			case "Ÿ" : novoTexto = novoTexto + 'Y'; break;

			case "À" : novoTexto = novoTexto + 'A'; break;
			case "È" : novoTexto = novoTexto + 'E'; break;
			case "Ì" : novoTexto = novoTexto + 'I'; break;
			case "Ò" : novoTexto = novoTexto + 'O'; break;
			case "Ù" : novoTexto = novoTexto + 'U'; break;

			case "Â" : novoTexto = novoTexto + 'A'; break;
			case "Ê" : novoTexto = novoTexto + 'E'; break;
			case "Î" : novoTexto = novoTexto + 'I'; break;
			case "Ô" : novoTexto = novoTexto + 'O'; break;
			case "Û" : novoTexto = novoTexto + 'U'; break;

			case "Ã" : novoTexto = novoTexto + 'A'; break;
			case "Õ" : novoTexto = novoTexto + 'O'; break;
			case "Ñ" : novoTexto = novoTexto + 'N'; break;

			case "Ç" : novoTexto = novoTexto + 'C'; break;

			default: novoTexto = novoTexto + texto.charAt(i);
		}
	}

	return novoTexto;
}




//*****************************************************************************
//* Funções o <tr> da lista
//*****************************************************************************
var objOn=null;

//*****************************************************************************
//* Utilizado para mudar o estilo conforme passa-se sobre o item
//*****************************************************************************
function ChangeClass(obj, classe)
{
	if (obj) {
		if (obj.className != 'gridListSelected') {
			obj.className=classe+'On'; //usa o estilo que indica que está sobre ele
		}
	}
}

//*****************************************************************************
//* Utilizado para mudar o estilo ao default após ter mudado de item (chamado pela função ChangeClass()
//*****************************************************************************
function ChangeClassOff(obj,classe)
{
	if (obj) {
		if (obj.className != 'gridListSelected') {
			obj.className = classe;
		}
	}
}



/**************************************************************************************************/
/*      Funcao: habilitaCampos(form){
Parametros:
- form: Formulário em que seus campos serão ativados/desativados
Retorno: nenhum
Descricao: Desativa/Ativa todos os campos de um formulário
*/
/**************************************************************************************************/
function habilitaCampos(form){
	for (var i=0; i<form.elements.length; i++) {
		form.elements[i].disabled = !form.elements[i].disabled;
		if ( form.elements[i].type != "button") {
			if ( (form.elements[i].type != "radio") && (form.elements[i].type != "checkbox") ){
				if (form.elements[i].disabled) {
					form.elements[i].style.border = "1px solid #CCCCCC";
				} else {
					form.elements[i].style.border = "1px solid #BFB8BF";
				}
			}
			if (form.elements[i].disabled) {
				form.elements[i].style.backgroundColor = "#ECECEC";
			} else {
				form.elements[i].style.backgroundColor = "#FFFFFF";
			}
		}
	}
}


/**************************************************************************************************/
/*      Funcao: habilitaCampo(campo){
Parametros:
- campo: Campo será ativado/desativado
Retorno: nenhum
Descricao: Desativa/Ativa um determinado campo
*/
/**************************************************************************************************/
function habilitaCampo(campo){

	if ( (campo.disabled) || (campo.readOnly) ) {
		campo.style.border = "1px solid #CCCCCC";
		campo.style.backgroundColor = "#ECECEC";
	} else {
		campo.style.border = "1px solid #BFB8BF";
		campo.style.backgroundColor = "#FFFFFF";
	}
}


/**************************************************************************************************/
/*      Funcao: setFormReadOnly(form, travar){
Parametros:
- form: formulário que terá seus campos manipulados
- travar: booeano para o status do campo Bloqueiar/Desbloquear
Retorno: nenhum
Descricao: Bloqueia/Desbloqueia todos os campos de um formulário para edição
*/
/**************************************************************************************************/
function setFormReadOnly(form, travar){
    if (travar == undefined) {
      travar = false;
    }
    for (var i=0; i<form.elements.length; i++) {        
        if ( (form.elements[i].type != "radio") && (form.elements[i].type != "checkbox") && (form.elements[i].type != "select-one") ){
            form.elements[i].readOnly = travar;        
        } else {
            form.elements[i].disabled = travar;
        }
    }
}

/**************************************************************************************************/
/*      Funcao: selecionaItemCombo(form){
Parametros:
- campo: Campo do tipo SELECT
- valor: Valor a ser selecionado no SELECT
Retorno: nenhum
Descricao: Seleciona um valor em um Select
*/
/**************************************************************************************************/
function selecionaItemCombo(campo, valor){
	for (var i=0; i<campo.options.length; i++) {
		if (campo.options[i].value == valor) {
			campo.selectedIndex = i;
			break;
		}
	}
}



/**************************************************************************************************/
/*      Funcao: selecionaTodosChecks(form){
Parametros:
- form: Formulario onde os checkboxes estão
Retorno: nenhum
Descricao: Muda o atributo para CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
function selecionaTodosChecks(form){
	for (var i=0; i<form.elements.length; i++) {
		if ( form.elements[i].type == "checkbox") {
			form.elements[i].checked = true;
		}
	}
}

/**************************************************************************************************/
/*      Funcao: inverteSelecaoChecks(form){
Parametros:
- form: Formulario onde os checkboxes estão
Retorno: nenhum
Descricao: Inverte o estado de CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
function inverteSelecaoChecks(form){
	for (var i=0; i<form.elements.length; i++) {
		if ( form.elements[i].type == "checkbox") {
			form.elements[i].checked = !form.elements[i].checked;
		}
	}
}

/**************************************************************************************************/
/*      Funcao: retiraSelecaoCkecks(form){
Parametros:
- form: Formulario onde os checkboxes estão
Retorno: nenhum
Descricao: Muda o atributo para NÃO CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
function retiraSelecaoCkecks(form){
	for (var i=0; i<form.elements.length; i++) {
		if ( form.elements[i].type == "checkbox") {
			form.elements[i].checked = false;
		}
	}
}

/**************************************************************************************************/
/*      Funcao: existeCheckSelecionado(form){
Parametros:
- form: Formulario onde os checkboxes estão
Retorno: existe ou não um campo checkbox selecionado
Descricao: Retorna a existencia ou não de um campo checkbox selecionado
*/
/**************************************************************************************************/
function existeCheckSelecionado(form){
	var retorno = false;
	for (var i=0; i<form.elements.length; i++) {
		if ( form.elements[i].type == "checkbox") {
			if (form.elements[i].checked ) {
				retorno = true;
				break;
			}
		}
	}
	return retorno;
}



/**************************************************************************************************/
/*      Funcao: redimensionaJanelaCentralizando(width, height){
Parametros:
- width: nova largura
- height: nova altura
Retorno: nenhum
Descricao: Redimensiona uma janela popup e a centraliza no desktop
*/
/**************************************************************************************************/
function redimensionaJanelaCentralizando(width, height){
	var screenW = screen.availWidth;
	var screenH = screen.availHeight;
	var winW;
	var winH;

	if ( (width != '') || (height != '') ) {
		self.resizeTo(width, height);
	}

	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
		}
	}

	self.moveTo(( (screenW - winW) / 2 ), ( (screenH - winH) / 2 ) - 15);
}


function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	curleft += obj.x;
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	curtop += obj.y;
	return curtop;
}



function preencheCombo2Niveis(Indice, CampoDest, arrayDados) {

	while ( CampoDest.options.length >0 ) {
		CampoDest.options[0] = null;
	}

	CampoDest.options[CampoDest.options.length] = new Option();
	var j = CampoDest.options.length

	if (parseInt(Indice) >= 0) {
		for (i = 0; i < arrayDados[Indice].length; i++) {
			CampoDest.options[j] = new Option(arrayDados[Indice][i][1], arrayDados[Indice][i][0]);
			j++;
		}
	}

}

function converteMaiuscula(event)
{
	evt = (event) ? event : (window.event) ? event : null;
	if (evt) {
		var charCode = (evt.charCode) ? evt.charCode :
		((evt.keyCode) ? evt.keyCode :
		((evt.which) ? evt.which : 0));
		var tecla = String.fromCharCode(charCode).toUpperCase();
		event.keyCode = tecla.charCodeAt(0);
	}
}

function converteMinuscula(event){
	evt = (event) ? event : (window.event) ? event : null;
	if (evt) {
		var charCode = (evt.charCode) ? evt.charCode :
		((evt.keyCode) ? evt.keyCode :
		((evt.which) ? evt.which : 0));
		var tecla = String.fromCharCode(charCode).toLowerCase();
		event.keyCode = tecla.charCodeAt(0);
	}
}


function formataFloat(num, isMoney){
	x = 0;

	if(num<0) {
		num = Math.abs(num);
		x = 1;
	}
	if(isNaN(num)) {
		num = "0";
	}
	cents = Math.floor((num*100+0.5)%100);

	num = Math.floor((num*100+0.5)/100).toString();

	if(cents < 10) {
		cents = "0" + parseInt(cents);
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3))+'.' + num.substring(num.length-(4*i+3));
	}
	if (isMoney) {
		ret = num + ',' + cents;
	} else {
		ret = num;
		//if (cents != '00') {
		ret = ret + ',' + cents;
		//}
	}
	if (x == 1) {
		ret = ' - ' + ret;
	}
	
	return ret;
}

function StringToFloat(valor){
	valor = valor.replace(/\./g,"");
	valor = valor.replace(",",".");

	return parseFloat(valor);
}

function str_pad(input, pad_length, pad_string, pad_type)
{
	input = String (input);
	pad_string = pad_string != null ? pad_string : " ";
	if (pad_string.length > 0) {
		var padi = 0;
		pad_type = pad_type != null ? pad_type : "STR_PAD_RIGHT";
		pad_length = parseInt (pad_length);
		switch (pad_type) {
			case "STR_PAD_BOTH":
			input = str_pad (input,
			input.length + Math.ceil ((pad_length - input.length) / 2.0),
			pad_string,
			"STR_PAD_RIGHT"
			);
			case "STR_PAD_LEFT":
			var buffer = "";
			for (var i = 0, z = pad_length - input.length; i < z; ++i) {
				buffer += pad_string.charAt(padi);
				if (++padi == pad_string.length)
				padi = 0;
			}
			input = buffer + input;
			break;
			default:
			for (var i = 0, z = pad_length - input.length; i < z; ++i) {
				input += pad_string.charAt(padi);
				if (++padi == pad_string.length)
				padi = 0;
			}
			break;
		}
	}

	return input;
}


function RegistraLog(path, id_registro, dados)
{

	if ((dados.length == 3) || (dados.length == 4)) {
		loadXMLDoc(path + 'include/php/ajax_registra_log.php?id_item=' + id_registro + '&msg=' + dados[0] + '&tipo_erro=' + dados[1] + '&tipo_log=' + dados[2]+ '&sistema=' + dados[3]);
	} else {
		loadXMLDoc(path + 'include/php/ajax_registra_log.php?id_item=' + id_registro + '&campo=' + dados[0] + '&valor_antigo=' + dados[1] + '&valor_novo=' + dados[2] + '&tipo_erro=' + dados[3] + '&tipo_log=' + dados[4]+ '&sistema=' + dados[5]);
	}
}

/**
*
*
*Função que registra a alteração de algum campo, guardando suas informações, e dizendo para que serve esse armazenamento
*path = variável que irá dar a referência para a chamada do arquivo (ajax)
*tipoErro = No caso de armazenamento em banco, deverá dizer o tipo de log
*sistema = Como a função é genérica, deverá dizer qual sistema está usando-a
*tabela = No caso de armazenamento em banco, tabela que será inserida
*item = Campo que está sendo alterado
*RegistraLogDb = (S/N) boolean;
*RegistraLogTxt = (S/N) boolean;
*RegistraLogEmail = (S/N) boolean;
*/
function RegistraAlteracaoCampo(path, tipoErro, sistema, tabela, id, nome, info, campo, valorAntigo, valorAtual, RegistraLogDb, RegistraLogTxt, RegistraLogEmail){

	loadXMLDoc(path + 'include/php/ajax_registra_alteracao_campo.php?tipoerro=' + tipoErro + '&tabela=' + tabela + '&id=' + id + '&nome=' + nome + '&info=' + info + '&campo=' + campo + '&valor_antigo=' + valorAntigo + '&valor_atual=' + valorAtual + '&registra_db=' + RegistraLogDb + '&registra_txt=' + RegistraLogTxt + '&registra_email=' + RegistraLogEmail + '&sistema=' + sistema);

}


function GetRadioGroupValue(obj)
{
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			return obj[i].value;
		}
	}

	return false;
}

Array.prototype.in_array = function (obj)
{
	for (var i = 0; i <= this.length; i++) {
		if (this[i] == obj) {
			return true;
		}
	}

	return false;
}

Array.prototype.removeElement = function(obj)
{
	for(i = 0; i < this.length; i++) {
		if (this[i] == obj) {
			this.splice(i, 1);
		}
	}
}

String.prototype.removeHTMLTags = function()
{
	var strInputCode = this;

	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) { return (p1 == "lt")? "<" : ">"; });
	var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

	return strTagStrippedText;
}

String.prototype.removeBreakLines = function()
{
	var strInputCode = this;

	strInputCode = strInputCode.replace(/\r\n/g," ");
	strInputCode = strInputCode.replace(/\n/g," ");
	strInputCode = strInputCode.replace(/\r/g," ");

	return strInputCode;
}
