	//*********************************************************************************
	//*****************************  Global Functions  ********************************
	//*********************************************************************************
	var bInitialized = false;
	var FLAG_NORMAL = 0;
	var FLAG_Latest = 1;
	var FLAG_MostRead = 2;
	var FLAG_SEARCH = 3;
	var FLAG_Highlight = 4;
	var FLAG_FILTER = 5;
	var query_flag;
	var cookies_attr = {days:30, path:'/'};
	var iframe;

	/*handsome*/
	var broadcast_data = [];
	var broadcast_markers = [];
	broadcast_index = 0;
	var broadcast_marker;
	broadcastIntervalId = 0;

	function addSlashes(str) {
		return str.replace(/([^a-zA-Z0-9])/g, '\\$1');
	}

	var addScene_flag = 0;
	function addScene(flag) {
		if (!iframe.contentWindow.location.toString().match(addSlashes(tagala.config.newPostUrl)))
		{
			iframe_navigate(tagala.config.newPostUrl);
			addScene_flag = 1;
		}
		else
		{
			if (!flag) getMapPosition();
			with (iframe.contentWindow)
			{
				$('start_date').value = querytime();
			}
		}
	}

	function addPath() {
		addScene('Path');
		_createPgLine([]);
	}

	function addArea() {
		addScene('Area');
		_createPgGon([])
	}

	function Logon() {
		iframe_navigate(tagala.config.blog_url + 'admin.php');
	}

	var logonNode = new Element('a', {href:'javascript: Logon();'});
	logonNode.appendLocale('login', 'strong');

	function Logout() {
		iframe_navigate(tagala.config.blog_url + 'admin.php?op=blogSelect&blogId=' + $F('session_id') + '&action=Logout');
		updateLoginStatus('');
	}

	function updateLoginStatus(blogId)
	{
		if (blogId) $('session_id').value = blogId;
		blogId = $F('session_id');
		if (blogId.empty())
			$('message').update().appendA('javascript: Logon();').appendLocale('login', 'strong').toLocale();
		else
			$('message').update().appendA('javascript: Logout();').appendLocale('logout', 'strong').toLocale();
	}

	function Home() {
		dest_url = '';
		iframe_navigate(tagala.config.blogPageUrl);

		// add by connie, 20080520
		hideMyNearby();
		if (mapid) hideMyMap(mapid);
	}

	var resizeTimerID = null;
	function onResizeWin() {
		if (resizeTimerID == null) {
			resizeTimerID = (function() {
				resizeTimerID = null;
				map.checkResize();
				centerTheMap();
			}).delay(500);
		}
	}

	function opacity(id, opacStart, opacEnd, seconds) {
		var steps, delta, stepsPerSec = 10; // Steps per second
		if (delta = (opacEnd - opacStart) / (steps = seconds * stepsPerSec)) $R(1, steps).collect(function (i)
		{
			return {seconds:i / stepsPerSec, opacity:(opacStart + delta * i)};
		}).each(function (item)
		{
			Element.setOpacity.delay(item.seconds, $(id), item.opacity);
		});
	}

	function shiftOpacity(id, sec) {
		//if an element is invisible, make it visible, else make it ivisible
		if($(id).style.opacity == 0) {
			opacity(id, 0, 1, sec);
		} else {
			opacity(id, 1, 0, sec);
		}
	}

	var opacityTimerID = null;
	function showStaticLink() {
		if (!$('static_link_menu').visible()) {
			$('static_link_text').value = buildStaticLink();
			$('static_link_text').select();
			copy($('static_link_text'));
			$('static_link').update().appendLocale('link_copied', 'font', {color:'orange'}).toLocale();
			if (opacityTimerID == null)
				opacityTimerID = function() {
					opacityTimerID = null;
					opacity('static_link_menu', 0.9, 0, 1);
					(function() {
						showStaticLink();
						$('static_link_menu').setOpacity(0.9);
					}).delay(1);
				}.delay(5);
		} else {
			if (opacityTimerID != null)
			{
				window.clearTimeout(opacityTimerID);
				delete opacityTimerID;
				opacityTimerID = null;
			}
			$('static_link_text').value = '';
			$('static_link').update().appendLocale('static_link').toLocale();
		}
		$('static_link_menu').toggle();
	}

	function buildStaticLink(url) {
		var linkUrl = tagala.config.dst_url + tagala.config.site_url + 'index.php?';
		if (!map) return;
		linkUrl += 'mapY=' + (map.getCenter().lat()*1000000).round()/1000000 + '&mapX=' + (map.getCenter().lng()*1000000).round()/1000000 + '&zoom=' + map.getZoom();
		linkUrl += '&dt=' + querytime() + '&dt_mode=' + querymode();
		if (iframe.contentWindow.location.toString().match(tagala.config.searchUrl))
			linkUrl += '&search=1&' + searchCriteria;
		else if (iframe.contentWindow.location.toString().match(tagala.config.blogPageUrl))
			linkUrl += '&view=' + escape(url ||
			iframe.contentWindow.tagala.history.get() ||
			tagala.config.dst_url + tagala.config.blog_url + 'ajax.php?op=Summary');
		else
			linkUrl += '&redirecturl=' + escape(iframe.contentWindow.location.toString());
		return linkUrl;
	}

	function copy(elem) {
		if (elem.createTextRange) {
			var range = elem.createTextRange();
			if (range)
				range.execCommand('Copy');
		} else {
			var flashcopier = 'flashcopier';
			if(!$(flashcopier)) {
				var divholder = $(document.body).appendDiv(flashcopier);
			}
			$(flashcopier).update().appendTag('embed',
			{
				src:'_clipboard.swf',
				FlashVars:'clipboard=' + encodeURIComponent(elem.value),
				width:0,
				height:0,
				type:'application/x-shockwave-flash'
			});
		}
	}


	//*********************************************************************************
	//*****************************  Time & Timeline Control  *************************
	//*********************************************************************************
	function __setInterval(calendar) {
		var val = calendar.date.getFullYear() + '-' + (calendar.date.getMonth()+1) + '-' + calendar.date.getDate();
		switch (calendar.params.inputField)
		{
			case $('qstartdate'):
				_setIntervalLeft(val);
				break;
			case $('qenddate'):
				_setIntervalRight(val);
				break;
			default:
		}
	}

	function checkData(ssDate) {
		queryData('startdate='+ssDate+'&enddate='+ssDate, FLAG_NORMAL);
	}

	function genXML() {
		//Clear XML first
		_clearXml();

		var startDate = '';
		var endDate = '';
		if (timeMovie().flash_querytimeInterval && /([0-9]+\/[0-9]+\/[0-9]+)\/([0-9]+\/[0-9]+\/[0-9]+)/.test(querytimeInterval()))
		{
			startDate = RegExp.$1;
			endDate   = RegExp.$2;
		}

		var boundCrteria = '';
		if (map)
		{
			var bounds = map.getBounds();
			var lngL = bounds.getSouthWest().lng();
			var lngR = bounds.getNorthEast().lng();
			var latB = bounds.getSouthWest().lat();
			var latT = bounds.getNorthEast().lat();
			var leftTopLng     = (lngL * 1000000).round()/1000000;
			var rightBottomLng = (lngR * 1000000).round()/1000000;
			var rightBottomLat = (latB * 1000000).round()/1000000;
			var leftTopLat     = (latT * 1000000).round()/1000000;
			boundCrteria = '&leftUp_latitude=' + leftTopLat + '&leftUp_longitude=' + leftTopLng + '&rightDown_latitude=' + rightBottomLat + '&rightDown_longitude=' + rightBottomLng;
		}

		//allOrMostReadOrLatest, 1 for MostRead, 2 for Latest, 3 for Latest without MostRead, 4 for Random
		var urlXMLMostRead = tagala.config.blog_url + 'index.php?op=MultiSearch' + boundCrteria + '&startTime=' + startDate + '&endTime=' + endDate + '&allOrMostReadOrLatest=1&maxPosts=' + tagala.config.maxPosts;
		new Ajax.Request(urlXMLMostRead,
		{
			evalJS:false,
			method:'get',
			onSuccess:genXMLMostReadResponse
		});

		var urlXMLLatest = tagala.config.blog_url + 'index.php?op=MultiSearch' + boundCrteria + '&startTime=' + startDate + '&endTime=' + endDate + '&allOrMostReadOrLatest=3&maxPosts=' + tagala.config.maxPosts;
		new Ajax.Request(urlXMLLatest,
		{
			evalJS:false,
			method:'get',
			onSuccess:genXMLLatestResponse
		});

		/*handsome*/
		var urlXMLBroadcast = tagala.config.blog_url + 'index.php?op=displayBroadcast' + boundCrteria + '&nowTime=' + querytime() + '&maxBroadcasts=200';
		new Ajax.Request(urlXMLBroadcast,
		{
			evalJS:false,
			method:'get',
			onSuccess:genXMLBroadcastResponse
		});
	}

	/*handsome*/
	function genXMLBroadcastResponse(response) {
		var json = response.responseJSON;
		if (json && json.broadcasts) {
			packXMLwithoutRank(json);
		}
	}

	function packXMLwithoutRank(json) {
		if (broadcast_marker != null)
			map.removeOverlay(broadcast_marker);
		var broadcast_content;
		broadcast_data = [];
		broadcast_markers = [];
		broadcast_index = Math.floor(Math.random()*json.broadcasts.length);
		var xmlStr = '<?xml version="1.0" encoding="utf-8" ?><data>';
		for (var i=0;i<json.broadcasts.length;i++) {
			broadcast_content = json.broadcasts[i].post_content.replace(/\[(\d{3})\]/g, '<img src="' + tagala.config.blog_url + 'plugins/broadcast/templates/smiley/$1.gif" />');
			xmlStr += '<event postid="broadcastid' + json.broadcasts[i].guid + '" blogid="' + json.broadcasts[i].userid + '" ';
			xmlStr += ' start="' + json.broadcasts[i].display_date + '" ';
			xmlStr += ' end="' + json.broadcasts[i].display_date + '" ';
			xmlStr += ' title="' + json.broadcasts[i].user + ':' + json.broadcasts[i].post_content.replace(/\"/g, '\&quot\;').replace(/\'/g, '\&apos\;') + '" rank="4" />';

			broadcast_data.push(new Array(json.broadcasts[i].userPic,json.broadcasts[i].userid,json.broadcasts[i].userName,'first',broadcast_content,json.broadcasts[i].post_longitude,json.broadcasts[i].post_latitude,'10',json.broadcasts[i].display_date,json.broadcasts[i].blogUrl,json.broadcasts[i].blogId));
		}
		xmlStr += '</data>';
		if (json.broadcasts.length==0) xmlStr='';
			_loadXmlObj(xmlStr);
		clearInterval(broadcastIntervalId);
		displayBroadcastMarkers();
	}

	function displayBroadcastMarkers() {
		//var userUrl;
		if(broadcast_marker!=null)
			map.removeOverlay(broadcast_marker);
			while(broadcast_markers.length>0) {
				var oldmarker = broadcast_markers.shift();
				map.removeOverlay(oldmarker);
			}

			if(broadcast_index>=broadcast_data.length) {
				broadcast_index = broadcast_index%(broadcast_data.length);
			}

			var BroadcastIcon = new GIcon();
			BroadcastIcon.image = tagala.config.blog_url + "plugins/broadcast/templates/imgs/comment.png";
			BroadcastIcon.iconSize = new GSize(45, 50);
			BroadcastIcon.iconAnchor = new GPoint(16, 43);
			BroadcastIcon.infoWindowAnchor = new GPoint(40, 5);
			markerOptions = { icon:BroadcastIcon };
			if (broadcast_data.length>0) {
			//userUrl = broadcast_data[broadcast_index][9];
			broadcast_marker = new GMarker(new GLatLng(broadcast_data[broadcast_index][6], broadcast_data[broadcast_index][5]), {icon:BroadcastIcon, title:broadcast_data[broadcast_index][2], zIndexProcess:orderOfBroadcast});
			broadcast_markers.push(broadcast_marker);

			map.addOverlay(broadcast_marker);
			//map.setZoom(broadcast_data[broadcast_index][8]);
			var markerDiv = '<div id="rotate_marker" style="height:90px; width:230px; background:#EFEFEF; border:1px solid #999999; padding:1px;　" >';
			markerDiv += '<table><tr><td rowspan=2>';
			markerDiv += '<img src="' + broadcast_data[broadcast_index][0] + '" width=40 height=50 />';
			markerDiv += '</td><td align=left>&nbsp;<a href=javascript:showUserUrl('+broadcast_data[broadcast_index][10]+')><B>';
			markerDiv += broadcast_data[broadcast_index][2] + '</B></a>:</td></tr><tr><td align=left>&nbsp;';
			markerDiv += broadcast_data[broadcast_index][4] + '<BR>(' + broadcast_data[broadcast_index][8] + ')';
			markerDiv += '</td></tr></table>';
			markerDiv += '</div>';

			//map.closeInfoWindow();
			//map.panTo(new GLatLng(broadcast_data[broadcast_index][7], broadcast_data[broadcast_index][6]));
			broadcast_marker.openInfoWindowHtml(markerDiv);

			GEvent.addListener(broadcast_marker, 'click', function(){
				broadcast_marker.openInfoWindowHtml(markerDiv);
			});

			broadcast_index++;
		}
		broadcastIntervalId = window.setTimeout('displayBroadcastMarkers();', 5000); //the setTimeout() method is called, passing in the expression that we want to run after the time delay
	}

	function showUserUrl( blogId ) {
		var user_blogUrl = tagala.config.blog_url + 'ajax.php?blogId=' + blogId;
		if(iframe.contentWindow.tagala.view)
			iframe.contentWindow.tagala.view.browse(user_blogUrl);
	}

	function genXMLMostReadResponse(response) {
		var json = response.responseJSON;
		if (json && json.posts)
			packXMLwithRank(json, FLAG_MostRead);
	}

	function genXMLLatestResponse(response) {
		var json = response.responseJSON;
		if (json && json.posts)
			packXMLwithRank(json, FLAG_Latest);
	}

	function packXMLwithRank(json, rank) {
		var xmlStr = '<?xml version="1.0" encoding="utf-8" ?><data>';
		for (var i=0;i<json.posts.length;i++) {
			xmlStr += '<event postid="' + json.posts[i].guid + '" blogid="' + json.posts[i].blogid + '" ';
			if (json.posts[i].start_date)
				xmlStr += 'start="' + stripDate(json.posts[i].start_date) + '" ';
			if (json.posts[i].end_date)
				xmlStr += 'end="' + stripDate(json.posts[i].end_date) + '" ';
			xmlStr += 'title="' + json.posts[i].post_title.replace(/\"/g, '\&quot\;').replace(/\'/g, '\&apos\;') + '" rank="' + rank + '" />';
		}
		xmlStr += '</data>';
		if (json.posts.length==0) xmlStr='';
		switch (rank) {
			case 1:
				latestXML = xmlStr;
				break;
			case 2:
				mostReadXML = xmlStr;
				break;
			case 3:
				searchXML = xmlStr;
				break;
		}
		_loadXmlObj(xmlStr);
	}

	function stripDate(dateStr) {
		return /([0-9]+)\/0?([0-9]+)\/0?([0-9]+)/.test(dateStr) ? RegExp.$1 + '/' + RegExp.$2 + '/' + RegExp.$3 : '';
	}


	//*********************************************************************************
	//*****************************  Google Map Control  ******************************
	//*********************************************************************************
	var mapCenter_Y, mapCenter_X;
	var sceneX = '';
	var sceneY = '';
	var map;
	var pgLine;
	var pgGon;
	var mostReadItems;
	var latestItems;
	var highlightItems;
	var mostReadItems_pgGon;
	var latestItems_pgGon;
	var mostReadItems_pgLine;
	var latestItems_pgLine;
	var shadow_order_default = 0;
	var scene_order_default = 5000000;
	var search_order_default = 7000000;
	var highlight_order = 9000000;
	var broadcast_order = 10000000;  //added by Handsome

	// ===== marker image icon =====
	var mIcon, defaultIcon, shadow_Icon, highlight_bgIcon, search_bgIcon;

	function centerTheMap() {
		var point = new GLatLng(mapCenter_Y, mapCenter_X);
		map.panTo(point);
	}

	function orderOfShadow(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat()) + shadow_order_default;
	}

	function orderOfScene(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat()) + scene_order_default;
	}

	function orderOfSearch(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat()) + scene_order_default;	//use same level with normal scenes
	}

	function orderOfHighlight(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat()) + highlight_order;
	}

	//added by Handsome
	function orderOfBroadcast(marker,b) {
		return GOverlay.getZIndex(marker.getPoint().lat()) + broadcast_order;
	}

	function createSceneMarker(point, icon, guid, blogid, name, flag) {
		if ((flag==FLAG_Highlight && highlightItems.get(guid)) || (flag==FLAG_SEARCH && searchItems.get(guid)) || (flag==FLAG_MostRead && mostReadItems.get(guid)) || (flag==FLAG_Latest && latestItems.get(guid))) return;
		var bgIcon = new GIcon();
		bgIcon.iconSize = new GSize(38, 54);
		bgIcon.iconAnchor = new GPoint(19, 51);
		var shmarker, bgmarker, marker;
		switch (flag)
		{
			case FLAG_Highlight:
				bgIcon.image = 'image/tags/current.gif';
				shmarker = new GMarker(point, {clickable:false,icon:shadow_Icon,zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(point, {clickable:false,title:name,icon:bgIcon,zIndexProcess:orderOfHighlight});
				marker = new GMarker(point, {title:name,icon:icon,zIndexProcess:orderOfHighlight});
				highlightItems.set(guid,
				{
					marker:marker,
					background:bgmarker,
					shadow:shmarker
				});
				break;
			case FLAG_SEARCH:
				bgIcon.image = 'image/tags/icon-search.png';
				shmarker = new GMarker(point, {clickable:false,icon:shadow_Icon,zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(point, {clickable:false,title:name,icon:bgIcon,zIndexProcess:orderOfSearch});
				marker = new GMarker(point, {title:name,icon:icon,zIndexProcess:orderOfSearch});
				searchItems.set(guid,
				{
					marker:marker,
					background:bgmarker,
					shadow:shmarker
				});
				break;
			case FLAG_MostRead:
				bgIcon.image = 'image/tags/icon-hot.png';
				shmarker = new GMarker(point, {clickable:false,icon:shadow_Icon,zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(point, {clickable:false,title:name,icon:bgIcon,zIndexProcess:orderOfScene});
				marker = new GMarker(point, {title:name,icon:icon,zIndexProcess:orderOfScene});
				mostReadItems.set(guid,
				{
					marker:marker,
					background:bgmarker,
					shadow:shmarker
				});
				break;
			case FLAG_Latest:
				bgIcon.image = 'image/tags/icon-new.png';
				shmarker = new GMarker(point, {clickable:false,icon:shadow_Icon,zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(point, {clickable:false,title:name,icon:bgIcon,zIndexProcess:orderOfScene});
				marker = new GMarker(point, {title:name,icon:icon,zIndexProcess:orderOfScene});
				latestItems.set(guid,
				{
					marker:marker,
					background:bgmarker,
					shadow:shmarker
				});
				break;
		}
		if (map)
		{
			map.addOverlay(shmarker);
			map.addOverlay(bgmarker);
			map.addOverlay(marker);
		}
		GEvent.addListener(marker, 'click', function() {
			marker_click_event(guid, blogid, name);
		});
	}

	function marker_click_event(guid, blogid, name) {
		if (iframe.contentWindow.location.toString().match(addSlashes(tagala.config.newPostUrl)))
		{
			var answer = confirm(tagala.locale.tr('quit_edit'));
			if (answer) showdata(guid, blogid, name);
		}
		else
			showdata(guid, blogid, name);
	}

	var locate_flag = false;
	var locate_post = {};
	function locateMe(lat,lng,guid,name,sdate,edate) {
		map.panTo(new GLatLng(lat,lng));
		//map.savePosition();
		//Create highlight marker
		tagala.common.setCookie('mapX', lng, cookies_attr);
		tagala.common.setCookie('mapY', lat, cookies_attr);
		locate_flag = true;
		locate_post.Y = lat;
		locate_post.X = lng;
		locate_post.guid = guid;
		locate_post.name = name;
		new Ajax.Request(tagala.config.site_url + 'json_getScene.php',
		{
			evalJS:false,
			postBody:'articleId=' + guid,
			onSuccess:highlightRecordResponse
		});

		if (sdate)
		{
			_setDate(sdate);
			_GetTime(sdate);
			tagala.common.setCookie('dt', sdate, cookies_attr);
		}
		else if (edate)
		{
			_setDate(edate);
			_GetTime(edate);
			tagala.common.setCookie('dt', edate, cookies_attr);
		}
	}

	function getZoomLevel() {
		var zoomlevel = map.getZoom() + 1;
		if (zoomlevel > 18)
			zoomlevel = 18;
		return zoomlevel;
	}

	function getMapPosition() {	//retriece mouse click position on map and fill into blog field
		with (iframe.contentWindow)
		{
			if ($('longitude')) {
				$('longitude').value = sceneX;
				$('latitude').value = sceneY;
			}
		}
	}

	function getMapCenter(){
		var center = map.getCenter();
		return center;
	}

	function updateInputLatLng(overlay)
	{
		var LatLngArray = $R(0, overlay.getVertexCount(), false).collect(function (i)
		{
			return {lng:(overlay.getVertex(i).lng()*1000000).round()/1000000,lat:(overlay.getVertex(i).lat()*1000000).round()/1000000};
		});

		with (iframe.contentWindow)
		{
			if ($('longitude')) {
				$('longitude').value = LatLngArray.pluck('lng').join(',');
				$('latitude').value = LatLngArray.pluck('lat').join(',');
			}
		}
	}

	function ClearOverlays()
	{
		if (pgLine != null)
		{
			map.removeOverlay(pgLine);
			pgLine = null;
		}
		if (pgGon != null)
		{
			map.removeOverlay(pgGon);
			pgGon = null;
		}
	}

	function _createPgLine(points, disableEdit)
	{
		if (!pgLine)
		{
			pgLine = new GPolyline(points, '#b22222', 5, 0.7);
			map.addOverlay(pgLine);
			GEvent.addListener(pgLine, 'mouseover', function(point) { pgLine.enableEditing(); });
			GEvent.addListener(pgLine, 'mouseout', function() { pgLine.disableEditing();updateInputLatLng(pgLine); });
		}
		if (!disableEdit) pgLine.enableDrawing();
	}

	function _createPgGon(points, disableEdit)
	{
		if (!pgGon)
		{
			pgGon = new GPolygon([], '#b11111', 5, 0.7, '#b11111', 0.5);
			map.addOverlay(pgGon);
			GEvent.addListener(pgGon, 'mouseover', function() { pgGon.enableEditing(); });
			GEvent.addListener(pgGon, 'mouseout', function() { pgGon.disableEditing();updateInputLatLng(pgGon); });
		}
		if (!disableEdit) pgGon.enableDrawing();
	}

	function editPathOrArea(lats, lngs) {
		var _lats = lats.split(',');
		var _lngs = lngs.split(',');
		if (_lats.length > 1 && _lats.length == _lngs.length)
		{
			var points = [];
			for (var i=0; i<_lats.length; i++)
			{
				points.push(new GLatLng(_lats[i], _lngs[i]));
			}
			(_lats[0] != _lats[_lats.length-1] ? _createPgLine : _createPgGon)(points, true);
		}
	}


	//*********************************************************************************
	//*****************************  MyMap Information  *****************************
	//*********************************************************************************
	var counter = 1;
	var marker1, marker2;
	var cursorOffsetX = Prototype.Browser.IE ? 7 : 8;
	var cursorOffsetY = Prototype.Browser.IE ? 23 : 28;
	var myMaps = $H();
	var myMapOverlays = $H();
	var mapsShown;
	var gpolyline = [];
	var gpolyline1; // add by connie, 20080513
	var mapid; // add by connie, 20080520
	var map_folder = 'mymaps/maps/';

	// ===== marker image icon =====
	var m1Icon, m2Icon;

	function loadMarker()
	{
		$('pin_img').observe('click', pin);
		$('cleanB').observe('click', cleanpin);
		$('pinmark').show();
	}

	function unloadMarker()
	{
		cleanpin();
		$('pin_img').stopObserving('click', pin);
		$('cleanB').stopObserving('click', cleanpin);
		$('pinmark').hide();
	}

	function change_position(e) {
		e = e || window.event;
		var x = Event.pointerX(e) - $('map').cumulativeOffset().left;//e.clientX - getElementLeft($('map'));
		var y = Event.pointerY(e) - $('map').cumulativeOffset().top;//e.clientY - getElementTop($('map'));
		var maxX = $('map').getWidth();//getElementWidth('map');
		var maxY = $('map').getHeight();//getElementHeight('map');

		$('marker' + counter).setStyle(
		{
			left:(x-cursorOffsetX) + 'px',
			top:(y-cursorOffsetY) + 'px'
		});

		if (x < 0)
			$('marker' + counter).setStyle({left:(-cursorOffsetX) + 'px'});
		if (y < 0)
			$('marker' + counter).setStyle({top:(-cursorOffsetY) + 'px'});
		if (x >= maxX)
			$('marker' + counter).setStyle({left:(maxX - cursorOffsetX - 1) + 'px'});
		if (y >= maxY)
			$('marker' + counter).setStyle({top:(maxY - cursorOffsetY - 1) + 'px'});
	}

	function pin(e) {
		if ($('marker' + counter).visible())
			start_marking(e);
		else
			end_marking(e);
	}

	function start_marking(e) {
		$(document.body).observe('mousemove', change_position);
		$('marker' + counter).observe('click', record);
		$('pin_img').src = 'mymaps/Images/Bm' + counter + '.png';
		$('marker' + counter).src = 'mymaps/Images/marker' + counter + '.png';
		$('marker' + counter).show();
		change_position(e);
	}

	function end_marking(e) {
		$(document.body).stopObserving('mousemove', change_position);
		$('marker1').stopObserving('click', record);
		$('marker2').stopObserving('click', record);
		$('marker1').hide();
		$('marker2').hide();
		$('pin_img').src = 'mymaps/Images/Bm' + (counter == 1 ? 3 : counter == 2 ? 2 : 'u') + '.png';
	}

	function cleanpin() {
		hideAllMyMaps();
		end_marking();
		switch (counter)
		{
			case 3:
				$('pin_img').observe('click', pin);
				map.removeOverlay(marker2);
			case 2:
				map.removeOverlay(marker1);
			default:
				counter = 1;
		}
		$('pin_img').src = 'mymaps/Images/Bm3.png';
		var _css = {fontWeight:bold, color:red};
		with (iframe.contentWindow) {
			$('LmapA').appendLocale('unselect').toLocale();
			$('LmapB').appendLocale('unselect').toLocale();
			$('LmapA').setStyle(_css);
			$('LmapB').setStyle(_css);
			$('map_scale').hide();
			$('map_add').hide();
			$('map_update').hide();
			$('ErrorDiv').hide();
		}
	}

	function record(e) {
		e = e || window.event;
		var x = Event.pointerX(e) - $('map').cumulativeOffset().left;//e.clientX - getElementLeft($('map'));
		var y = Event.pointerY(e) - $('map').cumulativeOffset().top;//e.clientY - getElementTop($('map'));
		var mlatlng = map.fromContainerPixelToLatLng(new GPoint(x, y));

		with (iframe.contentWindow)
		{
			if(counter == 1) {
				marker1 = new GMarker(mlatlng, {title:'第一定位點',icon:m1Icon});
				map.addOverlay(marker1);
				$('Alx').value = mlatlng.lng();
				$('Aly').value = mlatlng.lat();
				counter++;
				end_marking();
				if(document.all)
					$('LmapA').innerText = '已擷取';
				else
					$('LmapA').textContent = '已擷取';
				$('LmapA').style.cssText = 'color:blue;';
			}
			else if(counter == 2)
			{
				marker2 = new GMarker(mlatlng, {title:'第二定位點',icon:m2Icon});
				map.addOverlay(marker2);
				$('Blx').value = mlatlng.lng();
				$('Bly').value = mlatlng.lat();
				counter++;
				end_marking();
				if(document.all)
					$('LmapB').innerText = '已擷取';
				else
					$('LmapB').textContent = '已擷取';
				$('LmapB').style.cssText = 'color:blue;';

				$('pin_img').stopObserving('click', pin);

				if ($('RmapB').style.color == 'blue' && $('LmapB').style.color == 'blue')
					$('map_scale').show();
			}
		}
	}

	function addMyMap(newMyMap)
	{
		if (newMyMap) myMaps.set(newMyMap.guid, newMyMap);
	}

	function removeMyMap(mapId)
	{
		if (myMaps.unset(mapId)) hideMyMap(mapId);
	}

	function showMyMap(mapId)
	{
		var myMap;
		if (myMap = myMaps.get(mapId))
		{
			mapsShown.push(mapId);
			drawMyMap(myMap.guid, myMap.filename, 100, myMap.leftTopLat, myMap.leftTopLng, myMap.rightBottomLat, myMap.rightBottomLng, myMap.upper, myMap.lower);
		}
	}

	function drawMyMap(mapId, strSRC, nOpacity, laTopLeft, loTopLeft, laBottomRight, loBottomRight, upper, lower) {
		//畫我的地圖
		var myMapZoom = map.getZoom();
		if (myMapZoom > upper)
			myMapZoom = upper;
		else if (myMapZoom < lower)
			myMapZoom = lower;
		var boundaries = new GLatLngBounds(new GLatLng(laBottomRight,loTopLeft), new GLatLng(laTopLeft,loBottomRight));
		var myMapOverlay = new GGroundOverlay(map_folder + strSRC + '_' + myMapZoom + '.jpg', boundaries);
		map.addOverlay(myMapOverlay);
		myMapOverlays.set(mapId, myMapOverlay);
		mapid = mapId;

		//畫我的地圖框線
		var polypoints = [];
		var polypoint = new GPoint(loTopLeft,laTopLeft);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loBottomRight,laTopLeft);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loBottomRight,laBottomRight);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loTopLeft,laBottomRight);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loTopLeft,laTopLeft);
		polypoints.push(polypoint);

		gpolyline[mapId]=new GPolyline(polypoints, '#00FFFF', 5);
		map.addOverlay(gpolyline[mapId]);
	}

	// add by connie, 20080513
	function showMyNearby(loTopLeft, laTopLeft, loBottomRight, laBottomRight) {
		var polypoints = [];
		var polypoint = new GPoint(loTopLeft,laTopLeft);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loBottomRight,laTopLeft);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loBottomRight,laBottomRight);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loTopLeft,laBottomRight);
		polypoints.push(polypoint);
		var polypoint = new GPoint(loTopLeft,laTopLeft);
		polypoints.push(polypoint);

		//gpolyline1=new GPolyline(polypoints, '#FF00FF', 5);
		//map.addOverlay(gpolyline1);

		gpolyline1=new GPolygon(polypoints, '#FF69B4', 5, 0.7, '#FF69B4', 0.5);
		map.addOverlay(gpolyline1);
	}

	// add by connie, 20080513
	function hideMyNearby()
	{
		if (map && gpolyline1) map.removeOverlay(gpolyline1);
		gpolyline1 = '';
	}

	// add by connie, 20080513
	function moveToMyNearbyCenter(loTopLeft, laTopLeft, loBottomRight, laBottomRight)
	{
		var lng, lat;
		var bounds = map.getBounds();
		var dMapLng = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng()).abs(), dMyNearbyLng;
		var dMapLat = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat()).abs(), dMyNearbyLat;

		dMyNearbyLng = (parseFloat(loTopLeft) - parseFloat(loBottomRight)).abs();
		dMyNearbyLat = (parseFloat(laTopLeft) - parseFloat(laBottomRight)).abs();
		if ((dMyNearbyLat / dMyNearbyLng) > (dMapLat / dMapLng))
		{
			// Resize by latitude
			while (dMyNearbyLat > dMapLat)
			{
				dMapLat *= 2;
				map.zoomOut();
			}
			while (dMyNearbyLat < (dMapLat /= 2)) map.zoomIn();
		}
		else
		{
			// Resize by longtitude
			while (dMyNearbyLng > dMapLng)
			{
				dMapLng *= 2;
				map.zoomOut();
			}
			while (dMyNearbyLng < (dMapLng /= 2)) map.zoomIn();
		}
		lng = (parseFloat(loTopLeft) + parseFloat(loBottomRight)) / 2;
		lat = (parseFloat(laTopLeft) + parseFloat(laBottomRight)) / 2;
		map.panTo(new GLatLng(lat, lng));
	}

	function hideMyMap(mapId) {
		if (mapsShown.include(mapId) && map) {
			var myMapOverlay;
			if (myMapOverlay = myMapOverlays.get(mapId))
				map.removeOverlay(myMapOverlay);
			map.removeOverlay(gpolyline[mapId]);
			mapsShown = mapsShown.without(mapId);
		}
	}

	function hideAllMyMaps()
	{
		mapsShown.each(hideMyMap);
	}

	function moveToMyMapCenter(mapId)
	{
		// modify by connie, 20080513
		//if (!mapsShown.contains(mapId)) return;

		var myMap, lng, lat;
		var bounds = map.getBounds();
		var dMapLng = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng()).abs(), dMyMapLng;
		var dMapLat = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat()).abs(), dMyMapLat;
		if (myMap = myMaps.get(mapId))
		{
			dMyMapLng = (parseFloat(myMap.leftTopLng) - parseFloat(myMap.rightBottomLng)).abs();
			dMyMapLat = (parseFloat(myMap.leftTopLat) - parseFloat(myMap.rightBottomLat)).abs();
			if ((dMyMapLat / dMyMapLng) > (dMapLat / dMapLng))
			{
				// Resize by latitude
				while (dMyMapLat > dMapLat)
				{
					dMapLat *= 2;
					map.zoomOut();
				}
				while (dMyMapLat < (dMapLat /= 2)) map.zoomIn();
			}
			else
			{
				// Resize by longtitude
				while (dMyMapLng > dMapLng)
				{
					dMapLng *= 2;
					map.zoomOut();
				}
				while (dMyMapLng < (dMapLng /= 2)) map.zoomIn();
			}

			lng = (parseFloat(myMap.leftTopLng) + parseFloat(myMap.rightBottomLng)) / 2;
			lat = (parseFloat(myMap.leftTopLat) + parseFloat(myMap.rightBottomLat)) / 2;
			map.panTo(new GLatLng(lat, lng));
		}
	}

	function redrawMyMaps() {
		mapsShown.each(function (mapId)
		{
			hideMyMap(mapId);
			showMyMap(mapId);
		});
	}

	//*********************************************************************************
	//*****************************  Query Broadcasts Information, by handsome *************************
	//*********************************************************************************
	function showBroadcast(postid) {
		var urlXMLGetBroadcast = tagala.config.blog_url + 'index.php?op=getClickedBroadcast&broadcastId=' + postid;
		new Ajax.Request(urlXMLGetBroadcast,
		{
			evalJS:false,
			method:'get',
			onSuccess:genXMLClickedBroadcastResponse
		});
	}

	function genXMLClickedBroadcastResponse(response) {
		var json = response.responseJSON;
		if (json && json.broadcast) {
			displayClickedBroadcastMarkers(json.broadcast);
		}
	}

	function displayClickedBroadcastMarkers(broadcast) {
		map.removeOverlay(broadcast_marker);
		var broadcastContent = broadcast.post_content.replace(/\[(\d{3})\]/g, '<img src="' + tagala.config.blog_url + 'plugins/broadcast/templates/smiley/$1.gif" />');
		var markerDiv = "<div id='view_marker' style='height:90px; width:230px; background:#EFEFEF; border:1px solid #999999; padding:1px;　' >";
		markerDiv += "<table><tr><td rowspan=2>";
		markerDiv += "<img src='" + broadcast.userPic + "' width=40 height=50 />";
		markerDiv += "</td><td align=left>&nbsp;<a href=javascript:showUserUrl("+broadcast.blogId+")><B>";
		markerDiv += broadcast.userName + "</B></a>:</td></tr><tr><td align=left>&nbsp;";
		markerDiv += broadcast.post_content + "<BR>(" + broadcast.display_date + ")";
		markerDiv += "</td></tr></table>";
		markerDiv += "</div>";

		var BroadcastIcon = new GIcon();
		BroadcastIcon.image = tagala.config.blog_url + "plugins/broadcast/templates/imgs/comment.png";
		BroadcastIcon.iconSize = new parent.GSize(45, 50);
		BroadcastIcon.iconAnchor = new parent.GPoint(16, 43);
		BroadcastIcon.infoWindowAnchor = new parent.GPoint(40, 5);
		markerOptions = { icon:BroadcastIcon, zIndexProcess:orderOfBroadcast };

		broadcast_marker = new GMarker(new GLatLng(broadcast.post_latitude, broadcast.post_longitude), markerOptions);

		map.addOverlay(broadcast_marker);
		broadcast_marker.openInfoWindowHtml(markerDiv);
	}

	//*********************************************************************************
	//*****************************  Query Posts Information  *************************
	//*********************************************************************************
	var dest_url = '';
	var searchXML = '';
	var mostReadXML = '';
	var latestXML = '';

	function showdata(guid, blogid, name) {
		dest_url = tagala.config.blog_url + 'ajax.php?op=ViewArticle&blogId=' + blogid + '&articleId=' + guid;
		iframe_navigate(tagala.config.blogPageUrl);
	}

	function queryData(criteria, flag) {
		query_flag = flag;

		// Check if criteria contains no latlng region, then limit the search region.
		if (!criteria.match('lngL') && map) {
			var bounds = map.getBounds();
			var lngL = bounds.getSouthWest().lng();
			var lngR = bounds.getNorthEast().lng();
			var latB = bounds.getSouthWest().lat();
			var latT = bounds.getNorthEast().lat();
			criteria += '&lngL=' + ((lngL * 2 - lngR)*1000000).round()/1000000;
			criteria += '&lngR=' + ((lngR * 2 - lngL)*1000000).round()/1000000;
			criteria += '&latB=' + ((latB * 2 - latT)*1000000).round()/1000000;
			criteria += '&latT=' + ((latT * 2 - latB)*1000000).round()/1000000;
		}

		criteria += '&maxPosts=' + tagala.config.maxPosts;

		// Using AJAX to get Scenes
		if (flag == FLAG_SEARCH)
		{
			myMaps = $H();
			new Ajax.Request(tagala.config.site_url + 'json_getScene.php',
			{
				evalJS:false,
				postBody:criteria,
				onSuccess:searchRecordResponse
			});
		}
		else
		{
			//allOrMostReadOrLatest, 1 for MostRead, 2 for Latest, 3 for Latest without MostRead, 4 for Random
			new Ajax.Request(tagala.config.site_url + 'json_getScene.php',
			{
				evalJS:false,
				postBody:criteria + '&allOrMostReadOrLatest=1',
				onSuccess:mostReadRecordResponse
			});
			new Ajax.Request(tagala.config.site_url + 'json_getScene.php',
			{
				evalJS:false,
				postBody:criteria + '&allOrMostReadOrLatest=3',
				onSuccess:latestRecordResponse
			});
		}
	}

	function highlightRecordResponse(response) {
		var json = response.responseJSON;
		if (json && json.posts)
			getRecordResponse(json, FLAG_Highlight);
	}

	function mostReadRecordResponse(response) {
		var json = response.responseJSON;
		if (json && (typeof(json) == 'object') && json.posts)
			getRecordResponse(json, FLAG_MostRead);
	}

	function latestRecordResponse(response) {
		var json = response.responseJSON;
		if (json && (typeof(json) == 'object') && json.posts)
			getRecordResponse(json, FLAG_Latest);
	}

	function searchRecordResponse(response) {
		var json = response.responseJSON;
		if (json && (typeof(json) == 'object') && json.posts)
		{
			getRecordResponse(json, FLAG_SEARCH);
			packXMLwithRank(json, FLAG_SEARCH);
			iframe.contentWindow.showResults(json);
			iframe.contentWindow.doGetRss2Feed();
		}
	}

	function getRecordResponse(json, flag) {
		switch (flag)
		{
			case FLAG_SEARCH:
				json.maps.each(function (myMap)
				{
					myMaps.set(myMap.guid, myMap);
				});
				clearSearchItems();
				break;
			case FLAG_MostRead:
				//clearMostReadItems();
				if (map)
				{
					var _bounds = map.getBounds();
					mostReadItems.each(function (pair)
					{
						if (!_bounds.contains(pair.value.marker.getLatLng()))
						{
							removeOverlay(pair.value);
							mostReadItems.unset(pair.key);

							if (mostReadItems_pgGon.get(pair.key))
							{
								map.removeOverlay(mostReadItems_pgGon.get(pair.key));
								mostReadItems_pgGon.unset(pair.key);
							}
							if (mostReadItems_pgLine.get(pair.key))
							{
								map.removeOverlay(mostReadItems_pgLine.get(pair.key));
								mostReadItems_pgLine.unset(pair.key);
							}
						}
					});
				}
				break;
			case FLAG_Latest:
				//clearLatestItems();
				if (map)
				{
					var _bounds = map.getBounds();
					latestItems.each(function (pair)
					{
						if (!_bounds.contains(pair.value.marker.getLatLng()))
						{
							removeOverlay(pair.value);
							latestItems.unset(pair.key);

							if (latestItems_pgGon.get(pair.key))
							{
								map.removeOverlay(latestItems_pgGon.get(pair.key));
								latestItems_pgGon.unset(pair.key);
							}
							if (latestItems_pgLine.get(pair.key))
							{
								map.removeOverlay(latestItems_pgLine.get(pair.key));
								latestItems_pgLine.unset(pair.key);
							}
						}
					});
				}
				break;
			case FLAG_Highlight:
				_highlightEvent(locate_post.guid);
				clearHighlightItems();
				break;
		}

		json.posts.each(function (post)
		{
			if (post.post_latitude && post.post_longitude) {
				var item, points = post.post_latitude.split(',').zip(post.post_longitude.split(','));
				if ((points.size() > 1) && ![FLAG_SEARCH, FLAG_Highlight].include(flag))
				{
					var Npoints = points.collect(function (point)
					{
						return new GLatLng(point[0], point[1]);
					});
					if (Npoints.first() == Npoints.last())
					{
						// Polygon
						var Npolygon = new GPolygon(Npoints, null, 5, 0.7, '#aaaaff', 0.5);
						if (flag == FLAG_MostRead)
						{
							if (item = mostReadItems_pgGon.get(post.guid)) map.removeOverlay(item);
							mostReadItems_pgGon.set(post.guid, Npolygon);
						}
						else if (flag == FLAG_Latest)
						{
							if (item = latestItems_pgGon.get(post.guid)) map.removeOverlay(item);
							latestItems_pgGon.set(post.guid, Npolygon);
						}
						if (map)
						{
							map.addOverlay(Npolygon);
							GEvent.addListener(Npolygon, 'click', function(point) {
								GEvent.trigger(map, 'click', null, point);
							});
						}
					}
					else
					{
						// Path
						var Npolyline = new GPolyline(Npoints, '#8888ff', 5, 0.7);
						if (flag == FLAG_MostRead)
						{
							if (item = mostReadItems_pgLine.get(post.guid)) map.removeOverlay(item);
							mostReadItems_pgLine.set(post.guid, Npolyline);
						}
						else if (flag == FLAG_Latest)
						{
							if (item = latestItems_pgLine.get(post.guid)) map.removeOverlay(item);
							latestItems_pgLine.set(post.guid, Npolyline);
						}
						if (map)
						{
							map.addOverlay(Npolyline);
							GEvent.addListener(Npolyline, 'click', function(point) {
								GEvent.trigger(map, 'click', null, point);
							});
						}
					}
				}
				var point = new GLatLng(points.first()[0], points.first()[1]);
				var myIcon = new GIcon();
				if (post.tag_icons.length!=0)
				{
					myIcon.image = post.tag_icons[0].filename;
					myIcon.iconSize = new GSize(32, 32);
					myIcon.iconAnchor = new GPoint(16, 43);
					myIcon.infoWindowAnchor = new GPoint(16, 16);
				}
				else
					myIcon = defaultIcon;
				createSceneMarker(point, myIcon, post.guid, post.blogid, post.post_title, flag);
			}

			// locate infowindow
			if (locate_flag) {
				locate_flag = false;
				/*if (map.getZoom()<18)
				{
					var opts = {zoomLevel:getZoomLevel(), mapType:G_NORMAL_MAP};
					map.showMapBlowup(new GLatLng(locate_post.Y,locate_post.X), opts);
				}*/
			}
		});
	}

	//*********************************************************************************
	//*****************************  Search Options Information  **********************
	//*********************************************************************************
	var searchItems;
	var searchCriteria;
	var _dragSelect;

	function dragend(nw, ne, se, sw, nwpx, nepx, sepx, swpx, mode) {
		//alert('nw:'+nw+',ne:'+ne+',se:'+se+',sw:'+sw+',nwpx:'+nwpx+',nepx:'+nepx+',sepx:'+sepx+',swpx:'+swpx+',mode:'+mode);
		$('map_search_menu').hide();
		if (mode == FLAG_SEARCH)
			searchBlogs('lngL=' + sw.lng() + '&lngR=' + ne.lng() + '&latB=' + sw.lat() + '&latT=' + ne.lat());
		else if (mode == FLAG_FILTER)
		{
			with (iframe.contentWindow)
			{
				$('longitudeBottomLeft').value = (sw.lng()*1000000).round()/1000000;
				$('latitudeBottomLeft').value = (sw.lat()*1000000).round()/1000000;
				$('longitudeTopRight').value = (ne.lng()*1000000).round()/1000000;
				$('latitudeTopRight').value = (ne.lat()*1000000).round()/1000000;
			}
		}
		else if (mode == 'FLAG_NEARBY')
		{
			$('nearby_set_menu', 'nearby_set_menu').invoke('toggle');

			with (iframe.contentWindow)
			{
				if ($('longitudeBottomLeft')) {
					$('longitudeBottomLeft').value = (sw.lng()*1000000).round()/1000000;
					$('latitudeBottomLeft').value = (sw.lat()*1000000).round()/1000000;
					$('longitudeTopRight').value = (ne.lng()*1000000).round()/1000000;
					$('latitudeTopRight').value = (ne.lat()*1000000).round()/1000000;
					$('nearbysetok').show();
					$('nearby_set_menu').value = '';
				}
			}
		}
	}

	function dragSelect(mode) {
		_dragSelect.select(mode);
	}

	function BoxSearchFilter(mode) {
		dragSelect(mode);

		// modify by connie, 20080513
		if(mode == 'FLAG_NEARBY') $('nearby_set_menu').toggle();
		else $('map_search_menu').toggle();
	}

	function DateSearchMenu() {
		if (!$('date_search_menu').visible())
		{
			$('date_search_menu').show();
			if (queryInterval()=='0') _selectInterval();
		}
		else
		{
			$('date_search_menu').hide();
			if (queryInterval()=='1') _selectInterval();
		}
	}

	function DateCallback(sdate,edate) {
		if (sdate || edate)
			searchBlogs('startdate=' + sdate + '&enddate=' + edate);
	}

	function TagSearchMenu() {
		$('tag_search_menu').toggle();
	}

	function checkTag(key) {
		var tags = $('tags_text').value.split(',').reject(function (tag) { return tag.blank(); }).invoke('strip');
		if (tags.include(key))
			tags = tags.reject(function (tag) { return tag == key; });
		else
			tags.push(key);
		$('tags_text').value = tags.join(', ');
	}

	function TagCallback(tags_str) {
		var tags = tags_str.split(',').reject(function (tag) { return tag.blank(); }).invoke('strip');
		if (tags.length) searchBlogs('tag=' + encodeURIComponent(tags.join(',')));
	}

	function checkKey(e) {
		var key = e.charCode ? e.charCode : e.keyCode;
		if (key == 13) KeywordCallback($('sitesearch').value);
	}

	function KeywordCallback(keyword) {
		if (Object.isString(keyword) && !keyword.blank()) searchBlogs('keyword=' + encodeURIComponent(keyword.strip()));
	}

	function searchBlogs(criteria) {
		searchCriteria = criteria;
		if (!iframe.contentWindow.location.toString().match(tagala.config.searchUrl))
			iframe_navigate(tagala.config.searchUrl);
		else
			queryData('search=1&' + criteria, FLAG_SEARCH);
	}

	function clearSearchItems() {
		if (map)
			searchItems.values().each(removeOverlay);
		searchItems = $H();

		hideAllMyMaps();

		if (timeMovie())
		{
			genXML();
			//_clearXml();
			//_loadXmlObj(mostReadXML);
			//_loadXmlObj(latestXML);
		}
	}

	function clearMostReadItems() {
		if (map)
		{
			mostReadItems.values().each(removeOverlay);
			mostReadItems_pgGon.values().each(map.removeOverlay);
			mostReadItems_pgLine.values().each(map.removeOverlay);
		}
		mostReadItems = $H();
		mostReadItems_pgGon = $H();
		mostReadItems_pgLine = $H();
	}

	function clearLatestItems() {
		if (map)
		{
			latestItems.values().each(removeOverlay);
			latestItems_pgGon.values().each(map.removeOverlay);
			latestItems_pgLine.values().each(map.removeOverlay);
		}
		latestItems = $H();
		latestItems_pgGon = $H();
		latestItems_pgLine = $H();
	}

	function clearHighlightItems() {
		if (map)
			highlightItems.values().each(function (item, idx)
			{
				removeOverlay(item);
				_unhighlightEvent(idx);
			});
		highlightItems = $H();
	}

	function highlight(guid, blogid)
	{
		var item;
		if (item = searchItems.get(guid))
		{
			var shmarker, bgmarker, marker;
			if (map)
			{
				removeOverlay(item);
				shmarker = new GMarker(item.shadow.getPoint(), {clickable:false,icon:item.shadow.getIcon(),zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(item.background.getPoint(), {clickable:false,title:item.marker.getTitle(),icon:highlight_bgIcon,zIndexProcess:orderOfHighlight});
				marker = new GMarker(item.marker.getPoint(), {title:item.marker.getTitle(),icon:item.marker.getIcon(),zIndexProcess:orderOfHighlight});
				map.addOverlay(shmarker);
				map.addOverlay(bgmarker);
				map.addOverlay(marker);
			}
			GEvent.addListener(marker, 'click', function() {
				marker_click_event(guid, blogid, item.marker.getTitle());
			});
			searchItems.unset(guid);
			searchItems.set(guid,
			{
				marker:marker,
				shadow:shmarker,
				background:bgmarker
			});

			_highlightEvent(guid);
		}
	}

	function unhighlight(guid)
	{
		var item;
		if (item = searchItems.get(guid))
		{
			var shmarker, bgmarker, marker;
			if (map)
			{
				removeOverlay(item);
				shmarker = new GMarker(item.shadow.getPoint(), {clickable:false,icon:item.shadow.getIcon(),zIndexProcess:orderOfShadow});
				bgmarker = new GMarker(item.background.getPoint(), {clickable:false,title:item.marker.getTitle(),icon:search_bgIcon,zIndexProcess:orderOfSearch});
				marker = new GMarker(item.marker.getPoint(), {title:item.marker.getTitle(),icon:item.marker.getIcon(),zIndexProcess:orderOfSearch});
				map.addOverlay(shmarker);
				map.addOverlay(bgmarker);
				map.addOverlay(marker);
			}
			GEvent.addListener(marker, 'click', function() {
				marker_click_event(guid, blogid, item.marker.getTitle());
			});
			searchItems.unset(guid);
			searchItems.set(guid,
			{
				marker:marker,
				shadow:shmarker,
				background:bgmarker
			});

			_unhighlightEvent(guid);
		}
	}

	//*********************************************************************************
	//*****************************  GControl: Timeline  **********************************
	//*********************************************************************************
	function TimelineControl() {}

	TimelineControl.prototype = new GControl();

	TimelineControl.prototype.initialize = function(map) {
		var img_timeline = document.createElement('img');
		img_timeline.id = 'img_timeline';
		img_timeline.src = 'image/timeline.jpg';
		img_timeline.style.cssText = 'width:70px;height:18px;border:solid 1px black';
		GEvent.addDomListener(img_timeline, 'click', function() {
			var elem = $('timeline-CollapseButton');
			if (document.all)
				elem.fireEvent('onclick', Splitter.toggleCollapseExpandButton);
			else
			{
				var e = document.createEvent('MouseEvents');
				e.initEvent('click', false, true);
				elem.dispatchEvent(e);
			}
		});
		map.getContainer().appendChild(img_timeline);
		return img_timeline;
	}

	// By default, the control will appear in the top left corner of the
	// map with 7 pixels of padding.
	TimelineControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, -4));
	}

	// Sets the proper CSS for the given button element.
	TimelineControl.prototype.setButtonStyle_ = function(button) {
		Object.extend(button.style,
		{
			textDecoration:'underline',
			color:'#0000cc',
			backgroundColor:'white',
			font:'small Arial',
			border:'1px solid black',
			padding:'2px',
			marginBottom:'3px',
			textAlign:'center',
			width:'6em',
			cursor:'pointer'
		});
	}

	//*********************************************************************************
	//*****************************  GControl: DropDown Maptypes*************************
	//*********************************************************************************
	function MDControl(){} MDControl.prototype=new GControl();

	MDControl.prototype.initialize=function(map) {
		var container = map.getContainer().appendDiv();
		var selMap = container.appendTag('select',
		{
			id:'selMap',
			className:'s_button',
			title:'Change Map Type'
		});
		// Create options list for map types
		var mts = map.getMapTypes();
		mts.each(function (type, idx)
		{
			selMap.options[idx] = new Option('   ' + type.getName(), idx);
		});

		selMap.selectedIndex = 0;
		GEvent.addDomListener(selMap, 'change', function() {
			map.setMapType(mts[selMap.options[selMap.selectedIndex].value]);
			selMap.blur();
		});
		return container;
	}

	MDControl.prototype.getDefaultPosition= function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(7,7));
	}

	//*********************************************************************************
	//*****************************  Initialization  **********************************
	//*********************************************************************************
	tagala.onload = function ()
	{
		if (bInitialized) return true;
		bInitialized = true;
		var cookies = tagala.common.getCookies();
		iframe = $('tabInfo_frame0')

		// Set default title
		setTitle();

		//lightwindowInit
		//lightwindowInit();

		$('static_link').update().appendLocale('static_link').toLocale();
		// Google Map
		if (GBrowserIsCompatible()) {
			// ===== Create marker image icon =====
			mIcon = new GIcon();
			mIcon.image = 'image/marker.gif';
			mIcon.iconSize = new GSize(20, 20);
			mIcon.iconAnchor = new GPoint(10, 10);

			defaultIcon = new GIcon();
			defaultIcon.image = 'image/tags/scenery.png';
			defaultIcon.iconSize = new GSize(32, 32);
			defaultIcon.iconAnchor = new GPoint(16, 43);

			shadow_Icon = new GIcon();
			shadow_Icon.image = 'image/tags/shadow.png';
			shadow_Icon.iconSize = new GSize(59, 54);
			shadow_Icon.iconAnchor = new GPoint(19, 51);

			highlight_bgIcon = new GIcon();
			highlight_bgIcon.image = 'image/tags/current.gif';
			highlight_bgIcon.iconSize = new GSize(38, 54);
			highlight_bgIcon.iconAnchor = new GPoint(19, 51);

			search_bgIcon = new GIcon();
			search_bgIcon.image = 'image/tags/icon-search.png';
			search_bgIcon.iconSize = new GSize(38, 54);
			search_bgIcon.iconAnchor = new GPoint(19, 51);

			// ===== Create marker image icon =====
			m1Icon = new GIcon();
			m1Icon.image = 'mymaps/Images/marker1.png';
			m1Icon.iconSize = new GSize(16, 28);
			m1Icon.iconAnchor = new GPoint(cursorOffsetX, cursorOffsetY);
			m2Icon = new GIcon();
			m2Icon.image = 'mymaps/Images/marker2.png';
			m2Icon.iconSize = new GSize(16, 28);
			m2Icon.iconAnchor = new GPoint(cursorOffsetX, cursorOffsetY);

			map = new GMap2($('map'));
			var uiOptions = map.getDefaultUI();
			uiOptions.controls.largemapcontrol3d  = true;
			uiOptions.controls.maptypecontrol = false;
			map.setUI(uiOptions);
			geocoder = new GClientGeocoder();
			//map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 50)));
			//map.addControl(new GLargeMapControl());
			//map.removeMapType(G_HYBRID_MAP);
			map.addMapType(G_PHYSICAL_MAP);
			//map.addMapType(G_SKY_VISIBLE_MAP);
			//map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize((document.all) ? 77 : 78, 7)));
			map.addControl(new MDControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize((document.all) ? 77 : 78, 7)));
			map.addControl(new TimelineControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7)));

			if (cookies.mapY && cookies.mapX)
			{
				mapCenter_Y = cookies.mapY;
				mapCenter_X = cookies.mapX;
			}
			else
			{
				mapCenter_Y = '25.040796';
				mapCenter_X = '121.517924';
			}
			var myMapZoom = parseInt(cookies.zoom ? cookies.zoom : 15);
			if (myMapZoom > 18) myMapZoom = 18;
			if (myMapZoom < 0) myMapZoom = 0;
			map.setCenter(new GLatLng(mapCenter_Y, mapCenter_X), myMapZoom);

			//***************  ContextMenu**************
			tagala.menu = new tagala.Contextmenu(map);

			var moveendTimerID = null;
			var zoomendTimerID = null;
			GEvent.addListener(map, 'moveend', function() {
				if (moveendTimerID == null) {
					moveendTimerID = function() {
						moveendTimerID = null;
						if (map) map.savePosition();
						//$('qrcode').src = 'http://qrcode.jp/qr?q=http://140.96.111.97/ITeS/svc.php?lon=' + (map.getCenter().lng()*1000000).round()/1000000 + escape('&') + 'lat=' + (map.getCenter().lat()*1000000).round()/1000000;
						mapCenter_Y = map.getCenter().lat();
						mapCenter_X = map.getCenter().lng();
						var sdate = querytime();
						queryData('startdate='+sdate+'&enddate='+sdate, FLAG_NORMAL);
						if (timeMovie()) genXML();
						if (iframe.contentWindow.location.toString().match(tagala.config.searchUrl)) _loadXmlObj(searchXML);
						// set cookies
						tagala.common.setCookie('mapX', mapCenter_X, cookies_attr);
						tagala.common.setCookie('mapY', mapCenter_Y, cookies_attr);
					}.delay(tagala.config.sameRequestTimeDelay);
				}
			});

			GEvent.addListener(map, 'zoomend', function() {
				if (zoomendTimerID == null) {
					zoomendTimerID = function() {
						zoomendTimerID = null;
						redrawMyMaps();
						var sdate = querytime();
						queryData('startdate='+sdate+'&enddate='+sdate, FLAG_NORMAL);
						if (timeMovie()) genXML();
						if (iframe.contentWindow.location.toString().match(tagala.config.searchUrl)) _loadXmlObj(searchXML);
						// set cookies
						tagala.common.setCookie('zoom', map.getZoom(), cookies_attr);
					}.delay(tagala.config.sameRequestTimeDelay);
				}
			});

			map.enableScrollWheelZoom();
		}
		// Draw retengle in gmap.
		//rect_div();
		_dragSelect = new DragSelectControl( {}, {overlayRemoveTime:3000}, {dragend:dragend} );
		map.addControl(_dragSelect);

		// Initial some variable;
		mostReadItems = $H();
		mostReadItems_pgGon = $H();
		mostReadItems_pgLine = $H();
		latestItems = $H();
		latestItems_pgGon = $H();
		latestItems_pgLine = $H();
		highlightItems = $H();
		searchItems = $H();
		mapsShown = [];

		// Load tags cloud
		new Ajax.Request('json_getTags.php',
		{
			evalJS:false,
			method:'get',
			onSuccess:setTagsCloudResponse
		});

		// Adjust Flash Timeline, and get events today
		if (timeMovie()) {
			var dt_show = cookies.dt ? cookies.dt : str_today;
			if (cookies.dt_mode)
				_setDate(dt_show, cookies.dt_mode);
			else
				_setDate(dt_show);
			_GetTime(dt_show);
		}

		// Get Cookie to redirect page.
		if (cookies.redirecturl)
		{
			iframe_navigate(cookies.redirecturl);
			tagala.common.deleteCookie('redirecturl');
		}
		else if (cookies.search)
		{
			searchCriteria = document.cookie.replace(/\;\s/g, '&');
			iframe_navigate(tagala.config.searchUrl);
		}
		else if (cookies.view)
		{
			dest_url = cookies.view;
			iframe_navigate(tagala.config.blogPageUrl);
		}
		else
			iframe_navigate(tagala.config.blogPageUrl);
		updateLoginStatus();
	}

	function setTagsCloudResponse(response) {
		var json = response.responseJSON;
		if (json && json.tags && Object.isArray(json.tags))
		{
			$('tags').update();
			json.tags.each(function (tag, idx)
			{
				if (idx) $('tags').insert(', ');
				$('tags').appendA('javascript:checkTag("' + tag.name + '");',
				{
					title:'Click this to add/remove condidtions'
				}).setStyle(
				{
					textDecoration:'none'
				}).insert(tag.name + '(' + tag.cnt + ')');
			});
			$('tag_search_menu');
			$('tag_search_menu').show().setStyle(
			{
				height:($('tags').getHeight() + $('tags_text').getHeight() + $('tag_reset').getHeight() + 8) + 'px'
			}).hide();
		}
	}

	function setTitle(title)
	{
		titlePrefix = 'tagala 你的時空記憶';
		if (title) titlePrefix += ' ' + title;
		document.title = titlePrefix;
	}

	function lifemapPost()
	{
		iframe.contentWindow.location = tagala.config.dst_url + tagala.config.blog_url + 'admin.php?op=newajaxPost&event=nthulife';
	}

	function iframe_navigate(src)
	{
		if (iframe.contentWindow.location.toString().match(src))
		{
			if (iframe.contentWindow.location.toString().match(tagala.config.blogPageUrl) && dest_url && !dest_url.blank())
				iframe.contentWindow.tagala.view.browse(dest_url);
			else if (iframe.contentWindow.location.toString().match(tagala.config.searchUrl) && searchCriteria && !searchCriteria.blank())
				queryData('search=1&' + searchCriteria, FLAG_SEARCH);
			else
				iframe.contentWindow.location = src;
		}
		else if (src)
			iframe.contentWindow.location = src;
	}

	function removeOverlay(item)
	{
		if (map && item)
		{
			map.removeOverlay(item.marker);
			map.removeOverlay(item.background);
			map.removeOverlay(item.shadow);
		}
	}
