AWP.Layer.Vector = OpenLayers.Class(OpenLayers.Layer.Vector, {
	checked: false,
	awp_wkt: new OpenLayers.Format.WKT(),
    initialize: function(config) {
		config = config || {};
		
		this.layerId = config.layerId || '';
		this.category = config.category || '';
		this.server = config.server || {};
		
		this.namespace = config.namespace || this.server.namespace;
		this.layers = this.namespace + ':' + (config.layers || '');
		
		this.text = config.name || this.layerId || 'Untitled layer';
		this.icon = config.icon || 'image/layer.png';
		
		if (config.checked === true) this.checked = true;
		
		var options = {
			visibility: config.visibility === true ? true : false,
			styleMap: new OpenLayers.StyleMap({
				'default': new OpenLayers.Style(AWP.cfg.VECTOR_STYLE['default']),
				'select': new OpenLayers.Style(AWP.cfg.VECTOR_STYLE['select']),
				'temporary': new OpenLayers.Style(AWP.cfg.VECTOR_STYLE['temporary'])
			})
		};
		
		OpenLayers.Layer.Vector.prototype.initialize.apply(this, [config.name, options]);
		
		if (this.layerId) {
			AWP.Layer.array.push(this);
			AWP.Layer.items[this.layerId] = this;
		}
/*AWP.layerSelectedFeatures.events.on({
			featuresadded: function(features) {
				var sel = document.getElementById('features');
				var features = AWP.layerSelectedFeatures.features;
				
				var feature;
				var html = ['<option value=""> - Select a Feature - </option>'];
				for (var i = 0; i < features.length; i++) {
					feature = features[i];
					html.push('<option value="' + feature.fid + '">' + feature.fid + '</option>');
				}
				
				sel.innerHTML = html.join('');
			}
		});*/
	},
	moveTo2: function(bounds, zoomChanged, minor) {
        OpenLayers.Layer.Vector.prototype.moveTo.apply(this, arguments);
        //if (this.visibility && !this.loaded) {
			var southPanel = AWP.mainPanel.getComponent('south');
			if (southPanel.collapsed) {
				southPanel.addListener('expand', this.loadData, this, {single: true})
				southPanel.expand();
			} else {
				 this.loadData();
			}
        //}
    },
    /**
     * 目前仅发现 layer "temp_simplified_geom" 属此类型，但已被注释。
     */
	loadData: function() {
		if (!this.loaded) {
			if (true || this.location != null) {
				var onFail = function(e) {
					this.events.triggerEvent("loadend");
				};
				this.events.triggerEvent("loadstart");
				Ext.Ajax.request({
					url: AWP.cfg.serviceURL,
					params: {
						action: 'AWP.layerColumns',
						layerName: this.layers,
						format: 'json'
					},
					success: OpenLayers.Function.bind(this.layerColumns, this),
					failure: function() {alert('sorry')}
				});
				this.loaded = true;
			}
		}
	},
	layerColumns: function(response, options) {
		try {
			var json = eval('(' + response.responseText + ')');
		} catch (e) {
			alert(e + '\n\n' + response.responseText);
			return
		}
		AWP.log(json);
		var columns = json['columns'];
		
		var tab_id = 'awp-tabpanel-tab-' + this.layerId;
		var tab = AWP.tabPanel.getItem(tab_id);
		if (!tab) {
			tab = AWP.tabPanel.add({id: tab_id, title: this.name, closable: true});
			tab.show();
			tab.addListener('activate', this.showTab, this);
			tab.addListener('deactivate', this.hideTab, this);
			tab.addListener('beforedestroy', this.clearFeatures, this);
		} else {
			tab.show();
		}
		
		if (!this.awp_store) {
			this.awp_store = new AWP.Layer.Store(columns);
			this.awp_store.addListener('load', this.afterLoad, this);
			//this.awp_store.addListener('beforeload', this.setResolution, this);
		}
		if (!this.awp_grid) {
			this.awp_grid = new AWP.Layer.Grid({layer: this, tab: tab, columns: columns});
			this.awp_grid.render();
			//var vectorLayer = this.map.getLayerByName('Vector Features');
			//vectorLayer.events.register("featureselected", this, this.selectRowByFeature);
		}
		
		this.awp_store.baseParams = {
			action: 'AWP.layerVectors',
			layerName: this.layers,
			format: 'json'
		};
		
		this.awp_store.setDefaultSort('gid', 'ASC');
		this.awp_store.load({params: {start: 0}});
	},
	afterLoad: function(store, records, options) {
		if (this.features) {
			this.removeFeatures(this.features);
			this.destroyFeatures();
		}
		
		this.features = [];
		var maxBounds = new OpenLayers.Bounds();
		for (var i = 0; i < records.length; i++) {
			var record = records[i], feature = this.awp_wkt.read(record.data.the_geom);
			if (!feature) {
				pre(record.data)
			} else {
				feature.attributes.record = record;
				feature.fid = this.layerId + '.' + record.data.gid;
				record.feature = feature;
				this.features.push(feature);
				
				maxBounds.extend(feature.geometry.getBounds());
			}
		}
		
		var zoomLevel = this.map.getZoomForExtent(maxBounds);
		if (zoomLevel != this.map.getZoom) this.map.setCenter(maxBounds.getCenterLonLat(), zoomLevel);
		
		this.addFeatures(this.features);
	},
	destroyFeatures: function() {
		if (this.features) {
			for (var i = 0, len = this.features.length; i < len; i++) {
				if (!this.features[i]) continue;
				
				if (this.features[i].attributes.record) {
					this.features[i].attributes.record.feature = null;
					this.features[i].attributes.record = null;
				}
				if (this.features[i].attributes.records) {
					for (var j = 0; j < this.features[i].attributes.records.length; j++) {
						if (this.features[i].attributes.records[j]) {
							this.features[i].attributes.records[j].feature = null;
							this.features[i].attributes.records[j] = null;
						}
					}
				}
				this.features[i].destroy();
				this.features[i] = null;
			}
			this.features = null;
		}
	},
	selectRow: function(sm, rowIndex, record) {
		if (record.feature) {
			this.drawFeature(record.feature, AWP.cfg.VECTOR_STYLE['temporary']);
		}
	},
	unselectRow: function(sm, rowIndex, record) {
		if (record.feature) {
			this.drawFeature(record.feature, AWP.cfg.VECTOR_STYLE['default']);
		}
	}
})
