﻿/*
*   TNRIS.UserLayerWindow - custom layer creation in the GEMSS application
*       -- GeoRSS feeds
*       -- User drawn Shapes
*       -- GPS imported spreadsheet
*       -- KML/GML imports
*       -- Smart Layer
*/

TNRIS.UserLayerWindow = function(config) {
    Ext.apply(this, config, {
        id: 'userLayerWindow'
    });
    
    this.form = new Ext.FormPanel({
        labelAlign:'top',
        bodyStyle: {'background-color': 'transparent'},
        defaultType: 'textfield',
        layout: 'form',
        items: [
            {
                id: 'name',
                fieldLabel: "Name",
                allowBlank: false,
                blankText: 'Every Layer must have a name',
                anchor: '100%',
                maxLength: 200,
                msgTarget: 'under'
            },
            {
                id: 'teaser',
                fieldLabel: "Teaser",
                allowBlank: false,
                blankText: 'Every Layer must have a teaser',
                anchor: '100%',
                maxLength: 100,
                msgTarget: 'under'
            },
            {
                id: 'keywords',
                fieldLabel: "Keywords",
                allowBlank: true,
                anchor: '100%',
                msgTarget: 'under'
            },
            {
                xtype: 'htmleditor',
                id: 'description',
                allowBlank: true,
                blankText: 'Every Layer must have a description.',
                fieldLabel: "Description",
                height: 10,
                maxLength: 500,
                anchor: '100%'
            }

        ]
    });
    
    TNRIS.UserLayerWindow.superclass.constructor.call(this, {
        title: 'New Layer',
        width: 600,
        height: 400,
        layout: 'form',
        modal: true,
        plain: true,
        stateful: false,
        items: this.form,
        buttonAlign: 'center',
        buttons: [
            {
                id: 'layer-window-ok',
                text: 'Save',
                scope: this,
                handler: this.createLayer
            },
            {
                id: 'layer-window-cancel',
                text: 'Cancel',
                scope: this,
                handler: function() {
                    this.close();
                }
            }
        ]
    });
};

Ext.extend(TNRIS.UserLayerWindow, Ext.Window, 
    /** @scope TNRIS.UserLayerWindow */
    {
    show: function() {
        TNRIS.UserLayerWindow.superclass.show.call(this);
        this.form.items.each(function(item) {
            item.setRawValue(this.layer.get(item.getId()));
        }, this);
    },
    
    createLayer: function() {
        var values = this.form.form.getValues(false);
        values.source_type = "xml";
        // save to server
        this.el.mask('Creating Layer...', 'x-mask-loading');
        this.form.items.each(function(item) {
            this.layer.set(item.getId(), item.getValue());
        }, this);
        this.layer.commit(function(status, message) {
            this.el.unmask();
            if (status == "success") {
                gemss.app.msg("Layer Saved", "Changes to the {0} layer were saved.", this.layer.name());
                this.close();
            } else {
                Ext.Msg.alert("Error", "There was a problem saving your changes.  " + message + "  Please try again.");
            }
        }.bind(this));
    }
});

TNRIS.NewLayerWindow = function(config) {
    Ext.apply(this, config, {
        mapPanel: Ext.getCmp('mapPanel')
    });
    
    this.layerTypeCombo = new Ext.form.ComboBox({
        id: 'layerTypeCombo',
        fieldLabel: "Type of Layer",
        mode: 'local',
        hiddenName: 'f',
        editable: false,
        forceSelection: true,
        width: 250,
        triggerAction: 'all',  // don't filter the list by the current selection - always display all available choices
        store: [['draw', 'Drawing'], ['kml', 'KML File'], ['csv', 'Comma Separated File (CSV)']],
        listeners: { 'select': {scope: this, fn: this.onLayerTypeChange}},
        value: 'draw'
    });

    this.form = new Ext.form.FormPanel({
            id: 'newLayerForm',
            fileUpload: true,
            url: 'upload/layerImport.aspx',
            items: [
                {
                    id: 'layerName',
                    xtype: 'textfield',
                    allowBlank: false,
                    name: 'layer_name',
                    fieldLabel: 'Layer Name',
                    width: 100
                },
                this.layerTypeCombo,
                new Ext.form.TextField({
                    allowBlank: false,
                    id: 'temp_upload',
                    inputType: 'file',
                    name: 'temp_upload',
                    fieldLabel: 'KML File',
                    width: 250,
                    blankText: "Please enter a publicly accessible URL to a kml file",
                    msgTarget: 'under'
                }),
                new Ext.form.TextField({
                    allowBlank: false,
                    id: 'kml_url',
                    name: 'kml_url',
                    fieldLabel: 'KML URL',
                    width: 250,
                    blankText: "Browse and selct the kml file to import"
                })
            ]
        });
    
    TNRIS.NewLayerWindow.superclass.constructor.call(this, {
        id: 'newLayerWindow',
        title: 'New Layer',
        layout: 'form',
        width: 400,
        height: 300,
        modal: true,
        closable: false,
        buttonAlign: 'center',
        items: this.form,
        buttons: [
            {
                id: 'layer-window-ok',
                text: 'Save',
                scope: this,
                handler: this.createLayer
            },
            {
                id: 'layer-window-cancel',
                text: 'Cancel',
                scope: this,
                handler: function() {
                    this.hide();
                }
            }
        ],
        listeners: { 'show': {scope: this, fn: function() { 
            this.form.form.reset();
            this.layerTypeCombo.setValue('draw');
            this.onLayerTypeChange(this.layerTypeCombo); }}}
    });
};

Ext.extend(TNRIS.NewLayerWindow, Ext.Window,
    /** @scope TNRIS.NewLayerWindow */
    {
    onLayerTypeChange: function(typeCombo, record, index) {
        switch(typeCombo.getValue()) {
            case 'draw':
                this.hideField('temp_upload');
                this.hideField('kml_url');
                break;
            case 'kml':
                this.hideField('temp_upload');
                this.showField('kml_url');
                break;
            case 'csv':
                this.showField('temp_upload');
                this.hideField('kml_url');
                break;
            default: break;
        }
    },
    
    hideField: function(id) {
        var c = this.findById(id);
        c.disable();
        c.hide();
        c.getEl().up('.x-form-item').setDisplayed(false); // hide label
    },
    
    showField: function(id) {
        var c = this.findById(id);
        c.show();
        c.enable();
        c.getEl().up('.x-form-item').setDisplayed(true); // show label
    },
    
    createLayer: function() {
        var layer;
        switch(this.layerTypeCombo.getValue()) {
            case 'draw':
                this.hide();
                layer = TNRIS.LayerFactory.createLayer({source_type: 'xml'});
                this.mapPanel.addLayer(layer);
                break;
            case 'kml':
                if (this.form.form.isValid()) {
                    this.hide();
                    var url = this.findById('kml_url').getValue();
                    layer = TNRIS.LayerFactory.createLayer({source_type: 'kml', source_url: url});
                    this.mapPanel.addLayer(layer);
                }
                break;
            case 'csv':
                this.form.form.submit({
                    success: this.onSuccess,
                    failure: this.onFailure,
                    scope: this
                });
                this.hide();
                break;
            default: break;
        }
    },
    
    onSuccess: function(form, action) {
        var layer = TNRIS.LayerFactory.createLayer({source_type: 'xml', name: form.findField('layer_name').getValue(), columnConfigs: action.result.columnConfigs});
        this.mapPanel.addLayer(layer);
        layer.loadShapeData(action.result.shapeData);
        gemss.app.msg('Import Completed', '{0} shapes were successfully imported to the {1} layer', layer.getShapeStore().getCount(), layer.name());
    },
    
    onFailure: function(form, action) {
        var o = action;
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
