// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.6/standard_upgrade_03/wwwroot/js/standard/dynamiclayer.js $ 
// $Date: 6-01-12 14:00 $
// $Revision: 35 $ 
// $Author: Kpo $
// =============================================================== 

DynamicLayers = SpatialMap.Class({
    
    layers: [],
    
    initialize: function () {
    },
    
    add: function (dynamicLayer) {
        this.layers.push (dynamicLayer);
    },
    
    setOptions: function (options) {
        this.get(options.name).setOptions (options);
    },
    
    get: function (name) {
        for (var i=0;i<this.layers.length;i++) {
            if (this.layers[i].name==name) {
                return this.layers[i];
            }
        }
        this.layers.push (new DynamicLayer (name));
        return this.layers[this.layers.length-1];
    },
    
    addWKT: function (options) {
        /**
         * options = {
         *     name:'userdatasource',
         *     wkt: 'POINT(11 22).
         *     style: {},
         *     params: {}, //a optional property list of attributes to add to the objekt on the server
         *     clear: false
         * }
         */
        if (!options.name) {
            options.name = 'userdatasource';
        }
        cbKort.log ('DynamicLayers.addWKT - ',options);
        this.get(options.name).draw (options);
    },
    
    addFromDatasource: function (options) {
        /**
         * options = {
         *     name: 'userdatasource',
         *     datasource: '',
         *     command: 'read',
         *     style: {},
         *     params: {}, //a optional property list of attributes to add to the objekt on the server
         *     clear: false
         * }
         */
        if (!options.name) {
            options.name = 'userdatasource';
        }
        cbKort.log ('DynamicLayers.addFromDatasource - ',options);
        this.get(options.name).drawFromDatasource (options);
    },
    
    show: function (name) {
        this.get(name).updateMap ();
    },
    
    remove: function (name) {
        for (var i=0;i<this.layers.length;i++) {
            if (this.layers[i].name==name) {
                this.layers[i].remove ();
                break;
            }
        }
    },
    
    removeAll: function () {
        for (var i=0;i<this.layers.length;i++) {
            this.layers[i].remove ();
        }
    },

    destroy: function (name) {
        for (var i=0;i<this.layers.length;i++) {
            if (this.layers[i].name==name) {
                this.layers[i].destroy();
                break;
            }
        }
    },
    
    zoomTo: function (name,buffer) {
        this.get (name).zoomTo (buffer);
    },
    
    setDefaultStyle: function (name,style) {
        this.get (name).setDefaultStyle (style);
    },
    
    showEditDialog: function (name) {
        this.get (name).showDialog ();
    },
    
    /**
     * Activate the control that can draw a LINE in the map
     *      and measure a distance
     * 
     * Parameters:
     * name - {String} The name of the dynamiclayer
     * options - {Object} Containing: handler: {Function}, displayname: {String}
     */
    registerEditHandler: function (name,options) {
        this.get (name).registerEditHandler (options);
    },
    
    CLASS_NAME: 'DynamicLayers'
});


DynamicLayer = SpatialMap.Class({
    name: null,
    render: 'client', //'server' or 'client'
    layers: {
        point: 'userpoint',
        linestring: 'userline',
        polygon: 'userpolygon'
    },
    mapReady: false,
    layerDefaults: {
        singleTile: false
    },
    
    dialog: null,
    toolmode: null,
    handlers: [],
    activeMode: '',
    snap: true,
    selectedFeature: null,
    radius: 100,
    
    style: {
        fillColor: "#FF0000",
        fillOpacity: 0.5,
        pointRadius: 6,
        strokeColor: "#FF0000",
        strokeOpacity: 0.5,
        strokeWidth: 3
    },
    
    attributesDefault: {
    	note: '',
    	label: '',
    	fillcolor: null,
    	strokecolor: null
    },
    
    features: null, //List of feature id's and wkt: {id:'OpenLayers.Feature.Vector_1814',wkt:'POINT(111 222)',style:{}}
    
    initialize: function (name) {
        this.name = name;
        this.features = [];
    },
    
    setOptions: function (options) {
        SpatialMap.Util.extend (this, options);
    },
    
    draw: function (options) {
    	cbKort.log('DynamicLayer.draw () - ',this,options);
        if (options.clear) {
            this.deleteFeatures ();
        }
        if (!options.attributes) {
        	options.attributes = {};
        }
        options.attributes = SpatialMap.Util.applyDefaults (options.attributes,this.attributesDefault);
        var style = this.clone (this.style);
        if (options.style) {
            SpatialMap.Util.extend (style, options.style);
        }
        
        if (this.render == 'client') {
            var drawoptions = {styles: style};
            cbKort.mapObj.drawWKT (options.wkt.toString(),SpatialMap.Function.bind (function (style,options,event) {
                var feature = {id:event.id,wkt:event.wkt,style:style,params:options.params,attributes:options.attributes};
            	this.features.push (feature);
                this.addWKTToServer (feature);
            },this,style,options),drawoptions);
        } else {
            var feature = {id:null,wkt:options.wkt,style:style,params:options.params,attributes:options.attributes};
	        this.features.push (feature);
	        this.addWKTToServer (feature);
	        this.updateMap ();
        }
    },
    
    drawFromDatasource: function (options) {
        if (options.clear) {
            this.deleteFeatures ();
        }
        if (!options.attributes) {
        	options.attributes = {};
        }
        options.attributes = SpatialMap.Util.applyDefaults (options.attributes,this.attributesDefault);
        var style = this.clone (this.style);
        if (options.style) {
            SpatialMap.Util.extend (style, options.style);
        }
        
        var params = {
            page: 'dynamiclayer-read-datasource',
            datasource: options.datasource,
            command: options.command || 'read'
        };
        SpatialMap.Util.extend (params, options.params);
        var url = cbKort.getUrl (params);
        var wkt = [];
        var cbHttp  = new CBhttp();
        // call server to get wkt
        var pComp = cbHttp.executeUrl(url, false);
        if (pComp!=null && pComp.isPComposite()) {
            var rowList = pComp.get(0);
            var featurewkt = null;
            for (var i=0;i<rowList.size();i++) {
                var row = rowList.row(i);
                if (row!=null) {  
                    var tmpwkt = row.column('shape_wkt').getValue();
                    if (tmpwkt) {
                        wkt.push (tmpwkt)
                    }
                }
            }
        }
        
        if (wkt.length) {
            for (var i=0;i<wkt.length;i++) {
                if (this.render == 'client') {
                    var drawoptions = {styles: style};
                    cbKort.mapObj.drawWKT (wkt[i],SpatialMap.Function.bind (function (style,options,event) {
                        var feature = {id:event.id,wkt:event.wkt,style:style,params:options.params,attributes:options.attributes};
                    	this.features.push (feature);
                        this.addWKTToServer (feature);
                    },this,style,options),drawoptions);
                } else {
                    var feature = {id:null,wkt:wkt[i],style:style,params:options.params,attributes:options.attributes};
                	this.features.push (feature);
                    this.addWKTToServer (feature);
                }
            }
            this.updateMap ();
        }
    },
    
    
    addWKTToServer: function (feature) {
        //Add wkt to server
        var type = feature.wkt.toString().split('(')[0].replace(/ /g,'').toLowerCase().replace(/multi/,'');
        
        if (!feature.attributes) {
        	feature.attributes = this.clone(this.attributesDefault);
        }
        feature.attributes.fillcolor = new Color (feature.style.fillColor).rgb;
        feature.attributes.strokecolor = new Color (feature.style.strokeColor).rgb;
        
        var params = {
            dynamiclayer: this.layers[type],
            dynamicdatasource: this.name,
            geometrycolumn: "shape_wkt",
            shape_wkt: feature.wkt,
            columnnames: this.getColumnNames (feature.attributes),
            page: 'dynamiclayer-write'
        };
        
        SpatialMap.Util.extend (params, feature.attributes);
        var url = cbKort.getUrl (params);
        var request = new CBhttp ();
        request.executeUrl(url);
        this.activateHandlerButtons (true);
        cbKort.events.fireEvent ('DYNAMICLAYER_FEATURE_ADDED',this,feature); 
    },
    
    getColumnNames: function (attributes) {
    	var s = [];
    	for (var name in attributes) {
    		s.push (name);
    	}
    	return s.join (',');
    },
    
    updateMap: function (hide) {
        if (this.render == 'server') {
            if (!this.mapReady) {
                var host = cbKort.host;
                if (typeof host == 'string') {
                    host = [host];
                }
                var layers = this.getLayerList (',');
                for (var i=0;i<host.length;i++) {
                    host[i] = host[i]+(host[i].indexOf('?')+1 ? '&' : '?')+'useddynamiclayers='+layers;
                }
                this.mapReady = true;
                var layer = {
                    id: this.name,
                    host: host,
                    layername: layers,
                    basemap: false,
                    visible: false
                };
                SpatialMap.Util.extend (layer, this.layerDefaults);
                cbKort.log ('DynamicLayer.updateMap () - ',layer);
                cbKort.addAdditionalLayer (layer);
            }
            if (!hide) {
                cbKort.setAdditionalLayerVisibility (this.name,true,true);
            } else {
                cbKort.setAdditionalLayerVisibility (this.name,false);
            }
        }
    },
    
    getLayerList: function (seperator) {
        var layers = '';
        var count = 0;
        for (var name in this.layers) {
            layers += (count ? seperator : '')+this.layers[name];
            count++;
        }
        return layers;
    },
    
    zoomTo: function (buffer) {
        if (this.render == 'client' && this.features.length > 0) {
            var list = [];
            for (var i=0;i<this.features.length;i++) {
                list.push (this.features[i].id);
            }
            cbKort.mapObj.zoomToFeature (list,buffer);
        } else if (this.render == 'server') {
            var layers = this.getLayerList (',');
            var params = {
                page: 'dynamiclayer-status',
                dynamiclayer: layers
            };
            var url = cbKort.getUrl (params);
            var request = new CBhttp ();
            var pcol = request.executeUrl(url);
            if (pcol!=null) {
                var rowlist = pcol.get(0);
                if (rowlist!=null) {
                    var resp = [];
                    for (var i=0;i<rowlist.size ();i++) {
                        var row = rowlist.row(i);
                        var options = {
                            name: row.column("name").getValue(),
                            rowcount: row.column("rowcount").getValue(),
                            xmin: row.column("xmin").getValue(),
                            ymin: row.column("ymin").getValue(),
                            xmax: row.column("xmax").getValue(),
                            ymax: row.column("ymax").getValue()
                        };
                        resp.push (options);
                    }
                    if (resp.length) {
                        var extent = {x1:null,y1:null,x2:null,y2:null};
                        for (var i=0;i<resp.length;i++) {
                            if (!extent.x1 || resp[i].xmin < extent.x1) {
                                extent.x1 = resp[i].xmin;
                            }
                            if (!extent.y1 || resp[i].ymin < extent.y1) {
                                extent.y1 = resp[i].ymin;
                            }
                            if (!extent.x2 || resp[i].xmax > extent.x2) {
                                extent.x2 = resp[i].xmax;
                            }
                            if (!extent.y2 || resp[i].ymax > extent.y2) {
                                extent.y2 = resp[i].ymax;
                            }
                        }
                        buffer = buffer || 0;
                        extent = {
                            x1: extent.x1-buffer,
                            y1: extent.y1-buffer,
                            x2: extent.x2+buffer,
                            y2: extent.y2+buffer
                        }
                        cbKort.mapObj.zoomToExtent (extent);
                    }
                }
            }
        }
    },
    
    /**
     * APIMethod: deleteFeatures
     */
    deleteFeatures: function () {
        this.activateHandlerButtons (false);
        var call = false;
        var list = [];
        for (var i=0;i<this.features.length;i++) {
            list.push (this.features[i].id);
        }
        if (list.length) {
            call = true;
            cbKort.mapObj.deleteFeature (list);
        }
        this.features = [];
        this.selectedFeature = null;
        
        if (call) {
            this.update ();
        }
    },
    
    remove: function () {
        this.deleteFeatures ();
        if (this.render == 'server') {
            this.updateMap (true);
        }
    },
    
    destroy: function () {
        if (this.dialog) {
            this.closeDialog ();
        }
        this.deleteFeatures ();
    },
    
    update: function () {
        //Call server to remove all feature
    	var layers = [];
    	for (var name in this.layers) {
    		layers.push (this.layers[name]);
    	}
    	
        var params = {
            dynamiclayer: layers.join (','),
            dynamicdatasource: this.name,
            page: 'dynamiclayer-delete'
        };
        var url = cbKort.getUrl (params);
        var request = new CBhttp ();
        var pcol = request.executeUrl(url);
        
        this.save ();
    },
    
    save: function () {
        if (this.features.length > 0) {
            this.activateHandlerButtons (true);
            for (var i=0;i<this.features.length;i++) {
                this.addWKTToServer (this.features [i]);
            }
            this.updateMap ();
        } else {
            this.activateHandlerButtons (false);
            this.updateMap (true); //Hide
        }
    },
    
    setDefaultStyle: function (style) {
        this.style = this.clone (style);
    },
    
    showDialog: function () {
        if (this.dialog == null) {
            this.createDialog ();
        }
        if (this.toolmode == null) {
            this.toolmode = cbKort.registerToolMode(null, null, null, null, true, SpatialMap.Function.bind(this.setMode, this, ''));
        }
        this.dialog.showDialog ();
        if (this.activeMode != '') {
            this.setMode (this.activeMode);
        }
    },
    
    closeDialog: function () {
        this.dialog.closeDialog ();
        this.closeHandler ();
    },
    
    createDialog: function () {
        this.dialog = new Dialog(cbInfo.getString('workinglayer.dialog.title'),SpatialMap.Function.bind(this.closeHandler, this));
        var html =    '<table class="divtable" style="width:100%;">' +
                      '  <tr align="left">' +
                      '    <td class="heading3td"><span id="dynamiclayer_'+this.name+'_header">' + cbInfo.getString('standard.tool.drawing.header') + '</span></td>' +
                      '  </tr>' +
                      '  <tr align="left">' +
                      '    <td>' +
                      '      <div class="drawFeature">' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_polygon" class="drawFeaturePolygonInactive" title="' + cbInfo.getString('standard.tool.drawing.drawpolygon') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_line" class="drawFeatureLineInactive" title="' + cbInfo.getString('standard.tool.drawing.drawline') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_point" class="drawFeaturePointInactive" title="' + cbInfo.getString('standard.tool.drawing.drawpoint') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_circle" class="drawFeatureCircleInactive" title="' + cbInfo.getString('standard.tool.drawing.drawcircle') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_circleradius" class="drawFeatureCircleradiusInactive" title="' + cbInfo.getString('standard.tool.drawing.drawcircleradius') + '"></div>' +
                      '      </div>' +
                      '    </td>' +
                      '  </tr>' +
                      '  <tr align="left">' +
                      '    <td>' +
                      '      <div class="drawFeature">';
        if (this.render == 'client') {
            html +=   '        <div id="dynamiclayer_'+this.name+'_mode_move" class="featureMoveInactive" title="' + cbInfo.getString('standard.tool.drawing.moverotate') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_modify" class="featureModifyInactive" title="' + cbInfo.getString('standard.tool.drawing.modify') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_delete" class="featureDeleteInactive" title="' + cbInfo.getString('standard.tool.drawing.delete') + '"></div>';
        }
        html +=       '        <div id="dynamiclayer_'+this.name+'_mode_select" class="featureSelectInactive" title="' + cbInfo.getString('standard.tool.drawing.select') + '"></div>' +
                      '        <div id="dynamiclayer_'+this.name+'_mode_selectrectangle" class="drawFeatureRegularPolygonInactive" title="' + cbInfo.getString('standard.tool.drawing.selectrectangle') + '"></div>' +
                      '      </div>' +
                      '    </td>' +
                      '  </tr>' +
                      '  <tr align="left">' +
                      '    <td>' +
                      '      <input id="dynamiclayer_'+this.name+'_usesnap" checked="checked" type="checkbox"/>' + cbInfo.getString('standard.tool.drawing.usesnap') + 
                      '    </td>' +
                      '  </tr>' +
                      '  <tr align="left">' +
                      '    <td>' +
                      '        <button class="menubutton" id="dynamiclayer_'+this.name+'_delete_all">' + cbInfo.getString('standard.tool.drawing.deleteall') + '</button>' +
                      '    </td>' +
                      '  </tr>' +
                      '  <tr align="left">' +
                      '    <td>' +
                      '      <span style="display:none;" id="dynamiclayer_'+this.name+'_datasource">' + cbInfo.getString('standard.tool.drawing.datasource') + ':<br/>' +
                      '        <input id="dynamiclayer_'+this.name+'_datasource_select" style="width:100%"></input>' +
                      '      </span>' +
                      '      <span style="display:none;" id="dynamiclayer_'+this.name+'_radius">' +
                      '        Radius: <input id="dynamiclayer_'+this.name+'_radius_input" value="'+this.radius+'"/>' +
                      '      </span>' +
                      '    </td>' +
                      '  </tr>';
        if (this.handlers.length) {
            html +=   '  <tr>' +
                      '    <td>' + cbInfo.getString('standard.tool.drawing.functions') + ':<br/>';
            for (var i=0;i<this.handlers.length;i++) {
                html += '        <button class="menubutton dynamiclayer_buttons" style="width:100%;" id="dynamiclayer_'+this.name+'_handlers_'+i+'">'+this.handlers[i].displayname+'</button>';
            }
            html +=   '    </td>' +
                      '  </tr>';
        }
        html +=       '</table>';
        this.dialog.addContentHTML(html);

        $('dynamiclayer_'+this.name+'_mode_polygon').onclick = SpatialMap.Function.bind(this.setMode, this, 'polygon');
        $('dynamiclayer_'+this.name+'_mode_line').onclick = SpatialMap.Function.bind(this.setMode, this, 'line');
        $('dynamiclayer_'+this.name+'_mode_point').onclick = SpatialMap.Function.bind(this.setMode, this, 'point');
        $('dynamiclayer_'+this.name+'_mode_circle').onclick = SpatialMap.Function.bind(this.setMode, this, 'circle');
        $('dynamiclayer_'+this.name+'_mode_circleradius').onclick = SpatialMap.Function.bind(this.setMode, this, 'circleradius');
        if (this.render == 'client') {
            $('dynamiclayer_'+this.name+'_mode_move').onclick = SpatialMap.Function.bind(this.setMode, this, 'move');
            $('dynamiclayer_'+this.name+'_mode_modify').onclick = SpatialMap.Function.bind(this.setMode, this, 'modify');
            $('dynamiclayer_'+this.name+'_mode_delete').onclick = SpatialMap.Function.bind(this.setMode, this, 'delete');
        }
        $('dynamiclayer_'+this.name+'_mode_select').onclick = SpatialMap.Function.bind(this.setMode, this, 'select');
        $('dynamiclayer_'+this.name+'_mode_selectrectangle').onclick = SpatialMap.Function.bind(this.setMode, this, 'selectrectangle');

        $('dynamiclayer_'+this.name+'_usesnap').onclick = SpatialMap.Function.bind(this.useSnap, this);
        $('dynamiclayer_'+this.name+'_usesnap').checked = this.snap;

        $('dynamiclayer_'+this.name+'_delete_all').onclick = SpatialMap.Function.bind(this.remove, this);

        $('dynamiclayer_'+this.name+'_radius_input').onkeyup = SpatialMap.Function.bind(this.setRadius, this);
        
        for (var i=0;i<this.handlers.length;i++) {
            $('dynamiclayer_'+this.name+'_handlers_'+i).onclick = SpatialMap.Function.bind(this.callHandlers, this, i);
        }
        this.activateHandlerButtons (this.features.length);
    },
    
    callHandlers: function (i) {
        if (this.handlers[i].handler) {
            var wkt = [];
            for (var j=0;j<this.features.length;j++) {
                wkt.push (this.features[j].wkt);
            }
            this.handlers[i].handler (this.name,wkt);
        }
    },
    
    activateHandlerButtons: function (activate) {
        if (this.dialog) {
            for (var i=0;i<this.handlers.length;i++) {
                $('dynamiclayer_'+this.name+'_handlers_'+i).disabled = !activate;
            }
        }
    },
    
    useSnap: function () {
        this.snap = $('dynamiclayer_'+this.name+'_usesnap').checked;
        cbKort.mapObj.drawSnap (this.snap);
    },

    //Called when dialog is closed be pressing the x
    closeHandler: function () {
        this.setMode ('');
        cbKort.setToolMode ();
        cbKort.mapObj.drawSnap (false);
    },
    
    registerEditHandler: function (options) {
        // confirm required properties are supplied
        var required = {
            handler: true,
            displayname: true
        };
        var go = true;
        for (var prop in required) {
            if (!(prop in options)) {
                go = false;
                cbKort.log ('DynamicLayer.registerEditHandler ('+name+') - Missing property "' + prop + '" in options.');
            }
        }
        if (go) {
            this.handlers.push (options);
        }
    },
    
    setMode: function (mode) {
        if (mode != '') {
            cbKort.setToolMode (this.toolmode);
        }
        this.activeTool = $('dynamiclayer_'+this.name+'_mode_'+this.activeMode);
        switch(this.activeMode) {
            case 'polygon':
                this.activeTool.className = 'drawFeaturePolygonInactive';
            break;
            case 'line':
                this.activeTool.className = 'drawFeatureLineInactive';
            break;
            case 'point':
                this.activeTool.className = 'drawFeaturePointInactive';
            break;
            case 'circle':
                this.activeTool.className = 'drawFeatureCircleInactive';
            break;
            case 'circleradius':
                this.activeTool.className = 'drawFeatureCircleradiusInactive';
            break;
            case 'move':
                this.activeTool.className = 'featureMoveInactive';
            break;
            case 'modify':
                this.activeTool.className = 'featureModifyInactive';
            break;
            case 'select':
                this.activeTool.className = 'featureSelectInactive';
            break;
            case 'selectrectangle':
                this.activeTool.className = 'drawFeatureRegularPolygonInactive';
            break;
            case 'delete':
                this.activeTool.className = 'featureDeleteInactive';
            break;
        }
        
        if (mode != 'circleradius') {
        	hideBlock($('dynamiclayer_'+this.name+'_radius'));
        }
        hideBlock($('dynamiclayer_'+this.name+'_datasource'));

        if (mode != '') {
            this.useSnap ();
            this.activeMode = mode;
            cbKort.mapObj.setClickEvent ();
            this.activeTool = $('dynamiclayer_'+this.name+'_mode_'+this.activeMode);
            switch(this.activeMode) {
                case 'polygon':
                    this.activeTool.className = 'drawFeaturePolygonActive';
                    cbKort.mapObj.drawPolygon (SpatialMap.Function.bind(this.featureAdded, this),{styles: this.clone (this.style),keyboard:true});
                break;
                case 'line':
                    this.activeTool.className = 'drawFeatureLineActive';
                    cbKort.mapObj.drawLine (SpatialMap.Function.bind(this.featureAdded, this),{styles: this.clone (this.style),keyboard:true});
                break;
                case 'point':
                    this.activeTool.className = 'drawFeaturePointActive';
                    cbKort.mapObj.drawPoint (SpatialMap.Function.bind(this.featureAdded, this),{styles: this.clone (this.style)});
                break;
                case 'circle':
                    this.activeTool.className = 'drawFeatureCircleActive';
                    cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.featureAdded, this),{draw: {sides: 40},styles: this.clone (this.style)});
                break;
                case 'circleradius':
                    this.activeTool.className = 'drawFeatureCircleradiusActive';
                    // Show radius input
                    if (!isBlock ($('dynamiclayer_'+this.name+'_radius'))) {
                    	showBlock($('dynamiclayer_'+this.name+'_radius'));
                    }
                    cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.featureAdded, this),{draw: {sides: 40, radius: this.radius},styles: this.clone (this.style)});
                break;
                case 'move':
                    this.activeTool.className = 'featureMoveActive';
                    cbKort.mapObj.drawMove (SpatialMap.Function.bind(this.featureModified, this));
                break;
                case 'modify':
                    this.activeTool.className = 'featureModifyActive';
                    cbKort.mapObj.drawModify (SpatialMap.Function.bind(this.featureModified, this));
                break;
                case 'select':
                    this.activeTool.className = 'featureSelectActive';
                    cbKort.getDatasourceSelect().searchDatasource ('dynamiclayer_'+this.name+'_datasource_select',SpatialMap.Function.bind (this.setCurrentDatasource,this));
                    showBlock($('dynamiclayer_'+this.name+'_datasource'));
                    cbKort.mapObj.panzoom ();
                    cbKort.mapObj.setClickEvent (SpatialMap.Function.bind(this.clickFeature, this));
                break;
                case 'selectrectangle':
                    this.activeTool.className = 'drawFeatureRegularPolygonActive';
                    cbKort.getDatasourceSelect().searchDatasource ('dynamiclayer_'+this.name+'_datasource_select',SpatialMap.Function.bind (this.setCurrentDatasource,this));
                    showBlock($('dynamiclayer_'+this.name+'_datasource'));
                    cbKort.mapObj.drawRegularPolygon (SpatialMap.Function.bind(this.clickFeature, this),{draw: {sides: 4, irregular: true},styles: this.clone (this.style)});
                break;
                case 'delete':
                    this.activeTool.className = 'featureDeleteActive';
                    cbKort.mapObj.drawSelect (SpatialMap.Function.bind(this.featureModified, this));
                break;
            }
        }
    },
    
    setCurrentDatasource: function (event,ui) {
        this.selectedDatasource = ui.item.value;
        cbKort.log ('DynamicLayer.setCurrentDatasource () - ',this.selectedDatasource);
    },
    
    setRadius: function () {
        var r = $('dynamiclayer_'+this.name+'_radius_input').value - 0;
        if (typeof r == 'number' || r == '') {
            this.radius = r;
            this.setMode (this.activeMode);
//        } else {
//            $('dynamiclayer_'+this.name+'_radius_input').value = this.radius;
        }
    },

    clickFeature: function (wkt) {
        if (typeof wkt != 'string') {
            if (wkt.hasOwnProperty('wkt')) {
                wkt = wkt.wkt;
            }
    	    wkt = wkt.toString();
        }
        var ds = this.selectedDatasource;
        if (ds) {
            var options = {
                wkt: wkt,
                datasource: ds
            }
            this.wktlist = cbKort.getDatasourceSelect ().query (options);
            
            if (this.wktlist) {
                for (var i=0;i<this.wktlist.length;i++) {
                    cbKort.mapObj.drawWKT(this.wktlist[i],SpatialMap.Function.bind(this.featureAdded, this),{styles: this.clone (this.style)});
                }
            }
            this.setMode (this.activeMode);
        } else {
            cbKort.log ('DynamicLayer.datasourceselect - no datasource selected')
        }
        return false;
    },
    
    featureAdded: function (feature) {
        var f = {id:feature.id,wkt:feature.wkt,style:this.clone (this.style)};
        this.features.push (f);
        if (this.render == 'server') {
            cbKort.mapObj.deleteFeature (feature.id);
        }

        //Add wkt to server
        this.addWKTToServer (f);
        
        this.updateMap ();
    },
    
    featureModified: function (event) {
        if (this.isValidFeature (event.id)) {
            if (event.type == 'SELECT') {
                if (this.activeMode == 'delete') {
                    for (var i=0;i<this.features.length;i++) {
                        if (this.features[i].id == event.id) {
                            this.features.splice (i,1);
                            break;
                        }
                    }
                    cbKort.mapObj.deleteFeature (event.id);
                    this.update ();
                } else {
                    this.selectedFeature = event.id;
                }
            } else if (event.type == 'UNSELECT') {
                this.selectedFeaure = null;
            } else if (event.type == 'MODIFY') {
                for (var i=0;i<this.features.length;i++) {
                    if (this.features[i].id == event.id) {
                        this.features[i].wkt = event.wkt;
                        break;
                    }
                }
                this.update ();
            }
        } else if (event.type != 'DELETE') {
            cbKort.mapObj.deselectFeatures (event.id);
            //HACK - I don't know how to fix this. Select event is triggert before the virtual points are added.
            setTimeout (SpatialMap.Function.bind(this.setMode, this, this.activeMode),500);
            cbKort.log ('DynamicLayer.featureModified - selected feature not valid', this, event);
        }
    },
    
    isValidFeature: function (id) {
        var ready = false;
        for (var i=0;i<this.features.length;i++) {
            if (this.features[i].id == id) {
                ready = true;
                break;
            }
        }
        return ready;
    },
    
    clone: function (obj) {
        returnObj = {};
        for (name in obj) {
            returnObj[name] = obj[name]; 
        }
        return returnObj;
    },
    
    CLASS_NAME: 'DynamicLayer'
});

