﻿var nlscidades = "lscidades_";
var ndadoscidade = "dadoscidade_";

$.listacidadesselect = function(categ) {
    var id = $('#dpEstados' + categ).val();
    var ls = $.jCache.getItem(nlscidades + id);
    if (ls == null) {
        $.exec("wsCep.asmx/CarregaCidades", "{idEstado: '" + id + "'}", false, function(dados) {
            ls = (typeof dados.d) == 'string' ? eval('(' + dados.d + ')') : dados.d;
            $.jCache.setItem(nlscidades + id, ls);
        });
    }

    var combo = $('#dpCidades' + categ);
    combo.attr('disabled', true).removeOption(/./);
    combo.attr('disabled', false).addOption('', ' -- Cidades -- ');
    $('#dpBairros' + categ).attr('disabled', true).removeOption(/./);
    $('#dpBairros' + categ).addOption('', ' -- Bairros -- ');
    if (ls != null) if (ls.length > 0) for (var i = 0; i < ls.length; i++) combo.addOption(ls[i].IdCidade, ls[i].NomeCidade, false);
}
$.carregacidades = function(loadmapa) {
    if (loadmapa == null) loadmapa = true;
    var idEstado = $('#dpEstados').val();
    if (idEstado == '')  idEstado = -1;
    else {
        var ls = $.jCache.getItem(nlscidades + idEstado);
        if (ls == null) {
            $.exec("wsCep.asmx/CarregaCidades", "{idEstado: '" + idEstado + "'}", false, function(dados) {
                ls = (typeof dados.d) == 'string' ? eval('(' + dados.d + ')') : dados.d;
                $.jCache.setItem(nlscidades + idEstado, ls);
            });
        }
        var combo = $('#dpCidades');
        combo.attr('disabled', true).removeOption(/./);
        combo.attr('disabled', false).addOption('', ' -- Cidades -- ');
        $('#dpBairros').attr('disabled', true).removeOption(/./);
        $('#dpBairros').addOption('', ' -- Bairros -- ');
        var estado = null;
        if (ls != null) {
            if (ls.length > 0) {
                if (estado == null) estado = ls[0].Estado;
                for (var i = 0; i < ls.length; i++) combo.addOption(ls[i].IdCidade, ls[i].NomeCidade, false);
            } else estado = $.procuraestado(idEstado);
        } else estado = $.procuraestado(idEstado);
        if (loadmapa && (estado != null)) $.loadmapa(divMap, estado.LatLong.Longitude + "," + estado.LatLong.Latitude, estado.LatLong.Zoom);
    }
}
$.centralizacidade = function(cidade, idCidade) {
    if (idCidade == null) idCidade = $('#dpCidades').val();
    if (cidade == null) cidade = $.procurarcidade(idCidade);
    $.centralizamapalatlong(divMap, cidade.LatLong.Latitude, cidade.LatLong.Longitude, cidade.LatLong.Zoom);
}
$.procurarcidade = function(id) {
    var retorno = $.jCache.getItem(ndadoscidade + id);
    if (retorno == null) {
        $.exec("wsCep.asmx/ProcurarCidade", "{idCidade: '" + id + "'}", false, function(dados) {
            retorno = (typeof dados.d) == 'string' ? eval('(' + dados.d + ')') : dados.d;
            $.jCache.setItem(ndadoscidade + id, retorno);
        });
    }
    return retorno;
}
