var iframe_obj;

$(document).ready(function(){
    if (!iframe_obj){
       var iframe = document.createElement("iframe");
       iframe.setAttribute("id","iframe_obj");
       iframe.setAttribute("name","iframe_obj");
       iframe.setAttribute("width","0");
       iframe.setAttribute("height","0");
       iframe.setAttribute("border","0");
       iframe.setAttribute("style","width:0; height:0; border:0px");
       document.body.appendChild(iframe);
    }
});

function abrir_autenticacao(link,target){
    if ($('#tipo_autenticacao').val()=="S"){
        $('#window_r').css('visibility','visible');
        $('#aut_senha_r').focus();
        $('#aut_target_r').val(target);
        $('#aut_link_r').val(link);

        var enviar = function(e){
            if (e.keyCode==13)
               enviar_autenticacao();
        }

        $('#aut_login_r').bind('keyup',enviar);
        $('#aut_senha_r').bind('keyup',enviar);
        $('#aut_senha_rr').bind('keyup',enviar);
    }
    else{
        $('#window').css('visibility','visible');
        $('#aut_senha').focus();
        $('#aut_target').val(target);
        $('#aut_link').val(link);

        var enviar = function(e){
            if (e.keyCode==13)
               enviar_autenticacao();
        }

        $('#aut_login').bind('keyup',enviar);
        $('#aut_senha').bind('keyup',enviar);
    }
}

function enviar_autenticacao(){
    var login = "";
    var senha = "";
    var target= "";
    var link  = "";

    try{
        if ($('#tipo_autenticacao').val()=="S"){
           login = $('#aut_login_r').val();
           senha = $('#aut_senha_r').val();
           senhar = $('#aut_senha_rr').val();
           target= $('#aut_target_r').val();
           link  = $('#aut_link_r').val();

           if (senha!=senhar)
              throw "Senhas diferentes\ndigite novamente";
        }
        else{
             login = $('#aut_login').val();
             senha = $('#aut_senha').val();
             target= $('#aut_target').val();
             link  = $('#aut_link').val();
        }

        $.post("/portal/recursos/autentica_login.php", "aut_login="+login+"&aut_senha="+senha, function(data){
            var dados=$.trim(data.replace(/\+/g," "));

						//alert(dados);
            if (dados=="1"){
               location.href=link;
               $('#window').css('visibility','hidden');
            }
            else{
                 $('#window').css('visibility','hidden');
                 alert("Login inválido");
                 location.href="/portal/";
            }
        });
    }
    catch (e){
          alert(e);
    }
}

function oculta_janela(id, obj){
   var c_jan = document.getElementById(id);
   if (c_jan.style.display == 'none'){
      c_jan.style.display = '';
      obj.src='img/nodeclose.jpg';
   }
   else{
       c_jan.style.display = 'none';
       obj.src='img/node.jpg';
   }
}

function abrir_menu_combobox(combobox){
   var dados  = combobox.options[combobox.selectedIndex].value;
   window.href= dados;
}

function menu_clique(obj){
     var uls = obj.childNodes;

     for (var i=0; i<=uls.length-1; i++){
         if (uls[i].nodeName=="UL"){
             if (uls[i].style.display=="")
                uls[i].style.display = "none";
             else
                 uls[i].style.display = "";
         }
     }
 }

function ler_rss(endereco,jan){
     $("#"+jan).html("<span>Carregando aguarde...</span>").css({backgroundColor:"#808080",padding:"3px",color:"#FFFFFF",fontWeight:"bold"});

     $.ajax({type:"POST", url:endereco, dataType:"xml", complete:function(dados){
         alert(dados);
     }});
}

function enviar_fale_conosco(cod){
     var dados = new Array();
     dados.push('nome='+escape($('#nome_fale_'+cod).val()));
     dados.push('email='+escape($('#email_fale_'+cod).val()));
     dados.push('destinado='+escape($('#destinado_fale_'+cod).val()));
     dados.push('assunto='+escape($('#assunto_fale_'+cod).val()));
     dados.push('texto='+escape($('#texto_fale_'+cod).val()));

     $("#mostra_msg_"+cod).html("<span>Enviando aguarde...</span>").css({backgroundColor:"#808080",padding:"3px",color:"#FFFFFF",fontWeight:"bold"});

     $.post("recursos/enviar_fale_conosco.php", dados.join("&"), function(data){
          var dados=$.trim(data.replace(/\+/g," "));

          if (dados!="SUCESSO"){
             alert("Houve um erro ao tentar enviar dados, entre em contato com o administrador do site!");
             $("#mostra_msg_"+cod).html("").css({backgroundColor:"",padding:"",color:"",fontWeight:""});
          }
          else
              $("#mostra_msg_"+cod).html("<span>Email enviado com sucesso</span>").css({backgroundColor:"#808000",padding:"3px",color:"#FFFFFF",fontWeight:"bold"});
    });
}

function enviar_enquete(enquete){
     var opcoes = $('.enquete_voto_'+enquete);
     var selecao = null;

     $.each(opcoes, function(i,n){
           if (n.checked)
              selecao = n.value;
     });

     if (selecao!=null)
        window.open('recursos/enquete_voto.php?enquete='+enquete+'&cod='+selecao, '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=yes, width=300, height=350')
     else
         alert("Selecione primeiro uma opção para votar");
}

function ver_enquete(enquete){
     window.open('recursos/enquete_voto.php?enquete='+enquete, '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=yes, width=300, height=350')
}

var ap01_noticia_client = {
     salvar_noticia : function(form){
        if ($('#titulo').val()==""){
           alert('Campo titulo obrigatório');
        }
        else
        if ($('#resumo').val()==""){
           alert('Campo resumo obrigatório');
        }
        else
            $('#'+form).submit();
     },
     salvar_denuncia : function(form){
        if ($('#irregularidades').val()==""){
           alert('Campo Irregularidades ou Delitos Verificados obrigatório');
           $('#irregularidades').focus();
        }
        else
        if ($('#pessoas_envolvidas').val()==""){
           alert('Campo Pessoas ou Empresas Envolvidas obrigatório');
           $('#pessoas_envolvidas').focus();
        }
        else
        if ($('#testemunhas').val()==""){
           alert('Campo Testemunhas ou Pessoas que possam ajudar obrigatório');
           $('#testemunhas').focus();
        }
        else
        if ($('#nome').val()==""){
           alert('Campo Nome obrigatório');
           $('#nome').focus();
        }
        else
        if ($('#telefone').val()==""){
           alert('Campo Telefone obrigatório');
           $('#telefone').focus();
        }
        else{
             if (confirm('Você está prestes a enviar uma denúncia ao Ministério Público do Estado do Amapá.\n Deseja realmente enviar?')){
                $('#'+form).submit();
             }
        }
     },
     copiar_resumo:function(){
        $("#texto").val($("#resumo").val());
     },
     init:function(){
        $('#anexo').MultiFile(4);
     }
}

var rssReader = {
     execute:function(componente,site,janela){
         var dados = new Array();
         dados[0] = "site="+site;
         dados[1] = "janela="+janela;

         $('#'+componente).html("<center><span style='font-size:13pt;font-family:arial;font-weight:normal'>Carregando..</span><img src='img/wait.gif' align='top'></center>");
         $.post("/portal/apl/ap10_rss/carrega_canal.php", dados.join("&"), function(data){
              var dados=$.trim(data.replace(/\+/g," "));
              $('#'+componente).html(dados);
        });
     }
}

var noticia = {
    container:null,
    qtd:null,
    indice:null,
    interval:null,
    timeout:null,
    executa_noticia:function(container, qtd){
        this.container = container;
        this.qtd       = qtd;
        this.indice    = 1;
        this.interval  = setInterval("javascript: noticia.rondomica();",10000);
    },
    rondomica:function(){
        if (this.indice<this.qtd){
           $(this.container).triggerTab(this.indice);
           this.indice++;
        }
        else{
             $(this.container).triggerTab(this.indice);
             this.indice = 1;
        }
    }
}

function imprimir_component(comp){
    try{
        var oIframe  = document.getElementById('iframe_print');
        var oContent = document.getElementById(comp).innerHTML;

        if (oIframe==null){
            oIframe = document.createElement("iframe");
            oIframe.setAttribute("id","iframe_print");
            oIframe.setAttribute("name","iframe_print");
            oIframe.setAttribute("width","0");
            oIframe.setAttribute("height","0");
            oIframe.setAttribute("border","0");
            oIframe.setAttribute("style","width:0; height:0; border:0px");

            $(document.body).append(oIframe);
        }

        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.write("<html><head><title>title</title>");
        oDoc.write("</head><body onload='this.focus(); this.print();'>");
        oDoc.write(oContent + "</body></html>");
        oDoc.close();
    }
    catch (e){
          self.print();
    }
}

var questionario = {
    serializar:function(nome_form){
        var lista      = new Array();
        var perguntas  = new Array();

        var dupricadosLista = function(lista){
             var novaLista = new Array();

             for (var i=0; i<=lista.length-1; i++){
                 if (!contemLista(lista[i], novaLista))
                    novaLista.push(lista[i]);
             }
             return novaLista;
        }

        var contemLista = function(valor, lista){
             var valor = false;

             for (var i=0; i<=lista.length-1; i++){
                 if (lista[i]==valor)
                    valor = true;
             }
             return valor;
        }

        $("#"+nome_form+" input[@type=hidden]").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        $("#"+nome_form+" input[@type=text]").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        $("#"+nome_form+" select").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        $("#"+nome_form+" textarea").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        $("#"+nome_form+" input[@type=checkbox]:checked").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        $("#"+nome_form+" input[@type=radio]:checked").each(function(i,n){
             if (n.name!="undefined"){
                lista.push(n.name+"="+escape(n.value));
                perguntas.push(n.name.split("_")[1]);
             }
        });

        return [lista.join("&"),dupricadosLista(perguntas)];
    },
    limpar_form:function(nome_form){
        $("#"+nome_form+" input[@type=text]").each(function(i,n){
             n.value = "";
        });

        $("#"+nome_form+" select").each(function(i,n){
             n.selectedIndex = 0;
        });

        $("#"+nome_form+" textarea").each(function(i,n){
             n.value = "";
        });

        $("#"+nome_form+" input[@type=checkbox]:checked").each(function(i,n){
             n.checked = false;
        });

        $("#"+nome_form+" input[@type=radio]:checked").each(function(i,n){
             n.checked = false;
        });
    },
    salvar_form:function(url,form_nome,param){
        var dado        = questionario.serializar(form_nome);
        var queryString = dado[0];

        var d1 = param.split("=")[1];
        var d1 = d1.split(",");

        param = "";

        if (d1.length>0){
           for (var i=0; i<=d1.length-1; i++){
               if (!eval("valida_pergunta_"+d1[i]+"();")){
                  alert("Preencha todos os dados requeridos");
                  return;
               }
           }
        }
        $("#"+form_nome+"_load").css("display","");
        $.post(url, param+'&'+queryString, function(data){
            var dados = $.trim(data.replace(/\+/g," "));
            $("#"+form_nome+"_load").css("display","none");
            $("#container_apl_"+form_nome.split("_")[2]).html(dados);
        });
    }
}
