function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function atualizaValorCampo(campo, valorOn){
	var valor = campo.value;
	var novoValor;
	var alteraValor = false;
	
	if(valor == valorOn){
		novoValor = '';
		alteraValor = true;
	}else if(valor == ''){
		novoValor = valorOn;
		alteraValor = true;
	}
	
	if(alteraValor)
		campo.value = novoValor;
}
function carregaValoresSubmitPasso2() { 
    document.envie_seu_arquivo_prosseguir_passo2.tipoProduto.value = document.getElementsByName('tpProd')[0].value; 
    document.envie_seu_arquivo_prosseguir_passo2.tituloTrabalho.value = document.getElementById('tituloTrabalho').value;
    document.envie_seu_arquivo_prosseguir_passo2.action='acao.php'; 
}

function toggleDiv(select, id) {
    var sel = select.options[select.selectedIndex].text;
    var edit = document.getElementsByName(id+'text')[0];
    var div = document.getElementById(id+'div');
    var txt = document.getElementsByName(id+'text');
    if (sel.toLowerCase() == 'outro' || sel.toLowerCase() == 'color plus') {
        edit.disabled = false;
        div.style.display = 'block';
        txt[0].focus();
    } else {
        document.getElementsByName(id+'text')[0].value = '';
        edit.disabled = true;
        div.style.display = 'none';
    }
}

function esqueceuSenha(op) {
    var div = document.getElementById('esqueceuSenha');
    
    if (op) div.style.display = 'block'; 
    else div.style.display = 'none';
}

function tipoPessoa(op) {
    var divPj = document.getElementById('pessoaJuridica');
    var divPf = document.getElementById('pessoaFisica');
    
    if (op.value == 'f') {
        divPf.style.display = 'block';
        divPj.style.display = 'none';
    } else {
        divPj.style.display = 'block';
        divPf.style.display = 'none';
    }
}

function detalharOrcamento(id) {
    document.getElementById("codigo").value=id;
    document.getElementById("orcamentos").submit();
}


function detalharUsuario(id) {
    document.getElementById("codigo").value=id;
    document.getElementById("usuarios").submit();
}

function ativaUsuario(id) {
	document.getElementById("acao").value="ativa";
	document.getElementById("codigo").value=id;
    document.getElementById("form_cliente").submit();	
}

function desativaUsuario(id) {
	document.getElementById("acao").value="desativa";
	document.getElementById("codigo").value=id;
    document.getElementById("form_cliente").submit();	
}

function verPedidosUsuario(id) {
	document.getElementById("acao").value="pedidos_usuario";
    document.getElementById("codigo").value=id;
    document.getElementById("form_cliente").submit();	
}

function trocaPedidosUsuario() {
	document.getElementById("acao").value="troca_pedidos_usuario";
    document.getElementById("form_consulta").submit();	
}


function atualizarCadastro() {
    var secao = document.getElementById("acao").value;
    
    if (secao != 'atualizarCadastro')
        return false;
        
    return true;
}

function submitFrete() {
/*    var acao = document.getElementById("acao").value;
    
    if (acao != 'prossegue_compra_frete')
        return false;
  */      
    return true;
}

function prosseguir_frete() {
    document.formDadosEntrega.acao.value = "prossegue_compra_frete";
    document.formDadosEntrega.submit();    
}

function atualizar_frete(ultimo, atual) {
    if (ultimo.value == atual.value) {  
        return false;
    }
    
    document.formDadosEntrega.acao.value = "atualiza_frete";
    document.formDadosEntrega.submit();
}

function copiaEndereco(){
    var formCliente = document.getElementById("atualizaDadosClienteForm")
    var formClienteInputs = formCliente.getElementsByTagName("input");
    var formClienteSelects = formCliente.getElementsByTagName("select");

    var formEntrega = document.getElementById("formDadosEntrega");
    var formEntregaInputs = formEntrega.getElementsByTagName("input");
    var formEntregaSelects = formEntrega.getElementsByTagName("select");

    for (x in formClienteInputs)
        if (formClienteInputs[x].type != 'hidden' && formClienteInputs[x].type != 'image' ) 
            formEntregaInputs[x].value = formClienteInputs[x].value;
        
    for (x in formClienteSelects)
        formEntregaSelects[x].value = formClienteSelects[x].value;
}

function atualizaFrete(cidade, cep){
    /*
    if (estado == '23' && cidade == '4343')
        document.getElementById("motoboy").style.display = 'block';
    else
        document.getElementById("motoboy").style.display = 'none';
    */
    /*
    var url = $("#url").val()+"/acaoAjax.php?secao=tabela_frete&idCidade="+cidade+"&cep="+cep;
    var urlValida = url +"&valida='valida'";
    $("#resposta").load(urlValida,{}, function(){
        if ($("#resposta > p").val() == undefined) {
            $("#frete").load(url,{}, function(){
    	        $("#loading").hide();
		        $("#frete").show();
            });
            $("#loading").show(); 
            $("#frete").hide();
            
        }                    
    });
    */
}

function escondeConfirmaPedido() {
    document.getElementById("confirmaPedido").style.display = 'none';
    document.getElementById("titulo").value = "Pagamento";
}


function detalharPedido(id) {
    document.getElementById("acao").value= "detalhar_pedido";
    document.getElementById("codigoPedido").value=id;
    document.getElementById("pedidos").submit();
}



/**
* Calcula o total da compra na página de caracteristicas
*/
function calculaTotal(){
    var total = 0;
    
    //preco base do template
    var precoTemplate = parseFloat($("#precoProduto").val().replace(",","."));
    //desconto da quantidade    
    var custoQuantidade = parseFloat($("#selectQuantidade :selected").attr('custo').replace(",","."));
    //numero de 'unidades'
    var quantidade = parseFloat($("#selectQuantidade :selected").attr('quantidade').replace(",","."));
    var subTotal = parseFloat(parseFloat(precoTemplate) + parseFloat(custoQuantidade)) * parseFloat(quantidade);
    subTotal = subTotal.toFixed(2);
    total += parseFloat(subTotal);
    var totalParametros = 0;
    //Percorre os parametros e acumula o valor das opcoes selecionadas
    $("select[name*='parametros']").each(function(x){
        var selectedIndex = $(this).attr('selectedIndex');
        totalParametros += parseFloat($(this).find( "option:eq(" + selectedIndex +")" ).attr('id').replace(",","."));
    });
    
    //total de acrescimo pelos parametros selecionados
    totalParametros = parseFloat(totalParametros) * parseFloat(quantidade);
    
    total += parseFloat(totalParametros);
    
    //atualiza o total
    $("#total").val(total.toFixed(2).replace(".",","));
    
    
//    alert(precoTemplate);
//    alert(custoQuantidade);
//    alert(totalParametros);
//    alert(total);
        
    //atualiza o texto da quantidade    
    var qtd = jQuery.trim($("#selectQuantidade :selected").text());
    $("#quantidade").val(qtd);
}

/**
* Troca o subtotal quando são editados os valores de papel e acabamento
*/

function trocaSubtotal(select, idParametro){
 
    // var quantidade;
    // contem o custo do valor do parametro
    var option = select.options[select.selectedIndex];
    var selectedId = parseFloat(option.id).toFixed(2);
    var subtotal = getSubtotalFormatado();
    var valorAnterior = parseFloat(document.getElementById('custoValorAnterior'+idParametro).value).toFixed(2);
    document.getElementById('custoValorAnterior'+idParametro).value = selectedId;
    
    // pega a quantidade selecionada;
    // quantidade = option.getAttribute('textovalor');
    
    //pega o primeiro valor do select para dividir a quantidade e multiplicar pelo valor certo.
    // var primeiroValorSelect = select.options[0].getAttribute('textovalor');
    // var quantidadeFormatada = parseInt(quantidade) / parseInt(primeiroValorSelect);

    subtotal = (parseFloat(subtotal) + parseFloat(selectedId) - valorAnterior).toFixed(2);
    // var total = (parseFloat(quantidadeFormatada) * subtotal).toFixed(2);
    
/*
    alert('ID: ' + selectedId +
          '\nSubtotal1: ' + subtotal +
          '\ncustoValorAnterior: ' + valorAnterior +
          '\nquantidade: ' + quantidade +
          '\nPrimeiro valor: ' + primeiroValorSelect +
          '\nQuantidade Formatada: ' + quantidadeFormatada +
          '\nTotal: ' + total);
  */    
          
     
    atualizaTotal(subtotal);
    
    
 }
 
 function atualizaTotal(subtotal){
 
//    var subtotal = $("#subtotal").val().replace(".","");
//    subtotal = parseFloat(subtotal.replace(",", ".")).toFixed(2);

    $("#subtotal").val(subtotal.replace(".",","));
    var quantidade;
    
    $("#selectQuantidade option:selected").each(function(){
               quantidade = $(this).attr('quantidade');
            });
            
    var total = parseFloat(quantidade * subtotal).toFixed(2);
    total = total.replace(".",",");
    
    $("#total").val(total);
/*
    alert(  'Subtotal' + subtotal + 
            '\nQuantidade selecionada: ' + quantidade +
            '\nTotal: ' + total);
 */
 }
 
 function getSubtotalFormatado(){
 
    var subtotal = $("#subtotal").val().replace(".","");
    subtotal = parseFloat(subtotal.replace(",",".")).toFixed(2);
    
    return subtotal;
    
}
 
 
 function editarProduto(idProdutoCarrinho){
 
    $("#idProdutoCarrinho").val(idProdutoCarrinho);
    $("#form_carrinho #acao").val('editar_produto');
    $("#form_carrinho").submit();
 
 }
 
 function carregaValorFrete(vlrFrete){
    document.formDadosEntrega.valorFrete.value = vlrFrete;
 }
 
 function mostraCortina() {
    var newdiv = document.createElement('div');
    newdiv.id = 'bloqueio';
    newdiv.style.width = screen.width + 'px';
    newdiv.style.height = '1200px';
    newdiv.style.position = "absolute";
    newdiv.style.top = '0px';
    newdiv.style.left = '0px';
    newdiv.style.zindex='1000';

    var opa = 5;
    if(document.all){
        newdiv.style.filter = 'Alpha(opacity='+opa+')';
    }else{
        newdiv.style.opacity = opa/100;
    }
//    document.getElementsByTagName("body")[0].style.overflow='hidden';
    document.getElementsByTagName("body")[0].appendChild(newdiv);
 }
 
 function fazUpload() {
    var arq = document.getElementById('arquivo')

    //Se não tem arquivo não coloca a imagem de atividade.
    if (arq.value == '')
        return false;
    else {
        //Se não responde ao document.all é porque não é I.E., não precisa validar o caminho.
        if (document.all) {
            var arqName = arq.value;
            regEx = /^([a-zA-Z]:\\.+\.[\w\d]{3,})|(\\.+\.[\w\d]{3,})$/;
            //Se o caminho for válido, mas o arquivo não existir, será pego na validação do PHP
            if (!regEx.test( arqName )) {
                alert("O arquivo informado não existe. Verifique.")
                return false;
            }
        }
    }

    document.getElementById('fileRow').style.display='none';
    document.getElementById('loadingRow').style.display='block';
    document.getElementById('sendRow').style.display='none';

	mostraCortina();
 }
 
 function mostraDivResponder(){
    document.getElementById('responder').style.display = 'block';
    document.getElementById('rejeitar').style.display = 'none';
    
    if (document.getElementById('responderOrcamento') !=  null)
        document.getElementById('responderOrcamento').style.display = 'none';
    if (document.getElementById('rejeitarOrcamento') !=  null)
        document.getElementById('rejeitarOrcamento').style.display = 'inline';
    
    
    document.getElementById('confirmarResposta').style.display = 'inline';
    document.getElementById('confirmarRejeicao').style.display = 'none';
    return false;
 }

 function mostraDivRejeitar(){
    document.getElementById('responder').style.display = 'none';
    document.getElementById('rejeitar').style.display = 'block';
    
    if (document.getElementById('rejeitarOrcamento') !=  null)
        document.getElementById('rejeitarOrcamento').style.display = 'none';
    if (document.getElementById('responderOrcamento') !=  null)
        document.getElementById('responderOrcamento').style.display = 'inline';
    
    document.getElementById('confirmarResposta').style.display = 'none';
    document.getElementById('confirmarRejeicao').style.display = 'inline';
    return false;
 }


 
 function abreAtendimento() {
    window.open("http://printstore.mysuite.com.br/empresas/pst/atendimento.php","janela1", "width=600,height=450,scrollbars=NO");
}

//Retorna o nÃºmero de caracteres jÃ¡ digitados e a quantidade de caracteres que ainda podem ser digitados
//nomeCampo = nome do textArea
//tamTotal = mÃ¡ximo de caracteres permitido
//nomeDigitado = nome do local que receberÃ¡ a quantidade de caracteres jÃ¡ digitados
//nomeRestante = nome do local que receberÃ¡ a quantidade de caracteres disponÃ­veis 
function caracteresDisponiveis(evento, campo, tamTotal, nomeDigitado, nomeRestante){
  tam = campo.value.length;

  var keyCode = evento.keyCode;
  var charCode = evento.charCode;
  var deleteKey = false;
  var backspaceKey = false;
  var moveKey = false;

  if (keyCode==46 && charCode==0) deleteKey = true;
  if (keyCode==8 && charCode==0) backspaceKey = true;
  if (((keyCode>=33 && keyCode<=40) || keyCode==9) && charCode==0) moveKey = true;
    
  if (deleteKey || backspaceKey || moveKey) 
     return true;
  
  if (tam > tamTotal) 
    return false;
  
  str="";
  str=str+tam;

  labelDigitado = document.getElementById(nomeDigitado);
  labelRestante = document.getElementById(nomeRestante);

  labelDigitado.innerHTML = str;
  labelRestante.innerHTML = tamTotal - str;

  if (tam >= tamTotal){
    aux = campo.value;
    campo.value = aux.substring(0,tamTotal);
    labelDigitado.innerHTML = tamTotal
    labelRestante.innerHTML = 0
    return false;
  }
  return true;
}

function carregarFlash(idFlash, admin, height, width){    
        
        if(confirm("Tem certeza que deseja ir para outra página?\n\nSALVE SUAS ALTERAÇÕES ANTES DE CONTINUAR.\n\nPressione 'OK' para continuar ou 'Cancelar' para permanecer na página atual.")){
        
//            alert('Flash: ' + idFlash + "\nAdmin: " + admin + "\nHeight: " + height + "\nWidth: " + width);
        
            admin = (admin == '') ? 'false' : admin;
        
            $("#editorFlash").load($("#url").val() + '/acaoAjax.php?secao=carregar_flash&id='+idFlash + '&admin=' + admin + '&height=' + height + "&width=" + width );
            
            $("#loading").ajaxStart(function(){
                $(this).show();
            });
                
    //        alert($("#url").val() + '/acaoAjax.php?secao=carregar_flash&id='+idFlash);
            
            $("#loading").ajaxStop(function(){
                $(this).hide();
            });
        
        }    
            return false;
        
        
    }

function confirmaAlteracoes(){
    return confirm("SALVE SUAS ALTERAÇÕES ANTES DE CONTINUAR\nClique em 'Cancelar' para voltar ao editor e salvar,\nClique em 'Ok' para continuar se já estiver salvo.");
}

function confirmaAlteracoesVoltar(e){
    
    var confirma = confirmaAlteracoes();
    
    if(confirma)
        voltar(e);
    
    return false;
}
function confirmaAlteracoesReutilizarTemplate(e){
	
	var confirma = confirmaAlteracoes();
	
	if(confirma){
		e.preventDefault();
		document.getElementById('acao').value = 'reutilizar_template';
		document.getElementById('template_form_cadastro').submit();
	}else
		return false;
}

function confirmaExclusao(){
    return confirm('As alterações feitas no produto serão perdidas. Clique em OK para prosseguir.');
}

function editarTemplate(idTemplate){
    document.location.href=$("#urlADM").val()+'/lista_templates/editar/'+idTemplate;
}

function eliminarTemplate(idTemplate){
    
    var confirma = confirm('Tem certeza que deseja eliminar o template ' + idTemplate);
    if(confirma){
        document.getElementById('idTemplate').value = idTemplate;
        document.getElementById('form_eliminar_template').submit();
    }
    
    return false;

}

function publicarTemplate(idTemplate){
    
    var confirma = confirm('Tem certeza que deseja publicar o template ' + idTemplate);
    if(confirma){
        document.getElementById('idTemplatePublicar').value = idTemplate;
        document.getElementById('form_publicar_template').submit();
    }
    
    return false;

}

function templatePublicado(idTemplate){

    var confirma = confirm('Tem certeza que deseja colocar em teste o template ' + idTemplate);
    if(confirma){
        document.getElementById('idTemplateTeste').value = idTemplate;
        document.getElementById('form_colocar_em_teste_template').submit();
    }
    
    return false;
}


function trocaImagemPreview(op) {

    if (op == 'frente')
        step = -1;
    else if (op == 'verso')
        step = 1;
    else 
        step = op;

    var imgAtual = $("#atual").val();
    var totalImagens = parseInt($("#countFolhas").val()) * 2;
    var temp = parseInt(imgAtual) + parseInt(step);
    
    //Verifica se deve parar a execuçao
    if ((parseInt(temp) <= 0) || 
        (parseInt(temp) > parseInt(totalImagens)))
        return;
        
    var proxImg = parseInt(imgAtual) + parseInt(step);

    $("#imagem"+imgAtual).css({display:'none'});
    $("#imagem"+proxImg).css({display:''});
    $("#nEditado"+imgAtual).css({display:'none'});
    $("#nEditado"+proxImg).css({display:''});
    $("#atual").val(proxImg);

    if (op == 'frente' || op == 'verso'){
        //Marca se é frente ou verso
	    if (eval(parseInt(proxImg)%2) == 0){
	        $("#frente").css({'font-weight':'normal'});
	        $("#verso").css({'font-weight':'bold'});
	    } else { 
	        $("#verso").css({'font-weight':'normal'});
	        $("#frente").css({'font-weight':'bold'});
	    }
    } else {    
	    //Muda o estilo de < e >
	    if (parseInt(proxImg) == 1)
	        $("#anterior").css({display : 'none'});
	    else 
	        $("#anterior").css({display : ''});
	        
	    if (parseInt(proxImg) == parseInt(totalImagens))
	        $("#seguinte").css({display : 'none'});
	    else 
	        $("#seguinte").css({display : ''});
	        
        //atualiza o número da página
        $("#pgAtual").html(proxImg);	        
    }
            
    
}

function toggleImagem(idImagem){
//    alert("?");
//    alert($("#idImagemAnterior").val());
    $("#"+$("#idImagemAnterior").val()).css({display:'none'});
    $("#"+idImagem).css({display:''});
    $("#idImagemAnterior").val(idImagem);

}

function folhaAnterior(idFolha){
     toggleFolha(parseInt(idFolha) - 1, idFolha);
}

function folhaSeguinte(idFolha){
    toggleFolha(parseInt(idFolha) + 1, idFolha);
}

function toggleFolha(idFolha, idfolhaAnterior){

    var idAnterior = "#"+idfolhaAnterior;
    var id = "#"+idFolha;
//    alert(id + '\n' + idAnterior);
//    alert(id + '\n' +$(id).html());
//    alert(idAnterior + '\n' +$(idAnterior).html());
    
    $(idAnterior).css({display:'none'});
    $(id).css({display:''});
    
    
    if(idFolha == '1'){
        $("#anterior").css({display:'none'});
        $("#anteriorVazio").css({display:''});
    }else{
        $("#anterior").css({display:''});
        $("#anteriorVazio").css({display:'none'});
    }
    if(idFolha == $("#countFolhas").val()){
//    	alert('Ultima Folha');
        $("#seguinte").css({display:'none'});
        $("#seguinteVazio").css({display:''});
    }else{
//    	alert('Caiu no else');
        $("#seguinte").css({display:''});
        $("#seguinteVazio").css({display:'none'});
    }
    

}
    
function adicionarFiltro(){
    var oSel = document.getElementById('filtroTema');
    var oOptions = oSel.options;

    var cell = document.getElementById("selectTemas");
    var br = document.createElement('br');
    
    var newSelect = document.createElement('select');
    newSelect.name = 'filtro[tema][]';
//    newSelect.style.margin = '5px';
    for (i = 0; i< oOptions.length; i++){
        var newOption = document.createElement('option');
        newOption.value = oOptions[i].value; 
        newOption.innerHTML = oOptions[i].innerHTML;
        newSelect.appendChild(newOption); 
    }
    
    cell.insertBefore(newSelect, cell.lastChild.previousSibling);
    cell.insertBefore(br, cell.lastChild.previousSibling);
    
    var a = document.getElementById('adicionarFiltro');
    if (parseInt(a.name) >= 2) 
	   cell.removeChild(a);
    else 
       a.name = parseInt(a.name) + 1;
    
    return;
}

//*********************************************/
/**

 Funções para criar e tratar XHTTPREquest

//**********************************************/

function createHttpRequest()
{
   
    var xmlHttp;
    try  {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
    }catch (e){
      // Internet Explorer
      try{
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e){
        try{
             xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){
              alert("Erro: seu browser nÃ£o suporta a tecnologia Ajax.");
              return false;
          }
        }
    }
    return xmlHttp;
   
}

function whenReady(httpRequest){
    if (httpRequest.readyState == 4) {      
        if (httpRequest.status == 200) {
            //alert("the function is ready to be processed");           
            return true;
        } else {
            //alert('Ocorreu um problema com o request. (Code: ' + httpRequest.status + ')');
            return false;
        }
    } else {
        return false;
    }
}

/**
 * FIM XHTTPRequest
 */

/**
 * receve o input que da submit no form e muda os valores dos 
 * campos acao e idProdutoCarrinho.
 *  
 * @param input
 * @return
 */

function eliminarProdutoCarrinho(input){
	var exclusao = confirmaExclusao();
	
	if(exclusao){
		$("#idProdutoCarrinho").val(input.value);
		document.getElementById('form_carrinho').acao.value = 'remover_produto';
		
	}else
		return exclusao;
}

function toggleEdicao(input, edicao){

	//if(confirmaAlteracoes()){
		var idFlash = document.getElementById('idFlashAtual').value;
		var url = document.getElementById('url').value;
		document.location.href = url + '/templates/produtos_edicao_' + edicao + '/' + idFlash + '#cabecalho';
	//}else
		//return false;

	
	
//	alert($("#subtitulo input").val());

}

function validarCPFAlert(input){
	//alert(validarCPF(cpf));
//	$("#validaCPF").text(validarCPF(input.value)).fadeOut(2000);
	if(!validarCPF(input.value)){
		input.style.background='#FAE0E5';
		input.style.color='#D03434';
	}else{
		input.style.background='#fff';
		input.style.color='#205A94';
	}
}

function validarCNPJ(input){
//	$("#validaCNPJ").text(vcnpj(input)).fadeOut(2000);
	if(!vcnpj(input)){
		input.style.background='#FAE0E5';
		input.style.color='#D03434';
	}else{
		input.style.background='#fff';
		input.style.color='#205A94';
	}
}

function voltar(e){
	if (e.preventDefault)
        //standart browsers
        e.preventDefault();
	else 
        // internet explorer
        e.returnValue = false;
	
	history.back();

}

function trocaAcaoMinhaConta(novaAcao){
    $("#formMinhaContaDados input[name='acao']").val(novaAcao);
}


function exibirElemento(idElemento){
	$("#"+idElemento).show();
}

function alteraAcaoSecaoSubmete(secao,acao,idFormulario){
	if(secao != null){
		$("#"+idFormulario+"_secao").val(secao);
	}
	if(acao != null){
		$("#"+idFormulario+"_acao").val(acao);
	}
	if(idFormulario != null){
		$("#"+idFormulario).submit();
	}
}
function confirmaExclusaoCarrinho(){
	if(confirm("Deseja excluir o carrinho gravado?")){
		alteraAcaoSecaoSubmete(null,'excluir_carrinho','form_carrinho_gravado');
	}
}

function redirecionamentoGravarCarrinho(urlLogin){
	alteraCancelarConfirmacao(true);
	document.location.href=urlLogin;
}

function alteraCancelarConfirmacao(cancelar){
	$("#cancelarConfirmacao").val(cancelar);
}

// Daqui em diante, minhas funções e meus testes 

function confirmaGerarPDF(){
    if( confirm("Você receberá esta prova por e-mail com um custo adicional.\nDeseja gerar a prova em PDF?"))
    {
    	$("#provaForm").submit();
  
    }
}
/*
 * 
 * @uthor: Douglas M.Santos
 * @contato: douglas@krieser.com.br
 * Especificação: Função feita para atualizar as caracteristicas do produto	na tela de confirmação dos
 * dados do produto.
 * Motivo: Bug apresentado pelo rogério, onde as características dos produtos não eram atualizadoas
 * corretamente.
 * Data:06/11/2009
 * 
 */
function setaParametros(e){
	var options = document.getElementById("combos").childNodes;
	for(i=0; i < options.length;i++){
		var opt = options[i];
		for(j=0; j<opt.length;j++ ){
			if(opt[j].selected==true){
				$("#papel").attr('value',opt[j].text);
			}
		}
		setaAcabamento();
	}
	
}

function setaAcabamento(){
	var options = document.getElementById('1').options;
	for(i=0; i < options.length;i++){
		var opt = options[i];
		if(opt.selected==true){
			$("#acabamento").attr('value',opt.text);
		}
	}
	setaEnvelope();
}

function setaEnvelope(){
	var options = document.getElementById('14').options
	for(i=0; i < options.length;i++){
		var opt = options[i];
		if(opt.selected==true){
			$("#envelope").attr('value',opt.text);
		}
	}
}

/*
 * 
 * @uthor: Douglas M.Santos
 * @contato: douglas@krieser.com.br
 * Especificação: Função feita para setar o combo com o número de ups selecionado na página anterior(Ao Criar um template, na
 * página de ADM).
 * Motivo: Organizar a variavel $_SESSION com campos de fácil acesso.
 * Data:16/11/2009
 * 
 */
function setaQuantidadeDeUps(){
	var options = document.getElementById('quantUps').options
	for(i=0; i < options.length;i++){
		var opt = options[i];
		if(opt.selected==true){
			$("#ups").attr('value',opt.text);
		}
	}
}










//function setaQuantidadeDeUps(){
//	var options = document.getElementById("upsCombo").options
//	for(i=0; i < options.length;i++){
//		var opt = options[i];
//		if(opt.selected==true){
//			alert(opt.text);
//			$("#ups").attr('value',opt.text);
//			alert(document.getElementById('ups').value);
//		}
//	}
//}
/*function confirmaAlteracoesVoltar(e){
    
    var confirma = confirmaAlteracoes();
    
    if(confirma)
        voltar(e);
    
    return false;
}
function confirmaAlteracoesReutilizarTemplate(e){
	
	var confirma = confirmaAlteracoes();
	
	if(confirma){
		e.preventDefault();
		document.getElementById('acao').value = 'reutilizar_template';
		document.getElementById('template_form_cadastro').submit();
	}else
		return false;
}
}*/

function confirmaGerarPDF(){
    if( confirm("Você receberá esta prova por e-mail com um custo adicional.\nDeseja gerar a prova em PDF?"))
    {
    	$("#provaForm").submit();
  
    }
}

function confirmaGerarProva()
{
	if(confirm("Você receberá esta prova por e-mail com um custo adicional.\nDeseja gerar a prova em PDF?"))
	{
		$("#provaForm").submit();
	}
	
}

function confirmaGerarProvaUsuarioNaoLogado()
{
	alert("Você precisa estar logado para fazer um pedido de prova.\nPor favor, efetue o login e solicite prova novamente.");
	$("#provaForm").submit();
}

function carregarProva(idPedido){
	   document.getElementById("idPedido").value = idPedido;
	   $("#provas_Carregar").submit();
	}

function editarProva(idPedido){
	document.getElementById("idPedidoProva").value = idPedido;
	$("#provas_Editar").submit();
}

function saibaMaisProva(){
//	window.open("saiba_mais_prova_pdf","menubar=1,resizable=1,width=350,height=250");
    window.open("../saiba_mais_prova_pdf");
}