var limite = 0;
var alfaindex = -1;

function pegaParametros(nomeForm) {
	var Parametros = new Array();
	for (var i=0 ; i < nomeForm.elements.length; i++) {
		if ( (((nomeForm.elements[i].type=="checkbox") || (nomeForm.elements[i].type=="radio")) && (nomeForm.elements[i].checked)) || ((nomeForm.elements[i].type!="checkbox") && (nomeForm.elements[i].type!="radio"))) {
			var parametro = encodeURIComponent(nomeForm.elements[i].name);
			parametro += "=";
			parametro += rawurlencode(nomeForm.elements[i].value);
			Parametros.push(parametro);
		}
	}
	return Parametros.join("&");
}

function criaXHR() {
	var xhr;
	try {
		xhr = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) {
		try {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e) {
			xhr = false;
		}
	}
	if (!xhr && typeof XMLHttpRequest != 'undefined') {
		xhr = new XMLHttpRequest();
	}
	return xhr;
}

function Carregando() {
	document.write("<center><img src='./imagens/load.gif'></center>Carregando, aguarde...");
}

function rawurldecode(str) {
	var n, strCode, strDecode = ""
	for (n = 0; n < str.length; n++) {
		if (str.charAt(n) == "%") {
			strCode = str.charAt(n + 1) + str.charAt(n + 2);
			strDecode += String.fromCharCode(parseInt(strCode, 16));
			n += 2;
		} else {
			strDecode += str.charAt(n);
		}
	}
	return strDecode;
}

function /*out: String*/ number_format( /* in: float   */ number,
/* in: integer */ laenge,
/* in: String  */ sep,
/* in: String  */ th_sep ) {

	number = Math.round( number * Math.pow(10, laenge) ) / Math.pow(10, laenge);
	str_number = number+"";
	arr_int = str_number.split(".");
	if(!arr_int[0]) arr_int[0] = "0";
	if(!arr_int[1]) arr_int[1] = "";
	if(arr_int[1].length < laenge){
		nachkomma = arr_int[1];
		for(i=arr_int[1].length+1; i <= laenge; i++){  nachkomma += "0";  }
		arr_int[1] = nachkomma;
	}
	if(th_sep != "" && arr_int[0].length > 3){
		Begriff = arr_int[0];
		arr_int[0] = "";
		for(j = 3; j < Begriff.length ; j+=3){
			Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
			arr_int[0] = th_sep + Extrakt +  arr_int[0] + "";
		}
		str_first = Begriff.substr(0, (Begriff.length % 3 == 0)?3:(Begriff.length % 3));
		arr_int[0] = str_first + arr_int[0];
	}
	return arr_int[0]+sep+arr_int[1];
}

function moeda(valor) {
	if (valor=="") return;
	return number_format(valor,4,',','.');
}

function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent)
	while(1) {
		curtop += obj.offsetTop;
		if(!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else if(obj.y)
	curtop += obj.y;
	return curtop;
}
function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent)
	while(1) {
		curleft += obj.offsetLeft;
		if(!obj.offsetParent)
		break;
		obj = obj.offsetParent;
	}
	else if(obj.x)
	curleft += obj.x;
	return curleft;
}
function rawurlencode(str) {
	var hex_chars = "0123456789ABCDEF";
	var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
	var n, strCode, hex1, hex2, strEncode = "";

	for(n = 0; n < str.length; n++) {
		if (noEncode.test(str.charAt(n))) {
			strEncode += str.charAt(n);
		} else {
			strCode = str.charCodeAt(n);
			hex1 = hex_chars.charAt(Math.floor(strCode / 16));
			hex2 = hex_chars.charAt(strCode % 16);
			strEncode += "%" + (hex1 + hex2);
		}
	}
	return strEncode;
}

var cores = new Array("#fffbea","#fff6d3");

//esquema de cores iMask
var corImask = new Array(
"#FFFFCC", //bgFocus
"#808080", //borderFocus
"#fff", //bgBlur
"#808080", //borderBlur
"#8f8", //bgValid
"#808080", //borderValid
"#f88", //bgInvalid
"#800"  //borderInvalid
);

function isEmpty(pStrText){
	var   len = pStrText.length;
	var pos;
	var vStrnewtext = "";

	for (pos=0; pos<len; pos++){
		if (pStrText.substring(pos, (pos+1)) != " "){
			vStrnewtext = vStrnewtext + pStrText.substring(pos, (pos+1));
		}
	}
	if (vStrnewtext.length > 0)
	return false;
	else
	return true;
}
function criaCampo(nome, cont, size, valor, tipo, evento, id) {
	var _excluir = false;
	if (nome.indexOf('::excluir') > -1) { //campo chave p/exclusao, separa nome p/evento n ter no array ::excluir
		var nome = nome.substring(0,nome.indexOf('::excluir'));
		_excluir = true;
	}
	var input = document.createElement('input');
	input.type = (nome.substring(0,2)=='id')? 'hidden' : 'text';
	input.id = nome+'_'+cont;
	input.name = nome+'_'+cont;
	input.value = (valor)? valor : '';
	if (evento) { //instala eventos
		evento = evento.split(':~:');
		if (!document.all) { //ff
			for (var x=0; x <= evento.length-1; x+=2) input.setAttribute(evento[x],evento[x+1]);
		}
		else { //ie
			for (var x=0; x <= evento.length-1; x+=2) {
				if (evento[x].substring(0,2)=='on') {
					var eventos = "input."+evento[x]+"= function() {"+(evento[x+1])+"}";
					eval(eventos);
				}
				else input.setAttribute(evento[x],evento[x+1]);
			}
		}
	}
	//classes dos campos
	var blurN = (nome=='tpusoconti')? 'preencheUsoContinuo(this);' : ''; //adaptacao da cd5011
	input.setAttribute("onfocus","this.className='input_focus'");
	input.setAttribute("onblur","this.className='input';"+blurN);
	input.className='input';

	input.autocomplete = 'off';
	if (!document.all) input.size = size;
	else input.setAttribute("size",size);
	if (_excluir) { //monta campo de exclusao
		if (!tipo) var td = document.createElement('td');
		else var td = document.createElement(tipo);
		var lnkE = document.createElement('a');
		lnkE.href = "javascript:void(0);";

		var imgE = document.createElement('img');
		imgE.src = 'img/sair.gif';
		imgE.border = 0;
		imgE.align = 'absmiddle';
		imgE.title = "Clique para excluir...";
		imgE.style.cursor = "pointer";
		imgE.height = 16;
		imgE.width = 16;
		lnkE.appendChild(imgE);

		lnkE.id = nome+'_'+cont+'_'+id;
		lnkE.onclick = function() {
			var prd = this.id.split('_');
			if (confirm("Deseja excluir?")) {
				campoDinamicoExclui(this); //funçao de cada tela
			}
		}

		if (nome.substring(0,2)=='id') td.appendChild(lnkE);
	}
	else {
		if (!tipo) var td = (nome.substring(0,2)=='id')? input : document.createElement('td');
		else var td = (nome.substring(0,2)=='id')? input : document.createElement(tipo);
	}
	if ((nome.substring(0,2)!='id') || (_excluir)) {
		td.appendChild(input);
		if (_excluir) td.appendChild(lnkE);
	}
	return td;
}
//IE bug de appendChild no tbody, exclui tbody criado no html e já cria um dinamico dai aceita appendChild
var tbodys_ja_criados = new Array();
var tbodys_ja_criados_cont = 0;

function camposD(id,tipo,vlinput) {
	//IE bug de appendChild no tbody, exclui tbody criado no html e já cria um dinamico dai aceita appendChild
	if (document.all) {
		var ja_criado = false;
		for (xx in tbodys_ja_criados) {
			if (tbodys_ja_criados[xx] == id) {
				ja_criado = true;
				break;
			}
		}
		if (!ja_criado) {
			tbodys_ja_criados[tbodys_ja_criados_cont++] = id;
			var tb = document.getElementById(id).parentNode;
			tb.removeChild(document.getElementById(id));
			var evt = document.createElement('tbody');
			evt.id = id;
			tb.appendChild(evt);
		}
	}
	var evt = document.getElementById(id);

	var nomes = eval("nomes_"+id);
	var tamanhos = eval("tamanhos_"+id);
	try { var eventos = eval("eventos_"+id); } catch(e) {}
	try { var vlinput = vlinput.split('::'); } catch(e) {} //divide valor de cada campo
	var elem = (tipo)? document.createElement(tipo) : document.createElement('tr');
	elem.id = id+"_"+eval("linha_"+id);

	evt.appendChild(elem);

	for (var i=0;i<=(nomes.length-1);i++) {
		if (nomes[i].indexOf('::excluir') > -1) { //campo chave p/exclusao, separa nome p/evento n ter no array ::excluir
			var nome_evt = nomes[i].substring(0,nomes[i].indexOf('::excluir'));
		}
		else {
			var nome_evt = nomes[i];
		}
		try { var _valor2 = vlinput[i]; } catch(e) { var _valor2 = null; }
		try {
			var _eventos = eventos[nome_evt].replace(/contador/g, eval("linha_"+id));
		} catch(e) { var _eventos = null; }
		elem.appendChild(criaCampo(nomes[i], eval("linha_"+id),tamanhos[i],_valor2, tipo, _eventos, id));
	}
	eval("linha_"+id+"++");
}


/*
PARA MOEDA:
campo normal: onKeyUp="this.value=Formata(this.value,2)" onkeypress="return soNumeros(this,event)"
campo dinamico: eventos_tabelas["nrdovalorx"] = "style:~:text-align:right;:~:onkeyup:~:this.value=Formata(this.value,2):~:onkeypress:~:return soNumeros(this,event)";
*/

// máscara que só permite valores monetários (dec = numero de algarismos decimais)
function Formata(valor,dec) {
	// parte decimal e inteira do n?mero
	intstr = '';
	decstr = '';
	temp_valor = '';

	// remove todos os caracteres que n?o s?o v?lidos
	var validos = "0123456789";
	var numero_ok = '';
	for(i=0;i<valor.length;i++){
		if(validos.indexOf(valor.substr(i,1)) != -1) {
			temp_valor += valor.substr(i,1);
		}
	}

	// separa parte decimal de parte inteira
	if (temp_valor.length == 0) {
		intstr = "0";
		// concatena zeros
		for (i = 0; i < dec;i++) {
			decstr += "0";
		}
	}
	else if (temp_valor.length == 1) {
		intstr = "0";
		// concatena zeros
		for (i = 0; i < (dec - 1);i++) {
			decstr += "0";
		}
		decstr += temp_valor;
	}
	else if (temp_valor.length <= dec) {
		intstr = "0"
		decstr = temp_valor;
		for (i = temp_valor.length; i < dec; i++) {
			decstr += "0";
		}
	}
	else {
		intstr = temp_valor.substring(0,(temp_valor.length - dec));
		decstr = temp_valor.substring((temp_valor.length - dec),temp_valor.length);
	}

	// remove zeros a esquerda da parte inteira
	temp_valor = intstr;
	intstr = '';
	primeiro_valor = false;
	for(i=0;i<temp_valor.length;i++){
		if (primeiro_valor == false) {
			if (temp_valor.substr(i,1) != "0") {
				primeiro_valor = true;
				intstr += temp_valor.substr(i,1);
			}
		}
		else {
			intstr += temp_valor.substr(i,1);
		}
	}
	if(intstr.length == 0) {
		intstr = "0";
	}

	// adiciona "." a cada 3 algarismos (partindo da direita para esquerda)
	temp_valor = intstr;
	intstr = '';
	ponto = 0;
	for (i = temp_valor.length; i > 0;i--) {
		if ( ((ponto % 3) == 0) && (ponto != 0) ){
			intstr = temp_valor.substr(i -1,1) + "." + intstr;
		}
		else {
			intstr = temp_valor.substr(i -1,1) + intstr;
		}
		ponto++;
	}

	// concatena v?rgula entre parte inteira e decimal
	temp_valor = intstr + "," + decstr;

	// retorna valor concatenado com v?rgula, se estiver em branco, segue em branco (sem esse if, ele retorna a mascara cheia de zeros)
	if((intstr==0)&&(decstr==0))
	temp_valor = '';
	return temp_valor;
}

function stripslashes(str) {
	if (!isEmpty(str)) {
		var aa = str.replace(/\\"/g, '"');
		var bb = aa.replace(/\\'/g, "'");
		if (typeof(bb)=='undefined') bb = '';
		return bb;
	}
	else return '';
}


function soNumeros(valor,e) {
	var nao_digitou_alfa = true;
	valor2 = valor;
	total_digitado = valor2.value = valor2.value;
	tamanho = valor2.value.length;

	var chave=e.charCode? e.charCode : e.keyCode

	if((chave != 8) && (chave != 9)) {
		if (chave < 48 || chave > 57) {
			nao_digitou_alfa = false;
			return false;
		}
		if (nao_digitou_alfa == true) {
		}
		else {
			valor2.value = total_digitado;
		}
	}
}

function esse(id) {
	document.getElementById(id).style.backgroundColor = '#AAAAAA';
}
function esse2(id,cor) {
	document.getElementById(id).style.backgroundColor = cor;
}


//ARRUMA HORA DOS RELATOS
function checkTime(i) {
	if (i<10) {
		i="0" + i;
	}
	return i;
}
function hora(id) {
	if (document.getElementById(id)) {
		var hrTmp = document.getElementById(id).value;
		if ((isEmpty(hrTmp)) || (hrTmp=='__:__')) {
			try {
				var today=new Date();
				var h=today.getHours();
				var m=today.getMinutes();
				h=checkTime(h);
				m=checkTime(m);
				document.getElementById(id).value = h+':'+m;
			} catch(e) {}
		}
	}
}
