function buscar (obj) {
	var divs = $('formBuscaLateral').getElementsByTagName('div');
	for (indice = 0; indice < divs.length; indice ++) {
		divs[indice].style.display = "none";
	}

	$(obj).style.display = "block";
}

function changePage(newLoc)	 {
   nextPage = newLoc.options[newLoc.selectedIndex].value;
   if (nextPage != "") {
	  document.location.href = nextPage
   }
}

function abasDescricao (obj, agrupa, exclusao) {
	var divs = $(agrupa).getElementsByTagName('div');

	for (indice = 0; indice < divs.length; indice ++) {
		if(divs[indice].dir == exclusao) {
			var links = "l_"+divs[indice].id;
			divs[indice].style.display = "none";
			$(links).className = "";
		}
	}

	$(obj).style.display = "block";
	$("l_"+obj).className = "selected";
}

function controlaDiv (obj, agrupa, exclusao) {
	var divs = $(agrupa).getElementsByTagName('div');

	for (indice = 0; indice < divs.length; indice ++) {
		if(divs[indice].title == exclusao) {
			divs[indice].style.display = "none";
		}
	}

	$(obj).style.display = "block";
}

function abreFecha (obj, agrupa, exclusao) {
	var divs = $(agrupa).getElementsByTagName('div');

	for (indice = 0; indice < divs.length; indice ++) {
		if(divs[indice].dir == exclusao) {
			var links = "l_"+divs[indice].id;
			divs[indice].style.display = "none";
		}
	}
	$(obj).style.display = "block";
}


var fontes = new Array('fonte10','fonte11','fonte12','fonte13','fonte14');
tam = 2;
function fonte (x, obj) {
   tam+=x;
   if(tam > (fontes.length - 1)) tam = (fontes.length) - 1;
   if(tam < 0) tam = 0;
   $(obj).className = fontes[tam];
}

//###MASCARAR MOEDA###
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, ev, limite){
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var e = ev || window.event;
	var whichCode = e.keyCode ? e.keyCode : e.which;
	if (whichCode == 13 || whichCode == 8 || whichCode == 9) return true;
	key = String.fromCharCode(whichCode); // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida
	len = objTextBox.value.length;
	for(i = 0; i < len; i++)
		if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) objTextBox.value = '';
	if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
	if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
	if (len < limite) {
		if (len > 2) {
			aux2 = '';
			for (j = 0, i = len - 3; i >= 0; i--) {
				if (j == 3) {
					aux2 += SeparadorMilesimo;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			objTextBox.value = '';
			len2 = aux2.length;
			for (i = len2 - 1; i >= 0; i--)
			objTextBox.value += aux2.charAt(i);
			objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
		}
	}
	return false;
}


// ini: Calculo de metragem vs caixa
// -------------------------------------------------------------------------------
// Calcula a qtde de caixas, custo total.
var add = 1; // variavel que define se deve considerar adição de 10% a qtde.
function calculaM2(estMax) {
	
	estMax = calculaEstoqueMaximo(estMax);
	
	var iQtd = parseInt(estMax,10); // Total em estoque
	
	// Não deixa o valor ser superior à qtd total em estoque
	if ( $('quantidadeM').value > iQtd ) {
		$('quantidadeM').value = iQtd;
	}
	
	// atributo dinamico que informa a qtde de m2 por caixa
	m2_por_caixa = parseFloat($('m2_por_caixa').value.replace(',','.'), 10);

	// metragem digitada
	var qtdeM2 = parseFloat($('quantidadeM').value.replace(',','.'), 10);
	//alert(qtdeM2);

	if (isNaN (m2_por_caixa) ) {
		return false;
	}

	if (isNaN (qtdeM2)) {
		qtdeM2 = 0;
	}

	var qtde_caixa = Math.ceil(qtdeM2/m2_por_caixa*add);

	// seta a quantidade total de caixas;
	$('quantidade').innerHTML = qtde_caixa;

	// seta o defaultValue com o valor digitado.
	$('quantidadeM').defaultValue = $('quantidadeM').value;

	// altera a quantidade para valor corrigido considerando o total das caixas.
	var total_caixa = qtde_caixa * m2_por_caixa;
	if ( total_caixa > 0 ) {
		$('quantidadeM').value = Math.ceil(total_caixa); //total_caixa.formatMoney(2, ',','');
		$('quantidadeAlterada').style.display = "block";
	}
	
	// Valida estoque 
	if ( total_caixa > iQtd ) {
		$('qtd').value = iQtd;
		$('quantidadeM').value = iQtd;
		// corrige total de caixas
		qtde_caixa = Math.ceil(iQtd/m2_por_caixa);
		$('quantidade').innerHTML = qtde_caixa; 
	} else {
		$('qtd').value = $('quantidadeM').value;
	}
	
	if ($('M2PorCaixa') !== null) {
		var M2Total = parseFloat(M2PorCaixa) * qtde_caixa;
		$('M2PorCaixa').innerHTML = M2Total.formatMoney(); 
	}

}
/* Calcula o estoque maximo baseado na configuração de estoque do produto. 
   http://wb4b.5pmweb.com?def=1&task=5010
*/
function calculaEstoqueMaximo(estMax) {
	var produto_estoque = 0;
	var produto_estoque_fornecedor = 0;
	var produto_estoque_minimo_acao = 2; // padrão da madeiramadeira é usar estoque fornecedor.
	if ( $('produto_estoque') ) {
		produto_estoque = parseInt($('produto_estoque').value,10);
	} else {
		produto_estoque = estMax;
	}
	if ( $('produto_estoque_fornecedor') ) {
		produto_estoque_fornecedor = parseInt($('produto_estoque_fornecedor').value,10);
	}
	if ( $('produto_estoque_minimo_acao') ) {
		produto_estoque_minimo_acao = parseInt($('produto_estoque_minimo_acao').value,10);
	}
	if (isNaN(produto_estoque_fornecedor)) {
		produto_estoque_fornecedor = 0;
	}
	if (isNaN(produto_estoque_minimo_acao)) {
		produto_estoque_minimo_acao = 2;
	}

	switch (produto_estoque_minimo_acao) {
		case 1: // esgotado permite solicitacao - coloca um estoque absurdo!
			estMax = 999999;
			break;
		case 2: // usar estoque fornecedor
			estMax = produto_estoque+produto_estoque_fornecedor;
			break;
		case 3: // indisponivel - mantem somente estoque do produto.
			estMax = produto_estoque;
			break;
	}
	return estMax;
}
function calculaM2instalacao() {
	// metragem digitada
	var qtdeM2 = parseFloat($('m2_por_caixa').value.replace(',','.'), 10);

	// atributo dinamico que informa a qtde de m2 por caixa
	var m2_por_caixa = Math.ceil($('quantidadeM').value.replace(',','.'));

	if (isNaN (m2_por_caixa) ) {
		return false;
	}

	if (isNaN (qtdeM2)) {
		qtdeM2 = 0;
	}

	// var qtde_caixa = Math.ceil(qtdeM2/m2_por_caixa*addinstalacao);
	var	qtde_caixa = (qtdeM2*m2_por_caixa);
	qtde_caixa = ((Math.round(qtde_caixa*100))/100);

	// seta a quantidade total de caixas;
	$('quantidade').innerHTML = qtde_caixa;

	// seta o defaultValue com o valor digitado.
	$('quantidadeM').defaultValue = $('quantidadeM').value;

	$('quantidadeM').value = m2_por_caixa; //total_caixa.formatMoney(2, ',','');

	// altera a quantidade para valor corrigido considerando o total das caixas.
//	var total_caixa = qtde_caixa * m2_por_caixa;
//	if (total_caixa > 0) {
//		$('quantidadeAlterada').style.display = "block";
//	}

	// if($('qtd')){ $('qtd').value = $('quantidadeM').value }

}
function addPercentual() {
	// restaura o valor digitado pelo cliente.
	if ($('quantidadeM').defaultValue != "") {
		$('quantidadeM').value = $('quantidadeM').defaultValue;
	}
	if ($('add').checked) {
		add = 1.10; // 10%
		$('setePorcento').style.display = "block";
	} else {
		add = 1;
		$('setePorcento').style.display = "none";
	}
	calculaM2();
}
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [rev. #2]
// c: casas decimais, d: separador decimal, t: separador milhar.
Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
// -------------------------------------------------------------------------------
// fim: Calculo de metragem vs caixa

function mostraAcessorios(tag){
	$('divFlutuante').hide();
	$('divColado').hide();
	$('divPregado').hide();
	$('divGrampeado').hide();
	if(tag.search("Flutuante") > -1){
	  $('divFlutuante').show();
	}
	if(tag.search("Colado") > -1){
		$('divColado').show();
	}
	if(tag.search("Pregado") > -1){
		$('divPregado').show();
	}
	if(tag.search("Grampeado") > -1){
	  $('divGrampeado').show();
	}
}
//--------------------------------------------------------------------------------

function multiplica()
{
	tempValor1 = document.calculadora.valor1.value.replace(",",".");
	tempValor2 = document.calculadora.valor2.value.replace(",",".");
	tempSoma = (tempValor1 * tempValor2).toFixed(2);
	soma = tempSoma.toString().replace(".",",");
	$('calculadoraTotal').innerHTML = "<b><span style='float:left;'>Total:</span><br /><span class='fonte23'>"+soma+"m²</span></b>";
}

//---------------------------------------------------------------------------------

function mostra_detalhe2 (arquivo_descricao, imagens, produto_id, cor, urlCalculaPreco)
{
	mostra_detalhe(arquivo_descricao, imagens, produto_id, cor);
	if ($('quantidadeM') != null) {
		$('quantidadeM').value = 0; // Original: 1. Quantidade tem que ser 0, senao pode adicionar no carrinho sem fazer o cálculo de caixas.
	}
	if ($('quantidade') !== null) {
		$('quantidade').innerHTML = 0;
	}
	calcula_preco(urlCalculaPreco, produto_id, 1, 'valores');
}

function trocaConteudo(value) {

	//todas as opções do select
	var conteudoMadeira = new Array(['','Selecione'],['40','Até 40,00 m²'], ['70','Até 70,00 m²'],['120','Até 120,00 m²'],['200','Até 200,00 m²'],['','Todos']);
	var conteudoLaminado = new Array(['','Selecione'],['41','Até 41,00 m²'], ['71','Até 71,00 m²'],['121','Até 121,00 m²'],['201','Até 201,00 m²'],['','Todos']);
	var conteudoVinilico = new Array(['','Selecione'],['42','Até 42,00 m²'], ['72','Até 72,00 m²'],['122','Até 122,00 m²'],['202','Até 202,00 m²'],['','Todos']);
	var conteudoPorcelanato = new Array(['','Selecione'],['43','Até 43,00 m²'], ['73','Até 73,00 m²'],['123','Até 123,00 m²'],['203','Até 203,00 m²'],['','Todos']);
	var conteudoCarpete = new Array(['','Selecione'],['44','Até 44,00 m²'], ['74','Até 74,00 m²'],['124','Até 124,00 m²'],['204','Até 204,00 m²'],['','Todos']);

	//compara que valor veio
	if(value == 1) {
		var array = conteudoMadeira;
	} else if(value == 7) {
		var array = conteudoLaminado;
	} else if(value == 10) {
		var array = conteudoVinilico;
	} else if(value == 12) {
		var array = conteudoPorcelanato;
	} else if(value == 31) {
		var array = conteudoCarpete;
	};

	//remove todos os itens anteriores
	for(i = $('buscaPrecoLateral').options.length; i >= 0; i--) {
		$('buscaPrecoLateral').remove(i);
	};

	//coloca os itens novos
	for(i = 0; i < array.length; i++) {
		var Op = document.createElement("option");
		Op.text = array[i][1];
		Op.value = array[i][0];
		$('buscaPrecoLateral').options.add(Op);
	};
};

function abreDiv(obj) {
	var div = $(obj);
	if(div.style.display == "none") {
		div.style.display = "";
	} else {
		div.style.display = "none";
	}
}

//aba site
function desliza(obj) {
	if($(obj).style.display == "none") {
		new Effect.SlideDown($(obj), { duration: 1 });
	} else {
		new Effect.SlideUp($(obj), { duration: 1 });
	}
}

// Objetivo principal: Verificar se email imputado pelo internauta em um capo qualquer eh um email valido.
function valMail(szVal){
 var chars    = "@#$&[]()/\\\{}!^:'\"";
 var pat      = /^(.+)@(.+)$/;
 var emaildiv = szVal.match(pat);
 if(emaildiv==null)
  return false;
 var login    = emaildiv[1];
 var dominio  = emaildiv[2];
 for(var intX0=0;intX0<chars.length;intX0++)
  if(login.indexOf(chars.substr(intX0,1))!=-1)
   return false;
 for(var intX0=0;intX0<chars.length;intX0++)
  if(dominio.indexOf(chars.substr(intX0,1))!=-1)
   return false;
 return true;
}
// Objetivo principal: Verificar se string imputada pelo internauta  em um capo qualquer eh uma string que faz algum sentido ou eh uma palavra qualquer.
function valString(szBuf){
 if(szBuf.length == 0)
  return(false);
 szBuf = szBuf.toUpperCase();
 if((szBuf == "ASDF")||(szBuf == "QWER")||(szBuf == "1234"))
  return(false);
 return(true);
}
function MascaraFone(e, o){
 var sBuf = new String();
 var iKey = getKeyPress(e);
 if (!isControlKey(iKey) && getSel()==''){
  if(!isNumberKey(iKey)||o.value.length>13) return(false);
  if(o.value.length==1 && o.value!="(") o.value="("+o.value;
  if(o.value.length==3 && o.value.substring(2,2)!=") ") o.value=o.value+") ";
  if(o.value.length==8 && o.value.substring(8,9)!="-") o.value=o.value + "-";
  if (o.value.length==13 && o.value.substring(9,10)!="-"){
   sBuf=sBuf.concat(o.value.substring(0,8),o.value.substring(9,10),"-",o.value.substring(10));
   o.value=sBuf;
  }
 }
}
function valForm() {
 var msg="Os seguintes campos estao incorretos\n\n";
 var err = false;
 var fmForm = window.document.frm_garantia;

 msg += "-------------------------------------------------------------------";

 if(fmForm.numero.value==""){
  msg += "\n- Número do Pedido (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.numero.value)){
  msg += "\n- Número do Pedido (Esta incorrreto).";
  err  = true;
 }
 if(fmForm.produto.value==""){
  msg += "\n- Produto com problema (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.produto.value)){
  msg += "\n- Produto com problema (Esta incorrreto).";
  err  = true;
 }
 if(fmForm.descricao.value==""){
  msg += "\n- Descrição do problema (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.descricao.value)){
  msg += "\n- Descrição do problema (Esta incorrreto).";
  err  = true;
 }
 if(document.getElementById('foto1').value==""){
  msg += "\n- Fotos do produto com problema (Esta vazio).";
  err  = true;
 }
 if(fmForm.cep_a.value==""){
  msg += "\n- CEP (Primeira parte) (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.cep_a.value)){
  msg += "\n- CEP (Primeira parte) (Esta incorrreto).";
  err  = true;
 	}
 if(fmForm.cep_b.value==""){
  msg += "\n- CEP (Segunda parte) (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.cep_b.value)){
  msg += "\n- CEP (Segunda parte) (Esta incorrreto).";
  err  = true;
 }
 if(fmForm.endereco.value==""){
  msg += "\n- Endereço da instalação (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.endereco.value)){
  msg += "\n- Endereço da instalação (Esta incorrreto).";
  err  = true;
 }
 if(fmForm.numero_e.value==""){
  msg += "\n- Número (Esta vazio).";
  err  = true;
 } else if(!valString(fmForm.numero_e.value)){
  msg += "\n- Número (Esta incorrreto).";
  err  = true;
 }
 if(fmForm.bairro.value==""){
  msg += "\n- Bairro (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.bairro.value)){
  msg += "\n- Bairro (Formato incorreto).";
  err  = true;
 }
 if(fmForm.cidade.value==""){
  msg += "\n- Cidade (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.cidade.value)){
  msg += "\n- Cidade (Formato incorreto).";
  err  = true;
 }
 if(fmForm.estado.value==""){
  msg += "\n- Estado(UF) (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.estado.value)){
  msg += "\n- Estado(UF) (Formato incorreto).";
  err  = true;
 }
 if(fmForm.nome.value==""){
  msg += "\n- Nome do instalador (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.nome.value)){
  msg += "\n- Nome do instalador (Formato incorreto).";
  err  = true;
 }
 if(fmForm.ddd.value==""){
  msg += "\n- Telefone do instalador (DDD) (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.ddd.value)){
  msg += "\n- Telefone do instalador (DDD) (Formato incorreto).";
  err  = true;
 }
 if(fmForm.tel.value==""){
  msg += "\n- Telefone do instalador (Está vazio).";
  err  = true;
 } else if(!valString(fmForm.tel.value)){
  msg += "\n- Telefone do instalador (Formato incorreto).";
  err  = true;
 }

 msg += "\n-----------------------------------------------------------------";
 if(err){alert(msg);}
 return(!err);
}

//script para as perguntas area vip
function abasAreaVip (obj, agrupa) {
	var divs = $(agrupa).getElementsByTagName('dd');
	for (indice = 0; indice < divs.length; indice ++) {
		var links = "l_"+divs[indice].id;		
		divs[indice].style.display = "none";
		$(links).className = "";
	}
	$(obj).style.display = "block";
	$("l_"+obj).className = "fonteNegrito";
}

/**************************************/
/*			 ORDENAÇÃO				  */
/**************************************/
function filtroPrecoPisosMadeira() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '30'   : $('fto_px').value = 30; break;
		case '50'   : $('fto_px').value = 50; break;						
		case '31-50': $('fto_pn').value = 30; $('fto_px').value = 50; break;
		case '51-70': $('fto_pn').value = 51; $('fto_px').value = 70; break;						
		case '51'   : $('fto_pn').value = 51; break;
		case '71'   : $('fto_pn').value = 71; break;						
		case '95'   : $('fto_px').value = 95; break;												
		case '96-120': $('fto_pn').value = 96; $('fto_px').value = 120; break;												
		case '121'   : $('fto_pn').value = 121; break;						
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}
function filtroPrecoPisosLaminados() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '30'   : $('fto_px').value = 30; break;
		case '42'   : $('fto_px').value = 42; break;						
		case '31-50': $('fto_pn').value = 30; $('fto_px').value = 50; break;
		case '43-50': $('fto_pn').value = 43; $('fto_px').value = 50; break;
		case '51'   : $('fto_pn').value = 51; break;
		case '80'   : $('fto_px').value = 80; break;						
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}
function filtroPrecoPisosPorcelanato() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '35'   : $('fto_px').value = 35; break;
		case '36-70': $('fto_pn').value = 36; $('fto_px').value = 70; break;
		case '71'   : $('fto_pn').value = 71; break;
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}
function filtroPrecoPisosVinilicos() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '30'   : $('fto_px').value = 30; break;
		case '31-50': $('fto_pn').value = 30; $('fto_px').value = 50; break;
		case '51'   : $('fto_pn').value = 51; break;
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}
function filtroPrecoDeck() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '30'   : $('fto_px').value = 30; break;
		case '50'   : $('fto_px').value = 50; break;						
		case '31-50': $('fto_pn').value = 30; $('fto_px').value = 50; break;
		case '51-70': $('fto_pn').value = 51; $('fto_px').value = 70; break;						
		case '51'   : $('fto_pn').value = 51; break;
		case '71'   : $('fto_pn').value = 71; break;						
		case '95'   : $('fto_px').value = 95; break;												
		case '96-120': $('fto_pn').value = 96; $('fto_px').value = 120; break;												
		case '121'   : $('fto_pn').value = 121; break;						
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}
function filtroPrecoGramaSintetica() {
	var sel = $('ft_preco').options[$('ft_preco').selectedIndex].value;
	switch(sel) {
		case '30'   : $('fto_px').value = 30; break;
		case '50'   : $('fto_px').value = 50; break;						
		case '31-50': $('fto_pn').value = 30; $('fto_px').value = 50; break;
		case '51-70': $('fto_pn').value = 51; $('fto_px').value = 70; break;						
		case '51'   : $('fto_pn').value = 51; break;
		case '71'   : $('fto_pn').value = 71; break;						
		case '95'   : $('fto_px').value = 95; break;												
		case '96-120': $('fto_pn').value = 96; $('fto_px').value = 120; break;												
		case '121'   : $('fto_pn').value = 121; break;						
		default     : $('fto_pn').value = ''; $('fto_px').value = ''; break;
	}
}

/*****************
****PARCEIROS*****
*****************/
function Valida(theForm) {
	if (theForm.NomeUsuario.value=="") {
		alert("Informe o usuário.");
		theForm.NomeUsuario.focus();
		return false;
	}
	if (theForm.SenhaUsuario.value=="") {
		alert("Informe a senha.");
		theForm.SenhaUsuario.focus();
		return false;
	}
	return true;
}
function filtrar() {
	var form = $("frm_filtro");
	var erro = false;
	var mensagem = "Os seguintes erros foram encontrados:\n";

	if( $("dta_inicio").value == "" ) {
		erro = true;
		mensagem += "* Preencha a Data Inicial;\n";
	}

	if( $("dta_final").value == "" ) {
		erro = true;
		mensagem += "* Preencha a Data Final;\n";
	}

	if( erro ) {
		alert( mensagem );
		return false;
	} else {
		var url = '{{$__URL_SITE__}}/portal/parceiros/listagem.php?ajax=1&inicio='+ $("dta_inicio").value +'&fim='+ $("dta_final").value;
		getURL( url );
	}

	return false;
}
function limpar_filtrar() {
	$("dta_inicio").value = "";
	$("dta_final").value = "";

	var url = '{{$__URL_SITE__}}/portal/parceiros/listagem.php?ajax=1';
	getURL( url );

	return false;
}

if ($("frm_filtro")) {
	Event.observe("frm_filtro", "submit", filtrar);
	Event.observe("frm_filtro", "reset", limpar_filtrar);
}

//adiciona mascara de data
function MascaraData(event, data){
	if( mascaraInteiro(event) == false ){
		event.returnValue = false;
	}
	return formataCampo(data, '00/00/0000', event);
}
//valida data
function ValidaData(data){
	exp = /\d{2}\/\d{2}\/\d{4}/
	if(!exp.test(data.value))
		alert('Data Invalida!');
}
//valida numero inteiro com mascara
function mascaraInteiro(event){
	if (event.keyCode < 48 || event.keyCode > 57){
		event.returnValue = false;
		return false;
	}
	return true;
}
//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) {
	var boleanoMascara;

	var Digitato = evento.keyCode;
	exp = /\-|\.|\/|\(|\)| /g
	campoSoNumeros = campo.value.toString().replace( exp, "" );

	var posicaoCampo = 0;
	var NovoValorCampo="";
	var TamanhoMascara = campoSoNumeros.length;;

	if (Digitato != 8) { // backspace
		for(i=0; i<= TamanhoMascara; i++) {
			boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
								|| (Mascara.charAt(i) == "/"))
			boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(")
								|| (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
			if (boleanoMascara) {
				NovoValorCampo += Mascara.charAt(i);
				  TamanhoMascara++;
			}else {
				NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
				posicaoCampo++;
			  }
		  }
		campo.value = NovoValorCampo;
		  return true;
	} else {
		return true;
	}
}

function getURL( url ) {
	if( $("dta_inicio").value != "" && $("dta_final").value != "" ) {
		if( !url.indexOf('inicio') != -1 && !url.indexOf('fim') != -1 ) {
			url += "&inicio="+ $("dta_inicio").value +"&fim="+ $("dta_final").value;
		}
	}

	new Ajax.Request( url, {
							method: 'get',
							onLoading: function() {
								$("loading").show();
							},
							onSuccess: function(t) {
								$('d_lista').innerHTML = t.responseText;

								$("loading").hide();
							}
	});
}

function trocaCor (obj, agrupa) {
	var as = $(agrupa).getElementsByTagName('a');

	for (indice = 0; indice < as.length; indice ++) {
		if(as[indice].className == "selecionado") {
			as[indice].className = "";
		}
	}
	$(obj).className = "selecionado";
}
