DNow.SavedGeographyDialog = Class.create( aw.ui.Dialog, {

    initialize: function ( properties, events ) {
        this.inheritCSS = true;

        Object.extend( properties, {
            'title': 'Select a Saved Geography',
            'content': 'Loading...'
        });

        aw.ui.Dialog.prototype.initialize.apply( this, arguments );
    },

    afterDraw: function ( ) {
        aw.ui.Dialog.prototype.afterDraw.apply( this );

        var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
        if ((udm) && (udm.length > 0))
            udm = udm[0];
        else
            return;

        udm.retrieveData( 'SavedGeography', null, null, function ( geos ) {
            var savedGrid = new aw.ui.Grid({
                'columns': [{ 'index': 'name', 'label': 'Name', 'sorted': true, 'sortDirection': 'asc' },
                    { 'index': 'dateCreated', 'label': 'Date Created', 'type': 'date' },
                    { 'index': 'dateModified', 'label': 'Date Modified', 'type': 'date' }],
                'selectMultiple': false
            });

            this.setContent( savedGrid.draw( ) );
            savedGrid.loadData( geos );

            this._renderButton( 'OK', this._onSelectGeographyClick.bind( this, savedGrid ) );
            this._renderButton( 'Cancel', this.close.bind( this ) );
        }.bind( this ) );
    },

    _onSelectGeographyClick: function ( savedGrid ) {
        if (!savedGrid)
            return;

        var selectedGeos = savedGrid.getSelectedRecords( );
        if ((!selectedGeos) || (!selectedGeos.length > 0))
            return;

        var geo = selectedGeos[0];
        var gm = this.componentBus.getComponentReferences( 'aw.GeographyManager' );
        if ((gm) && (gm.length > 0))
            gm = gm[0];
        else
            return;

        if (geo.geoCollection) {
            gm.setActiveGeography( geo.geoCollection );
            this.close( );
        } else {
            var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
            if ((udm) && (udm.length > 0)) {
                udm[0].retrieveData( 'SavedGeography', geo.name, null, function ( gm, data ) {
                    if ((data) && (data.length > 0) && (data[0].geoCollection)) {
                        gm.setActiveGeography( data[0].geoCollection );

                        this.close( );
                    }
                }.bind( this, gm ) );
            }
        }
    },

    CLASS_NAME: 'DNow.SavedGeographyDialog'
});
