var MapFormUrl          = '/admin/maps/client-lookup';
var MapListFilterUrl    = '/admin/maps/list-filter';


var MapForm = {
    init:function() {
        $('#zone_group_id').change(function(){
            $.getJSON(
                baseUrl + MapFormUrl,
                {
                    zoneGroupId: $(this).val()
                },
                function(options)
                {
                    $('#client_id').html("");

                    for (var i = 0; i < options.length; i++)
                    {
                        $('#client_id').append('<option value="' + options[i].value + '">' + options[i].label + '</option>');
                    }

                    MapForm._toggleClientDropdown();
                }
            );
        });

        this._toggleClientDropdown();

    },
    
    _toggleClientDropdown:function() {
        if ($('#client_id option').length > 1)
        {
            $('#client_id_wrap').show();
        } else {
            $('#client_id_wrap').hide();
        }
    }
};

var MapListFilter = {
    init: function() {
        this._toggleFilters();

        $('#map-search-filter .filter').change(function() {
            params = new Object();

            $('#map-search-filter .filter').each(
                function() {
                    params[$(this).attr('name')] = $(this).val();
                }
            );

            $.getJSON(
                baseUrl + MapListFilterUrl,
                params,
                function(results) {
                    for(filter in results)
                    {
                        var value = $('#' + filter).val();
                        $('#' + filter).html("");

                        eval('var options = results.' + filter + ';');

                        for (var i = 0; i <  options.length; i++)
                        {
                            var selected = '';

                            if (options[i].value == value) {
                                selected = 'selected';
                            }
                            $('#' + filter).append('<option value="' + options[i].value + '"' + selected + '>' + options[i].label + '</option>');
                        }
                    }

                     MapListFilter._toggleFilters();
                }
            );
        });
    },

    _toggleFilters: function() {
        $('#map-search-filter .filter').each(
            function()
            {
                if ($(this).find('option').length > 1) {
                    $(this).parent().show();
                } else {
                    $(this).parent().hide();
                }
            }
        );
    }

};
