﻿/** @class TNRIS.WMSLayer
*/
TNRIS.WMSLayer = function(config) {
    TNRIS.WMSLayer.superclass.constructor.call(this, config);
    this.timer = new Ext.util.DelayedTask(
        function(){
            this.refresh();
            this.fireEvent('layer-refresh', {"time":this.timestamp});
            this.timer.cancel();
            this.timer.delay(this.config.refreshInterval * 60000);
        }
    ,this);
    
};

Ext.extend(TNRIS.WMSLayer, TNRIS.TileLayer, 
/** @scope TNRIS.WMSLayer */
{
    virtualEarthUrl: function(value) {
        this.timestamp = Ext.util.Format.date(new Date(), 'm/d/y H:i:s');
        var original = TNRIS.WMSLayer.superclass.virtualEarthUrl.call(this, value);
        var modified = this.appendToQueryString(original,"dt",this.timestamp);
        modified = this.appendToQueryString(modified,"type","wms");
        modified = this.appendToQueryString(modified,"refInt",this.config.refreshInterval);
        return modified;
    },
    
    refreshTimer: function(action) {
        if (action == "start") {
            if (this.config.refreshInterval != 0) 
            {
                this.fireEvent('layer-refresh', {"time":this.timestamp});
                this.timer.delay((this.config.refreshInterval * 60000));
            }
        }
        else if (action == "refresh") {
            this.timer.delay(10);
        }
    },
    
    refreshLayer: function(){
        this.refreshTimer("refresh");
    },
    
    clearTimer: function() {
        if (this.timer) {
            this.timer.cancel();
        }
    },
    
    addToMap: function(id, map, index, mapPanel) {
        TNRIS.WMSLayer.superclass.addToMap.call(this, id, map, index, mapPanel);
        this.refreshTimer("start");
    },
    
    removeFromMap: function() {
        this.clearTimer();
        TNRIS.WMSLayer.superclass.removeFromMap.call(this);
    },

   /** refresh the layer with url with latest time stamp without reloading the map */
   refresh: function() {
        this.map().DeleteTileLayer(this.mapId());
        var bounds = [this.footprintAsLongRectangle()];
        this.tileSource(this.addOverlay(this.mapId(), this.virtualEarthUrl(), 
         bounds, this.get('minZoomLevel'), this.get('maxZoomLevel'), 
        1, this.opacity(), this.index(), this.visible()));
    },
    
    /** to display refresh button on the layer legend */
    isRefreshable: function() {
        return true;
    },
    
    /** construct query string in valid format */
    appendToQueryString: function(link,name,value) {    
        url = link.split('?');
        if (null != url[1]) {
            link = link + "&"+name+"=" + value;
        }
        else{
            link = link + "?"+name+"=" + value;
        }
        return link;
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
