AWP.Marker = OpenLayers.Class(OpenLayers.Marker, {
	is_Drawn: false,
	initialize: function(lonlat, data) {
		this.lonlat = lonlat;
		this.icons = [];
		this.data = {};
		this.div = document.createElement('div');
		
		var size = new OpenLayers.Size(20, 20);
		// Basin 相关
		if (data.indicators) {
			// 可用于显示/隐藏 icon 时与选中 basin 进行对比
			this.basin_name	= data.basin_name;
			this.polygon	= data.polygon;
			
			for (var n in data.indicators) {
				var indicator	= data.indicators[n];
				if (indicator.icon) {
					var icon	= new OpenLayers.Icon(AWP.cfg.SEAWA_ICON_URL + indicator.icon, size);
					icon.data	= indicator;
					icon.marker	= this;
					icon.events	= new OpenLayers.Events(this, icon.imageDiv, null);
					icon.events.register('click', icon, this.onClick);
					/**
					 * @date 2010-06-02 客户要求取消 mouseover 行为，下同
					 */
					//icon.events.register('mouseover', icon, this.onMouseOver);
					//icon.events.register('mouseout', icon, this.onMouseOut);
					this.icons.push(icon);
				}
			}
			
			this.display(false);// 默认不显示
		// 实时数据相关
		} else {
			var icon = new OpenLayers.Icon(AWP.cfg.SEAWA_ICON_URL + data.icon, size);
			icon.data = data;
			icon.marker = this;
			icon.events = new OpenLayers.Events(this, icon.imageDiv, null);
			icon.events.register('click', icon, this.onClick);
			//icon.events.register('mouseover', icon, this.onMouseOver);
			//icon.events.register('mouseout', icon, this.onMouseOut);
			this.icons.push(icon);
		}
		//this.div.style.width = this.icons.length * size.w + 'px';
		//this.div.style.height = size.h + 'px';
		//this.events = new OpenLayers.Events(this, this.div, null);
		//OpenLayers.Marker.prototype.initialize.apply(this, [lonlat, icon]);
    },
    /**
     * 当用户点击 indicator icon 图标，弹出 tab 对话框
     */
	onClick: function(ee) {
		var data = this.data;
		// station 不存在，认为是 Basin 相关
		if (!data.station) {
			AWP.Marker.showIndicator(data, ee);
			
		// station 存在，实时数据相关
		} else {
			var popup = AWP.Marker.current_popup;
			if (popup) popup.destroy();
			AWP.Marker.current_popup = null;

			//if (this.popupMouseOver) this.popupMouseOver.hide();
			var popup = AWP.Marker.current_popup_onclick;
			if (popup) popup.destroy();
	
			popup = this.marker.createPopupOnClick(true, this);
			this.marker.map.addPopup(popup);
			AWP.Marker.current_popup_onclick = popup;
			popup.panIntoView();
	
			OpenLayers.Event.stop(ee);
		}
	},
	/**
	 * 当鼠标移到 icon 图标上
	 */
	onMouseOver: function(ee) {
		var popup = AWP.Marker.current_popup_onclick;
		if (popup && popup.visible()) return

		var popup = AWP.Marker.current_popup;
		var icon = AWP.Marker.current_icon;

		if (popup) {
			if (this == icon) {
				return
			} else {
				popup.destroy();
			}
		}

		popup = this.marker.createPopupMouseOver(true, this);
		this.marker.map.addPopup(popup);

		AWP.Marker.current_popup = popup;
		AWP.Marker.current_icon = this;

		OpenLayers.Event.stop(ee);
	},
	/**
	 * 目前取消此行为
	 */
	onMouseOut: function(ee) {
		var popup = AWP.Marker.current_popup;
		
		if (popup) {
			popup.destroy();
			AWP.Marker.current_popup = null;
		}
		OpenLayers.Event.stop(ee);
	},
	createPopupOnClick: function(closeBox, icon) {
		var popup;
		var popupData = this.data;
		var lonlat = this.lonlat;

		if (lonlat != null) {
//			var s = ['<table border="0" cellpadding="3" cellspacing="1" bgcolor="gray">'], data = icon.data;
//			for (var key in data) s.push('<tr bgcolor="white"><td>' + key + '</td><td>' + data[key] + '</td></tr>');
//			s.push('</table>');
			var data = icon.data;
			var s = ['<iframe width="100%" height="210" frameborder="0" marginheight="0" marginwidth="0"',
				' src="', AWP.cfg.serviceURL, '&task=drawRealtimeData&tmpl=component&basin_id=', data.basin_id,
				'&infotype_id=', data.infotype_id, '&station_strid=', data.station_strid, '&field=', data.field, '"></iframe>'];

			popupData.popupContentHTML = s.join('');
			popupData.popupSize = new OpenLayers.Size(410, 210);
			popupData.anchor = icon;
			popup = this.createPopup(closeBox);
		}
		return popup;
	},
	createPopupMouseOver: function(closeBox, icon) {
		var popup;
		var popupData = this.data;
		var lonlat = this.lonlat;

		if (lonlat != null) {
			var data = icon.data;
			var html_articles = [];
			var types = AWP.cfg.SEAWA_INDICATOR_ARTICLE_TYPES
			for (var i = 0; i < 5; i++) {
				if (data['title' + i]) {
					if (false) {
						html_articles.push(['<a',
						 	' href="javascript:void(0)"',
							' onclick="AWP.Marker.showIndicatorArticleInLightBox(',
							data.id, ',\'', data.basin, '\',\'', data.indicator, '\',\'', data.description, '\')"',
							' style="font-size: 10px;">', types[i], '</a>'].join(''));
					} else {
						html_articles.push(['<a class="modal" onclick="AWP.Marker.showIndicatorArticleInLightBox(this, event)"',
							' rel="{handler: \'iframe\', size: {x: 650, y: 500}}"',
							' href="', AWP.cfg.SEAWA_URL, 'index.php?option=com_content&view=article&tmpl=component&id=', data['article' + i],
							'" style="font-size: 10px;">', types[i], '</a>'].join(''));
					}
				}
			}
			popupData.popupContentHTML = [
				'<table width="100%" cellpadding="0" cellspacing="0" border="0" style="height:100%">',
					'<tr>',
						'<td rowspan="3" width="60" align="center" valign="top">',
						'<img width="50" height="50" src="',
							AWP.cfg.SEAWA_ICON_URL, data.icon, '" /></td>',
						'<td colspan="2"><span style="font-size: 14px; font-family: Lucida Grande, Lucida Sans Unicode, Helvetica, Arial, sans-serif; font-weight: bold">',
						data.description || data.station,
						'</span></td>',
					'</tr>',
					'<tr>',
						'<td colspan="2"><span style="font-size: 10px; color: gray">', data.basin_name || data.basin, '</span>',
						'<strong> - </strong>',
						'<span style="font-size: 10px; color: gray">', data.icon_name, '</span></td>',
					'</tr>',
					'<tr>',
						'<td style="line-height: normal">', html_articles.join('<br />'), '</td>',
						'<td align="right" vAlign="bottom">',
						'<span style="font-size: 9px; color: silver">', data.date, '</span></td>',
					'</tr>',
				'</table>',
			].join('');
			popupData.popupSize = new OpenLayers.Size(300, 100);
			popupData.anchor = icon;
			popup = this.createPopup(closeBox);
		}
		return popup;
	},
	createPopup: function(closeBox) {
		var popup = null;
		var popupData = this.data;
		var lonlat = this.lonlat;

        if (lonlat != null) {
            var id = this.id + "_popup";
            var anchor = {
				//size: new OpenLayers.Size(-10, -10),
               // offset: popupData.anchor.offset.add(15, 15)
				size: new OpenLayers.Size(0, 0),
                offset: popupData.anchor.offset.add(10, 10)
			};
			popup = new AWP.Popup(
				id,
				lonlat,
				popupData.popupSize,
				popupData.popupContentHTML,
				anchor,
				closeBox
			);
            if (popupData.overflow != null) {
                popup.contentDiv.style.overflow = popupData.overflow;
            }
        }
        return popup;
    },
	destroy: function() {
        // erase any drawn features
        this.erase();

        this.map = null;

        this.events.destroy();
        this.events = null;

		for (var i = 0, len = this.icons.length; i < len; i++) {
			this.icons[i].destroy();
		}
    },
	erase: function() {
		for (var i = 0, len = this.icons.length; i < len; i++) {
			this.icons[i].erase();
		}
    },
	draw: function(px) {
		var div = this.div;
		div.style.position = 'absolute';
		//div.style.border = '1px solid red';
		div.style.left	= px.x + "px";
		div.style.top	= px.y + "px";
		
		var feature		= new OpenLayers.Format.WKT().read(this.polygon);
		var p			= feature.geometry.components[0].components;
		this.feature	= feature;
//		var layer = AWP.map.getLayerByName("Vector Features");
//		layer.addFeatures([feature]);
//		layer.setVisibility(true);
		
		var pLen	= p.length - 1;
		var len		= this.icons.length;
		if (pLen > len) {// 如果多边形顶点数多于图标数
			var res		= AWP.map.resolution;
			var step	= Math.floor(pLen / len);
			for (var i = 0; i < len; i++) {
				var icon	= this.icons[i];
				var xy	= p[i * step];
				var dx	= Math.round((xy.x - this.lonlat.lon) / res * 0.3);
				var dy	= Math.round((xy.y - this.lonlat.lat) / res * 0.3);
				icon.offset	= new OpenLayers.Pixel(-icon.size.w / 2, -icon.size.h / 2);
				div.appendChild(icon.draw(new OpenLayers.Pixel(dx, -dy)));
				icon.x0	= dx;
				icon.y0	= dy;
			}
		} else {// 如果多边形顶点数少于图标数
			var res		= AWP.map.resolution;
			var step	= Math.ceil(len / pLen);
			for (var i = 0; i < pLen; i++) {// polygon 首尾点重合
				var xy	= p[i], xy2 = p[i + 1];
				for (var j = 0; j < step; j++) {
					if (i * step + j >= len) {
						continue;
					}
					var icon	= this.icons[i * step + j];
					var xj = xy.x + (xy2.x - xy.x) * j / step;
					var yj = xy.y + (xy2.y - xy.y) * j / step;
					var dx	= Math.round((xj - this.lonlat.lon) / res * 0.3);
					var dy	= Math.round((yj - this.lonlat.lat) / res * 0.3);
					icon.offset	= new OpenLayers.Pixel(-icon.size.w / 2, -icon.size.h / 2);
					div.appendChild(icon.draw(new OpenLayers.Pixel(dx, -dy)));
					icon.x0	= dx;
					icon.y0	= dy;
				}
			}
		}
		
		// 求出图标距中心的最小与最大距离
		var maxDist = 0, minDist = 0;
		//var s = [this.basin_name];
		for (var i = 0; i < len; i++) {
			var icon	= this.icons[i];
			icon.a0	= Math.atan2(icon.y0, icon.x0);
			icon.d0	= Math.sqrt(Math.pow(icon.y0, 2) + Math.pow(icon.x0, 2));
			maxDist	= Math.max(maxDist, icon.d0);
			minDist	= minDist == 0 ? icon.d0 : Math.min(minDist, icon.d0);
			//s.push([maxDist, minDist, icon.d0, icon.a0, icon.px.x, icon.px.y])
		}//alert(s.join('\n'))
		for (var i = 0; i < len; i++) {
			var icon	= this.icons[i];
			icon.e0		= maxDist - minDist;
			icon.r0		= maxDist == minDist ? 1 : (icon.d0 - minDist) / (maxDist - minDist);
			icon.mind0	= minDist;
		}
		
		this.is_Drawn = true;
		return div;
	},
	isDrawn: function() {
		return this.is_Drawn;
	},
	moveTo: function (px) {
		this.div.style.left	= px.x + "px";
		this.div.style.top	= px.y + "px";
		// 不改变初始位置，只是移动图标
		//this.lonlat = this.map.getLonLatFromLayerPx(px);
		
		var len	= this.icons.length;
		var all_farawary = true;
		for (var i = 0; i < len; i++) {
			var icon1 = this.icons[i];
			var icon2 = this.icons[i == len - 1 ? 0 : i + 1];
			var d = Math.sqrt(Math.pow(icon1.px.x - icon2.px.x, 2) + Math.pow(icon1.px.y - icon2.px.y, 2));
			if (d < icon1.size.w * 0.8) {
				all_farawary = false;
			}
		}
		if (all_farawary && !this.all_farawary) {
			this.all_farawary = AWP.map.zoom;
		}
		
		var lastZoom = AWP.Layer.Markers.lastZoom;
		if ((lastZoom < AWP.map.zoom && !all_farawary)	// 放大时，并且没有散开
			|| (lastZoom > AWP.map.zoom && (!this.all_farawary || this.all_farawary > AWP.map.zoom))) {// 缩小时，并且
			var z = 1 + Math.max(0, AWP.map.zoom - (AWP.cfg.defaultZoomLevel || AWP.map.defaultZoomLevel));
			//s.push('\n');
			for (var i = 0; i < len; i++) {
				var icon = this.icons[i];
				icon.moveTo(new OpenLayers.Pixel(
					(icon.mind0 + icon.e0 * (z * 2 - 1) * icon.r0) * Math.cos(icon.a0),
					-(icon.mind0 + icon.e0 * (z * 2 - 1) * icon.r0) * Math.sin(icon.a0)
				));
			}
		}
		//alert(s.join('\n'))
	},
	display: function(display) {
		for (var i = 0, len = this.icons.length; i < len; i++) {
			this.icons[i].display(display);
		}
	},
	CLASS_NAME: 'AWP.Marker'
});

/**
 * 显示点击 indicator icon 后出现的 tab 窗口
 */
AWP.Marker.win = null;
AWP.Marker.showIndicator = function(data, e) {
	if (data.station) {
		return;
	}
	
	var id = data.id;
	var basin = data.basin;
	var indicator = data.indicator;
	var description = data.description;

	if (!AWP.Marker.win) {
		AWP.Marker.win = AWP.Marker.createIndicatorTabsWindow();
	}
	AWP.Marker.win.setTitle(description || (basin + ' - ' + indicator));
	
	AWP.Marker.win.show();
	AWP.Marker.win.mask.dom.style.backgroundColor = OpenLayers.Element.getStyle(document.body, 'background-color');

	if (!AWP.tabPanel) {
		AWP.tabPanel = AWP.Layer.TabPanel.SEAWA({
			renderTo: AWP.Marker.win.body.dom,
			height: AWP.Marker.win.body.getSize().height
		});

		AWP.Marker.win.on('hide', function() {
			if (this.items) {
	            this.items.each(function(item){
	                this.remove(item);
	            }, this);
	        }
		}, AWP.tabPanel);
	}
	
	var types = AWP.cfg.SEAWA_INDICATOR_ARTICLE_TYPES;
	var order = {0:0,1:1,3:3,4:4,2:2};
	for (var i in order) {
		if (data['article' + i] == '' && i != 2) continue;
		var tab_id = 'seawa-tabpanel-tab-indicator_' + id + '_' + i;
		var tab = AWP.tabPanel.getItem(tab_id);
		if (!tab) {
			tab = AWP.tabPanel.add({
				id: tab_id,
				title: types[i]
				//closable: true	// 2010-08-19 #82 需求
				/*,
                autoLoad: {
                	url: AWP.cfg.serviceURL,
                	params: 'action=AWP.showIndicatorArticle&article_id=' + data['article' + i]
                }*/
			});
			tab.show();
		}
		
		tab.body.update([
			'<iframe frameborder="0" width="100%" height="100%" src="index2.php?option=', AWP.cfg.SEAWA_COM,
			'&action=showIndicatorArticle&article_id=' + (data['article' + i] || 0),
			'&tab=', i, '&indicator_id=', id, '&width=', tab.getInnerWidth() - 50, '"></iframe>'
		].join(''));
	}
}
AWP.Marker.createIndicatorTabsWindow = function() {
	var size	= ML.getSize();
	var width	= size.width * 0.9;
	var height	= size.height * 0.9;
	
	AWP.Marker.win = new Ext.Window({
		layout		: 'fit',
		width		: width,
		height		: height,
		//bodyStyle: 'border: 1px solid red',
		closeAction	: 'hide',
		//plain: true,
		title		: 'Untitled',
		modal		: true
	});

	AWP.Marker.win.beforeShow = function() {
        delete this.el.lastXY;
        delete this.el.lastLT;
        if(this.x === undefined || this.y === undefined) {
            var xy = this.el.getAlignToXY(this.container, 'c-c');
            var pos = this.el.translatePoints(xy[0], xy[1]);
            this.x = this.x === undefined? pos.left : this.x;
            this.y = this.y === undefined? pos.top : this.y;
        }
		
        this.el.setLeftTop(this.x, this.y);

        if (this.expandOnShow){
            this.expand(false);
        }
		
        if(this.modal){
            Ext.getBody().addClass("x-body-masked");
            this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
            this.mask.fadeIn({endOpacity: 0.9, duration: 2});
        }
    }
	AWP.Marker.win.afterHide = function() {
		this.proxy.hide();
		if (this.monitorResize || this.modal || this.constrain || this.constrainHeader){
		    Ext.EventManager.removeResizeListener(this.onWindowResize, this);
		}
		if(this.modal){
		    this.mask.fadeOut();
		    Ext.getBody().removeClass("x-body-masked");
		}
		if(this.keyMap){
		    this.keyMap.disable();
		}
		this.fireEvent("hide", this);
	}
	
	return AWP.Marker.win;
}

AWP.Marker.showIndicatorArticleInLightBox = function(el, e) {
	new Event(e).stop();
	SqueezeBox.fromElement(el);

	var color = (function(element, style) {
        element = OpenLayers.Util.getElement(element);

        var value = null;
        if (element && element.style) {
            value = element.style[OpenLayers.String.camelize(style)];
            if (!value) {
                if (document.defaultView && document.defaultView.getComputedStyle) {
                    var css = document.defaultView.getComputedStyle(element, null);
                    value = css ? css.getPropertyValue(style) : null;
                } else if (element.currentStyle) {
                    value = element.currentStyle[OpenLayers.String.camelize(style)];
                }
            }

            var positions = ['left', 'top', 'right', 'bottom'];
            if (window.opera &&
                (OpenLayers.Util.indexOf(positions,style) != -1) &&
                (OpenLayers.Element.getStyle(element, 'position') == 'static')) {
                value = 'auto';
            }
        }

        return value == 'auto' ? null : value;
    })(document.body, 'background-color');
	document.getElementById('sbox-window').style.backgroundColor = color;
}
