DNow.FileViewer = Class.create( aw.ui.Panel, {

    _activeDataType: null,
    _dataTypeDropDown: null,
    _dataRecords: null,
    _grid: null,
    _propertiesPanel: null,

    _onUserSettingsReceived_fx: null,
    _onDataTypesChanged_fx: null,
    _onUserDataActionExecuted_fx: null,

	_onWizardJobUpdated_fx: null,

    initialize: function ( properties, events ) {
        this._activeDataType = null;
        this._dataTypeDropDown = null;
        this._dataRecords = null;
        this._grid = null;
        this._propertiesPanel = null;

        this.inheritCSS = true;

        aw.ui.Panel.prototype.initialize.apply( this, arguments );

        this.componentBus.getComponentReferences( 'aw.UserDataManager', function ( components ) {
            if ((components) && (components.length > 0)) {
                var udm = components[0];

                // this._onUserSettingsReceived_fx = this._onUserSettingsReceived.bind( this );
                this._onDataTypesChanged_fx = this._onDataTypesChanged.bind( this );
                this._onUserDataActionExecuted_fx = this._onUserDataActionExecuted.bind( this );

                // udm.registerEvent( 'onusersettingsreceived', this._onUserSettingsReceived_fx );
                udm.registerEvent( 'ondatatypeschanged', this._onDataTypesChanged_fx );
                udm.registerEvent( 'onactionexecuted', this._onUserDataActionExecuted_fx );

                if ((udm.dataTypes) && (udm.dataTypes.length > 0))
                    this._onDataTypesChanged( udm.dataTypes );

                // if (udm.userSettings)
                //     this._onUserSettingsReceived( udm.userSettings );
            }
        }.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 ) );

    },

    destroy: function ( ) {
        if (this.componentBus) {
            var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
            if ((udm) && (udm.length > 0)) {
                udm = udm[0];
                
                // if (this._onUserSettingsReceived_fx) {
                //     udm.unregisterEvent( 'onusersettingsreceived', this._onUserSettingsReceived_fx );
                //     this._onUserSettingsReceived_fx = null;
                // }
                
                if (this._onDataTypesChanged_fx) {
                    udm.unregisterEvent( 'ondatatypeschanged', this._onDataTypesChanged_fx );
                    this._onDataTypesChanged_fx = null;
                }
                
                if (this._onUserDataActionExecuted_fx) {
                    udm.unregisterEvent( 'onactionexecuted', this._onUserDataActionExecuted_fx );
                    this._onUserDataActionExecuted_fx = null;
                }
            }

			var wm = this.componentBus.getComponentReferences( 'aw.WizardManager' );
			if ((wm) && (wm.length > 0)) {
				wm = wm[0];
				if (this._onWizardJobUpdated_fx) {
					wm.unregisterEvent( 'onwizardjobupdated', this._onWizardJobUpdated_fx );
					this._onWizardJobUpdated_fx = null;
				}
			}
        }

        this._activeDataType = null;
        this._dataTypeDropDown = null;
        this._dataRecords = null;
        this._grid = null;
        this._propertiesPanel = null;

        aw.ui.Panel.prototype.destroy.apply( this );
    },

    draw: function ( ) {
        aw.ui.Panel.prototype.draw.apply( this );

        this._grid = new aw.ui.Grid({
            'columns': [
                { 'label': 'Name', 'index': 'nameTruncated', 'sorted': true, 'sortDirection': 'asc' },
                { 'label': 'Type', 'index': 'typeLabel' },
                { 'label': 'Date Created', 'index': 'dateCreated', 'type': 'date' },
                { 'label': 'Date Modified', 'index': 'dateModified', 'type': 'date' }
            ]
        },{
            'onselectionchanged': this._onGridSelectionChanged.bind( this )
        });

        this._propertiesPanel = new aw.ui.Panel({
            'title': 'File Properties',
            'titleVisibility': true,
            'minWidth': 300,
            'width': 300
        });

        this._dataTypeDropDown = new aw.ui.Control.DropDown({
            'label': 'View:',
            'options': [{'label':'Loading...'}]
        },{
            'change': this._onDataTypeDropDownChange.bind( this )
        });

        //this._uploadFileButton = new aw.ui.Control.Button( { 'label': 'Upload File', 'disabled': true }, { 'click': this._onUploadFileClick.bind( this ) } );

        this.add(
            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': 'File Controls',
                        'items': [
                            new aw.ui.Toolbar.Column({
                                'items': [
                                    new aw.ui.Toolbar.Row({
                                        'items': [
                                            this._dataTypeDropDown
                                        ]
                                    })
                                    // new aw.ui.Toolbar.Row({
                                    //     'items': [
                                    //         this._uploadFileButton
                                    //     ]
                                    // })
                                ]
                            })
                        ],
                        'helpCallback': this._onHelpClick.bind( this, 'Files:File Controls' )
                    })
                ]
            }));

        this.add(
            new aw.ui.Panel.Splitter({
                'titleVisibility': false,
                'orientation': 'horizontal',
                'items': [
                    new aw.ui.Panel({
                        'titleVisibility': false,
                        'minWidth': 500,
                        'width': 1000,
                        'items': [this._grid]
                    }),
                    this._propertiesPanel
                ]
            }));

        return this.canvas;
    },

    setActiveDataType: function ( datatype ) {
        if (!datatype)
            return;

        this._activeDataType = datatype;

        if (this._dataTypeDropDown)
            this._dataTypeDropDown.selectByValue( datatype.key, false );

        var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
        if ((udm) && (udm.length > 0))
            udm[0].retrieveData( datatype.key, null, null, this._onDataRetrieved.bind( this ) );
    },

    _getDataRecordByKey: function ( key ) {
        if ((!key) || (!this._dataRecords) || (!this._dataRecords.length > 0))
            return null;

        for (var i=0, len=this._dataRecords.length; i < len; i++) {
            if (this._dataRecords[i].key == key)
                return this._dataRecords[i];
        }

        return null;
    },

    _onActionClicked: function ( action, records, bConfirm ) {
        if ((!action) || (!records) || (!records.length > 0))
            return;

        if ((action.toLowerCase() == 'delete') && (bConfirm !== true)) {
            new aw.ui.Dialog.Confirm({'title': 'Delete', 'content': 'Are you certain you want to delete the selected data items?'},{'onconfirm': this._onActionClicked.bind( this, action, records, true )});
            return;
        }

        for (var i=0, len=records.length; i < len; i++) {
            records[i].executeAction( action );
        }
    },

    _onDataRetrieved: function ( data ) {
        if (this._grid) {
            this._dataRecords = data;
            var dataLoad = [];
            var d = null;
            for (var i=0; d=data[i]; i++) {
                dataLoad.push({
                    '_key': d.key,
                    'name': d.name,
					'nameTruncated': (d.name.length > 57) ? (d.name.substring(0, 57) + '...') : d.name,
                    'type': d.type,
                    'typeLabel': d.typeLabel,
                    'dateCreated': d.dateCreated,
                    'dateModified': d.dateModified
                });
            }

            this._grid.loadData( dataLoad );
            this._onGridSelectionChanged( this._grid.getSelectedRecords( ) );
        }
    },

    _onDataTypeDropDownChange: function ( control ) {
        var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
        if ((udm) && (udm.length > 0))
            this.setActiveDataType( udm[0].getDataTypeByKey( control.getValue() ) );
    },

    _onDataTypesChanged: function ( datatypes ) {
        this._activeDataType = null;

        if (this._dataTypeDropDown) {
            this._dataTypeDropDown.clear( );

            var datatype = null;
            for (var i=0; datatype=datatypes[i]; i++) {
                this._dataTypeDropDown.addOption( datatype.key, datatype.label );

                if (!this._activeDataType)
                    this.setActiveDataType( datatype );
            }
        }
    },

    _onGridSelectionChanged: function ( records ) {

        if (this._propertiesPanel) {
            this._propertiesPanel.clear( );
            
            var i, rLen = 0, sLen = 0, aLen = 0, 
                field, properties, record,
                selectedRecords = [],
                selectedTypes = [],
                selectedActions = [],
                actionButtons = [],
                action = null;

            for (i = 0, rLen = records.length; i < rLen; i++) {
                selectedRecords.push( this._getDataRecordByKey( records[i]._key ) );
            }

            if ((selectedRecords) && (selectedRecords.length > 0)) {
                for (i = 0, sLen = selectedRecords.length; i < sLen; i++) {
                    record = selectedRecords[i];
                    if (selectedTypes.indexOf( record.type ) < 0)
                        selectedTypes.push( record.type );

                    if (selectedActions.length > 0)
                        selectedActions.intersect( record.getActions( ) );
                    else
                        selectedActions = record.getActions( );
                }
            }

            if ((!selectedRecords) || (sLen < 1)) {
                properties = '<strong>No files selected.</strong>';
            } else if (sLen === 1) {
                record = selectedRecords[0];

                properties = '<div class="properties"><p><strong>File Name:</strong> ' + record.name + '</p>' +
                    '<p><strong>Type:</strong> ' + record.type + '</p>' +
                    '<p><strong>Date Created:</strong> ' + record.dateCreated + '</p>' +
                    '<p><strong>Date Modified:</strong> ' + record.dateModified + '</p>' +
                    '<hr size="1" />' +
                    '<div class="details"><p><strong>Loading details....</strong></p></div></div>';

                var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
                if ((udm) && (udm.length > 0)) {
                    field = (record.type === "CustomPolygon") ? ["PolygonName"] : null;
                    udm[0].retrieveData( record.type, record.name, null, this._onSelectionDetailsReceived.bind( this ), null, field);
                }
            } else if (sLen > 1) {
                properties = '<p><strong>Number of Items:</strong> ' + sLen + '</p>' +
                    '<p><strong>Type:</strong> ' + (selectedTypes.length > 1) ? 'Multiple Types' : selectedTypes[0] + '</p>';
            }

            for (i = 0, aLen = selectedActions.length; i < aLen; i++) {
                action = selectedActions[i];
                actionButtons.push( new aw.ui.Control.Button( { 'label': action },{ 'click': this._onActionClicked.bind( this, action, selectedRecords ) } ) );
            }

            this._propertiesPanel.add(
                new aw.ui.Toolbar({
                    'region': 'bottom',
                    'height': 60,
                    'items': [
                        new aw.ui.Toolbar.Row({
                            'items': actionButtons
                        })
                    ]
                })
            );

            this._propertiesPanel.add(
                new aw.ui.HTML({
                    'html': properties
                })
            );
        }
    },

    _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
        });
    },

    _onSelectionDetailsReceived: function ( data ) {
        if ((!this._propertiesPanel) || (!data) || (!data.length === 1))
            return;

        var propertiesCanvas = this._propertiesPanel.canvas.down('div.properties');
        var detailsCanvas = this._propertiesPanel.canvas.down('div.details');
        if ((propertiesCanvas) && (detailsCanvas)) {
            if (data[0].details) {
                var d = [], detailKey = null;
                for (detailKey in data[0].details) {
                    d.push( '<p><strong>' + detailKey + ':</strong> ' + data[0].details[detailKey] + '</p>' );
                }
                detailsCanvas.update( d.join('') );
            } else {
                detailsCanvas.update( '<p><strong>No details found.</strong></p>' );
            }
        }
    },

   _onUploadFileClick: function ( control ) {
        new aw.ui.Dialog.Geocode({
            'componentBus': this.componentBus
        });
    },

    _onUserDataActionExecuted: function ( parameters ) {
        if ((!this._activeDataType) || (this._activeDataType.key === '') || (parameters.datatype.toLowerCase() == this._activeDataType.key.toLowerCase())) {
            if (parameters.action.match( 'save|delete|copy|rename|export' ))
                this.setActiveDataType( this._activeDataType );
        }
    },

    _onUserSettingsReceived: function ( settings ) {
        if ((!settings) || (!this._uploadFileButton))
            return;

        if (settings.enableUploadedLocations === true)
            this._uploadFileButton.enable( );
        else
            this._uploadFileButton.disable( );
    },

    _onWizardJobUpdated: function ( job ) {
        if (!job || !job.disposition || job.disposition === "" ||
            job.userDataTypes.length < 1 ) {
            return;
        }

        var refresh = false;
        if (job.disposition.toLowerCase() === 'complete') {
            var activeType = this._activeDataType.key.toLowerCase();
            if (activeType === "") {
                refresh = true;
            } else {
                var jobType;
                var userDataTypes = job.userDataTypes;
                for (var i = 0, l = userDataTypes.length; i < l; i++) {
                    if (activeType === userDataTypes[i].toLowerCase()) {
                        refresh = true;
                        break;
                    }
                }
            }
        }

        if (refresh === true) {
            var udm = this.componentBus.getComponentReferences( 'aw.UserDataManager' );
            if ((udm) && (udm.length > 0)) {
                udm[0].retrieveData( activeType, null, null, this._onDataRetrieved.bind( this ) );
            }
        }
    },

    CLASS_NAME: 'DNow.FileViewer'
});

