DNow.MapViewer = Class.create(aw.ui.Panel, {

    _customPolygonsButton: null,
    _customPolygonsControl: null,

    _map: null,

    _panelDropButton: null,

    _userLocationFiles: [],

    _onWizardJobUpdated_fx: null,

    initialize: function (properties, events) {

        this._customPolygonsButton = null;
        this._customPolygonsControl = null;

        this._map = null;

        this._panelDropButton = null;

        this._userLocationFiles = [];

        this.inheritCSS = true;

        aw.ui.Panel.prototype.initialize.apply(this, arguments);


        this.componentBus.getComponentReferences('aw.QueryManager', function (components) {
            if ((components) && (components.length > 0)) {
                var qm = components[0];
                qm.registerEvent('onquerydatasetschanged', this._onQueryDatasetsChanged.bind(this));

                var datasets = qm.getAllQueryDatasets();
                if ((datasets) && (datasets.length > 0))
                    this._onQueryDatasetsChanged(datasets);
            }
        } .bind(this));


        if (this.componentBus) {
            this.componentBus.getComponentReferences('aw.GeographyManager', function (components) {
                if ((components) && (components.length > 0)) {
                    var gm = components[0];
                    gm.registerEvent('onactivegeographychanged', this._onActiveGeographyChanged.bind(this));
                    gm.registerEvent('onboundschanged', this._onBoundsChanged.bind(this));
                    gm.registerEvent('onallocatedatasetchanged', this._onAllocateDatasetChanged.bind(this));

                    if (gm.activeGeography)
                        this._onActiveGeographyChanged(gm.activeGeography, true);

                    if (gm.allocateDataset)
                        this._onAllocateDatasetChanged(gm.allocateDataset);
                }
            } .bind(this));

            this.componentBus.getComponentReferences('aw.UserDataManager', function (components) {
                if ((components) && (components.length > 0)) {
                    var udm = components[0];
                    udm.registerEvent('onusersettingsreceived', this._onUserSettingsReceived.bind(this));
                    udm.registerEvent('onactionexecuted', this._onUserDataActionExecuted.bind(this));

                    if (udm.userSettings)
                        this._onUserSettingsReceived(udm.userSettings);

                    this._initializeUserPoints();
                }
            } .bind(this));

            this.componentBus.getComponentReferences('aw.ThematicsManager', function (components) {
                if ((components) && (components.length > 0)) {
                    var tm = components[0];
                    tm.registerEvent('activethematicchanged', this._onActiveThematicChanged.bind(this));
                    tm.registerEvent('thematicschanged', this._onThematicsChanged.bind(this));
                    tm.registerEvent('paletteschanged', this._onPalettesChanged.bind(this));
                    tm.registerEvent('geographylevelschanged', this._onGeographyLevelsChanged.bind(this));
                    tm.registerEvent('variableschanged', this._onVariablesChanged.bind(this));

                    if (tm.variables)
                        this._onVariablesChanged(tm.variables);
                }
            } .bind(this));

            this.componentBus.getComponentReferences('aw.WizardManager', function (components) {
                if ((components) && (components.length > 0)) {
                    var wm = components[0];

                    this._onWizardJobUpdated_fx = this._onWizardJobUpdated.bind(this);
                    wm.registerEvent('onwizardjobupdated', this._onWizardJobUpdated_fx);
                }
            } .bind(this));
        }
    },

    draw: function () {
        aw.ui.Panel.prototype.draw.apply(this);

        /*
        //Rally 773 - Retail Centre Points UPDATE: These have been moved to the query manager in order to permission them
        //Create the retail centre layers and group - have to add the layers to the group after everything is created otherwise it won't work - bug?
        var majorCity = new aw.ui.Map.Layer.Static({ 'key': 'majorCity', 'label': 'Major City', 'labelTemplate': 'rc_major_city_label', 'drawPriority': 9, 'showInLegend': true, 'visible': true, 'icon': './custom/img/Acxiom/RC_major_city.png', 'labelControllable': true, 'parameters': { 'service': 'major_city_rc'} });
        var majorRegional = new aw.ui.Map.Layer.Static({ 'key': 'majorRegional', 'label': 'Major Regional', 'labelTemplate': 'rc_major_regional_label', 'drawPriority': 8, 'showInLegend': true, 'visible': true, 'icon': './custom/img/Acxiom/RC_major_regional.png', 'labelControllable': true, 'parameters': { 'service': 'major_regional_rc'} });
        var regional = new aw.ui.Map.Layer.Static({ 'key': 'regional', 'label': 'Regional', 'labelTemplate': 'rc_regional_label', 'drawPriority': 7, 'showInLegend': true, 'visible': true, 'icon': './custom/img/Acxiom/RC_regional.png', 'labelControllable': true, 'parameters': { 'service': 'regional_rc'} });
        var subRegional = new aw.ui.Map.Layer.Static({ 'key': 'subRegional', 'label': 'Sub-Regional', 'labelTemplate': 'rc_sub_regional_label', 'drawPriority': 6, 'visible': false, 'icon': './custom/img/Acxiom/RC_sub_regional.png', 'labelControllable': true, 'parameters': { 'service': 'sub_regional_rc'} });
        var majorDistrict = new aw.ui.Map.Layer.Static({ 'key': 'majorDistrict', 'label': 'Major District', 'labelTemplate': 'rc_major_district_label', 'drawPriority': 5, 'visible': false, 'icon': './custom/img/Acxiom/RC_major_district.png', 'labelControllable': true, 'parameters': { 'service': 'major_district_rc'} });
        var district = new aw.ui.Map.Layer.Static({ 'key': 'district', 'label': 'District', 'labelTemplate': 'rc_district_label', 'drawPriority': 4, 'visible': false, 'showInLegend': true, 'icon': './custom/img/Acxiom/RC_district.png', 'labelControllable': true, 'parameters': { 'service': 'district_rc'} });
        var minorDistrict = new aw.ui.Map.Layer.Static({ 'key': 'minorDistrict', 'label': 'Minor District', 'labelTemplate': 'rc_minor_district_label', 'drawPriority': 3, 'visible': false, 'icon': './custom/img/Acxiom/RC_minor_district.png', 'labelControllable': true, 'parameters': { 'service': 'minor_district_rc'} });
        var local = new aw.ui.Map.Layer.Static({ 'key': 'local', 'label': 'Local', 'labelTemplate': 'rc_local_label', 'drawPriority': 2, 'visible': false, 'icon': './custom/img/Acxiom/RC_local.png', 'labelControllable': true, 'parameters': { 'service': 'local_rc'} });
        var minorLocal = new aw.ui.Map.Layer.Static({ 'key': 'minorLocal', 'label': 'Minor Local', 'labelTemplate': 'rc_minor_local_label', 'drawPriority': 1, 'visible': false, 'icon': './custom/img/Acxiom/RC_minor_local.png', 'labelControllable': true, 'parameters': { 'service': 'minor_local_rc'} });
        var rcGroup = new aw.ui.Map.Layer.Group({ 'key': 'RetailCentres', 'label': 'RETAILNATION', 'drawPriority': 179, 'collapsed': true });
        //---------------------------------------------
        */

        this._map = new aw.ui.Map({
            'componentBus': this.componentBus,
            'layers': [
                new aw.ui.Map.Layer.Static({ 'key': 'base', 'label': 'Base', 'drawPriority': 0, 'visible': true, 'icon': './core/img/Map/Layer/base.png', 'parameters': { 'service': 'base'} }),
            //rcGroup, //Rally 773
                new aw.ui.Map.Layer.Static({ 'key': 'aerial', 'label': 'Aerial', 'drawPriority': 1, 'visible': false, 'icon': './core/img/Map/Layer/aerial.png', 'parameters': { 'service': 'satellite' }, 'attribution': 'Copyright ' + new Date().getFullYear() + '. DigitalGlobe, Inc. All rights reserved.' }),
                new aw.ui.Map.Layer.Static({ 'key': 'roads', 'label': 'Roads', 'drawPriority': 2, 'visible': true, 'icon': './core/img/Map/Layer/roads.png', 'showInLegend': true, 'parameters': { 'service': 'roads'} }),
                new aw.ui.Map.Layer.GeographySelection({ 'visible': true, 'drawPriority': 20, 'showInLegend': true, 'opacity': 0.5, 'labelControllable': true, 'labelTemplate': 'GeographySelectionLabel' }),
                new aw.ui.Map.Layer.Label({ 'visible': true, 'drawPriority': 300 })
            ],
            'controls': [
                new aw.ui.Map.Control.Features({ 'group': 'Mapping Tools', 'componentBus': this.componentBus }),
                new aw.ui.Map.Control.Annotations({ 'group': 'Mapping Tools', 'componentBus': this.componentBus, 'drawPriority': 301 })
            ]
        }, {
            'controladded': this._onMapControlAdded.bind(this),
            'controlremoved': this._onMapControlRemoved.bind(this),
            'controltoggled': this._onMapControlToggled.bind(this),
            'zoomchanged': this._onMapZoomChanged.bind(this)
        });

        this._mappingToolsButton = new aw.ui.Control.Button.Toggle({ 'label': 'Mapping Tools', 'toggled': true, 'icon': './core/img/Map/Control/wrench.png' }, { 'toggle': this._onMappingToolsButtonToggled.bind(this) });

        //this._panelDropButton = new aw.ui.Control.Button.Drop( { 'label': 'View Panels' } );

        this._variableDropDown = new aw.ui.Control.DropDown({ 'label': 'Variable:', 'options': [{ 'value': null, 'label': 'Loading...'}] }, { 'change': this._onVariableDropDownChange.bind(this) });
        this._geographyDropDown = new aw.ui.Control.DropDown({ 'label': 'Geography (based on zoom):', 'options': [{ 'value': null, 'label': 'Loading...'}] }, { 'change': this._onGeographyDropDownChange.bind(this) });
        this._colorsDropDown = new aw.ui.Control.DropDown({ 'label': 'Colors:', 'options': [{ 'value': null, 'label': 'Loading...'}] }, { 'change': this._onColorsDropDownChange.bind(this) });

        this.add([
            this._map,
            new aw.ui.Toolbar({
                'region': 'top',
                'height': 100,
                'cssClass': 'DNow_Toolbar',
                'items': [
                    new aw.ui.Toolbar.Group({
                        'label': 'Geography Selection',
                        'cssClass': 'geoselection',
                        'items': [
                            new DNow.GeographyBar({
                                'componentBus': this.componentBus
                            })
                        ],
                        'helpCallback': this._onHelpClick.bind(this, 'Geography Selection')
                    }),
                    new aw.ui.Toolbar.Group({
                        'label': 'Mapping Options',
                        'items': [
                            new aw.ui.Toolbar.Row({
                                'items': [
                                    this._mappingToolsButton,
                                    new aw.ui.Control.Button({
                                        'label': 'Export Map'
                                    }, {
                                        'click': this._onExportMapClick.bind(this)
                                    })
                                ]
                            })
                        ],
                        'helpCallback': this._onHelpClick.bind(this, 'Map:Mapping Options')
                    }),
                    new aw.ui.Toolbar.Group({
                        'label': 'Thematic Controls',
                        'items': [
                            new aw.ui.Toolbar.Row({
                                'items': [
                                    this._toggleThematicsButton,
                                    new aw.ui.Toolbar.Column({
                                        'items': [
                                            this._variableDropDown,
                                            this._geographyDropDown,
                                            this._colorsDropDown
                                        ]
                                    })
                                ]
                            })
                        ],
                        'helpCallback': this._onHelpClick.bind(this, 'Map:Thematic Controls')
                    })
                ]
            })
        ]);

        /*
        //Rally 773 - Retail Centre Points. UPDATE: These have been moved tot he quesry manager in order to permission them.
        //Add each layer to the group layer because of possible bug
        rcGrp = this._map.getLayerByKey("RetailCentres");
        rcGrp.addLayer(minorLocal);
        rcGrp.addLayer(local);
        rcGrp.addLayer(minorDistrict);
        rcGrp.addLayer(district);
        rcGrp.addLayer(majorDistrict);
        rcGrp.addLayer(subRegional);
        rcGrp.addLayer(regional);
        rcGrp.addLayer(majorRegional);
        rcGrp.addLayer(majorCity);
        //---------------------------------------------------------
        */

        return this.canvas;
    },

    hide: function () {
        aw.ui.Panel.prototype.hide.apply(this);

        if (this._map)
            this._map.hide();
    },

    show: function () {
        aw.ui.Panel.prototype.show.apply(this);

        if (this._map)
            this._map.show();
    },

    _getUserLocationFileByName: function (name) {
        if ((!name) || (!this._userLocationFiles) || (!this._userLocationFiles.length > 0))
            return null;

        for (var i = 0; i < this._userLocationFiles.length; i++) {
            if (this._userLocationFiles[i].name == name)
                return this._userLocationFiles[i];
        }

        return null;
    },

    _initializeUserPoints: function () {
        var udm = this.componentBus.getComponentReferences('aw.UserDataManager');
        if ((!udm) || (!udm.length > 0))
            return;

        udm = udm[0];

        var doIt = function () {
            udm.retrieveData('UserLocationFile', null, null, function (locationFiles) {
                this._userLocationFiles = [];
                if ((!locationFiles) || (!locationFiles.length > 0)) {
                    if (this._userPointsMapGroup)
                        this._map.removeLayer(this._userPointsMapGroup);
                } else {
                    if (this._userPointsMapGroup)
                        this._userPointsMapGroup.removeAllLayers();
                    else
                        this._userPointsMapGroup = this._map.addLayer(new aw.ui.Map.Layer.Group({ 'drawPriority': 7, 'key': 'UserLocationFiles', 'label': 'Location Files', 'visible': true }));

                    for (var i = 0; i < locationFiles.length; i++) {
                        this._userPointsMapGroup.addLayer(new aw.ui.Map.Layer.Point.LocationFile({ 'key': locationFiles[i].key, 'label': locationFiles[i].name, 'labelControllable': true, 'labelTemplate': 'UserLocationLabel', 'options': true, 'visible': false }));
                    }

                    this._userLocationFiles = locationFiles;
                }

            } .bind(this));
        } .bind(this);

        window.setTimeout(doIt, 500);
    },

    _onActiveGeographyChanged: function (geoCollection, resetMapZoom, minx, miny, maxx, maxy) {
        if (!geoCollection)
            return;

        resetMapZoom = (resetMapZoom === false ? false : true);
        if ((geoCollection) && (geoCollection.anchor) && (geoCollection.anchor.x) && (geoCollection.anchor.y) && (resetMapZoom === true))
            this._map.setCenter(geoCollection.anchor.y, geoCollection.anchor.x);

        if ((geoCollection) && (geoCollection.geos) && (geoCollection.geos.length > 0)) {
            if ((resetMapZoom === true) && (minx) && (miny) && (maxx) && (maxy)) {
                this._map.zoomToExtent(minx, miny, maxx, maxy);
            } else if (resetMapZoom === true) {
                var gm = this.componentBus.getComponentReferences('aw.GeographyManager');
                if ((gm) && (gm.length > 0))
                    gm[0].computeBounds(geoCollection);
            }
        }
    },

    _onActiveThematicChanged: function (thematic) {
        if ((!thematic) || (!this._variableDropDown) || (!this._geographyDropDown) || (!this._colorsDropDown) || (!this._map) || (!this._map.layers))
            return;

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];

        this._variableDropDown.selectByValue(tm.activeThematic.variable, false);
        this._geographyDropDown.selectByValue(tm.activeThematic.geography, false);
        this._colorsDropDown.selectByValue(tm.activeThematic.palette, false);

        var layer = null;
        var variable = tm.getVariableByKey(this._variableDropDown.getValue());

        if (variable)
            this._variableDropDown.setAlt(variable.namePath);

        var geographyLevel = null;
        if (this._geographyDropDown.getValue() == 'auto')
            geographyLevel = tm.getAutoGeographyLevel(this._map.getScale());
        else
            geographyLevel = tm.getGeographyLevelByKey(this._geographyDropDown.getValue());

        var palette = tm.getPaletteByKey(this._colorsDropDown.getValue());

        var i = this._map.layers.length;
        while (i--) {
            layer = this._map.layers[i];
            if (layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true) {
                layer.setVariable(variable);
                layer.setGeography(geographyLevel);

                if ((palette) && (layer.palette != palette.key)) {
                    layer.setPalette(palette.key);
                    layer.setColors(palette.colors);
                }
            }
        }
    },

    _onAllocateDatasetChanged: function (dataset) {
        if (this._map) {
            var _layer = null;
            var i = this._map.layers.length;
            while (i--) {
                _layer = this._map.layers[i];
                if (_layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true)
                    this._map.removeLayer(layer);
            }
        }

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((tm) && (tm.length > 0))
            tm[0].setAllocateDataset(dataset);
    },

    _onBoundsChanged: function (minx, miny, maxx, maxy) {
        if ((minx) && (miny) && (maxx) && (maxy))
            this._map.zoomToExtent(minx, miny, maxx, maxy);
    },

    _onColorsDropDownChange: function (control) {
        if ((!control) || (!control.getValue()))
            return;

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];

        var palette = tm.getPaletteByKey(control.getValue());
        if (palette) {
            tm.setActiveThematicPalette(palette);
            var _layer = null;
            var i = this._map.layers.length;
            while (i--) {
                _layer = this._map.layers[i];
                if (_layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true) {
                    if (_layer.palette != palette.key) {
                        _layer.setPalette(palette.key);
                        _layer.setColors(palette.colors);
                    }
                }
            }
        }
    },

    _onExportMapClick: function (control) {
        if (this.isSessionValidated() !== true) {
            new aw.ui.Dialog.Error({ 'title': 'Access Denied', 'content': 'You must be logged in to access this functionality.' });
            return;
        }

        new aw.ui.Dialog.ExportMap({ 'componentBus': this.componentBus, 'map': this._map });
    },

    _onGeographyDropDownChange: function (control) {
        if ((!control) || (!control.getValue()))
            return;

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];

        var geographyLevel = null;
        if (control.getValue() == 'auto')
            geographyLevel = tm.getAutoGeographyLevel(this._map.getScale());
        else
            geographyLevel = tm.getGeographyLevelByKey(control.getValue());

        if (geographyLevel) {
            tm.setActiveThematicGeography(geographyLevel);
            var _layer = null;
            var i = this._map.layers.length;
            while (i--) {
                _layer = this._map.layers[i];
                if (_layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true)
                    _layer.setGeography(geographyLevel);
            }
        }
    },

    _onGeographyLevelsChanged: function (geographyLevels) {
        this._updateGeographyDropDown(this._map.getScale());
    },

    _onHelpClick: function (topic) {
        if (this.componentBus) {
            var help = this.componentBus.getComponentReferences('DNow.Help');
            if ((help) && (help.length > 0)) {
                help[0].loadTopicByTitle(topic);
                return;
            }
        }

        new DNow.Help({
            'componentBus': this.componentBus,
            'activeTopicKey': topic
        });
    },

    _onMapControlAdded: function (control) {
        //if ((!control) || (!this._panelDropButton))
        //    return;

        //this._panelDropButton.add( new aw.ui.Control.Button.Toggle( { 'label': control.title, 'toggled': control.isVisible( ), 'icon': control.icon },{'toggle': function ( control ) { control.toggle( ); }.bind( this, control ) } ) );
    },

    _onMapControlRemoved: function (control) {
        //if ((!control) || (!this._panelDropButton))
        //    return;

        //this._panelDropButton.remove( this._panelDropButton.getItemByLabel( control.title ) );
    },

    _onMapControlToggled: function (control) {
        /*if ((!control) || (!this._panelDropButton))
        return;

        var button = this._panelDropButton.getItemByLabel( control.title );
        if (button)
        button.setToggled( control.isVisible(), false );*/

        if ((!control) || (!this._mappingToolsButton))
            return;

        this._mappingToolsButton.setToggled(control.isVisible(), false);
    },

    _onMappingToolsButtonToggled: function (control) {
        if ((!this._map) || (!this._map.controlGroups))
            return;

        for (var key in this._map.controlGroups) {
            this._map.controlGroups[key].toggle();
        }
    },

    _onMapZoomChanged: function (scale) {
        this._updateGeographyDropDown(scale);
    },

    _onPalettesChanged: function (palettes) {
        if (!this._colorsDropDown)
            return;

        this._colorsDropDown.clear();
        var palette = null, options = [];
        for (var i = 0; palette = palettes[i]; i++) {
            options.push({ 'value': palette.key, 'label': palette.name });
        }

        this._colorsDropDown.addOptions(options);

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((tm) && (tm.length > 0) && (tm[0].activeThematic))
            this._onActiveThematicChanged(tm[0].activeThematic);
    },

    _onThematicsChanged: function (thematics) {
        if ((!this._map) || (!this._map.layers) || (!this._map.layers.length > 0))
            return;

        var i, iLen;
        var layers = this._map.layers;
        var layer = null;
        for (i = 0, iLen = layers.length; i < iLen; i++) {
            layer = this._map.layers[i];
            if (layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true)
                this._map.removeLayer(layer);
        }

        if ((thematics) && (thematics.length > 0)) {
            var thematic = null,
                thematicLayer = null,
                properties = null;
            for (i = 0, iLen = thematics.length; i < iLen; i++) {
                thematic = thematics[i];
                properties = {
                    'active': thematic.active,
                    'colors': (thematic.colors) ? thematic.colors : [],
                    'cutoffs': (thematic.ranges) ? thematic.ranges : [],
                    'dataset': thematic.dataset,
                    'name': thematic.name,
                    'drawPriority': 3,
                    'opacity': 0.8
                };

                if (thematic.key)
                    Object.extend(properties, { 'key': thematic.key });

                thematicLayer = new aw.ui.Map.Layer.Thematic(properties);
                this._map.addLayer(thematicLayer);
            }
        }
    },

    _onUserDataActionExecuted: function (parameters) {
        if (!parameters)
            return;

        if (parameters.datatype == 'UserLocationFile') {
            if (parameters.action == 'delete') {
                this._onUserLocationFileDeleted(parameters);
            } else {
                this._initializeUserPoints();
            }
        } else if ((parameters.datatype == 'CustomPolygon') && (parameters.action == 'View/Edit')) {
            var cpm = this.componentBus.getComponentReferences('aw.CustomPolygonManager');
            if ((cpm) && (cpm.length > 0))
                cpm[0].setActivePolygonSetByName(parameters.name);

            this.show();
        }
    },

    _onUserLocationFileDeleted: function (parameters) {
        if ((!parameters) || (!this._map))
            return;

        if (this._userPointsMapGroup) {
            var locationFile = this._getUserLocationFileByName(parameters.name);
            if (!locationFile)
                return;

            this._userPointsMapGroup.removeLayerByKey(locationFile.key);
            if (this._userPointsMapGroup.layers.length < 1) {
                this._map.removeLayer(this._userPointsMapGroup);
                this._userPointsMapGroup = null;
            }
        }
    },

    _onUserSettingsReceived: function (settings) {
        if (!settings)
            return;
        if (settings.enableCustomPolygons === true) {
            if (!this._customPolygonsControl) {
                this._customPolygonsControl = new aw.ui.Map.Control.CustomPolygons({ 'group': 'Mapping Tools', 'componentBus': this.componentBus, 'drawPriority': 5 });
                this._map.addControl(this._customPolygonsControl);
            }
        } else {
            if (this._customPolygonsControl) {
                this._map.removeControl(this._customPolygonsControl);
                this._customPolygonsControl = null;
            }
        }
    },

    _onWizardJobUpdated: function (job) {
        if (!job || !job.disposition || job.disposition === "" ||
            job.userDataTypes.length < 1) {
            return;
        }

        if (job.disposition.toLowerCase() === 'complete') {
            var userDataTypes = job.userDataTypes;
            for (var i = 0, l = userDataTypes.length; i < l; i++) {
                switch (userDataTypes[i]) {
                    case "CustomPolygon":
                        var cpm = this.componentBus.getComponentReferences('aw.CustomPolygonManager')[0];
                        if (cpm) {
                            cpm._getCustomPolygonSets();
                        }
                        break;
                    case "UserLocationFile":
                        this._initializeUserPoints();
                        break;
                    default:
                        // Do nothing
                        break;
                }
            }
        }
    },

    _onVariableDropDownChange: function (control) {
        if ((!control) || (!control.getValue()))
            return;

        if (control.getValue() == 'more') {
            new DNow.VariableDialog({ 'componentBus': this.componentBus }, { 'onvariableselected': this._onVariableSelected.bind(this) });
            return;
        }

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];

        var variable = tm.getVariableByKey(control.getValue());
        if (variable) {
            tm.setActiveThematicVariable(variable);
            var _layer = null;
            var i = this._map.layers.length;
            while (i--) {
                _layer = this._map.layers[i];
                if (_layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true)
                    _layer.setVariable(variable);
            }
        }
    },

    _onVariablesChanged: function (variables) {
        if (!this._variableDropDown)
            return;

        this._variableDropDown.clear();
        var variable = null, options = [], namePath = null;
        for (var i = 0; variable = variables[i]; i++) {
            namePath = (variable.namePath) ? variable.namePath : 'Unknown';
            options.push({ 'value': variable.variableKey, 'label': ((namePath.length > 40) ? '...' + namePath.substring(namePath.length - 40) : namePath) });
        }

        options.push({ 'value': 'more', 'label': 'More variables...' });

        this._variableDropDown.addOptions(options);

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((tm) && (tm.length > 0) && (tm[0].activeThematic))
            this._onActiveThematicChanged(tm[0].activeThematic);
    },

    _onVariableSelected: function (variable) {
        if (!variable)
            return;

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];
        tm.setActiveThematicVariable(variable);
        var _layer = null;
        var i = this._map.layers.length;
        while (i--) {
            _layer = this._map.layers[i];
            if (_layer.derivesFrom('aw.ui.Map.Layer.Thematic') === true)
                _layer.setVariable(variable);
        }
    },

    _updateGeographyDropDown: function (scale) {
        if ((!scale) || (!this._geographyDropDown))
            return;

        var tm = this.componentBus.getComponentReferences('aw.ThematicsManager');
        if ((!tm) || (!tm.length > 0))
            return;

        tm = tm[0];

        this._geographyDropDown.clear();

        var geographyLevels = tm.getGeographyLevelsByScale(scale);
        if ((geographyLevels) && (geographyLevels.length > 0)) {
            var options = [], geographyLevel = null;
            for (var i = 0; geographyLevel = geographyLevels[i]; i++) {
                options.push({ 'value': geographyLevel.key, 'label': geographyLevel.name });
            }
            this._geographyDropDown.addOptions(options);
            this._onActiveThematicChanged(tm.activeThematic);
        } else {
            this._geographyDropDown.addOption(null, 'No Geographies Available');
        }
    },

    //Rally - Permission the RETAILNATION map layers using Calgary datasets
    _onQueryDatasetsChanged: function (datasets) {
        var map = this.componentBus.getComponentReferences('aw.ui.Map');
        if ((map) && (map.length > 0)) {
            map = map[0];

            var noCal = true;
            for (var n = 0; dataset = datasets[n]; n++) {
                if ((dataset.variant) && (dataset.variant.toLowerCase().indexOf("userlocationfile:") < 0)) {
                    noCal = false;
                    break;
                }
            }

            var pointDatasetGroup = map.getLayerByKey('pointsets');
            if (noCal) {
                map.removeLayerByKey('pointsets');
            }
            else {
                if (pointDatasetGroup)
                    pointDatasetGroup.removeAllLayers();
                else
                    pointDatasetGroup = map.addLayer(new aw.ui.Map.Layer.Group({ 'key': 'pointsets', 'label': 'RETAILNATION', 'drawPriority': 6, 'collapsed': true }));

                var retailLayers = new Array(8);
                for (var m = 0; dataset = datasets[m]; m++) {
                    if ((dataset.variant) && (dataset.variant.toLowerCase().indexOf("userlocationfile:") < 0)) {
                        //'icon': './custom/img/Acxiom/RC_regional.png' //use this for icon maybe
                        var layerProperties = { 'Regional': { 'order': '2', 'fillColor': 'ff8040' },
                            'District': { 'order': '5', 'fillColor': '0000ff' },
                            'Local': { 'order': '7', 'fillColor': 'cccccc' },
                            'Major_City': { 'order': '0', 'fillColor': 'ff00ff' },
                            'Major_District': { 'order': '4', 'fillColor': '008040' },
                            'Major_Regional': { 'order': '1', 'fillColor': 'ff0000' },
                            'Minor_District': { 'order': '6', 'fillColor': '00ffff' },
                            'Minor_Local': { 'order': '8', 'fillColor': '8000ff' },
                            'Sub-Regional': { 'order': '3', 'fillColor': 'ffff00' }
                        };
                        //pointDatasetGroup.addLayer(new aw.ui.Map.Layer.Point.Query({ 'key': 'listlayer_' + dataset.key, 'label': dataset.name, 'labelTemplate': 'QueryLabel', 'labelControllable': true, 'options': false, 'dataset': dataset.key, 'query': '<All/>', 'visible': true, 'drawPriority': layerProperties[dataset.name.replace(" ", "_")].order, 'parameters': { 'fillc': layerProperties[dataset.name.replace(" ", "_")].fillColor, 'outw': 1, 'outc': '00000', 'symst': 'diamond'} }));
                        retailLayers[layerProperties[dataset.name.replace(" ", "_")].order] = { 'key': 'listlayer_' + dataset.key, 'label': dataset.name, 'labelTemplate': 'QueryLabel', 'labelControllable': true, 'visible': false, 'showInLegend': true, 'dataset': dataset.key, 'query': '<All/>', 'visible': true, 'drawPriority': '5', 'parameters': { 'fillc': layerProperties[dataset.name.replace(" ", "_")].fillColor, 'outw': 1, 'outc': '00000'} };
                        //Add 'symst': 'diamond' as a parameter once core adds it in.
                    }
                }
                //There is a bug in the core code where draw priorities are not respected in a group layer. 
                //The loop below is a work-around. Can get rid of once the bug is fixed.
                for (var p = retailLayers.length - 1; p >= 0; p--) {
                    pointDatasetGroup.addLayer(new aw.ui.Map.Layer.Point.Query(retailLayers[p]));
                }
            }
        }
    },
    //---------------------------------------------

    CLASS_NAME: 'DNow.MapViewer'
});
