//Variavel Global para categoria
function popup(acao,larg,alt) {
	//var r;
	//r=Math.round((Math.random()*9)+1);
	window.open(acao,larg,"scrollbars=yes,resizable=yes, width="+larg+",height="+alt);
}
// --------------------------
/* EXECUTAR JAVASCRIPT DENTRO DE JANELA CARREGADA COM AJAX*/
function extraiScript(texto){
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            eval(codigo);
        }
    }
}
// --------------------------
/*  FUNÇÃO AJAX*/
function ajaxRead(file,destino){
	var xmlObj = null;
	if(window.XMLHttpRequest){
	  xmlObj = new XMLHttpRequest();
	} else if(window.ActiveXObject){
	  xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	  return;
	}
	xmlObj.onreadystatechange = function(){   
		if(xmlObj.readyState == 1){
			//**** USAR PARA ARQUIVOS HTML *****
			updateObj(destino,"Aguarde...");
	     }
		if(xmlObj.readyState == 4){
			if (xmlObj.status == 200) { //se nao ocorreu nenhum erro
				//**** USAR PARA ARQUIVOS HTML *****
				texto=unescape(xmlObj.responseText.replace(/\+/g," "));
				updateObj(destino, xmlObj.responseText);
				extraiScript(texto);
				/* extraindo script e executando */
			} else {
	            alert("Houve um problema ao obter os dados:\n" + xmlObj.statusText);
	        }
		}
	}
	xmlObj.open ('GET', file, true);
	xmlObj.send ('');
}
// --------------------------
function updateObj(obj, data){
	document.getElementById(obj).innerHTML = data;
}
// --------------------------
function AlternarAbas(menu,conteudo){
	for (i=0;i<arAbas.length;i++){
		m = document.getElementById(arAbas[i].menu);
		m.className = 'normal';
		
		c = document.getElementById(arAbas[i].conteudo)
		c.className = 'inativo';
	}
	m = document.getElementById(menu)
	m.className = 'ativo';
	c = document.getElementById(conteudo)
	c.className = 'content';
}
// --------------------------
// ALTERNAR ABAS //
function stAba(menu,conteudo){
	this.menu = menu;
	if(conteudo){this.conteudo = conteudo;}
}
// --------------------------
function AlternarOpcao(conteudo){
	for (i=0;i<arOpcao.length;i++)
	{
		c = document.getElementById(arOpcao[i].conteudo)
		c.style.display = 'none';
	}
	c = document.getElementById(conteudo)
	c.style.display = '';
}
function stOp(conteudo)
{
	this.conteudo = conteudo;
}
// --------------------------
function displayMessage(url)
{
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(400,180);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}
// --------------------------
function displayStaticMessage(messageContent,cssClass)
{
	messageObj.setHtmlContent(messageContent);
	messageObj.setSize(300,150);
	messageObj.setCssClassMessageBox(cssClass);
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
}
// --------------------------
function closeMessage()
{
	messageObj.close();	
}
/************** ONFOCUS INPUT *******************/
function textOn(txt)	{ document.getElementById(txt).className="textboxOn"; }
function textNormal(txt){ document.getElementById(txt).className=""; }
/************************************************/
// --------------------------
function updateObj(obj,data){
	if (obj){
		document.getElementById(obj).innerHTML = data;
	}
}
// --------------------------

function buscaCep(cep,endereco_cliente,numero_endereco,complemento,bairro_cliente,cidade_cliente,estado_cliente,estado_funcao,destino,no_focus){

	var xmlObj = null;
	if(window.XMLHttpRequest){
		xmlObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		return;
	}
	xmlObj.onreadystatechange = function(){
		if(xmlObj.readyState == 1){
			//**** USAR PARA ARQUIVOS HTML *****
			abre = "Aguarde... Localizando endereço!";
			if(document.getElementById(destino)){
				document.getElementById(destino).style.display = '';
				updateObj(destino,abre);
			}
		}
		if(xmlObj.readyState == 4){
			if (xmlObj.status == 200){ //se nao ocorreu nenhum erro
				//**** USAR PARA ARQUIVOS HTML *****
				if(document.getElementById(destino)){
					document.getElementById(destino).style.display = 'none';
				}
				resposta = xmlObj.responseText.split("|");
				
				// VERIFICA SE HÁ RESPOSTA NA CONSULTA DO CEP
				if(resposta[0].length>0 && resposta[2].value!= 'undefined'){
					var total_cep = cep.substr(-3,3);
					
				// VERIFICA SE TOTAL CEP ACABA COM "000" \\
				
					try {
						if (total_cep == "000") {
							
							//LANÇA A EXEÇÃO SE ACABAR COM "000" EXECUTA O "so_cidade"							
							throw "so_cidade";
						}
						else {
							//LANÇA A EXEÇÃO SE NÃO ACABAR COM "000" EXECUTA O "tudo"	
							throw "tudo";
						}
					} 
					//O "catch" RECEBE O VALOR DE throw E ATRIBUI A VARIÁVEL DECLARADA, NO CASO A VARIÁVEL SHOW
					catch (show) {
						//SE A VARIÁVEL SHOW RECEBE O VALOR DO throw 'so_cidade' EXIBIRA APENAS A CIDADE E O ESTADO
						if (show == "so_cidade") {
							document.getElementById(cidade_cliente).value = resposta[2];
							document.getElementById(estado_cliente).value = resposta[3];
							document.getElementById(estado_funcao).value = resposta[3];
							
							if (no_focus == 1) {
								if (numero_endereco != '') {
									document.getElementById(endereco_cliente).value = ''
									document.getElementById(bairro_cliente).value = ''
									document.getElementById(complemento).value = '';
									document.getElementById(numero_endereco).value = '';
									document.getElementById(endereco_cliente).focus();
								}
							}
						}
						//SE A VARIÁVEL SHOW RECEBE O VALOR DO throw 'so_cidade' EXIBIRA TUDO
						if (show == "tudo") {
							document.getElementById(endereco_cliente).value = resposta[0];
							document.getElementById(bairro_cliente).value = resposta[1];
							document.getElementById(cidade_cliente).value = resposta[2];
							document.getElementById(estado_cliente).value = resposta[3];
							document.getElementById(estado_funcao).value = resposta[3];
							
							if (no_focus == 1) {
								if (numero_endereco != '') {
									if (document.getElementById(endereco_cliente)) {
										document.getElementById(complemento).value = '';
										document.getElementById(numero_endereco).value = '';
										document.getElementById(numero_endereco).focus();
									}
								}
							}
						}	
					}
				}else{
					document.getElementById(endereco_cliente).value='';
					document.getElementById(bairro_cliente).value='';
					document.getElementById(cidade_cliente).value='';
					document.getElementById(estado_cliente).value='';
					document.getElementById(estado_funcao).value='';

					if(numero_endereco != ''){
						if(document.getElementById(numero_endereco)){
							document.getElementById(complemento).value='';
							document.getElementById(numero_endereco).value='';	
						}
					}

					if (no_focus == 1){
						document.getElementById(endereco_cliente).focus();
					}
				}
			}else{
				alert("Houve um problema ao obter os dados:\n" + xmlObj.statusText);
			}
		}
	}
	xmlObj.open ('GET', '/adm/funcoes/busca_cep.php?cep='+cep, true);
	xmlObj.send ('');
}

// --------------------------
function cobranca_buscaCep(cobranca_cep,cobranca_endereco,cobranca_numero_endereco,cobranca_complemento,cobranca_bairro,cobranca_cidade,cobranca_estado,cobranca_estado_funcao,destino,no_focus){

	var xmlObj = null;

	if(window.XMLHttpRequest){
		xmlObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		return;
	}

	xmlObj.onreadystatechange = function(){
		if(xmlObj.readyState == 1){
			//**** USAR PARA ARQUIVOS HTML *****
			abre = "Aguarde... Localizando endereço!";
			if(document.getElementById(destino)){
				document.getElementById(destino).style.display = '';
				updateObj(destino,abre);
			}
		}

		if(xmlObj.readyState == 4){
			if (xmlObj.status == 200){ //se nao ocorreu nenhum erro
				//**** USAR PARA ARQUIVOS HTML *****
				if(document.getElementById(destino)){
					document.getElementById(destino).style.display = 'none';
				}
				resposta = xmlObj.responseText.split("|");


				// VERIFICA SE HÁ RESPOSTA NA CONSULTA DO CEP
				if(resposta[0].length>0 && resposta[2].value!= 'undefined'){
					var total_cep = cobranca_cep.substr(-3,3);
					
				// VERIFICA SE TOTAL CEP ACABA COM "000" \\
				
					try {
						if (total_cep == "000") {
							
							//LANÇA A EXEÇÃO SE ACABAR COM "000" EXECUTA O "so_cidade"							
							throw "so_cidade";
						}
						else {
							//LANÇA A EXEÇÃO SE NÃO ACABAR COM "000" EXECUTA O "tudo"	
							throw "tudo";
						}
					} 
					//O "catch" RECEBE O VALOR DE throw E ATRIBUI A VARIÁVEL DECLARADA, NO CASO A VARIÁVEL SHOW
					catch (show) {
						//SE A VARIÁVEL SHOW RECEBE O VALOR DO throw 'so_cidade' EXIBIRA APENAS A CIDADE E O ESTADO
						if (show == "so_cidade") {
							document.getElementById(cobranca_cidade).value=resposta[2];
							document.getElementById(cobranca_estado).value=resposta[3];
							document.getElementById(cobranca_estado_funcao).value=resposta[3];
							
							if (no_focus == 1) {
								if (numero_endereco != '') {
									document.getElementById(cobranca_endereco).value = ''
									document.getElementById(cobranca_bairro).value = ''
									document.getElementById(cobranca_complemento).value = '';
									document.getElementById(cobranca_numero_endereco).value = '';
									document.getElementById(cobranca_endereco).focus();
								}
							}
						}
						//SE A VARIÁVEL SHOW RECEBE O VALOR DO throw 'so_cidade' EXIBIRA TUDO
						if (show == "tudo") {
							document.getElementById(cobranca_endereco).value=resposta[0];
							document.getElementById(cobranca_bairro).value=resposta[1];
							document.getElementById(cobranca_cidade).value=resposta[2];
							document.getElementById(cobranca_estado).value=resposta[3];
							document.getElementById(cobranca_estado_funcao).value=resposta[3];
							
							if (no_focus == 1){
								if (cobranca_numero_endereco != ''){
									if (document.getElementById(cobranca_endereco)){
										document.getElementById(cobranca_complemento).value='';
										document.getElementById(cobranca_numero_endereco).value='';	
										document.getElementById(cobranca_numero_endereco).focus();
									}
								}
							}
						}	
					}					
				}else{
					document.getElementById(cobranca_endereco).value='';
					document.getElementById(cobranca_bairro).value='';
					document.getElementById(cobranca_cidade).value='';
					document.getElementById(cobranca_estado).value='';
					document.getElementById(cobranca_estado_funcao).value='';

					if(cobranca_numero_endereco != ''){
						if(document.getElementById(cobranca_numero_endereco)){
							document.getElementById(cobranca_complemento).value='';
							document.getElementById(cobranca_numero_endereco).value='';	
						}
					}

					if (no_focus == 1){
						document.getElementById(cobranca_endereco).focus();
					}
				}
			}else{
				alert("Houve um problema ao obter os dados:\n" + xmlObj.statusText);
			}
		}
	}
	xmlObj.open ('GET', '/adm/funcoes/busca_cep.php?cep='+cobranca_cep, true);
	xmlObj.send ('');
}
// --------------------------
function verifica_estado(estado_selecionado,estado_funcao){
	if (estado_selecionado!=estado_funcao){
		document.getElementById('estado_cliente').value = estado_funcao;
	}
}
// --------------------------
function cobranca_verifica_estado(estado_selecionado,estado_funcao){

	if (estado_selecionado!=estado_funcao){
		document.getElementById('cobranca_estado').value = estado_funcao;
	}
}
// --------------------------
function verifica_endereco_cobranca(){
	if (document.getElementById('endereco_cobranca_diferente').checked==1){
		document.getElementById('libera_endereco_cobranca').style.display = '';
	}else{
		document.getElementById('libera_endereco_cobranca').style.display = 'none';
	}
}
// --------------------------
//Funcao que verifica se está selecionado um checkbox para executar a acao em todos
//Precisa ter o checkbox, com nome de vetor tipo 'checkbox[]'
function conta(check,trava)
{	var Form;
	
	Form = document.form;

	if (trava==1)
	{	if (check.checked == true)
		{	contador++;	}
		else
		{	contador--;	}
	}
	else
	{	if (contador == 0)
		{	alert ('Por favor, selecione os pedidos para prosseguir!');
			return false;
		}
	}
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function FormataValor(id,tammax,teclapres){
	// Internet Explorer
	if(window.event) {
		var tecla = teclapres.keyCode;
	// Nestcape / firefox
	}else if(teclapres.which) {
		var tecla = teclapres.which;
	}
	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;

	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 <= 2 ){
			document.getElementById(id).value = vr;
		}
		if ( (tam > 2) && (tam <= 5) ){
			document.getElementById(id).value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 6) && (tam <= 8) ){
			document.getElementById(id).value = vr.substr( 0, tam - 5 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 9) && (tam <= 11) ){
			document.getElementById(id).value = vr.substr( 0, tam - 8 ) + '' + vr.substr( tam - 8, 3 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam );
		}
		if ( (tam >= 12) && (tam <= 14) ){
			document.getElementById(id).value = vr.substr( 0, tam - 11 ) + '' + vr.substr( tam - 11, 3 ) + '' + vr.substr( tam - 8, 3 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam );
			}
		if ( (tam >= 15) && (tam <= 17) ){
			document.getElementById(id).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 );
		}
	}
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function FormataPct(id,tammax,teclapres){
	// Internet Explorer
	if(window.event) {
		var tecla = teclapres.keyCode;
	// Nestcape / firefox
	}else if(teclapres.which) {
		var tecla = teclapres.which;
	}
	vr = document.getElementById(id).value;
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;
	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 == 1){
			document.getElementById(id).value = vr;
		}
		if ( (tam > 1) && (tam <= 5) ){
			document.getElementById(id).value = vr.substr(0,1) + '.' + vr.substr(1,tam);
		}
		if ( (tam > 5) && (tam <= 10) ){
			document.getElementById(id).value = vr.substr( 0, 2) + '.' + vr.substr( 2, tam );
		}
	}
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function numeros_ponto(e){
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if ((tecla > 47 && tecla < 58) || (tecla > 45 && tecla < 47)) // numeros de 0 a 9 e ponto (.)
			return true;
	else
	{
		if (tecla != 8) { 
			// backspace
			event.keyCode = 0;
			//return false;
		}
		else {
			return true;
		}
	}
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function numeros(e){
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true;
	else
	{
		if (tecla != 8) {
			// backspace
			event.keyCode = 0;
			//return false;
		}
		else {
			return true;
		}
	}
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
// Funções para edição de campos relacionado a um evento (exemplo: listar_produto.php)
function editaCampo(div,url)
{
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function cancelaCampo(div,valor)
{
	document.getElementById(div).innerHTML = valor;
}
function atualizaCampo(div,url)
{
	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
function mudaEstilo(campo, span, prop)
{
	var valor = document.getElementById(campo).value;
	switch (prop)
	{
		case 'fontWeight':
			document.getElementById(span).style.fontWeight = valor; 
			break;
			
		case 'fontFamily':
			document.getElementById(span).style.fontFamily = valor; 
			break;
		
		case 'fontSize':
			document.getElementById(span).style.fontSize = valor; 
			break;
			
		case 'color':
			document.getElementById(span).style.color = valor; 
			break;
			
		case 'colorLink':
			document.getElementById(span).style.color = valor;
			document.getElementById(span).onmouseout = function(){
				document.getElementById(span).style.color = valor;
			}
			break;
		
		case 'colorLinkHover':
			var cor = document.getElementById(span).style.color;
			
			document.getElementById(span).onmouseover = function(){
				document.getElementById(span).style.color = valor;
			}
			document.getElementById(span).onmouseout = function(){
				document.getElementById(span).style.color = cor;
			};
			break;
			
		case 'imagem':
			document.getElementById(span).style.backgroundColor = valor; 
			break;
	} 
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function abrePaleta(div, input)
{
	var total = document.getElementsByTagName('div');
	for(var i=0;i<total.length;i++)
	{
		if(total[i].className=='pallet')
		{
			total[i].innerHTML='';
		}
	}
	
	var url='../interface/newpicker/picker.php?id_input='+input+'&div='+div;
	ajaxRead(url,div);
//	new Ajax.Updater(div,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', div]});
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
function setValuePicker(idLista, idInput, div)
{
	var cor = idLista.substring(1,7);
	document.getElementById(idInput).value = '#'+cor;
	document.getElementById(div).innerHTML='';
	document.getElementById(idInput).focus();
}
<!-- ------------------------------------------------------------------------------------------------------------ -->
//Função que fecha a colorPicker
function fechaPaleta(div)
{
	document.getElementById(div).innerHTML='';
}
//Função que muda a imagem da forma de pagamento nas opções da loja
function mudaImagemForma(input, imagem)
{
	document.getElementById(imagem).src="../imagens/forma"+input.value+".png";
}
//Função que troca a venda manual de ML, para TO e PL
function trocaVendaManual(link1,link2,link3)
{
	if (document.getElementById(link1).style.display == 'none')
	{
		document.getElementById(link1).style.display = '';
		document.getElementById(link2).style.display = 'none';
		document.getElementById(link3).style.display = 'none';
	}
}
//Função que habilita as datas do relatorio de carrinho abandonado
function enableDates(fieldSelect,fieldStartDate,fieldEndDate,hoje)
{
	if(fieldSelect.options[fieldSelect.selectedIndex].value==-1)
	{
		document.getElementById(fieldStartDate).disabled=false;
		$('f_data_ini').show();
		document.getElementById(fieldEndDate).disabled=false;
		$('f_data_fim').show();
	}
	else
	{
		document.getElementById(fieldStartDate).disabled=true;
		document.getElementById(fieldStartDate).value=hoje;
		$('f_data_ini').hide();
		document.getElementById(fieldEndDate).disabled=true;
		document.getElementById(fieldEndDate).value=hoje;
		$('f_data_fim').hide();
	}
}
//Função que envia o formulário da popUp do carrinho abandonado
function submitFormPopUp(Form,popupName,loja)
{
	if ($('acao').value == 'enviar_varios')
	{
		window.open('',popupName,"scrollbars=yes,resizable=no, width=700px,height=400px");
		var acao = 'carrinho_abandonado_enviar.php?loja=' + loja;
		Form.target=popupName;
	}
	else
	{
		var acao = 'carrinho_abandonado_excluir.php?loja=' + loja;
	}
	Form.action=acao;
	Form.submit();
}
//Função que checka a linha onde se encontra a radio button
function checkRadio(id)
{
	var radio = document.getElementById(id);
	if (radio.checked == true) {
		radio.checked = false;
	}
	else {
		radio.checked = true;
	}
}
//Função que abre uma popup para enviar email no carrinho abandonado
function openSend(link)
{
	window.open(link.href,'EnviaEmail',"scrollbars=yes,resizable=no, width=700px,height=400px");
}
//Função que faz o reload na página
function reloadPage()
{
	window.location.reload();
}
//Função que valida as caracteristicas
function addFeature(Form,divUp)
{
	if($('caracteristica').value=='')
	{
		alert('Informe a característica');
		return false;
	}

	sendFormAjax(Form,divUp);
	return false;
}
//Função que envia um formulário via Ajax
function sendFormAjax(Form,divUp)
{
	Form.request({
		onSuccess:function(transport)
		{
			$(divUp).innerHTML=transport.responseText;
			$(divUp).style.display = '';
            Form.reset();
		}
	});
	return false;
}

function limpaDiv(div)
{
	$(div).innerHTML='';
	$(div).style.display='none';
}
//Função que faz a mudança de elemento nos selects dos perfis
function changeSelects(selectLeft, selectRight)
{
	var total=$(selectLeft).options.length;
	var total2=$(selectRight).options.length;
	var j=total2;
	var k=0;
	var inclui = 0;
	var classOption='';
	var vetor=new Array();
	var	widthLeft = $(selectLeft+'Div').clientWidth;
	var	widthRight = $(selectRight+'Div').clientWidth;
	
	for(i=0;i<total;i++)
	{
		if($(selectLeft).options[i].selected==true)
		{
			inclui = 1;
			for(cont=0;cont<total2;cont++) 
			{
				if($(selectLeft).options[i].value == $(selectRight).options[cont].value)
				{
					inclui = 0;
					break;
				}
			}
			if(inclui==1)
			{
				var option = document.createElement('option');
				option.setAttribute("value", $(selectLeft).options[i].value);
				option.innerHTML = $(selectLeft).options[i].innerHTML;
				option.setAttribute("id", $(selectLeft).options[i].id);

				option.className = $(selectLeft).options[i].className;

				$(selectRight).appendChild(option);
				j++;
			}
			vetor[k] = $(selectLeft).options[i];
			k++;
		}
	}
	var total_vetor = vetor.length;
	for (i = 0; i < total_vetor; i++) {
		vetor[i].parentNode.removeChild(vetor[i]);
	}
	$(selectRight).style.width = widthRight+'px';
	$(selectLeft).style.width = widthLeft+'px';
}
//Função que faz a mudança de elemento nos selects das categorias
function changeSelectsCategorias(selectLeft, selectRight)
{
	var total=$(selectLeft).options.length;
	var total2=$(selectRight).options.length;
	var elementos='';
 
	if(total2>0)
	{
		for(i=0;i<total2;i++)
		{
			elementos += '|'+$(selectRight).options[i].id;
		}
	}
	for(i=0;i<total;i++)
	{
		if($(selectLeft).options[i].selected==true)
		{
			elementos += '|'+$(selectLeft).options[i].id;
		}
	}
	atualizaDiv(selectRight,'/adm/produtos/incluir_categorias_adicionais.php?elementos='+elementos);
}
//Função que faz a mudança de elemento nos selects das categorias
function removeOptionSelect(select)
{
	var total=$(select).options.length;
	var elemento = $(select);
	var elementos = new Array();
	var id_option='';
	var j = 0;
	
	for(i=0;i<total;i++)
	{
		if(elemento.options[i].selected==true)
		{
			var ident = elemento.options[i].id;
			elementos[j] = elemento.options[i];
			j++;
		}
	}
	for(i=0;i<total;i++)
	{
		if(elemento.options[i].id.indexOf(ident+'_')==0)
		{
			elementos[j] = elemento.options[i];
			j++;
		}
	}
	for(i=0;i<elementos.length;i++)
	{
		elementos[i].parentNode.removeChild(elementos[i]);
	}
}
//Função que envia os selects no formato dos perfis
function submitSelects(selectRight)
{
	var total = $(selectRight).options.length;

	if (total == 0) {
		return false;
	}

	for(i=0;i<total;i++)
	{
		$(selectRight).options[i].selected=true;
	}
}
//Função que valida o perfil ao criar ou editar um perfil
function validatePerfil(selectRight)
{
	if($('perfil').value=='')
	{
		alert('Digite o nome do perfil');
		return false;
	}
	var retorno = submitSelects(selectRight);
	if(retorno==false)
	{
		alert('Selecione alguma característica para adicionar ao perfil');
		return false;
	}
}
//Função que atyaliza uma parte do código (pela id) e atualiza com a url
function atualizaDiv(id,url)
{
	new Ajax.Updater(id,url,{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', id]});//insertion: Insertion.Bottom
}
//Função que atyaliza uma parte do código (pela id) e atualiza com a url abaixo do elemento
function atualizaDivBottom(id,url)
{
	new Ajax.Updater(id,url,{insertion: Insertion.Bottom,asynchronous:true,evalScripts:true,requestHeaders:['X-Update',id]});
}
//Função que muda o perfil do elemento de acordo com a categoria
function changeProfile(elemento,id_categoria)
{
	var id_categoria_mae = elemento.options[elemento.selectedIndex].value;
	var url = '../funcoes/perfil_exibir.php?id_categoria='+id_categoria+'&id_categoria_mae='+id_categoria_mae;
	atualizaDiv('colunaPerfil',url);
}
//Função para validar a categoria
function validaCategoria(Form,id_categoria_mae,leiloes)
{
	if(leiloes==0)
	{
		var categoria_mae = document.getElementById('categorias_select');
		var id_categoria_mae_select = categoria_mae.options[categoria_mae.selectedIndex].value;
		if(id_categoria_mae != id_categoria_mae_select){
			var confirmacao = confirm('todos os produtos que possuam alguma relação com as características do perfil antigo serão perdidas');
			if (confirmacao == false) {
				return false;
			}
		}
	}
}
function changeOptionsCarac(idSelect)
{
	if($('tipo2').checked == true)
	{
		$(idSelect).style.display = '';
	}
	else
	{
		$(idSelect).style.display = 'none';
	}
}
function changeOptionsCaracEdit(idSelect)
{
	if($('tipo2').checked == true)
	{
		$('tipo_novo').value = $('tipo2').value;
		$(idSelect).style.display = '';
	}
	else
	{
		$('tipo_novo').value = $('tipo1').value
		$(idSelect).style.display = 'none';
	}
}
function insertFeatureClient(opcao, elemento){
	if ($(opcao).value=='') {
		return false;
	}
	else {
		var cont = $('contador').value;
		cont++;
		$('contador').value = cont;
		var cont = $('contador').value;
		atualizaDivBottom(elemento, 'caracteristicas_cadastro_opcoes.php?opcao=' + $(opcao).value + '&cont=' + cont);
		$(opcao).value = '';
		$(opcao).focus();
	}
}
function removeFeatureCad(elemento)
{
	var cont = $('contador').value;
	cont--;
	$('contador').value = cont;
	var span = $(elemento);
	span.parentNode.removeChild(span);
}
function validaCaracteristicasCadastro()
{
	var caracteristica = $('caracteristica').value;
	var tipo2 = $('tipo2');
	var cont = $('contador').value;
	if(caracteristica=='')
	{
		alert('Caracteristica não informada!');
		$('caracteristica').focus();
		return false;
	}
	if(tipo2.checked==true)
	{
		if(cont < 2)
		{
			alert('Informe ao menos duas opções para caixa de seleção!');
			return false;
		}
	}
}
function validaCaracteristicasCadastroEdit()
{
	var caracteristica = $('caracteristica').value;
	var tipo2 = $('tipo2');
	var cont = $('contador').value;
	var tipo_ant = $('tipo_ant').value;
	var tipo_novo = $('tipo_novo').value;
	if(caracteristica=='')
	{
		alert('Caracteristica não informada!');
		$('caracteristica').focus();
		return false;
	}
	if(tipo2.checked==true)
	{
		if(cont < 2)
		{
			alert('Informe ao menos duas opções para caixa de seleção!');
			return false;
		}
	}
	if(tipo_ant!=tipo_novo)
	{
		var confirmation = confirm('Ao trocar o tipo da caracteristica os dados dos clientes serão perdidos\nDeseja realmente modificar o tipo da caracteristica?');
		return confirmation;
	}
}
function enviaForm(Form)
{
	$(Form).submit();
}
function mascara(o,f){
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value);
}
function valorBr(v)
{
 	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	v=v.replace(/(\d)(\d{11})$/,"$1.$2") //Coloca ponto antes dos 9 últimos digitos
	v=v.replace(/(\d)(\d{8})$/,"$1.$2") //Coloca ponto antes dos 7 últimos digitos
	v=v.replace(/(\d)(\d{5})$/,"$1.$2") //Coloca ponto antes dos 5 últimos digitos
	v=v.replace(/(\d)(\d{2})$/,"$1,$2") //Coloca virgula antes dos 2 últimos digitos
	return v
}
function numeros(v)
{
    return v.replace(/\D/g,"")
}
function telefone(v)
{
    v=v.replace(/\D/g,"");               //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígito
    return v;
}
function numeros2(v){
    return v.replace(/\D/g,"")
}	
function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}
function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}
function data(v){
	v=v.replace(/\D/g,"") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	return v
}
function cnpj2(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    return v
}
function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while (v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/, "") != "") {
		v = v.replace(/.$/, "")
	}
    return v
}
function changeEventLim()
{
	if($('tipo1').checked==true)
	{
		var valor=$('valor_inicial').value;
		$('valor_inicial').onkeypress=function(){mascara($('valor_inicial'),valorBr)};
		$('valor_final').onkeypress=function(){mascara($('valor_final'),valorBr)};
	}	
	else
	{
		$('valor_inicial').onkeypress=function(){mascara($('valor_inicial'),numeros)};
		$('valor_final').onkeypress=function(){mascara($('valor_final'),numeros)};
	}
}
function estenderFiltrosCli()
{
	var display = document.getElementById('filtros_cliente').style.display;
	var at = 	document.getElementById('at').value;
	if(display=='none')
	{
		document.getElementById('link_estender_filtros').innerHTML='Recolher Filtros';
		document.getElementById('filtros_cliente').style.display = '';
		if(at!=1){
			atualizaDiv('filtros_cliente', 'estender_filtros.php');
		}
		document.getElementById('exibir_tabela').value=1;
	}
	else
	{
		document.getElementById('link_estender_filtros').innerHTML='Estender Filtros';
		document.getElementById('filtros_cliente').style.display = 'none';
		document.getElementById('exibir_tabela').value='';
	}
	document.getElementById('at').value=1;
}
function validaLimitacao()
{
	var selecao = document.getElementById('forma_pagamento');
	if(selecao.value=='')
	{
		alert('Seleciona a forma de Pagamento!');
		selecao.focus();
		return false;
	}
}
/* Zera os campos com '0.00 ou 0' */
function limpaCampoZerado(id)
{
    var campo = document.getElementById(id);

    if(campo.value=='0.00' || campo.value=='0')
    {
       campo.value='';
    }
}
/* Gera uma nova consulta */
function selectProducts(idSelect,inputField,url)
{
	var nome_produto = $(inputField).value;
	atualizaDiv(idSelect,url+'?nome_produto='+nome_produto);

	return false;
}

function enviaDadosPedido(Form,selectRight)
{
	var total = $(selectRight).options.length;
	for(i=0;i<total;i++)
	{
		$(selectRight).options[i].selected=true;
	}
	$(Form).submit();
}

function selectFilterXML(Form,selectCat,selectProd)
{
	var totalCat = $(selectCat).options.length;
	var totalProd = $(selectProd).options.length;
	for(i=0;i<totalCat;i++)
	{
		$(selectCat).options[i].selected=true;
	}
	for(i=0;i<totalProd;i++)
	{
		$(selectProd).options[i].selected=true;
	}
	$(Form).submit();
}

function formatNumber(num)
{    
    var n = num.toString();
    var nums = n.split('.');
    var newNum = "";
    if (nums.length > 1)
    {
        var dec = nums[1].substring(0,2);
		if(dec.length==1)
			dec = dec+'0';
        newNum = nums[0] + "," + dec;
    }
    else
    {
		newNum = num+",00";
    }
	return newNum;
}

function calculaBonus(input,div,valor_bonus,max)
{
	max = parseFloat(max);
	var bonus = document.getElementById(input).value;

	if(bonus>max)
	{
		document.getElementById(input).value = max;
		valor_bonus = parseFloat(valor_bonus);
		var total = formatNumber(max * valor_bonus);
	}
	else
	{
		if(bonus != "") {
			bonus = parseFloat(bonus);
			valor_bonus = parseFloat(valor_bonus);
			var total = formatNumber(bonus * valor_bonus);
			total = total.toString();
		}
		else {
			var total = "";
		}
	}
	document.getElementById(div).innerHTML = total;
}

function displayDiv(div)
{
	var elemento = document.getElementById(div);

	if(elemento.style.display=='none')
		elemento.style.display = '';
	else
		elemento.style.display = 'none';
}

<!-- Funcao que conta os caracteres dentro de um Textarea -->
function caracterRestante(id,total, max)
{
	var rest = max - total;	
	if(rest < 0 )
	{
		valor = document.getElementById(id).value;
		valor = valor.substring(0,max);
		document.getElementById(id).value = valor;
		return (false); 
	}	
	document.getElementById('restante').innerHTML=rest;
}

//Função que valida as caracteristicas
function addImgCat(divUp)
{
	if($('categorias_select').value==0)
	{
		$(divUp).innerHTML = 'Selecione uma categoria para atualização de imagem';
		return false;
	}
	
	if($('imgCategoria').value=='')
	{
		$(divUp).innerHTML = 'Selecione uma imagem para a categoria';
		return false;
	}
}