dojo.require("dojo.io.*");

function loadDiv(vUrl, vDiv){
    loadDivCarregando(vDiv);
    
    //Carrega o HTML
    dojo.io.bind({
        url: vUrl,
        mimetype: "text/plain",
        useCache:false,
        changeUrl: true,
        executeScripts: true,
        load: function(type, data, evt){ 
            dojo.byId(vDiv).innerHTML = data;
            executeScript(data);            
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }
    });
}

function loadDiv(vUrl, vDiv, vSync){
    loadDivCarregando(vDiv);
    
    //Carrega o HTML
    dojo.io.bind({
        url: vUrl,
        mimetype: "text/plain",
        useCache:false,
        changeUrl: true,
        sync: vSync,
        load: function(type, data, evt){ 
            dojo.byId(vDiv).innerHTML = data;            
            executeScript(data);
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }             
    });
}

/** loadPane
 *  Carrega um ContentPane com a url informada
 *  vForm = o ID do form
 *  vPane = o ID do pane
 *  vSync = indica se é uma chamada sincrona ou não
 */
    function loadPane (vUrl, vPane, vSync){   
    //Carrega o HTML
    dojo.io.bind({
        mimetype: "text/plain",
        url: vUrl+'#'+Math.round(Math.random()*100000),
        useCache:false,
        changeUrl: false,
        sync: vSync,
        load: function(type, data, evt){ 
            dojo.widget.byId(vPane).setContent(data);
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }             
    });
    }


/** loadPaneForm
 *  Carrega um ContentPane com a url acessada por um form
 *  vForm = o ID do form
 *  vPane = o ID do pane
 *  vSync = indica se é uma chamada sincrona ou não
 */
    function loadPaneForm (vForm, vPane, vSync){   
    //Carrega o HTML
    dojo.io.bind({
        mimetype: "text/plain",
        formNode: document.getElementById(vForm),
        useCache:false,
        changeUrl: true,
        sync: vSync,
        load: function(type, data, evt){ 
            dojo.widget.byId(vPane).setContent(data);
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }            
    });
    }

/** loadPaneFormUpload
 *  Carrega um ContentPane com a url acessada por um form de Upload
 *  vForm = o ID do form
 *  vPane = o ID do pane
 *  vSync = indica se é uma chamada sincrona ou não
 */
    function loadPaneFormUpload (vForm, vPane, vSync){   
    //Carrega o HTML
    dojo.io.bind({
        mimetype: "text/html", // usar text/plain para upload gera erros!
        formNode: document.getElementById(vForm),
        useCache:false,
        changeUrl: true,
        sync: vSync,
        load: function(type, data, evt){ 
            data = dojo.io.iframeContentWindow(dojo.io.IframeTransport.iframe).document.body.innerHTML;
            if (data.match(/<pre>(.*)<\/pre>/i)) {
                // Internet Explorer [Jon Aquino 2006-05-06]
                data = RegExp.$1;
            }
            dojo.widget.byId(vPane).setContent(data);
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }              
    });
    }

/** executeScript
 *  Localiza e executa todas as tags SCRIPT contidas dentro de um texto
 */
function executeScript(content) {
    // handle <script src="foo"> first
    var src = new RegExp('<script.*?src=".*?"');
    var repl = new RegExp('<script.*?src="');
    var matches = src.exec(content);
    var semaphore = 0;
    
    if (matches != null) {
        for (i = 0; i < matches.length; i++) {
            // get the src of the script
            var scriptSrc = matches[i].replace(repl, '');
            scriptSrc = scriptSrc.substring(0, scriptSrc.length-1);
            
            // this evals remote scripts
            dojo.io.bind({
                url:      scriptSrc,
                load:     function(type, evaldObj) {/* do nothing */ },
                error:    function(type, error) {alert(type);
                alert(error); /* do nothing */ },
                mimetype: "text/javascript",
                sync:     true
            });
        }
    }
    
    // Remove the script tags we matched
    repl = new RegExp('<script.*?src=".*?".*?</script>');
    content = content.replace(repl, '');
    
    // Next, handle inline scripts
    
    // Clean up content: remove inline script  comments
    repl = new RegExp('//.*?$', 'gm');
    content = content.replace(repl, '\n');
    
    // Clean up content: remove carraige returns
    repl = new RegExp('[\n\r]', 'g');
    content = content.replace(repl, ' ');
    
    // Match anything inside <script> tags
    src = new RegExp('<script.*?</script>', 'g');
    matches = content.match(src);
    
    // For each match that is found...
    if (matches != null) {
        for (i = 0; i < matches.length; i++) {
            // Remove begin tag
            var repl = new RegExp('<script.*?>', 'gm');
            var script = matches[i].replace(repl, '');
            
            // Remove end tag
            repl = new RegExp('</script>', 'gm');
            script = script.replace(repl, '');
            
            // Execute commands
            setTimeout(script, 250);
        }
    }
}

function loadDivWipe(vUrl, vDiv, vSync){
    loadDivCarregando(vDiv);
    
    //Carrega o HTML
    dojo.io.bind({
        url: vUrl,
        mimetype: "text/plain",
        useCache:false,
        changeUrl: true,
        sync: vSync,
        load: function(type, data, evt){ 
            dojo.byId(vDiv).innerHTML = data;
            dojo.lfx.html.wipeIn(vDiv, 300).play();
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }             
    });
}

function loadDivCarregando(vDiv){    
    //Carrega o HTML
    dojo.io.bind({
        url: "includes/carregando.html",
        mimetype: "text/plain",
        useCache: true,
        changeUrl: true,
        sync: true,
        load: function(type, data, evt){ 
            dojo.byId(vDiv).innerHTML = data;            
            //executeScript(data);
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }             
    });
}

//vSync = true -> Chamada sincrona
function loadDivForm(vForm, vDiv, vSync){
    //loadDivCarregando(vDiv);
    
    //Carrega o HTML
    dojo.io.bind({
        //formNode: vForm,
        formNode: document.getElementById(vForm),
        mimetype: "text/plain",
        useCache:false,
        changeUrl: true,
        sync: vSync,
        method: "POST",
        load: function(type, data, evt){ 
            dojo.byId(vDiv).innerHTML = data;
        },                
        error: function(type, error){ 
            mensagemErro(error);
        }            
    });
}

function fazerLogin(){
    //Faz o login
    loadDivForm('frmLogin','divCabecalho',true);
    //Menu principal
    loadDiv("../servlet/controller?command=menu.Load&renderto=portal/includes/menuPrincipal.jsp","divMenuPrincipal");
    //Submenu: Oculto
    dojo.byId('divSubMenu').innerHTML = '';
    exibeOcultaDiv('divSubMenu', false);
    //Conteúdo: Página inicial    
    loadDiv('../servlet/controller?command=paginainicial.Load&renderto=portal/includes/paginaInicial.jsp&paginaInicial=true','divConteudo');
}

function fazerLogout(){
    //Carrega o div de Cabeçalho
    loadDiv("../servlet/controller?command=login.Logout&renderto=portal/includes/top.jsp","divCabecalho",true);
    //Menu principal
    loadDiv("../servlet/controller?command=menu.Load&renderto=portal/includes/menuPrincipal.jsp","divMenuPrincipal");
    //Submenu: Oculto
    dojo.byId('divSubMenu').innerHTML = '';
    exibeOcultaDiv('divSubMenu', false);
    //Conteúdo: Página inicial    
    loadDiv('../servlet/controller?command=paginainicial.Load&renderto=portal/includes/paginaInicial.jsp&paginaInicial=true','divConteudo');
}

function inicializaPagina(){   
    //Carrega o div de login   
    loadDiv("../servlet/controller?renderto=portal/includes/top.jsp","divCabecalho", true);
    //Menu principal
    loadDiv("../servlet/controller?command=menu.Load&renderto=portal/includes/menuPrincipal.jsp","divMenuPrincipal");
    //Submenu: Oculto
    dojo.byId('divSubMenu').innerHTML = '';
    exibeOcultaDiv('divSubMenu', false);
    //Enquete
    //loadDiv('../servlet/controller?command=paginainicial.Load&renderto=portal/includes/enquete.jsp','divEnquete');
    //Conteúdo: Página inicial    
    loadDiv('../servlet/controller?command=paginainicial.Load&renderto=portal/includes/paginaInicial.jsp&paginaInicial=true','divConteudo');
}

function esconderMenu(){
    //dojo.byId('divSubMenu').style.visibility='hidden';
    dojo.byId('divSubMenu').innerHTML = '';
}

function exibeOcultaDiv(vDiv,vMostra){
    if (vMostra) {
        dojo.byId(vDiv).style.visibility='visible';
    } else {
        dojo.byId(vDiv).style.visibility='hidden';
    }
}

function chamaMenu(idMenu, idConteudoHome){
    //Submenu: exibir os submenus do menu
    exibeOcultaDiv('divSubMenu',true);    
    loadDiv('../servlet/controller?command=submenu.Load&renderto=portal/includes/subMenu.jsp&idMenu='+idMenu,'divSubMenu');
    //Conteúdo: carregar o conteúdo home do menu
    loadDiv('../servlet/controller?command=conteudo.Load&indClassifica=FALSE&indListaExpandida=TRUE&idConteudo='+idConteudoHome+'&renderto=portal/includes/chamada.jsp','divConteudo');
}

/** chamaSubMenu
 *  Acionado quando o usuário seleciona um submenu
 *    idMenu = o id do menu selecionado
 *    indClassifica = indica se os conteudos pertencentes ao menu devem ser classificados
 *    idListaExpandida = indica se os conteudos devem ser exibidos com seus itens (true) ou apenas com a chamada (false)
 */
function chamaSubMenu(idMenu, indClassifica, indListaExpandida){
    loadDiv('../servlet/controller?command=conteudo.Load&indClassifica='+indClassifica+'&indListaExpandida='+indListaExpandida+'&idMenu='+idMenu+'&renderto=portal/includes/chamada.jsp','divConteudo');
}

function textCounter(field, countfield, maxlimit, idForm) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else 
        dojo.byId('remLen'+idForm).innerHTML = '<b>'+(maxlimit - field.value.length)+'</b>';
}
function escondeComentario(divComentario){
    dojo.lfx.html.wipeOut(divComentario, 300).play();
}

// FUNÇÕES PARA PAINEL ROTATIVO
/** Conteudo
 *  O objeto que contem os dados a serem exibidos em cada item do painel
 *    imagem = o scr da imagem
 *    descricao = a legenda da imagem
 *    href = o link da imagem e da legends
 */
function Conteudo(imagem, descricao, href) {
    this.imagem = imagem;
    this.descricao = descricao;
    this.href = href;
}

/** PainelRotativo
 *  O objeto que representa o painel rotativo
 *    vDiv = o DIV em que será exibido o painel
  *   divDescricao = o DIV em que será exibido a descricao do conteudo do painel
 *    conteudos = array de Conteudo, sao os itens do painel
 *    showTime = tempo padrão de permanência do item do painel (default = 5000 ms)
 */
fadeID = 0;
function PainelRotativo(vDiv,divDescricao) {
    this.conteudos = new Array();    
    this.i=0;
    this.continuo = true;
    this.showTime = 5000;
    var me = this;
    
 
   this.exibe = function(delay){    
       if (dojo.byId(vDiv) == null) return;
        window.clearTimeout(fadeID);
        dojo.byId(vDiv).innerHTML = '<a href="javascript:loadDiv(\'../servlet/controller?command=conteudo.Load&indClassifica=FALSE&indListaExpandida=TRUE&idConteudo='+this.conteudos[this.i].href+'&renderto=portal/includes/chamada.jsp\',\'divConteudo\');"><img style="vertical-align:middle" src="'+this.conteudos[this.i].imagem+'" border="0"><\a>';
        dojo.byId(divDescricao).innerHTML = '<a href="javascript:loadDiv(\'../servlet/controller?command=conteudo.Load&indClassifica=FALSE&indListaExpandida=TRUE&idConteudo='+this.conteudos[this.i].href+'&renderto=portal/includes/chamada.jsp\',\'divConteudo\');" class="linkMenu">'+this.conteudos[this.i].descricao+'<\a>';
        
        dojo.lfx.html.fadeIn(vDiv, 600).play();	
        dojo.lfx.html.fadeIn(divDescricao, 600).play();	
        
        if (delay && this.continuo) {            
            fadeID = window.setTimeout(function(){me.oculta()},this.showTime);
        }
    }     
   
   this.oculta = function(){
        if (dojo.byId(vDiv) == null) return;
        if (this.continuo) {
            window.clearTimeout(fadeID);
            dojo.lfx.html.fadeOut(vDiv, 600).play();
            dojo.lfx.html.fadeOut(divDescricao, 600).play();
            
            
            this.i++;
            if (this.i >= this.conteudos.length)
                this.i=0;
                        
            fadeID = window.setTimeout(function(){me.exibe(true)},600);
        }
    }
    
    this.anterior = function(){
        this.i = this.i-1;
        if (this.i < 0) 
            this.i = this.conteudos.length-1;
        this.exibe(false);
    }
    
    this.proximo = function (){
        this.i++;
        if (this.i >= this.conteudos.length)
            this.i=0;
        this.exibe(false);
    }
    
    this.parar = function(){
        this.continuo = !this.continuo;
        if (this.continuo) {
            this.exibe(true);
        }
    }
    
    this.inicia = function(){        
        //window.clearTimeout(fadeID);
        //this.parar;
        this.continuo = true;
        this.oculta(0);
    }
}

/**
 * cancelarUpload
 * Cancela o upload, zerando os campos referentes ao arquivo
 */
    cancelarUpload = function(){            
        loadPane('../servlet/controller?renderto=gestao/arquivo/formUpload.jsp','divArquivo',false);
    }
    
/**
 *Dá novo valor para o item do combo  troca a imagem
 **/    
      setVa1 = function(val){
        alert('a');
        dojo.byId('value1').value = val;
        alert('../web/files/thumb_"+val+".jpg');
       // img.src = "../web/files/thumb_"+val+".jpg";    
    }

/**
 * mensagemErro
 * Gera uma mensagem com detalhes sobre um erro de Ajax
 */
    function mensagemErro(error) {
        alert("Ocorreu um erro ao processar a requisição:"+
              "\n\nMensagem: " + error.message+
              "\nTipo: " + error.type+
              "\nCódigo: " + error.num +
              "\n\n Por favor, aguarde alguns instantes e tente novamente.");
    }

/**
 * refreshItemIserirTipoItem
 * Chamado ao se alterar o tipo de item na tela de inclusão de item
 * Atualiza os campos da tela de acordo com o tipo de item selecionado
 */
function refreshItemInserirTipoItem(tipoItem){    
    if (tipoItem == 'IMAGEM') {
        dojo.byId('camposItem').innerHtml = ''; //Força o aparecimento dos dados
        dojo.widget.byId('camposItem').setUrl('../servlet/controller?renderto=gestao/item/inserirImagem.jsp');        
    } else if (tipoItem == 'DOCUMENTO') {
        dojo.byId('camposItem').innerHtml = '';
        dojo.widget.byId('camposItem').setUrl('../servlet/controller?renderto=gestao/item/inserirDocumento.jsp');
    } else if (tipoItem == 'LINK') {
        dojo.byId('camposItem').innerHtml = '';
        dojo.widget.byId('camposItem').setUrl('../servlet/controller?renderto=gestao/item/inserirLink.jsp');        
    } else if (tipoItem == 'TEXTO')  {
        dojo.byId('camposItem').innerHtml = '';
        dojo.widget.byId('camposItem').setUrl('../servlet/controller?renderto=gestao/item/inserirTexto.jsp');
    }
}

/*Cor do menu Selecionado*/
    function mudaCor(id, k){
	for(i=0; i<k; i++){
            if(i%2==0){
			document.getElementById('legenda'+i).className='offEscuro';
		}else{
			document.getElementById('legenda'+i).className='offClaro';
                }
	}
	document.getElementById('legenda'+id).className='selecionado';
}
    
    /*OnMouseOver do menu, muda cor do quadradinho*/
    function menuOn(id){
	document.getElementById('quadrado'+id).className='on';
}
    /*OnMouseOut do menu, muda cor do quadradinho*/
    function menuOff(id){
          document.getElementById('quadrado'+id).className='base';
}    