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

AWP.Control.Identify = OpenLayers.Class(OpenLayers.Control, {
	title: "Identify",
	/**
	 * spatial links 点所在层
	 */
	layer: null,
	layerProximityCircle: null,
	vectorProximity: null,
	layerPlacemark: null,
    initialize: function() {
		OpenLayers.Control.prototype.initialize.apply(this, arguments);
		
		this.handler = new OpenLayers.Handler.Click(this, {
			"click": this.click
		});
		
//		this.events.register('activate', this, function() {
//			this.map.addLayer(this.layer);
//			this.layer.setVisibility(true);
//		});
//		this.events.register('deactivate', this, function() {alert('y')
//			this.map.removeLayers([this.layer]);
//		});
		
		OpenLayers.Event.observe('populate',
			'click',
			OpenLayers.Function.bindAsEventListener(this.onClickButton, this)
		);
		OpenLayers.Event.observe('populate_update',
			'click',
			OpenLayers.Function.bindAsEventListener(this.onClickUpdateButton, this)
		);
		OpenLayers.Event.observe('SPATIAL_LINK',
			'change',
			OpenLayers.Function.bindAsEventListener(this.onChangeSpatialLinkSelect, this)
		);
		// 为了解决 onchange 事件在 键盘操作时，firefox 下不响应的问题
		OpenLayers.Event.observe('SPATIAL_LINK',
			'keyup',
			function() {
				this.blur();
				this.focus();
			}
		);
		// 鼠标放在 spatial link 点上时，从下拉框中选择相对应的 option
		this.layer.events.register('featureselected', this, this.updateSelectedSpatialLink);
    },
    /**
     *
     */
    onClickButton: function() {
    	this.activate();
    	this.layer.setVisibility(true);
    	this.layer.div.style.cursor = 'pointer';
    },
    /**
     * 当点击更新按钮，根据当前选择的 SPATIAL_LINK 更新数据
     */
    onClickUpdateButton: function() {
    	var lon_lat = document.getElementById('SPATIAL_LINK').value;
    	if (lon_lat == 0) {
    		alert('Please select a spatial link');
    		return
    	} else {
    		var tmp = lon_lat.split('_');
    		var lon = tmp[0];
    		var lat = tmp[1];
    	}
    	
    	// 显示 loading 图标
		var fields = ['LAND_USE_REGION', 'AREA_FMU', 'AREA_NTS', 'AREA', 'BASIN', 'SUB_BASIN'];
		for (var i = 0, len = fields.length; i < len; i++) {
			document.getElementById('loading_' + fields[i]).style.display = '';
			document.getElementById(fields[i]).value = '';
		}
		
    	Ext.Ajax.request({
			url: AWP.cfg.serviceURL,
			params: {
				action		: 'identifyBySpatialLink',
				lon			: lon,
				lat			: lat,
				tmpl		: 'component',
				resolution	: this.map.getResolution() / 2
			},
			success: this.handleResults,
			failure: function(a,b,c,d) {//pre([a,b,c,d])
				alert('Identify Request failure')
			},
			scope: this
		});
    },
    /**
     * 当从 SPATIAL LINK 下拉框选择一个点，突出显示在地图上
     */
    onChangeSpatialLinkSelect: function() {
    	var lon_lat = document.getElementById('SPATIAL_LINK').value;
    	
    	var selected_feature = null;
    	for (var i = 0, feature; feature = this.layer.features[i]; i++) {
    		if (lon_lat == feature.geometry.x + '_' + feature.geometry.y) {
    			selected_feature = feature;
    		}
    	}
    	
    	if (selected_feature) {
    		this.map.getControlsByClass('AWP.Control.SelectFeature')[0].overFeature(selected_feature);
    	}
    },
    updateSelectedSpatialLink: function(evt) {
    	var feature = evt.feature;
    	var lon_lat = feature.geometry.x + '_' + feature.geometry.y;
    	var sel_spatial_link = document.getElementById('SPATIAL_LINK');
    	
    	for (var i = 0, option; option = sel_spatial_link.options[i]; i++) {
    		if (lon_lat == option.value) {
    			sel_spatial_link.selectedIndex = i;
    			break;
    		}
    	}
    	
    	// 如果是点击
    	if (evt.click) {
    		this.onClickUpdateButton();
    	}
    },
    markPlace: function(xy) {
    	if (this.layerPlacemark) {
			this.layerPlacemark.clearMarkers();
		} else {
			this.layerPlacemark = new OpenLayers.Layer.Markers("Place Marker");
			this.map.addLayers([this.layerPlacemark]);
		}
		
		var size	= new OpenLayers.Size(21, 25);
		var offset	= new OpenLayers.Pixel(-(size.w/2), -15);
		var icon	= new OpenLayers.Icon(AWP.cfg.baseURL + 'image/marker.png', size, offset);
		var marker	= new OpenLayers.Marker(xy, icon);
		this.layerPlacemark.addMarker(marker);
		this.layerPlacemark.setOpacity(0.5);
    },
    /**
     * 点击地图时触发
     */
	click: function(ee) {
		var lonlat = this.map.getLonLatFromViewPortPx(ee.xy);
		//AWP.mainPanel.getComponent('west').getComponent('identify').expand();
		//var grid = Ext.ComponentMgr.get('identify-grid');
		//if (grid) grid.store.removeAll();
		
		// 标记点击地点
		this.markPlace(lonlat);
		
		// 清除上次结果
		this.layer.removeFeatures(this.layer.features);
		
		// 画圆
		var r = document.getElementById('proximity').value;
		r = [10000, 20000, 50000, 100000][r] || 10000;
		this.drawProximityCircle(lonlat, r);
		
		// 缩放至圆最合适
		var map = this.map;
		var bounds = new OpenLayers.Bounds(lonlat.lon - r, lonlat.lat - r, lonlat.lon + r, lonlat.lat + r);
		var zoomLevel = map.getZoomForExtent(bounds);
		if (zoomLevel - 1 > map.getZoom() || zoomLevel < map.getZoom()) map.setCenter(lonlat, zoomLevel);
		
		// 显示 loading 图标
		var fields = ['LAND_USE_REGION', 'AREA_FMU', 'AREA_NTS', 'AREA', 'BASIN', 'SUB_BASIN'];
		for (var i = 0, len = fields.length; i < len; i++) {
			document.getElementById('loading_' + fields[i]).style.display = '';
			document.getElementById(fields[i]).value = '';
		}
		
		Ext.Ajax.request({
			url: AWP.cfg.serviceURL,
			params: {
				action: 'identify',
				//layerName: layer.layers,
				lon: lonlat.lon,
				lat: lonlat.lat,
				proximity: r,
				//srid: AWP.serverProj.replace('EPSG:', ''),
				resolution: this.map.getResolution() / 2
			},
			success: this.handleResults,
			failure: function(a,b,c,d) {//pre([a,b,c,d])
				alert('Identify Request failure')
			},
			scope: this
		});
		
		this.deactivate();
    	this.layer.div.style.cursor = 'default';
	},
	handleResults: function(response, options) {
		try {
			json = eval('(' + response.responseText + ')');
		} catch (e) {
			alert('Identify failure' + '\n' + e + '\n' + response.responseText);
			return
		}
		
		var is_populating = !!options.params.proximity;
		
		for (var i in json) {
			if (i == 'spatial_links') continue;
			var row = json[i];
			if (row) {
				// 暂时不显示除 SPATIAL_LINK 以外的其他地理数据
//				var feature = wkt.read(row.the_geom);
//				feature.fid = i + ': ' + row.gid;
//				features.push(feature);
				
				if (i == 'area_nts') {
					document.getElementById('AREA_NTS').value			= row.nts50k;
				} else if (i == 'area_fmu') {
					document.getElementById('AREA_FMU').value			= row.fmu_name;
				} else if (i == 'area_basin') {
					document.getElementById('BASIN').value				= row.sub_pf;
				} else if (i == 'area_subasin') {
					document.getElementById('SUB_BASIN').value			= row.stn_name;
				} else if (i == 'area_municipal') {
					document.getElementById('AREA').value				= row.geoname;
				} else if (i == 'bf_land_use_framework_projec') {
					document.getElementById('LAND_USE_REGION').value	= row.luf_name;
				}
			}
		}
		document.adminForm.LOCATION_EXPLICIT.value = 1;
		
		// 隐藏 loading 图标
		var fields = ['LAND_USE_REGION', 'AREA_FMU', 'AREA_NTS', 'AREA', 'BASIN', 'SUB_BASIN'];
		for (var i = 0, len = fields.length; i < len; i++) {
			document.getElementById('loading_' + fields[i]).style.display = 'none';
		}
		
		if (is_populating) {
			// 分析 features
			var wkt = new OpenLayers.Format.WKT(), features = [];
			var sel_spatial_link = document.getElementById('SPATIAL_LINK');
			for (var i = sel_spatial_link.options.length - 1; i > 0; i--) {
				sel_spatial_link.remove(i);
			}
			
			var option		= document.createElement('option');
			option.value	= options.params.lon + '_' + options.params.lat;
			option.text		= 'current: POINT(' + options.params.lon + ' ' + options.params.lat + ')';
			option.selected	= true;
			sel_spatial_link.add(option, null);
			
			for (var i = 0, len = json.spatial_links.length; i < len; i++) {
				var row = json.spatial_links[i]
				var feature = wkt.read(row.the_geom);
				feature.fid = 'SPATIAL_LINK: ' + row.gid;
				features.push(feature);
				
				var option		= document.createElement('option');
				option.value	= row.x + '_' + row.y;
				option.text		= row.gid + ': ' + row.the_geom;
				sel_spatial_link.add(option, null);
			}
			
			if (features.length && options.params.proximity) {
				alert(features.length + ' SPATIAL_LINK points found')
				this.layer.addFeatures(features);
			}
		}
	},
	drawProximityCircle: function(xy, r) {
		if (!this.layerProximityCircle) {
			this.layerProximityCircle = new OpenLayers.Layer.Vector("Proximity Circle", {
				style: {
					fillColor: '#ffffff',
					strokeColor: '#00ff00',
					fillOpacity: 0,
					strokeWidth: 1
				}
			});
			this.map.addLayers([this.layerProximityCircle]);
		}
		if (this.vectorProximity) {
			this.layerProximityCircle.removeFeatures([this.vectorProximity]);
			this.vectorProximity.destroy();
			this.vectorProximity = null;
		}
		
		var pointList = [];
		for (var i = 0; i < 61; i++) {
			var a = i * (2 * Math.PI) / 60;
			var newPoint = new OpenLayers.Geometry.Point(
				xy.lon + (r * Math.cos(a)),
				xy.lat + (r * Math.sin(a))
			);
			pointList.push(newPoint);
		}
		
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		this.vectorProximity = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]));
		this.vectorProximity.style = {
			fillColor: '#ffffff',
			strokeColor: '#00ff00',
			fillOpacity: 0.1,
			strokeWidth: 1
		};
		this.layerProximityCircle.addFeatures([this.vectorProximity]);
	},
    CLASS_NAME: "AWP.Control.Identify"
});
