//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 null;
	}
	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);
	        }
		}
	}
	
	if(file.indexOf('?') <  0){
		sep = '?';
	}else{
		sep = '&';
	}
	
	xmlObj.open ('GET', file+sep+'ignoreMe='+new Date().getTime(), 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 displayMessageSized(url,w,h)
{
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(w,h);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}
//-----------------------
function displayMessageSized(url,w,h)
{
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(w,h);
	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 escolhaSelecionados(opcao){
	
	
	if(opcao==1){
		document.getElementById('fretesEnv').style.display=''
		document.getElementById('todosFretes').checked=false	
	}
	else{
		document.getElementById('fretesEnv').style.display='none'
		document.getElementById('selecionadosFretes').checked=false
	}
}



function buscaCep(cep,endereco_cliente,numero_endereco,complemento,bairro_cliente,cidade_cliente,estado_cliente,estado_funcao,destino,no_focus,id_loja){

	var xmlObj = null;
	if(window.XMLHttpRequest){
		xmlObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		return null;
	}
	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();
					}
				}
				// INICIO DA VALIDACAO DO CEP PREENCHIDO
				if((resposta[0].length <= 0) && (document.getElementById('cidade_cliente').value == "")) {
					document.getElementById('erro_cep_invalido').value = '1';
					alert ('Este CEP não está cadastrado em nossa base de dados.');
				} else {
					document.getElementById('erro_cep_invalido').value = '0';
					document.getElementById('erro_cep_invalido_span').style.display = 'none';
				}
				if (document.getElementById('endereco_cobranca_diferente').checked == 1) {
					if ((resposta[0].length <= 0) && (document.getElementById('cobranca_cidade').value == "")) {
						document.getElementById('erro_cep_cobranca_invalido').value = '1';
						alert ('Este CEP não está cadastrado em nossa base de dados.');
					} else {
						document.getElementById('erro_cep_cobranca_invalido').value = '0';
						document.getElementById('erro_cep_cobranca_invalido_span').style.display = 'none';
					}
				}
				//FIM DA VALIDACAO DO CEP PREENCHIDO
			}else{
				alert("Houve um problema ao obter os dados:\n" + xmlObj.statusText);
			}
		}
	}
	
	xmlObj.open ('GET', '/adm/funcoes/busca_cep.php?cep='+cep+'&loja='+id_loja, 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,id_loja){

	var xmlObj = null;

	if(window.XMLHttpRequest){
		xmlObj = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		return null;
	}

	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+'&loja='+id_loja, 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 (teclapres){
	if(window.event) {
		var tecla = teclapres.keyCode;
	// Nestcape / firefox
	}else if(teclapres.which) {
		var tecla = teclapres.which;
	}
        
    } else {
        var tecla = null;
    }
	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 || tecla == null){ tam = tam - 1; }
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 || tecla == null ){
		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)
{
    var Parms = url.parseQuery();
	new Ajax.Updater(div,url,{
                              asynchronous:true,
                              evalScripts:true,
                              requestHeaders:['X-Update', div],
                              parameters: Parms
                            });
}
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 valida as caracteristicas
function addColor(Form,divUp)
{
	if($('cor').value=='')
	{
		alert('Informe a cor');
		return false;
	}
	
	if($('imagem_cor').value=='')
	{
		alert('Selecione uma imagem para a cor');
		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;
}

//Funcao envia formulario por ajax sem reset
function adiciona_premio(Form,divUp,idPremiacao)
{
	Form.request({
		onSuccess:function(transport)
		{
			if(transport.responseText == 'Sucesso') {
				
				window.location = 'fidelizacao.php?aba=fidelizacao_produto&id_cadastro_premiacao='+idPremiacao;
				
			} else {
				
				$(divUp).innerHTML=transport.responseText;
				$(divUp).style.display = '';
			
			}
		}
	});
	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, limite) {
	var total = $(selectLeft).options.length;
	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;
			
			var total2=$(selectRight).options.length;
			
			if(limite == 0 || total2 < limite) {

				for(cont=0;cont<total2;cont++) 
				{
					if($(selectLeft).options[i].value == $(selectRight).options[cont].value)
					{
						inclui = 0;
						vetor[k] = $(selectLeft).options[i];
						k++;
						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);
					
					vetor[k] = $(selectLeft).options[i];
					k++;
				
				}

			} else {
				
				alert('Seleção limitada a '+limite+' produtos.');
				
				break;
				
			}
			
		}
	}

	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';
	
}
//funciona com a funcao acima
function autoSelectTag(Form)
{
	// função pega os elementos dinâmicamente
	
	if (arguments.length>1){
		
		for(j=1;j<arguments.length; j++){
			
			var total = document.getElementById(arguments[j]).options.length;
			
			for(i=0;i<total;i++)
			{
				
				document.getElementById(arguments[j]).options[i].selected=true;
			}

		}			
	}

	//$(Form).submit();
}
//Função que faz a mudança de elemento nos selects dos perfis
function SelecionaPremios(selectLeft, selectRight) {
	
	var total=$(selectLeft).options.length;
	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;
			
			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);
			
		}
	}
	
	$(selectRight).style.width = widthRight+'px';
	$(selectLeft).style.width = widthLeft+'px';
	
}


function RemovePremios(selectLeft, selectRight) {
	
	var total=$(selectLeft).options.length;
	
	var	widthLeft = $(selectLeft+'Div').clientWidth;
	var	widthRight = $(selectRight+'Div').clientWidth;
	var k=0;
	var vetor = new Array();
	
	for(i=0;i<total;i++)
	{
		if($(selectLeft).options[i].selected==true)
		{
			
			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);
}

function enviaMarcas(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_marcas_adcionais.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 changeOptionsProd(idSelect,idLimit)
{
	if($('tipo').value == 2)
	{
		$(idSelect).style.display 	  = '';
		$(idLimit).style.display  	  = 'none';
		$(showTextArea).style.display = 'none';
	}
	else if($('tipo').value == 1)
	{
		$(idLimit).style.display  	  = '';
		$(idSelect).style.display 	  = 'none';
		$(showTextArea).style.display = 'none';
	}
	else
	{
		$(showTextArea).style.display = '';
		$(idSelect).style.display     = 'none';
		$(idLimit).style.display      = 'none';
	}
}
function changeOptionsProdEdit(idSelect,idLimit)
{
	if($('tipo2').checked == true)
	{
		$('tipo_novo').value = $('tipo2').value;
		$(idSelect).style.display 	  = '';
		$(idLimit).style.display  	  = 'none';
		$(showTextArea).style.display = 'none';
	}
	else if($('tipo1').checked == true)
	{
		$('tipo_novo').value = $('tipo1').value
		$(idLimit).style.display  	  = '';
		$(idSelect).style.display 	  = 'none';
		$(showTextArea).style.display = 'none';
	}
	else
	{
		$('tipo_novo').value = $('tipo1').value
		$(showTextArea).style.display = '';
		$(idSelect).style.display     = 'none';
		$(idLimit).style.display      = 'none';
	}
	
}
function insertFeatureProduct(opcao, elemento){

	if ($(opcao).value=='')
    {
		return false;
	}
	else
    {
		var cont = $('contador').value;
		cont++;
		$('contador').value = cont;
		var cont = $('contador').value;
		atualizaDivBottom(elemento,' informacao_produto_opcoes.php?opcao=' + $(opcao).value + '&cont=' + cont + '&valor2=' + $('valor2').value);
		$(opcao).value = '';
		$('valor2').value = '';
		$(opcao).focus();
	}
}
function removeFeatureCadInf(elemento)
{
	var cont = $('contador').value;
	cont--;
	$('contador').value = cont;
	var span = $(elemento);
	span.parentNode.removeChild(span);
}
function validaInformacaoProduto()
{
	var nome = $('nome_loja').value;
	var tipo2 = $('tipo2');
	
	var cont = $('contador').value;
	
	if(nome=='')
	{
		alert('Informação adicional não informada!');		
		$('nome_loja').focus();
		return false;
	}
	
	return informacoesAdicionais.validaRelacionadas();
}

function validaInformacaoProdutoEdit()
{
	var nome = $('nome_loja').value;	
	var cont = $('contador').value;
	var ativa = $('ativa').value;	
	
	if(nome=='')
	{
		alert('Informação adicional não informada!');		
		$('nome_loja').focus();
		return false;
	}
	if(ativa == 0){
		
		var confirmation = confirm('Ao inativar esta Informação Adicional, todos seus relacionamentos serão perdidos.\nDeseja realmente inativá-la?');
		return confirmation;
	}
	
	return informacoesAdicionais.validaRelacionadas();

}
function validaInformacaoOpcoes(){
	 
	
	var tipo_ant = $('tipo_ant').value;
	var tipo_novo = $('tipo_novo').value;
	var exibicao_ant = $('exibicao_ant').value;
	var exibicao_novo = $('exibicao_novo').value;	
	
	if(tipo_ant != ""){
		if(tipo_ant!=tipo_novo)
		{
			var confirmation = confirm('Ao trocar o tipo de informação adicional, as informações dos produtos serão perdidas.\nDeseja realmente modificar o tipo de informação?');
			return confirmation;
		}
	}
	if(tipo_novo == 1){
		if(exibicao_ant != '' && exibicao_ant!=exibicao_novo)
		{
			var confirmation = confirm('Ao trocar a forma de exibição, as opções e imagens já cadastradas serão perdidas.\nDeseja realmente modificar a forma de exibição?');
			return confirmation;
		}
	}
	return true;
	

}
function tipoNovo(valor){
	$('tipo_novo').value = valor;
}
function ExibicaoNovo(valor){
	$('exibicao_novo').value = valor;
}
function habilitaOrdem() {
		
	$('ordem').disabled = $('ordem').disabled ? 0 : 1
	if($('ordem').disabled == 1){
		$('ordem').value = "";
		$('ordem').style.background="#DDD";
	}else{
		$('ordem').style.background="#FFF";
	}
}


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 valorUSA(v)
{
	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito

	while(v.length < 3) {
		v = '0' + v;
	}
	if(v.length > 3 && v.charAt(0) == '0') {
		v = v.substr(1, v.length - 1);
	}
	
	v=v.replace(/(\d)(\d{2})$/,"$1.$2") //Coloca ponto 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,caminho)
{
	if(typeof(caminho) == "undefined") { caminho = '../pedidos/'; }
	var nome_produto = $(inputField).value;
	var sinal = "?";

	if(url.indexOf("?") >= 0){
		sinal = "&";
	}

	atualizaDiv(idSelect,caminho+url+sinal+'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 enviaDadosProduto(Form,selectRight)
{
	var total = $(selectRight).options.length;
	for(i=0;i<total;i++)
	{
		$(selectRight).options[i].selected=true;
	}
	$(Form).submit();
}

function enviaDadosArquivos(Form,selectRight)
{
	var total = $(selectRight).options.length;
	for(i=0;i<total;i++)
	{
		$(selectRight).options[i].selected=true;
	}
	$(Form).submit();
}

/**
 * Função dinâmica para auto selecionar selects antes de submeter o formulário
 * @param Array arguments - não declarado por ser dinâmico contém a lista de selects tags a ser oselecionados.
 * @return null
 * @obs: não ingessar a função.
 * @author rcampagnoli
 */
function selectFilterXML()
{
	
	var total = null;
		
        for(j=0;j<arguments.length; j++)
	{
                if ($(arguments[j]) != null) var total = $(arguments[j]).options.length;
                else var total = 0;

                for(i=0;i<total;i++)
	{
                        $(arguments[j]).options[i].selected=true;
                }
	}
}

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;
	}
}

function valida_compre_junto() {
	var selecionados = $$('.div_produto');
	
	if(selecionados.length > 1) {
		return true;
	} else {
		alert('Escolha pelo menos 1 produto para o Compre Junto');
		return false;
	}
}

//soma o preço de todos os produtos do compre junto
function compre_junto_total() {
	var total = parseFloat(valorUSA($('principal_preco').innerHTML)); //total recebe o valor do produto principal
	var produtos = document.getElementsByName("produtos_selecionados[]");
	
	for(i = 0; i < produtos.length; i++) {
		total = total + parseFloat(valorUSA($('preco_desconto_' + produtos[i].value).innerHTML));
	}
	total = total.toFixed(2);
	total = valorBr(total);
	$('cj_total').innerHTML = total;
}

//adiciona produto ao kit compre junto
function compre_junto_add_produto()
{
	var limite = 3 //limite de produtos no compre junto
	//var selecionados = document.getElementsByName("produtos_selecionados[]");
	var selecionados = $$('.div_produto');
	
	if(selecionados.length < 3) {
		var total  = $('selectFrom').options.length;
	
		for(i = 0; i < total; i++)
		{
			if($('selectFrom').options[i].selected==true)
			{
				if(!$('check' + $('selectFrom').options[i].value))
				{
					$('selectFrom').options[i].style.border = '1px solid #00f';
					new Ajax.Updater('div_produtos_selecionados', 'carrega_produto_compre_junto.php?id_produto=' + $('selectFrom').options[i].value, {method: 'get', insertion: Insertion.Bottom});
				}
			}
		}
		
		setTimeout("compre_junto_total()",500);
	} else {
		alert("Esta limitado a 2 produtos a criação do Compre Junto.");
	}

}

/**
 *Adiciona produto a lista
 */
function lista_add_produto(url){

	var selecionados = $$('.div_produto'); 
	
	if(selecionados){		 
		var total  = $('selectFrom').options.length;
		 
		for(i = 0; i < total; i++){
			  
			if($('selectFrom').options[i].selected==true){
				   
				if(!$('check' + $('selectFrom').options[i].value)){
				    	
					 $('selectFrom').options[i].style.border = '1px solid #00f';
					 new Ajax.Updater('div_produtos_selecionados', url+'?id_produto=' + $('selectFrom').options[i].value, {method: 'get', insertion: Insertion.Bottom});
				 }
			}
		}
	  
	} 
}

//retira produto do kit compre junto
function compre_junto_remove_produto(id_produto) {

	var total  = $('selectFrom').options.length;

	for(i = 0; i < total; i++)
	{
		if($('selectFrom').options[i].value == id_produto)
		{
			//$('selectFrom').options[i].className = 'selected_compre_junto';
			$('selectFrom').options[i].style.border = 'none';
		}
	}

	elemento = $('produto_' + id_produto);

	elemento.parentNode.removeChild(elemento);
	
	setTimeout("compre_junto_total()",500);
	
}

//retira produto do kit compre junto
function lista_remove_produto(id_produto) {

	var total  = $('selectFrom').options.length;

	for(i = 0; i < total; i++)
	{
		if($('selectFrom').options[i].value == id_produto)
		{
			//$('selectFrom').options[i].className = 'selected_compre_junto';
			$('selectFrom').options[i].style.border = 'none';
		}
	}

	elemento = $('produto_' + id_produto);

	elemento.parentNode.removeChild(elemento);	
	
}

// Mostra/Oculta variações dos produtos do compre junto
function compre_junto_variacoes(id_produto) {
	
	variacoes = $('variacoes_' + id_produto);
	
	if(variacoes.style.display == 'none') {
		variacoes.show();
	}
	else
	{
		variacoes.hide();
	}
}


function compre_junto_preco_produto(id_produto) {

	var indice = $('tipo_desconto_' + id_produto).selectedIndex;
	var tipo_desconto = $('tipo_desconto_' + id_produto).options[indice].value;
	var desconto = valorUSA($('desconto_' + id_produto).value);
	var preco_produto = $('preco_' + id_produto).value;
	var erro = 0;

	$('desconto_' + id_produto).value = desconto;

	if(tipo_desconto == 1) {

		if(desconto > 100) {
			erro = 1;
			alerta = 'O desconto não pode ser maior que 100%';
			maximo_desconto = '100.00';
		} else {
			desconto = (preco_produto / 100) * desconto;
		}
	}

	if(tipo_desconto == 0 && parseFloat(desconto) > preco_produto) {
		erro = 1;
		alerta = 'O valor do desconto não pode ser maior que o valor do produto.';
		maximo_desconto = valorUSA(preco_produto);
	}

	if(erro == 0) {
		var novo_preco = preco_produto - desconto;
		novo_preco = novo_preco.toFixed(2);
		novo_preco = valorBr(novo_preco);
		$('preco_desconto_' + id_produto).innerHTML = novo_preco;
	} else {
		preco_produto = valorBr(preco_produto);
		$('preco_desconto_' + id_produto).innerHTML = '0.00';
		$('desconto_' + id_produto).value = maximo_desconto;
		alert(alerta);
	}
	compre_junto_total();
}

//adiciona produto brinde
function brinde_add_produto()
{
	var selecionados = $$('.div_produto');
	
	var total  = $('selectFrom').options.length;

	for(i = 0; i < total; i++)
	{
		if($('selectFrom').options[i].selected==true)
		{
			if(!$('check' + $('selectFrom').options[i].value))
			{
				$('selectFrom').options[i].style.border = '1px solid #00f';
				new Ajax.Updater('div_produtos_selecionados', 'carrega_produto_brinde.php?id_produto=' + $('selectFrom').options[i].value, {method: 'get', insertion: Insertion.Bottom});
			}
		}
	}

}

//remove produto dos brindes
function brinde_remove_produto(id_produto) {

	var total  = $('selectFrom').options.length;

	for(i = 0; i < total; i++)
	{
		if($('selectFrom').options[i].value == id_produto)
		{
			//$('selectFrom').options[i].className = 'selected_compre_junto';
			$('selectFrom').options[i].style.border = 'none';
		}
	}

	elemento = $('produto_' + id_produto);

	elemento.parentNode.removeChild(elemento);
	
}

//coloca borda nos produtos ja selecionados
function verifica_selecionados()
{
	var total  = $('selectFrom').options.length;

	for(i = 0; i < total; i++)
	{
		if($('check' + $('selectFrom').options[i].value))
		{
			$('selectFrom').options[i].style.border = '1px solid #00f';
		}
	}

}

//busca produtos brindes
function brinde_busca_produtos(idSelect,inputField,url,caminho)
{
	var nome_produto = $(inputField).value;
	
	atualizaDiv(idSelect,'../produtos/'+url+'&nome_produto='+nome_produto);
	
	setTimeout("verifica_selecionados()",500);

	return false;
}

function var_forma(elemento) {
	
	if(elemento == ''){
		$('receba_online').show();
		$('legenda1').show();
		$('legenda2').show();
		$('legenda3').show();
		$('legenda4').show();
		$('urlRetorno').hide();
	}else{
		$('receba_online').hide();
		$('legenda1').hide();
		$('legenda2').hide();
		$('legenda3').hide();
		$('legenda4').hide();
		$('urlRetorno').show();
	}
	
	var elemento = 'var_forma_'+elemento;
	
	$$(".var_forma").each(function(e) {

		if(e.id == elemento) {
			e.show();
		} else {
			e.hide();
		}
	});
	
}

function ativaFormaPagamento(id){
	
	url = "formas_informacoes.php?id="+id;
	w = "700";
	h = "600";
	
	displayMessageSized(url,w,h);
}

function mudaTextoExplicativo(identificacao){
	$$(".texto_explicativo").each(function(e){
		e.hide();
	});
	
	$$(".texto_"+identificacao).each(function(e){
		e.show();
	});
}

function verificaConfiguracao(id,forma,tecnologia){
	window.location.href="pagamento_editar.php?id="+id+"&tecnologia="+tecnologia+"&aba=configurar";
}

function adiciona_premio_janela(id_premiacao)
{
	var existe = 0;
	
	var selecionado = $('selectFrom').selectedIndex;
	
	if(selecionado >= 0) {
		
		var id_produto = $('selectFrom').options[selecionado].value;
			
		$$('.premios').each(function(e){
			
			if(e.value == id_produto) {
				existe = 1;
			}
			
		});
		
		if(existe == 0) {
			
			linha++;
			
			displayMessageSized('carrega_premio.php?acao=adicionar_form&linha='+linha+'&id_produto='+id_produto+'&id_premiacao='+id_premiacao,400,220);
		
		} else {
			
			alert('Prêmio já cadastrado.');
		
		}
		
	} else {
		
		alert('Escolha um prêmio.');
		
	}

}

function remove_premio(linha,id_premiacao) {
	var ini;
	var fim;
	var id_produto;
	
	e = $('linha_' + linha);

	e.getElementsBySelector('.ini').each(function(f){
		ini = f.value;
	});

	e.getElementsBySelector('.fim').each(function(f){
		fim = f.value;
	});

	e.getElementsBySelector('.premios').each(function(f){
		id_produto = f.value;
	});
		
	var url = 'carrega_premio.php?acao=excluir&id_premiacao='+id_premiacao+'&id_produto='+id_produto+'&ini='+ini+'&fim='+fim;
	
	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) {
		window.location = 'fidelizacao.php?aba=fidelizacao_produto&id_cadastro_premiacao='+id_premiacao;
	  }
	});

	
}

function valida_premios() {
	
	var ini;
	var fim;
	var maximo = 1;
	var array_classificacao = new Array();
	var retorno = true;
	
	selecionados = $$(".premios_selecionados");
	
	selecionados.each(function(e) {
	
		e.getElementsBySelector('.ini').each(function(f){
			ini = parseInt(f.value);
		});

		e.getElementsBySelector('.fim').each(function(f){
			fim = parseInt(f.value);
		});
		
		for(i = ini; i <= fim; i++) {
			
			array_classificacao.push(i);
			
		}
		
		if(parseInt(fim) > maximo) {
			maximo = fim;
		}
	
	});
	
	for(i = 1; i <= maximo; i++) {
		
		if(array_classificacao.indexOf(i) == -1) {
			
			retorno = false;
			
			break;
		
		}
		
	}
	
	if(retorno == false) {
	
		alert('Faltam posições na classificação: '+i);
	
	}

	return retorno;

}

function adicionaBonus(Form,divUp)
{
	
	if($('bonus').value=='')
	{
		alert('Informe a quantidade de bônus');
		return false;
	}
	
	if($('descricao').value=='')
	{
		alert('Informe a descrição');
		return false;
	}

	sendFormAjax(Form,divUp);
	return false;
}

function inserirNegociacao(id_produto_preco_negociacao){
	
	var corpo;
	
	try{
		$('negociacao_linha').parentNode.removeChild($('negociacao_linha'));
	}catch (e) {
		var erro = 1;
	}

	var tbody = 'negocio_body_'+id_produto_preco_negociacao;
	var novo = 0;
	
	try{
		corpo = $(tbody);
	}catch(e){
		tbody = 'negocio_div_'+id_produto_preco_negociacao;
		novo = 1;
	}
	
	if(corpo == null){
		tbody = 'negocio_div_'+id_produto_preco_negociacao;
		novo = 1;
	}
	
	new Ajax.Updater(tbody, 'inserir_negociacao.php?id_produto_preco_negociacao='+id_produto_preco_negociacao+'&novo='+novo, {
		insertion: Insertion.Bottom
	});

	
}

function cancelaNegociacao(id_produto_preco_negociacao,novo){
	
	if(novo == 1){
		$('negocio_div_'+id_produto_preco_negociacao).innerHTML = '';
	}else{
		$('negociacao_linha').parentNode.removeChild($('negociacao_linha'));
	}

}

function liberaSelect(){

	if (document.getElementById('radioImagens').checked==1){
		document.getElementById('libera_select').style.display = '';
	}else{
		document.getElementById('libera_select').style.display = 'none';
	}

}

function carregaEditor(idEditor) {
	
	if(CKEDITOR.instances[idEditor]) {
		var instance = CKEDITOR.instances[idEditor];
		if (instance) { CKEDITOR.remove(instance); }
	}
	
	CKEDITOR.replace(idEditor);
	
}

function exportarExcel(form,action,target) {
	
	form = $(form);
	
	var antAction = form.action;
	var antTarget = form.target;
	
	form.action = action;
	form.target = target;
	
	form.submit();
	
	form.action = antAction;
	form.target = antTarget;
	
	return false;
	
}

/*
 * Funcao que alterna exibicao de divs
 * @params exibir (id da div a ser exibida)
 * @params ocultar array (ids de todos elementos envolvidos)
 */
function alternaExibicao(exibir,ocultar) {
	
	if(ocultar) {
		for(i=0;i<ocultar.length;i++) {
			$(ocultar[i]).hide();
		}
	}
	
	if(exibir) {
		$(exibir).show();
	}
	
}

function selecionaListas() {
	
	select = $('select_listas');
	total  = select.options.length;
	listas = new Array();
	selecionados = 0;
	
	for(i=0;i<total;i++) {
		if(select.options[i].selected) {
			listas[selecionados] = select.options[i].value;
			selecionados++;
		}
	}
	
	if(listas.length) {
		$('lista').value = listas.join(',');
	}
	
	closeMessage();
	
}

function buscaListas(multiplo) {
	
	if(multiplo == undefined) multiplo = 0;
	
	palavra = $('busca_listas').value;
	
	new Ajax.Updater('DHTMLSuite_modalBox_contentDiv', '/adm/extras/listas/funcoes/select_listas_clientes.php?multiplo='+multiplo+'&palavra='+palavra);
	
}
