﻿/** @class TNRIS.AreaOfInterest
@augments Ext.Window
@param {object} config
@config {VELatLong} point - position around which to place the window
*/
TNRIS.AreaOfInterest = function(config) {
    Ext.apply(this,config);
    
    Ext.applyIf(this,
        {
        width: 225,
        height: 250,
        pushpin: '<div class="aoiPushpin"><img src="images/pushPins/info_pin.png" /></div>'
    });
    
    TNRIS.AreaOfInterest.superclass.constructor.call(this, {
        draggable: false,        
        closeAction: 'close',
        layout: 'fit',
        listeners: {
            'close': {scope: this, fn: this.onClose},
            'render': {scope: this, fn: function() {
                if (null == this.point)
                {
                    return;
                }
                var anchorPos = this.mapPanel.getMap().LatLongToPixel(this.point);
                this.position([Math.floor(anchorPos.x), Math.floor(anchorPos.y)]);
            }}
        },
        tools: [
            { 
                id: 'minimize',
                handler: this.onMinimize,
                scope: this
            }
        ]
    });

    this.addClass('areaOfInterestWindow');
    this.mapPanel.on('view-change', this.onMapPan, this);
};

Ext.extend(TNRIS.AreaOfInterest, Ext.Window, 
    /** @scope TNRIS.AreaOfInterest */
    {
    load: function(searchPoint) {
        this.point = searchPoint;
        this.shape = new VEShape(VEShapeType.Pushpin, searchPoint);
        this.mapPanel.getMap().AddShape(this.shape);
        this.shape.SetCustomIcon(this.pushpin);
        this.mapPanel.on('beforemapclick', function(mapEvent, shapeAnchorId) {
            var shape = this.mapPanel.getMap().GetShapeByID(shapeAnchorId);
            if (shape == null || shape.GetID() != this.shape.GetID()) {
                return true;
            }
            if (!this.isVisible()) {
                var anchorPos = this.mapPanel.getMap().LatLongToPixel(this.point);
                this.position([Math.floor(anchorPos.x), Math.floor(anchorPos.y)]);
                this.show();
            }
            return false;
        }, this);
    },
        
    /** 
    positions the informationBubble around an anchor position
    @param {Array} anchorPos [containerX, containerY]
    */
    position: function(anchorPos) {
        var buffer = 1; // pixes away from anchor point for window
        var containerSize = this.mapPanel.body.getSize();
        var winSize = {width: this.width, height: this.height};
        var left, top;
        if (anchorPos[0] < (containerSize.width / 2)) {
            left = anchorPos[0] + buffer;
        } else {
            left = anchorPos[0] - winSize.width - buffer;
        }
        
        if (anchorPos[1] < (containerSize.height / 2)) {
            top = anchorPos[1];
        } else {
            top = anchorPos[1] - winSize.height;
        }
        this.setPosition(left, top);
    },
    
    onMapPan: function() {
        var anchorPos = this.mapPanel.getMap().LatLongToPixel(this.point);
        this.position([Math.floor(anchorPos.x), Math.floor(anchorPos.y)]);
    },
    
    onMinimize: function() {
        this.hide();
    },
    
    onClose: function() {
        this.mapPanel.getMap().DeleteShape(this.shape);
    }
});

TNRIS.AddressLocation = function(config) {
    Ext.apply(this,config);
    
    this.placeStore = new Ext.data.SimpleStore({
        fields: [{name: 'LatLong', mapping: 'LatLong'},
        {name: 'LatLongRect', mapping: 'LatLongRect'},
        {name: 'Locations', mapping: 'Locations'},
        {name: 'MatchCode', mapping: 'MatchCode'},
        {name: 'MatchConfidence', mapping: 'MatchConfidence'},
        {name: 'Name', mapping: 'Name'},
        {name: 'Precision', mapping: 'Precision'},
        {name: 'Score', mapping: 'Score'}]
    });
    
    this.placeStore.loadData(this.places);
    
    TNRIS.AddressLocation.superclass.constructor.call(this, {
        //cls: 'addressLocationWindow',
        title: 'Nearest Address',
        items: new Ext.DataView({
            store: this.placeStore,
            tpl: this.placesTemplate,
            overClass: 'x-view-over',
            emptyText: "No Places Found",
            itemSelector: 'div.place'
        })
    });
};

Ext.extend(TNRIS.AddressLocation, TNRIS.AreaOfInterest, 
    /** @scope TNRIS.AddressLocation */
    {
    placesTemplate: new Ext.XTemplate(
        '<tpl for=".">',
        '<div class="place">{Name}</div>',
        '</tpl>')
});

/** @class TNRIS.PointSearchWindow
@augments Ext.Window
*/
TNRIS.PointSearchWindow = function(config) {
    Ext.apply(this, config);
    
    Ext.applyIf(this,
        {
        shim: false,
        shapeLineColor: new VEColor(0,150,150,0.6),
        shapeFillColor: new VEColor(0,150,150,0.6),
        shapeIcon: '<div class="globePushpin"><img src="images/pushPins/greenGlobePin.png"></div>',
        shapeHighlightLineColor: new VEColor(0,255,0,0.6),
        shapeHighlightFillColor: new VEColor(0,255,0,0.6),
        shapeHighlightIcon: '<div class="globePushpin"><img src="images/pushPins/ochreGlobePin.png"></div>',
        shapeWidth: 2,
        resizable: false
        });
        
    TNRIS.PointSearchWindow.superclass.constructor.call(this, {
        //cls: 'pointSearchWindow',
		title: 'Feature Info',
        items: {
            xtype: 'tabpanel',
            layoutOnTabChange: true,
			enableTabScroll: true
        }
    });
    
    this.on('hide', function() {this.tabPanel.items.each(function(panel) { this.deactivatePanel(panel); }, this);}, this);
    this.on('show', function() { this.activatePanel(this.tabPanel.getActiveTab());}, this);
    this.tabPanel = this.items.get(0);
    
    this.mapPanel.on('map-change', this.onLayerRemoval, this);
};

Ext.extend(TNRIS.PointSearchWindow, TNRIS.AreaOfInterest, 
    /** @scope TNRIS.PointSearchWindow */
    {
    tabTemplate: new Ext.XTemplate(
        '<tpl for=".">',
        '   <div class="nameValuePair"><span class="fieldName">{fieldName}</span>:<span class="fieldValue">{fieldValue}</span></div>',
        '</tpl>'),
    
    load: function(searchPoint, dataArray) {
        TNRIS.PointSearchWindow.superclass.load.call(this, searchPoint);
        
        dataArray.each(function(data) {
            var layerId, featureType, featureArray, featureId, displayFields = [];
            data.each(function(item, index) {
                switch(item.fieldName) {
                    case 'shapeType':
                        featureType = item.fieldValue;
                        break;
                    case 'shapePoints':
                        featureArray = item.fieldValue;
                        break;
                    case 'layerId':
                        layerId = item.fieldValue;
                        break;
                    case 'id':
                        featureId = item.fieldValue;
                        break;
                    default:
                        displayFields.push({'fieldName': item.fieldName, 'fieldValue': item.fieldValue});
                        break;
                }
            });
            var layer = this.mapPanel.getLayerById(layerId);
            var shape = (new TNRIS.ShapeLayer()).veShapeFromPoints(featureType, featureArray);
            this.mapPanel.getMap().AddShape(shape);
            shape.SetLineColor(this.shapeLineColor);
            shape.SetFillColor(this.shapeFillColor);
            if (shape.GetType() != VEShapeType.Pushpin) {
                shape.HideIcon();
            } else {
                shape.SetCustomIcon(this.shapeIcon);
            }
            this.tabPanel.add({
                xtype: 'panel',
                html: this.tabTemplate.applyTemplate(displayFields),
                title: layer.name(),
                autoScroll: true,
                shape: shape,
                layer: layer,
                isLayerInformation: true,
                listeners: {
                    'activate': {scope: this, fn: this.activatePanel},
                    'deactivate': {scope: this, fn: this.deactivatePanel}
                }
            });
            this.tabPanel.doLayout();
        }.bind(this));
        this.tabPanel.activate(0);
    },
    
    activatePanel: function(panel) {
        panel.shape.SetLineColor(this.shapeHighlightLineColor);
        panel.shape.SetFillColor(this.shapeHighlightFillColor);
        if (panel.shape.GetType() != VEShapeType.Pushpin) {
            panel.shape.HideIcon();
        } else {
            panel.shape.SetCustomIcon(this.shapeHighlightIcon);
        }
    },
    
    deactivatePanel: function(panel) {
        panel.shape.SetLineColor(this.shapeLineColor);
        panel.shape.SetFillColor(this.shapeFillColor);
        if (panel.shape.GetType() != VEShapeType.Pushpin) {
            panel.shape.HideIcon();
        } else {
            panel.shape.SetCustomIcon(this.shapeIcon);
        }
    },
    
    onClose: function() {
        TNRIS.PointSearchWindow.superclass.onClose.call(this);
        
        var map = this.mapPanel.getMap();
        this.find('isLayerInformation', true).each(function(panel) {
            map.DeleteShape(panel.shape);
        }, this);
    },
    
    /** callback for TNRIS.MapPanel map-change event
    @param {Hashtable} args 'remove' key references any layers being removed
    */
    onLayerRemoval: function(args) {
        var layer = args.remove;
        if (null != layer) {
            var panelToRemove = null;
            this.find('isLayerInformation', true).each(function(panel) {
                if (panel.layer == layer) {
                    panelToRemove = panel;
                }
            }, this);
            if (null != panelToRemove) {
                this.mapPanel.getMap().DeleteShape(panelToRemove.shape);
                this.tabPanel.remove(panelToRemove);
                if (this.tabPanel.items.getCount() == 0) {
                    this.onClose();
                    this.close();
                }
                this.tabPanel.doLayout();
            }
        }
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
