if (!AWP.Control) AWP.Control = {};

AWP.Control.SelectFeature = OpenLayers.Class(OpenLayers.Control.SelectFeature, {
	selectedFeature: null,
	mouseoverFeature: null,
	popupSize: new OpenLayers.Size(200, 100),
	popupOnMouseOver: null,
	popupSizeOver: new OpenLayers.Size(180, 30),
	xyOver: null,
    initialize: function(layer) {
		var options = {
			multipleKey: 'ctrlKey',
			toggleKey: 'ctrlKey'
			//toggle: true,
		};
        OpenLayers.Control.prototype.initialize.apply(this, [options]);
		
		this.scope = this;
		this.selectStyle = AWP.cfg.VECTOR_STYLE['select']
		
        this.layer = layer;
        var callbacks = {
            click: this.clickFeature,
            clickout: this.clickoutFeature,
            over: this.overFeature,
            out: this.outFeature
        }
             
        this.callbacks = OpenLayers.Util.extend(callbacks, this.callbacks);
        this.handlers = {
            feature: new OpenLayers.Handler.Feature(
                this, layer, this.callbacks, {geometryTypes: this.geometryTypes}
            )
        };
		this.handlers.feature.mousemove = this.mousemove(this);
		
        if (this.box) {
            this.handlers.box = new OpenLayers.Handler.Box(
                this, {done: this.selectBox},
                {boxDivClassName: "olHandlerBoxSelectFeature"}
            ); 
        }
    },
	mousemove: function(obj) {
		return function(evt) {//alert('mouseover: ' + evt.xy)
			if (!this.callbacks['over'] && !this.callbacks['out']) {
				return true;
			}     
			this.handle(evt);
			obj.moveFeature(evt);
			return true;
		}
    },
	moveFeature: function(evt) {
		var feature = this.handlers.feature.layer.getFeatureFromEvent(evt);
		if (feature && this.popupOnMouseOver) {
			//this.popupOnMouseOver.moveTo(evt.xy);
		}
	},
	multipleSelect: function() {
		// this.handlers.feature.evt will be null if a row of grid is clicked
		try {
			return this.multiple || (this.handlers.feature.evt && this.handlers.feature.evt[this.multipleKey]);
		} catch (e) {
			return false;
		}
	},
	clickFeature: function(feature) {
		var selected = (OpenLayers.Util.indexOf(this.layer.selectedFeatures, feature) > -1);
		if (selected) {
			if (this.toggleSelect()) {
				this.unselect(feature);
			} else if(!this.multipleSelect()) {
				this.unselectAll({except: feature});
				if (!feature.popup || !feature.popup.visible()) {
					this.onSelect(feature);
				}
			}
		} else {
			if (!this.multipleSelect()) this.unselectAll({except: feature});
			this.select(feature);
		}
		this.handlers.feature.lastFeature = feature;
    },
    /**
     * 鼠标放到 feature 上触发
     */
	overFeature: function(feature) {
		// 如果 feature 未被选中
		if (OpenLayers.Util.indexOf(this.layer.selectedFeatures, feature) == -1) {
			// 把 feature 画成 temporary 样式
			this.layer.drawFeature(feature, AWP.cfg.VECTOR_STYLE['temporary']);
			// 在之前的 mouseoverFeature 上执行鼠标移出动作
			if (this.mouseoverFeature && this.mouseoverFeature != feature) {
				this.outFeature(this.mouseoverFeature);
			}
			// 把当前 feature 设置为 mouseoverFeature
			this.mouseoverFeature = feature;
			/**
			 * this.popupOnMouseOver  may be created by row select
			 */
			if (this.selectedFeature && this.selectedFeature.popup) {
				this.selectedFeature.popup.hide();
			}
			
			// 如果 popupOnMouseOver 尚未被创建
			if (!this.popupOnMouseOver) {
				this.popupOnMouseOver = AWP.Control.SelectFeature.createPopupOnMouseOver(this, feature);
				this.map.addPopup(this.popupOnMouseOver);
			} else {
				// 已创建则直接显示
				this.popupOnMouseOver.show();
			}
		} else {
			/**
			 * feature 在已经被选中的情况下，原动作是再次触发 mouseover 事件。
			 * 现改为不再响应动作，避免弹出对话框在被用户关闭后反复打开。
			 */
			//this.onSelect(feature);
		}
		
		this.layer.events.triggerEvent("featureselected", {feature: feature});
		//this.events.triggerEvent("mouseoverfeature", {feature: feature});
	},
	outFeature: function(feature) {
		if (OpenLayers.Util.indexOf(this.layer.selectedFeatures, feature) == -1) {
			this.layer.drawFeature(feature, feature.style || AWP.cfg.VECTOR_STYLE['default']);
			
			if (this.selectedFeature && this.selectedFeature.popup) {
				//this.selectedFeature.popup.show();
			}
			
			if (this.popupOnMouseOver) {
				this.map.removePopup(this.popupOnMouseOver);
				this.popupOnMouseOver.destroy();
				this.popupOnMouseOver = null;
			}
		}
		
		// 如果当前 feature 已经被选中，则不触发事件
		if (this.selectedFeature != feature) {
			this.layer.events.triggerEvent("featureunselected", {feature: feature});
		}
	},
	unselectAll: function(options) {
		var feature;
		// handle "mouseover" popups of "unselected" features
		for (var i = this.layer.features.length - 1; i >= 0; --i) {
			feature = this.layer.features[i];
			if (!options || options.except != feature) {
				this.unselect(feature);
			}
		}
		
		// 取消选择所有 features 的同时，还要记得清空 mouseoverFeature 和 selectFeature
		this.mouseoverFeature = null;
		this.selectFeature = null;
	},
	onSelect: function(feature) {
		if (this.selectedFeature && this.selectedFeature != feature) {
			if (this.selectedFeature.popup) {
				this.map.removePopup(this.selectedFeature.popup);
				this.selectedFeature.popup.destroy();
				this.selectedFeature.popup = null;
			}
		}
		this.selectedFeature = feature;
		
		if (this.popupOnMouseOver) {
			this.map.removePopup(this.popupOnMouseOver);
			this.popupOnMouseOver.destroy();
			this.popupOnMouseOver = null;
		}
		
		if (feature.popup) {
			feature.popup.show();
			feature.popup.panIntoView();
		} else if (feature.attributes.record) {
			feature.popup = feature.attributes.layer.createPopupOnClick(feature);
			this.map.addPopup(feature.popup);
			feature.attributes.layer.onCreatePopupOnClick(feature);
			feature.popup.panIntoView();
		} else if (feature.attributes.records && feature.attributes.records.length != 0) {
			feature.attributes.record = feature.attributes.records[0];
			feature.popup = feature.attributes.layer.createPopupOnClick(feature);
			this.map.addPopup(feature.popup);
			feature.attributes.layer.onCreatePopupOnClick(feature);
			feature.popup.panIntoView();
		} else if (feature.attributes.category == 'customer') {
			AWP.userContent.onClickFeaturePopup(feature);
		} else {
			// AWP admin 使用
			this.layer.events.triggerEvent("featureselected", {feature: feature, click: true});
		}
	},
	onUnselect: function(feature) {
		if (feature.popup) {
			this.map.removePopup(feature.popup);
			feature.popup.destroy();
			feature.popup = null;
		}
		
		if (this.popupOnMouseOver) {
			this.map.removePopup(this.popupOnMouseOver);
			this.popupOnMouseOver.destroy();
			this.popupOnMouseOver = null;
		}
		
		if (this.selectedFeature && this.selectedFeature == feature) {
			this.selectedFeature = null;
		}
		
		this.layer.events.triggerEvent("featureunselected", {feature: feature});
	},
	createPopupMouseOver: function(closeBox) {
		var popup;
		if (this.lonlat != null) {
			this.data.popupContentHTML = 'Station Name: ' + this.data.stn_name;
			this.data.popupSize = new OpenLayers.Size(265, 60);
			popup = this.createPopup(closeBox);
		}
		return popup;
	},
	createPopup: function(closeBox) {
		var popup = null;
		
        if (this.lonlat != null) {
            var id = this.id + "_popup";
            var anchor = (this.marker) ? this.marker.icon : null;
			popup = new AWP.Popup(
				id, 
				this.lonlat,
				this.data.popupSize,
				this.data.popupContentHTML,
				anchor, 
				closeBox
			);
            if (this.data.overflow != null) {
                popup.contentDiv.style.overflow = this.data.overflow;
            }    
            
            popup.feature = this;
        }        
        return popup;
    },
    /**
     * 在当前缩放级别(分辨率)下重新获取 feature
     */
	refreshFeature: function(feature) {
		feature = feature || this.selectedFeature;
		if (feature) {
			var layer = feature.attributes.layer;
			var vectorLayer = this.map.getLayerByName("Vector Features");
			
			if (feature.popup) {
				this.map.removePopup(feature.popup);
				this.selectedFeature.popup.destroy();
				this.selectedFeature.popup = null;
			}
			vectorLayer.removeFeatures([feature]);
			
			Ext.Ajax.request({
				url: AWP.cfg.serviceURL,
				feature: feature,
				params: {
					action		: 'getFeatureByResolution',
					layerName	: layer.layers,
					fid			: feature.fid,
					resolution	: AWP.map.getResolution()
				},
				scope: this,
				success: function(response, options) {
					//alert(response.responseText.length + ',\n' + response.responseText);
					var feature = options.feature, layer = feature.attributes.layer;
					var newFeature = layer.awp_wkt.read(response.responseText);
					
					for (var i = 0, len = layer.features.length; i < len; i++) {
						if (layer.features[i] == feature) {
							layer.features[i] = newFeature;
							break;
						}
					}
					
					newFeature.fid = feature.fid;
					newFeature.layer = feature.attributes.layer;
					newFeature.layerId = feature.layerId;
					newFeature.attributes.record = feature.attributes.record;
					newFeature.attributes.records = feature.attributes.records;
					for (var i = 0, r; r = feature.attributes.records[i]; i++) {
						r.feature = newFeature;
					}
					newFeature.attributes.layer = feature.attributes.layer;
					
					feature.destroy();
					feature = null;
					
					vectorLayer.addFeatures([newFeature]);
					this.clickFeature(newFeature);
				},
				failure: function() {alert('sorry')}
			});
		} else {
			alert('Please select a feature first');
		}
	},
    CLASS_NAME: "AWP.Control.SelectFeature"
});
AWP.Control.SelectFeature.createPopupOnMouseOver = function(control, feature) {
	var popup;
	if (feature.attributes.category == 'customer') {
		popup = new AWP.Popup(
			null, 
			feature.geometry.getBounds().getCenterLonLat(),
			control.popupSizeOver,
			feature.attributes.title,
			null
		);
	} else {
		popup = new AWP.Popup(
			null, 
			feature.geometry.getBounds().getCenterLonLat(),
			control.popupSizeOver,
			feature.fid,
			null
		);
	}
	
	return popup;
}
