﻿function jCidades()
{
   
    var jDT;
    var tpl;
    var mostraResultado = false;
    var retorno;
    var jDTLista;
    var indice;
    var editar = false;
    var piCidadeCode, piCidadeName, piCidade;
    var jDTEstados;
    
    var render = {
        main: function()
        {
            tpl.cidades.tpl_main.link = 'nova cidade';
            tpl.cidades.tpl_main.onclick = 'javascript:jsCidades.exec.novoCadastro()';
            tpl.cidades.tpl_main.link2 = 'pesquisa cidade';
            tpl.cidades.tpl_main.onclick2 = 'javascript:jsCidades.exec.main()';
            tpl.cidades.tpl_main.estado = render.estados();
            return tpl.cidades.tpl_main.getHtml();
        },
        estados: function()
	    {
            jDT = new jDatatable(Estados.listar().value); 
            on.sort("Nome", false);  
            jDTEstados = jDT;                     
            return render.addOptions("CodEstado", "Uf");
	    },
	    optionSelecione: function()
        {
            tpl.tpl_option.value =  "0";
            tpl.tpl_option.text = "";
            return tpl.tpl_option.getHtml();
        },
        addOptions: function(value, text)
	    {
	        if(jDT != null)
	        {
	            var sb = new StringBuilder();
	            sb.append(render.optionSelecione());
	            for (var i = 0; i < jDT.getTotRegs(); i++) 
	            {    		
		            tpl.tpl_option.value =  jDT.getDrValue(i, value);
		            tpl.tpl_option.text = jDT.getDrValue(i, text);    			
		            sb.append(tpl.tpl_option.getHtml());
	            };
	            return sb.toString();
	        };
	    },
        resultadoLista: function()
        {
            var sb = new StringBuilder();
            for (var i = 0; i < parseInt(jDTLista.getTotRegs()); i++)
            {
                tpl.cidades.tpl_trResultado.nome = jDTLista.getDrValue(i, "Nome");
                tpl.cidades.tpl_trResultado.sigla = jDTLista.getDrValue(i, "Uf");
                tpl.cidades.tpl_trResultado.onclickEditar = 'javascript:jsCidades.exec.editar(' + i + ')';
                tpl.cidades.tpl_trResultado.onclickExcluir = 'javascript:jsCidades.exec.excluir(' + parseInt(jDTLista.getDrValue(i, "CodCidade")) + ')';
                sb.append(tpl.cidades.tpl_trResultado.getHtml());
            };
            //jDTLista = jDT;
            //tpl.cidades.tpl_mainResultado.titulo = "Lista de Cidades";
            tpl.cidades.tpl_mainResultado.trResultado = sb.toString();
            return tpl.cidades.tpl_mainResultado.getHtml();
        },
        addOneOptions: function(valor)
	    {
	        if(jDT != null)
	        {
	            var sb = new StringBuilder();
	            tpl.tpl_option.value =  valor;
	            tpl.tpl_option.text = valor;    			
	            sb.append(tpl.tpl_option.getHtml());
	            return sb.toString();
	        };
	    },
        novoCadastro: function(pTitulo)
        {
            tpl.cidades.tpl_formCadastro.titulo = pTitulo;
            tpl.cidades.tpl_formCadastro.onclick = 'javascript:jsCidades.exec.inserir();';
            if(editar == false)
            {
                tpl.cidades.tpl_formCadastro.estado = render.estados();
            }
            else
            {
                tpl.cidades.tpl_formCadastro.estado = render.addOneOptions(jDT.getDrValue(indice, "Uf"));
                editar = false;
            };
            return tpl.cidades.tpl_formCadastro.getHtml();
        }
    };
    
    var on = {
        sort: function(pColuna, pReverse)
        {
            jDT.sort(pColuna, pReverse);            
        },
        selectCidade: function(value, text, row) 
        {
            piCidadeCode = value;
            piCidadeName = text; 
        },
        changeCidades: function()
        {
          
          return Enderecos.cidadesPescInc($get('txt_origemCidade'), $get('sel_estadoOrigem'));
        }
    };
    
    var ctrlRefs = {
        divMainConteudo: function(){return $('mainConteudo');},
        divTituloTopo: function(){return $('divTituloTopo');},
        divResultadoLista: function(){return $('divResultadoLista');},
        divCadastro: function(){return $('divCadastro');},
        divErro: function(){return $('divErro');},
        divPesquisa: function() { return $('pesquisa');}
    };
    
    var callbacks = {
        excluir: function(res)
        {
            if (res.value == 0)
            {
                jsCommon.exec.erroCadastro(ctrlRefs.divErro(), "Não foi possível excluir");
            }
            else
            {
                jsCommon.exec.sucessoCadastro(ctrlRefs.divErro(), "Operação realizada com sucesso.");
            };
        }
    };
    
    var startEnv = {
        listar: function()
        {
            if(piCidadeName != undefined)
            {
                var cidadeEstado = new Array();
                cidadeEstado = piCidadeName.split('-');
                jDTLista = new jDatatable(Cidades.listar(piCidadeCode, cidadeEstado[1].trim()).value); 
                ctrlRefs.divResultadoLista().style.display = '';
                $html(ctrlRefs.divResultadoLista(), render.resultadoLista());
            }
            else
            {
                alert("Selecione uma Cidade");
            };
        },
        main: function()
        {
            $html(ctrlRefs.divMainConteudo(), render.main());
            $html(ctrlRefs.divErro(), '');
            if(mostraResultado == true)
            {
                if (retorno.value == 0)
                {
                    jsCommon.exec.erroCadastro(ctrlRefs.divErro(), "Não foi possível atualizar");
                }
                else
                {
                    jsCommon.exec.sucessoCadastro(ctrlRefs.divErro(), "Operação realizada com sucesso.");
                };
                mostraResultado = false;
                ctrlRefs.divPesquisa().style.display = 'none';
            };
            startEnv.pesqInc();
            //startEnv.listar();            
        },
        pesqInc: function()
        {
            piCidade =  new IncrementalSearch('txt_cidade', Cidades.cidadesPescInc, 400);
            piCidade.onSelect = on.selectCidade; 
        },
        inserir: function()
        {
            var indice = parseInt($get($('cbx_sel_estadoCadastro'))) - 1;
            var UF = jDTEstados.getDrValue(indice,"Uf"); 
            retorno = Cidades.inserir(($get("txt_cod") == "" ? 0 : parseInt($get("txt_cod"))), $get("txt_nome"), $get($('cbx_sel_estadoCadastro')), UF, $get("txt_Descricao"));
            mostraResultado = true;
        },
        editar: function(pIndice)
        {
            $html(ctrlRefs.divErro(), '');
            ctrlRefs.divResultadoLista().style.display = 'none';
            ctrlRefs.divPesquisa().style.display = "none";
            editar = true;
            jDT = jDTLista;
            indice = pIndice;
            $html(ctrlRefs.divCadastro(), render.novoCadastro("Editar Cidade"));  
            $set('txt_cod', jDT.getDrValue(indice, "CodCidade"));
            $set('txt_nome', jDT.getDrValue(indice, "Nome"));            
            $set('txt_Descricao', jDT.getDrValue(indice, "Descricao"));
        },
        novoCadastro: function()
        {
            $html(ctrlRefs.divErro(), '');
            ctrlRefs.divResultadoLista().style.display = 'none';
            $html(ctrlRefs.divCadastro(), render.novoCadastro("Nova Cidade"));
            ctrlRefs.divCadastro().style.display = "";
            ctrlRefs.divPesquisa().style.display = "none";
        },
        excluir: function(pCod)
        {
            Cidades.excluir(pCod, callbacks.excluir);
        },
        getCidades: function()
        {
            return Cidades.listar();
        }
    };
    
    this.exec = {
        main: function()
        {
            startEnv.main();
        },
        listar: function()
        {
            startEnv.listar();
        },
        inserir: function()
        {
            startEnv.inserir();
            startEnv.main();
        },
        editar: function(pIndice)
        {
            ctrlRefs.divCadastro().style.display = "";
            startEnv.editar(pIndice);
        },
        excluir: function(pCod)
        {
            if (confirm("Você deseja realmente excluir?"))
            {
                startEnv.excluir(pCod);
                startEnv.listar();
                ctrlRefs.divPesquisa().style.display = 'none';
                ctrlRefs.divResultadoLista().style.display = 'none';
            }
        },
        novoCadastro: function()
        {
            startEnv.novoCadastro();
        },
        getCidades: function()
        {
            return startEnv.getCidades();
        }      
    };
    
    this.constructor = new function()
    {
        tpl = new Template("templates");
    };
};
