
//Const
var Const = {
	maxStay: 28 * 24 * 3600 * 1000,
	gmapKeys: {
		'test.w853.com': 'ABQIAAAAfTtfM37EX9CX4lv9sriA-RS4miB5Xok1T0_v6tYwPL7kl2A1MRQOs5qIMcp9nEzxQRyhlQ9F3umn5w',
		'www.w853.com': 'ABQIAAAAfTtfM37EX9CX4lv9sriA-RS4miB5Xok1T0_v6tYwPL7kl2A1MRQOs5qIMcp9nEzxQRyhlQ9F3umn5w',
		'w853.com': 'ABQIAAAAN5_WCiDam8KLZ8AJvxJWVhS4miB5Xok1T0_v6tYwPL7kl2A1MRRoZ8-dpnPY3XpmEb6ShhRRlOVDfg',
		'00853.com': 'ABQIAAAAIiZq3QbvBl_irwNuobWziRR0wYT5M3tRvuvJ7qhIPslBMsvXEhTj5tw3DhUFGs4sSfNKdbykTT1aVQ',
		'www.00853.com': 'ABQIAAAAIiZq3QbvBl_irwNuobWziRS73_dsUVtjC1WepCdCdVGP0WDAbhT-zmyn2W1oE3dKm-ZYn5C9LHQNRw'
	}
};

//Components
var MadCat = function(fn){
	this.events = {};
	if(fn) fn.apply(this);
};
$extend(MadCat.prototype, {
	set: function(){},
	get: function(){ return null },
	evt: function(key, fn){ this.events[key] = fn },
	init: function(){}
});



var AMap = new MadCat(function(){
	var curr = '';
	var hash = {};
	var elImg, elMap, elJmp, elTitle, elTxt, elButton;
	var me = this;
	
	var btnCurrent;
	
	this.init = function(){
		if(!(elMap = $('m_hotmap'))){
			HotelView.hideAMap();
			return;
		}
		elImg = $('imgAMap');
		elJmp = $('divAMapJump');
		elJmp.$('dfn')[0].onclick = function(){me.showPop(null)};
		elTitle = elJmp.$('strong')[0];
		elTxt = elJmp.$('p')[0];
		elButton = elJmp.$('a')[0];
		
		btnCurrent = $('spanCurrentArea');
		
		for(var i = 0, a = elMap.$('area'); i < a.length; i ++) hash[a[i].getAttribute('_zone_id')] = a[i];
		elButton.onclick = function(){
			var obj = curr ? {zoneId: curr, locationId: ''} : {};
			me.showPop(null);
			me.events.click(obj);
			return false
		};
		me.showPop(null);
	};
	this.set = function(query, result){
		if(HotelView.get() != 'area') return;
		HotelView.updateTip();
	};
	this.get = function(){
		return curr;
	};
	this.events.click = function(obj){
		if(MadCat.debug) alert('AMap click: ' + $toJson(obj));
	};
	this.showPop = function(el, name, txt){
		if(!elMap) return;
		if(!el){
			if(curr){
				setJmpPos([-1000, -1000]);
				curr = '';
			}
		}else{
			if(HotelView.get() != 'area'){
				window.HotelQuery.viewType = 'area';
				window.HotelView.set(HotelQuery);
			}
			if(document.documentElement.scrollTop > 250) document.documentElement.scrollTop = 170;
			elTitle.innerHTML = name;
			elTxt.innerHTML = txt;
			elButton.innerHTML = $s2t('查询@酒店').replace('@', name);
			setJmpPos(getAreaCenter(el));
			curr = el.getAttribute('_zone_id');
		}
		return false;
	};
	this.clickArea = function(id){
		hash[id].onclick();
	};
	
	this.getTipInfo = function(){
		var query = window.HotelQuery;
		var txt = c_data.zoneName[query.zoneId] || c_data.locationName[query.locationId];
		return txt ? {checked: true, text: txt + '酒店列表', fn: function(){me.events.click({});}} : {checked: false, text: '点击各区域板块显示该区域的商区信息', fn: null};
	};
	function getAreaCenter(el){
		var a = el.getAttribute('coords').match(/\d+/g);
		a.length = a.length >> 1 << 1;
		var x = 0, y = 0;
		for(var i = 0; i < a.length; i += 2){
			x += parseInt(a[i]);
			y += parseInt(a[i + 1]);
		}
		return [(x / a.length) << 1, (y / a.length) << 1];
	}
	function setJmpPos(p){
		var t = elImg.$getPos();
		//edit by cdchu
		var s = $$.browser.IE?[0,0]:[elImg.$parentNode().scrollLeft,elImg.$parentNode().scrollTop];
		elJmp.style.display = 'block';
		elJmp.style.left = p[0] - s[0] + t[0] - (elJmp.offsetWidth >> 1) + 20  + 'px';
		elJmp.style.top = p[1] - s[1] + t[1] - elJmp.offsetHeight - 5  + 'px';
	}
});
var EMap = new MadCat(function(){
	var me = this, map = {},
		markers = this.markers = [],
		mapPreciseSch = null,
		mapSearchBtn = null;
		
	this.Event = {
		X: function(e){
			return (e.clientX + (___.scrollLeft || __.body.scrollLeft)) || pageX;
		},
		Y: function(e){
			return (e.clientY + (___.scrollTop || __.body.scrollTop)) || pageY;
		},
		offsetX: function(e){
			return typeof e.offsetX=='undefined' ? e.layerX : e.offsetX;
		},
		offsetY: function(e){
			return typeof e.offsetY=='undefined' ? e.layerY : e.offsetY;
		},
		add: function(obj, evtType, fn, useCapture){
			var capture = useCapture || false;
			if (obj.attachEvent) {
				obj.attachEvent('on'+evtType, fn);
				if (capture && obj.nodeType != 9) obj.setCapture();
			} else obj.addEventListener(evtType, fn, capture);
		},
		remove: function(obj, evtType, fn, useCapture){
			var capture = useCapture || false;
			if (obj.detachEvent){
				obj.detachEvent('on'+evtType, fn);
				if (capture && obj.nodeType != 9) obj.releaseCapture();
			} else obj.removeEventListener(evtType, fn, capture);
		}
	};
	//create default icon
	this.getIcon = function(){
		var baseIcon = new GIcon();
		baseIcon.shadow = "http://pic.ctrip.com/hotels081118/marker_shadow.png";
		baseIcon.iconSize = new GSize(17, 17);
		baseIcon.shadowSize = new GSize(34, 20);
		baseIcon.iconAnchor = new GPoint(20, 17) //new GPoint(9, 17);
		baseIcon.infoWindowAnchor = new GPoint(9, 9);
		//baseIcon.infoShadowAnchor = new GPoint(18, 25);
		return baseIcon;
	};
	
	//create map control
	this.createControl = function(position, initFn, offsetX, offsetY){
		var pos = {
			'lt': G_ANCHOR_TOP_LEFT,
			'lb': G_ANCHOR_BOTTOM_LEFT,
			'rt': G_ANCHOR_TOP_RIGHT,
			'rb': G_ANCHOR_BOTTOM_RIGHT
		}, control = function(){};
		control.prototype = new GControl();
		control.prototype.initialize = initFn;
		control.prototype.getDefaultPosition = function(){
			return new GControlPosition(pos[position], new GSize(offsetX || 7, offsetY || 7));
		}
		return control;
	};
	//create hotel marker
	this.createMarker = function(latlng, index, hotelIndex){
		if (!latlng) return;
		var hotelIcon = new GIcon(this.getIcon());
		hotelIcon.image = "http://pic.ctrip.com/hotels081118/marker" + index  + ".png";
		var marker = new GMarker(latlng, { icon:hotelIcon });
		marker.id = hotelIndex;
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(HotelList.hotels[marker.id].toString('map'));
			setTimeout(idGmPop, 2000);
		});
		return marker;
	};
	
	this.refresh = function(){
		var localResult = $('localResult'),
			localSearch = $('localSearch'),
			resultTip = $('resultTip'),
			btnBack = $('btnBack');
		var ls = this.localSearch,
			dotX = HotelQuery.dotX,
			dotY = HotelQuery.dotY;
		if ((!dotX || !dotY) && ls && me.dotMkr) {
			me.dotMkr.hide();
			me.dotMkr = null;
			if (mapPreciseSch.status) mapPreciseSch.click();
		}
		map.closeInfoWindow();
		var zoomLevel = HotelQuery.zoomLevel,
			x = HotelQuery.mapCenterX,
			y = HotelQuery.mapCenterY,
			mapIndex = 0,
			lats = [], lngs = [];
		markers.each(function(el){el.hide()});
		for (var i = 0; i < HotelList.hotels.length; i++) {
			var hotel = HotelList.hotels[i];
			if (!hotel.position) continue;
			var mkr = markers[mapIndex],
				pos = hotel.position.split('|'),
				latlng = new GLatLng(pos[0], pos[1]);
			lats.push(pos[0]);
			lngs.push(pos[1]);
			if (mkr && hotel && pos) {
				mkr.setLatLng(latlng);
				mkr.id = i;
				if (mkr.isHidden()) mkr.show();
			} else {
				var newMkr = me.createMarker(latlng, mapIndex, i);
				if (newMkr) {
					markers.push(newMkr);
					// delay add marker wait map setCenter
					(function(map, newMkr){
						setTimeout(function(){
							map.addOverlay(newMkr);
						}, 100);
					})(map, newMkr);
				}
			}
			mapIndex++;
		}
		if (dotX && dotY) {
			var latlng = new GLatLng(dotX, dotY);
			if (me.dotMkr) {
				me.dotMkr.hide();
				me.dotMkr = null;
			}
			me.dotMkr = new GMarker(latlng, { title: HotelQuery.keyword});
			setTimeout(function(){map.addOverlay(me.dotMkr);}, 100);
			lats.push(dotX);
			lngs.push(dotY);
		}
		if (HotelResult.hotelFound) {
			var maxLat = Math.max.apply(null, lats),
				maxLng = Math.max.apply(null, lngs),
				minLat = Math.min.apply(null, lats),
				minLng = Math.min.apply(null, lngs),
				lat = minLat + (maxLat - minLat) / 2,
				lng = minLng + (maxLng - minLng) / 2,
				bounds = new GLatLngBounds(new GLatLng(minLat, minLng), new GLatLng(maxLat, maxLng));
			map.setCenter(new GLatLng(lat, lng), map.getBoundsZoomLevel(bounds));
		} else {
			if (HotelQuery.dotX && HotelQuery.dotY)
				map.setCenter(new GLatLng(HotelQuery.dotX, HotelQuery.dotY), 13);
			else map.setCenter(new GLatLng(HotelQuery.mapCenterX, HotelQuery.mapCenterY), HotelQuery.zoomLevel);
		}
		if (this.localSearch) this.localSearch.markers.each(function(el){ el.hide(); });
		
//				localResult = $('localResult'),
//				localSearch = $('localSearch'),
//				btnBack = $('btnBack'),
		localResult.innerHTML = '';
		localResult.style.display = "none";
		btnBack.style.display = "none";
		resultTip.style.display = "none";
		localSearch.style.display = '';

		if(this.toPop == 0 || this.toPop){
			if(HotelView.get() == 'emap'){
				GEvent.trigger(markers[this.toPop], 'click');
			}
			this.toPop = null;
		}
	};
	this.showPop = function(hotelIndex/* or hotel name [, hotel latlng]*/){
		var args = arguments, name, latlng, pos;
		if (args[1]) {
			name = $s2t(args[0]);
			pos = args[1];
		} else {
			var htl = HotelList.hotels[hotelIndex];
			name = $s2t(htl.name);
			latlng = htl.position.split('|');
		}
		this.getMap(function(){
			if (!pos)  pos = new GLatLng(latlng[0], latlng[1]);
			maskShow($('popMapContainer'));
			var mtgt = $('mtgt_unnamed_0');
			if (!me.popMap) {
				me.popMap = new GMap2($('pop_map'));
				me.popMap.setCenter(pos, 13);
				me.popMap.addControl(new GLargeMapControl());
				var icon = me.getIcon();
				icon.shadow = '';
				icon.iconSize = new GSize(19, 27);
				icon.shadowSize = new GSize(37, 34);
				icon.image = 'http://pic.ctrip.com/hotels081118/hotel_pointer.png';
				me.popMap.marker = new GMarker(pos, { icon: icon });
				me.popMap.addOverlay(me.popMap.marker);
				me.popMap.addControl(new (me.createControl('rt', function(){
					var btn = $c('a');
					btn.className = 'searchresult_popclose';
					btn.title = $s2t('关闭弹出地图');
					me.popMap.getContainer().appendChild(btn);
					btn.onmouseover = function(){ this.style.cursor = 'pointer'; };
					btn.onclick = function(){ maskShow();if(document.getElementById("show")!=null){document.getElementById("show").style.display="none"; }};
					return btn;
				})));
				me.popMap.label = new me.Rect(pos, name);
				me.popMap.addOverlay(me.popMap.label);
				//me..addOverlay(new me.Rect(pos, 'lsdjflksdjf'));
			} else {
				me.popMap.setCenter(pos, 13);
				me.popMap.label.reset(pos, name);
				me.popMap.marker.setLatLng(pos);
			}
		});
	};

	function idGmPop(){
		var img = document.$g('div.searchresult_abbrpic');
		if(!img) return;
		img[0].id = 'gm_pop_img'
		var el = img[0].parentNode;
		while(el && el.tagName != 'DIV') el = el.parentNode;
		if(!el) return;
		el = window.$(el);
		tit = el.$('h3');
		if(!tit) return;
		tit[0].id = 'gm_pop_tit';
		btn = el.$('input');
		if(!btn) return;
		for(var i =0; i < btn.length; i ++) if(!btn[i].id) btn[i].id = 'gm_pop_btn_' + i;
		for(var i = 0; i < 3; i ++) if(el) el = el.parentNode;
		if(!el) return;
		img = window.$(el).$('img');
		if(!img || img.length < 2) return;
		img[0].id = 'gm_pop_close';
	}
	
	// create marker label overlay
	this.createOverlay = function(){
		function Rect(latlng, txt){
			this.latlng = latlng;
			this.name = txt;
		};
		Rect.prototype = new GOverlay();
		Rect.prototype.initialize = function(map){
			var div = $c('div');
			div.className = 'searchresult_popname';
			div.innerHTML = this.name;
			div.style.width = this.name.replace(/[a-zA-Z0-9\(\)\s]{2}/g, 'a').length * 13 + 'px';
			div.style.marginTop = '-15px';
			div.style.textAlign = 'center';
			map.getPane(G_MAP_MAP_PANE).appendChild(div);
			this.map = map;
			this.div = div;
		};
		Rect.prototype.remove = function(){
			this.div.parentNode.removeChild(this.div);
		};
		Rect.prototype.copy = function(){
			return new Rect(this.latlng, this.name);
		};
		Rect.prototype.redraw = function(force){
			if (!force) return;
			var pos = this.map.fromLatLngToDivPixel(this.latlng);
			this.div.style.top = pos.y + 'px';
			this.div.style.left = pos.x + 'px';
		};
		Rect.prototype.reset = function(pos, txt){
			var pos = this.map.fromLatLngToDivPixel(pos);
			this.div.style.top = pos.y + 'px';
			this.div.style.left = pos.x + 'px';
			this.div.style.width = txt.replace(/[a-zA-Z0-9\(\)\s]{2}/g, 'a').length * 13 + 'px';
			this.div.innerHTML = txt;
		};
		return Rect;
	};
	
	this.pop = function(hotelIndex){
		EMap.toPop = hotelIndex;
		HotelView.set({viewType:'emap'});
		if(document.documentElement.scrollTop > 250) document.documentElement.scrollTop = 170;
	};
	
	this.getKey = function(){
		var keys = Const.gmapKeys,
			key = document.domain.match(/prototype\.(\w+)\.sh/);
		if (key) key = keys[key[1]];
		if (!key) key = keys[document.domain] || keys.online;
		return key;
	};

	this.set = function(query, result){
		var mapstate = "";
		if(HotelView.get() == 'emap'){
			if(!this.state){
				this.init(query, result);
			}else{
				if(this.state == 'ok'){
					var _this = this;
					setTimeout(function(){
						_this.refresh();
					}, 10);
				}
			}
			if(HotelQuery.dotX){
				mapstate = "dot";
			}else if(HotelQuery.coordinateX1){
				mapstate = "rec";
			}
			
			this.tipChecked = true;
			
			if(!mapstate) this.tipChecked = false;
			else if(mapstate&&mapstate == "rec") this.tipText = "框选搜索结果";
			else if(mapstate&&mapstate == "dot") this.tipText = "所选酒店范围:"+HotelQuery.keyword+"周围"+HotelQuery.radius+"公里";
			
			HotelView.updateTip();
		}
	};
	
	this.getTipInfo = function(){
		if(!HotelQuery.coordinateX1) this.tipChecked = false;
		return {
			checked: this.tipChecked,
			text: this.tipChecked ? this.tipText : '',
			fn: this.tipChecked ? onTipClick: null
		}
	};

	this.getMap = function(callback){
		if (me.isLoaded) return callback();
		this.key = this.getKey();
		$loadJs('http://ditu.google.cn/maps?file=googleapi&key='+this.key+'&v=2&async=2&hl=zh_cn', 'utf-8', function(){
			var timer = setInterval(function(){
				if (typeof GMap2 == 'undefined') return;
				clearInterval(timer);
				if (GBrowserIsCompatible()) {
					me.Rect = me.createOverlay();
					callback();
					me.isLoaded = true;
				}
				else me.state = 'failure';
			}, 20);
		})
	};
	
	// local search
	this.initLocalSearch = function(){
		if (!this.isInitLocalSearch) {
			var btnBackclickhandler = function(){
				localResult.style.display = "none";
				btnBack.style.display = "none";
				resultTip.style.display = "none";
				localSearch.style.display = "";
			}
			var me = this,
				ls = me.localSearch = new google.search.LocalSearch(), sHtml = [],
				noResult = $('noResult'),
				localResult = $('localResult'),
				localSearch = $('localSearch'),
				resultTip = $('resultTip'),
				btnBack = $('btnBack'),
				distancePerLatitude = 2 * Math.PI * 6378.137 / 360; // unit is kilometer
			ls.markers = [];
			ls.schBtn = $('schBtn');
			ls.words = $('nearbyhotel');
			ls.words.onkeydown = function(e){
				var e = $fixE(e);
				if (e.keyCode == 13) {
					ls.schBtn.click();
					return false;
				}
			};
			ls.words.onfocus = function(){
				noResult.style.display = 'none';
			};
			ls.setCenterPoint(me.map);
			ls.setResultSetSize(GSearch.LARGE_RESULTSET);
			me.post = function(res){
				var lat = res.lat, lng = res.lng,
					distance = $('rSel').value,
					deltaLatitude = distance / distancePerLatitude,
					distancePerLongitude = distancePerLatitude * Math.cos(lat),
					deltaLongitude = distance / distancePerLongitude;
				me.events.localsearch({
					dotX: lat,
					dotY: lng,
					radius: distance,
					keyword: res.titleNoFormatting,
					coordinateX1: lat - deltaLatitude,
					coordinateY1: lng - deltaLongitude,
					coordinateX2: lat - (-deltaLatitude),
					coordinateY2: lng - (-deltaLongitude)
				});
				mapPreciseSch.click();
			}
			ls.setSearchCompleteCallback(null, function(){
				var res = ls.results, resLen = res.length;
				if (resLen) {
					noResult.style.display="none";
					var	title = res[0].titleNoFormatting, keyWord = ls.words.value;
					if (resLen == 1 || title == keyWord || title == HotelQuery.cityName + keyWord || title == HotelQuery.cityName + '市' + keyWord) {
						me.post(res[0]);
						return;
					}
					// 8 markers
					ls.markers.each(function(el){ el.hide(); });
					for (var n = 0; n < resLen; n++) {
						var latlng = new GLatLng(res[n].lat, res[n].lng),
							mkr = ls.markers[n];
						sHtml.push('<a href="javascript:EMap.post(EMap.localSearch.results['+n+'])" title = "' + res[n].titleNoFormatting + '" class="searchresult_pinlink'+(n+1)+'" cdm="btn_li">' + res[n].title + '</a>');
						if (mkr) {
							mkr.setLatLng(latlng);
							if (mkr.isHidden()) mkr.show();
						} else {
							var icon = me.getIcon(),
								letter = String.fromCharCode('A'.charCodeAt(0) + n);
							icon.iconSize = new GSize(20, 20);
							icon.shadowSize = new GSize(37, 25);
							//baseIcon.iconAnchor = new GPoint(20, 17) //new GPoint(9, 17);
							icon.image = 'http://pic.ctrip.com/hotels081118/marker' + letter + '.png';
							var nMkr = new GMarker(latlng, {icon: icon});
							ls.markers.push(nMkr);
							me.map.addOverlay(nMkr);
						}
					}
					localResult.innerHTML = '<li>' + sHtml.join('</li><li>') + '</li>';
					localResult.style.display = '';
					btnBack.style.display = '';
					resultTip.style.display = '';
					resultTip.innerHTML = $s2t('您所搜索的关键字共有'+resLen+'个结果');
					localSearch.style.display = 'none';
					btnBack.onclick = btnBackclickhandler;
					sHtml.length = 0;
				} else {
					noResult.style.display = '';
					localResult.innerHTML = '';
					localResult.style.display = 'none';
				}
			});
			ls.schBtn.onclick = function(){
				if (ls.words.isNull()) {
					$alert(ls.words, $s2t('请输入关键字'), false, 'lb', 'lt');
					return false;
				}
				ls.execute((new RegExp(HotelQuery.cityName)).test(ls.words.value)?ls.words.value:(HotelQuery.cityName+ls.words.value));
			};
			me.isInitLocalSearch = true;
		}
		if(!ishidden(this.localSearch.words)){
			this.localSearch.words.focus();
		}
	};

	this.init = function(query, result){
		mapPreciseSch = $('mapPreciseSch');
		mapSearchBtn = $('mapSearchBtn');
		
		if(HotelView.get() != 'emap') return;
		this.state = 'init';
		this.getMap(function(){
			map = me.map = new GMap2($('htl_map'));
			//map.disableDoubleClickZoom();
			map.addControl(new GLargeMapControl());
			me.refresh();
			var c = map.getCenter();
			HotelQuery.mapCenterX = c.lat();
			HotelQuery.mapCenterY = c.lng();
			HotelQuery.zoomLevel = map.getZoom();
			me.state = 'ok';
			/* get latlng by city name
			new GClientGeocoder().getLatLng(query.cityName, function(c){
				map.setCenter(c, 11);
				me.refresh();
				me.state = 'ok';
			});*/
			
			var rect = $('rect'),
				bottomMask = $('bottomMask'),
				topMask = $('topMask'),
				mapSearchBox = $('mapSearchBox'),
				normalMap = $('normalMap'),
				satelliteMap = $('satelliteMap'),
				closeBtn = $('closeBtn'), rSel = $('rSel'),
				noResult = $('noResult'),
				x0, y0, x1, y1,
				cx0, cy0, cx1, cy1;
			mapSearchBtn.onclick = function(){
				map.closeInfoWindow();
				if (this.status) {
					bottomMask.style.display = topMask.style.display = 'none';
					this.className = 'searchresult_searchbtn';
					this.status = false;
				} else {
					this.className = 'searchresult_searchbtn_on';
					mapPreciseSch.className = 'searchresult_searchbtn3';
					mapPreciseSch.status = false;
					mapSearchBox.style.display = 'none';
					rSel.style.display = 'none';
					noResult.style.display = 'none';
					bottomMask.style.display = topMask.style.display = 'block';
					/*
					if (me.isInitLocalSearch && me.localSearch.markers.length) {
						me.localSearch.markers.each(function(el){el.hide();});
					}*/
					this.status = true;
				}
			};
			// switch map type button
			normalMap.onclick = function(){
				if (!this.status) {
					map.setMapType(G_NORMAL_MAP);
					satelliteMap.className = 'searchresult_searchbtn2';
					satelliteMap.status = false;
					this.className = 'searchresult_searchbtn2_on';
					this.status = true;
				}
			};
			satelliteMap.onclick = function(){
				if (!this.status) {
					map.setMapType(G_HYBRID_MAP);
					normalMap.className = 'searchresult_searchbtn2';
					normalMap.status = false;
					this.className = 'searchresult_searchbtn2_on';
					this.status = true;
				}
			};

			// precise search button
			mapPreciseSch.onclick = function(){
				map.closeInfoWindow();
				if (this.status) {
					this.className = 'searchresult_searchbtn3';
					mapSearchBox.style.display = 'none';
					rSel.style.display = 'none';
					this.status = false;
				} else {
					this.className = 'searchresult_searchbtn3_on';
					bottomMask.style.display = topMask.style.display = 'none';
					mapSearchBox.style.display = '';
					rSel.style.display = '';
					mapSearchBtn.className = 'searchresult_searchbtn';
					mapSearchBtn.status = false;
					this.status = true;
					me.initLocalSearch();
				}
			};
			closeBtn.onclick = function(){
				mapPreciseSch.click();
				rSel.style.display = 'none';
				noResult.style.display = 'none';
			};
			
			setOpacity(bottomMask, 0.3);
			setOpacity(topMask, 0);
			me.Event.add(topMask, 'mousedown', function(e){
				var e = $fixE(e),
					btn = e.button || e.which;
				if (btn != 1) return false;
				topMask.style.cursor = 'crosshair';
				x0 = me.Event.offsetX(e);
				y0 = me.Event.offsetY(e);
				cx0 = me.Event.X(e);
				cy0 = me.Event.Y(e);
				rect.style.left = x0 + 'px';
				rect.style.top = y0 + 'px';
				rect.style.width = 0;
				rect.style.height = 0;
				rect.style.display = 'block';
				if (e.preventDefault) e.preventDefault();
				else e.returnValue = false;
				function move(e){
					var e = $fixE(e),
						el = e.$target;
					x1 = me.Event.offsetX(e);
					y1 = me.Event.offsetY(e);
					cx1 = me.Event.X(e);
					cy1 = me.Event.Y(e);
					if (el == topMask) {
						rect.style.left = Math.min(x0, x1+1) + 'px';
						rect.style.top = Math.min(y0, y1+1) + 'px';
						rect.style.width = Math.abs(Math.abs(x1-x0)-2) + 'px';
						rect.style.height = Math.abs(Math.abs(y1-y0)-2) + 'px';
					}
				}
				me.Event.add(topMask, 'mousemove', move, true);
				function up(e){
					rect.style.display = 'none';
					if (e.stopPropagation) e.stopPropagation();
					else e.cancelBubble = true;
					topMask.style.display = 'none';
					bottomMask.style.display = 'none';
					topMask.style.cursor = 'normal';
					me.Event.remove(topMask, 'mousemove', move, true);
					me.Event.remove(topMask, 'mouseup', up);
					me.Event.remove(__, 'mouseup', up);
					mapSearchBtn.click();
					var e = $fixE(e),
						w = rect.style.width.toInt(),
						h = rect.style.height.toInt(),
						x2 = x0 + (cx1<cx0?-w:w),
						y2 = y0 + (cy1<cy0?-h:h),
						container = map.getContainer(),
						mapWidth = container.offsetWidth,
						mapHeight = container.offsetHeight;
					if (x2 == x0 && y2 == y0) return false;
					var latlng0 = map.fromContainerPixelToLatLng(new GPoint(x0, y0)),
						latlng2 = map.fromContainerPixelToLatLng(new GPoint(x2, y2)),
						zoomRate = Math.floor(((w/h)>(mapWidth/mapHeight)?(mapWidth/w):(mapHeight/h))/2);
					x0 = latlng0.lat();
					y0 = latlng0.lng();
					x2 = latlng2.lat();
					y2 = latlng2.lng();
					var scale = map.getZoom() + zoomRate;
					if (scale>17) scale = 17;
					var center = map.getCenter();
					QueryEngine.record({
						mapCenterX: center.lat(),
						mapCenterY: center.lng(),
						zoomLevel: map.getZoom()
					});
					me.events.mouseup({
						coordinateX1: Math.min(x0, x2),
						coordinateY1: Math.min(y0, y2),
						coordinateX2: Math.max(x0, x2),
						coordinateY2: Math.max(y0, y2),
						mapCenterX: x0+(x2-x0)/2,
						mapCenterY: y0+(y2-y0)/2,
						zoomLevel: scale
					});
				}
				me.Event.add(topMask, 'mouseup', up);
				me.Event.add(__, 'mouseup', up);
			})
		});
		// add title to marker
		___.onmouseover = function(e){
			var e = $fixE(e),
				el = e.$target,
				src = el.src,
				index = src?src.match(/marker(\d+)\.png/):null;
			if (el.tagName == 'IMG' && src && index) {
				el.title = el.alt = HotelList.hotels[EMap.markers[index[1]].id].name;
			}
			index = src ? src.match(/marker([A-H])\.png/) : null;
			if (el.tagName == 'IMG' && src && index) {
				el.title = el.alt = EMap.localSearch.results[index[1].charCodeAt(0) - 65].titleNoFormatting;
			}
		};
	};
	this.events.mouseup = function(obj){
		if(MadCat.debug) alert('EMap mouseup: ' + $toJson(obj));
	};
	function setOpacity(obj, alpha){
		if ($$.browser.IE) obj.style.filter = 'alpha(opacity=' + alpha * 100 + ')';
		else obj.style.opacity = alpha;
	}
	function onTipClick(){
		if (mapPreciseSch.status) mapPreciseSch.click();
		if (mapSearchBtn.status) mapSearchBtn.click();
		me.events.mouseup({});
	}
});

