﻿TNRIS.JSONLayer = function(config) {
    
    Ext.applyIf(this, {
        shapeLineColor: new VEColor(0,150,150,0.6),
        shapeFillColor: new VEColor(0,150,150,0.6),
        shapeIcon: '<div class="hurrtraxPushpin"><img src="images/pushpins/json.png" /></div>'
    });
    TNRIS.JSONLayer.superclass.constructor.call(this, config );
};

Ext.extend(TNRIS.JSONLayer, TNRIS.ShapeLayer, {
    
    load: function(map) {
        var store = this.getShapeStore();
        store.load({params: this.getStoreParams(map)});
    },
    
    createShapeStore: function(context) {
        this.jsonRoot = this.config.jsonRoot;
        var shapeRecord = new Ext.data.Record.create(this.getJsonRecord());
        var shapeReader = new Ext.data.JsonReader({root: this.jsonRoot},shapeRecord);
        var shapeProxy = new Ext.data.ScriptTagProxy({url: this.getBaseUrl()});
        
        var store = new Ext.data.Store({
            proxy: shapeProxy,
            reader: shapeReader,
            baseParams: this.getBaseParams(),
            autoLoad: false });
        this.stores.add(context, store);
        return store;
    },
    
    getJsonRecord: function() {
        var columns = this.columnConfigs();
        var jsonRecord = [];
        for (var i=0 ; i < columns.length; i++) {
            jsonRecord.push(columns[i].dbName);
        }
        return jsonRecord;
    },
    
    getGridStore: function() {
        return this.getShapeStore(); // both grid and map will have same data
    },
    
    loadGridData: function() {
        var store = this.getGridStore();
        this.fireEvent('loadGrid', store, [], {});
    },
    
    createNewVeShape: function(record) {
        //HACK: the record schema is not same for all layers
        var latLong = [new VELatLong(record.get('lat'),record.get('lng'))];
        return this.veShapeFromPoints('point',latLong);
    },
    
    getBaseUrl: function() {
        return (this.config.virtual_earth_url.split('?')[0]);
    },
    
    getStoreParams: function(map) {
        var maxRows = (null != this.config.jsonMaxRecords)? this.config.jsonMaxRecords : 50;
        var url = this.jsonServiceUrl(maxRows,map);
        var params = url.split('?')[1].split('&');
        
        var result = {};
        for (var i=0; i<params.length; i++) {
            var qsName = params[i].split('=')[0];
            var qsValue = params[i].split('=')[1];
            eval('result.' + qsName + '=' + qsValue);
        }
        return result;
    },

    jsonServiceUrl: function(maxRows,map) {
        if (null == this.config.virtual_earth_url) {
            throw "URL not found - Please contact administrator";
        }
        if (null == maxRows) { maxRows = 1; }
        
        var nwLatitude = 37.06; 
        var nwLongitude = -89.63;
        var seLatitude= 31.99;
        var seLongitude = -78.70;

        if (null !=map) {
            var mapView = map.GetMapView();
            nwLatitude = mapView.TopLeftLatLong.Latitude;
            nwLongitude = mapView.TopLeftLatLong.Longitude;
            seLatitude= mapView.BottomRightLatLong.Latitude;
            seLongitude = mapView.BottomRightLatLong.Longitude;
        }
        
        var vUrl = this.config.virtual_earth_url;
        vUrl = vUrl.replace('{nw_lat}',nwLatitude);
        vUrl = vUrl.replace('{nw_long}',nwLongitude);
        vUrl = vUrl.replace('{se_lat}',seLatitude);
        vUrl = vUrl.replace('{se_long}',seLongitude);
        vUrl = vUrl.replace('{max_rows}',maxRows);
        return vUrl;
    },
    
    fetchJsonSchema: function(callbackFn) {
        this.callbackFn = callbackFn;
        var serviceUrl = this.jsonServiceUrl();
        
        /*Ajax class is over ridden to enable cross domain scripting.
        It has a special property named scriptTag. Please see the custom script on extjs-extension.js file*/
        Ext.Ajax.request({
            url: serviceUrl,
            scriptTag: true,
            scope: this,
            success: function(response) {
                var responseItem = response.responseObject;                          
                var jsonRoot;
                var result= [];
                for (var obj in responseItem) { //find json root and its properties
                    jsonRoot = obj;
                    var jsonData = eval("responseItem." + jsonRoot)[0];
                    var hash = $H(jsonData);
                    var keys = hash.keys();
                    for(var i=0; i<keys.length; i++) {
                        result.push({"dbName":keys[i],"guiName":keys[i],"dbType": "Unknown","order":i,"isId": false,"isName":false,"isHidden":false,"isGeometry":false});
                    }
                    break;
                }
                this.callbackFn(jsonRoot,result);
            },
            failure: function(response) {
                this.callbackFn(null);
                throw "Unable to retrieve schema";
            }
        });
    },
    
    smartable: function(value) {
        return false;
    },
    
    isRefreshable: function() {
        return true;
    },
    
    
    refreshLayer: function() {
        if (null != this.map()) {
            this.load(this.map());
        }
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
