﻿var SCRIPTROOTSRC = (function(){
	var RELATIVE = /^[\w\.]+[^:]*$/;
	function makePath(href, path) {
		if (RELATIVE.test(href)) href = (path || "") + href;
		return href;
	};
	function getPath(href, path) {
		href = makePath(href, path);
		return href.slice(0, href.lastIndexOf("/") + 1);
	};
	// get the path to this script
	var scripts = document.getElementsByTagName('script');
	var script = scripts[scripts.length - 1];
	var path = getPath(script.src);
	return path;
})();

var UINDEX = function() {
	var MAP;
	var isIE = ($.browser.msie && $.browser.version.substr(0, 1) != '8') ? true : false;
	var _ROOT = 'http://' + document.location.hostname + '/mapgen/';
	var baseUrl = window.location.href;
	var embedUrl = isIE ? (_ROOT + SCRIPTROOTSRC + '../embed.html') : (SCRIPTROOTSRC + '../embed.html');
	var toMapUrl = isIE ? (_ROOT + SCRIPTROOTSRC + '../../map.jsp') : (SCRIPTROOTSRC + '../../map.jsp');
	var queryAddressUrl = SCRIPTROOTSRC + '../queryAddress.jsp';
	var defaultLatlng = new ULatLng(25.035405, 121.520255);
	var defaultZoomlevel = 9;
	var defaultIcon = new UIcon({
		image: 'http://maps.urmap.com/api/img/marker.gif',
		iconWidth: 16,
		iconHeight: 16,
		iconAnchor: new UPoint(8, 8),
		infoWindowAnchor: new UPoint(8, 0)
	});
	var searchMarker = new UMarker(new ULatLng(0,0));
	var tmpMrks = [];
	
	/* Iinitialize Map & Form */
	var Init = {
		map: function() {
			MAP = new UMap(document.getElementById('map'));
			//MAP.centerAndZoom(defaultLatlng, defaultZoomlevel);
			WriteAnchorUrl();
			// Add Marker Of Address Query
			MAP.addOverlay(searchMarker);
			searchMarker.addListener('click', searchMarkerClicked);
			// Right Clicked Menu
			MAP.addListener('contextmenu', function(e, latlng){
				UEvent.cancelDefault(e);
				ContextMenu.init(latlng);
				ContextMenu.show(latlng, $('.context-menu'));
			});
			MAP.addListener('moveend', WriteAnchorUrl);
		},
		initForm: function() {
			$('#mapSize > option').attr('selected', false);
			$('#mapSize > option').eq(0).attr('selected', true);
			$('.input-setup-size').eq(0).val('400');
			$('.input-setup-size').eq(1).val('300');
			$('#zoomController :radio').attr('checked', false);
			$('#zoomController :radio').eq(2).attr('checked', true);
			$('#typeController :radio').attr('checked', false);
			$('#typeController :radio').eq(1).attr('checked', true);
			$('#styleController :radio').attr('checked', false);
			$('#styleController :radio').eq(0).attr('checked', true);
		},
		formEvent: function() {
			// Setting Form
			$('#mapSize').bind('change', Setting.selectEvent);
			$('.setup-size :text').each(function(){
				$(this).bind('keypress', Setting.keyEvent).bind('change', Setting.changeEvent);
			});
			$('#zoomController :radio').bind('click', Setting.setZoomController);
			$('#typeController :radio').bind('click', Setting.setTypeController);
			// Add New Marker
			$('#add-button').bind('click', function(){
				if ($('#markerSection .marker-section .marker-content').length < 10) {
					var latlng = MAP.getCenter();
					Section.add(latlng);
				} else {
					alert('地標最多新增至十筆');
				}
			});
			$('#styleController :radio').bind('click', Setting.setStyleController);
			$('#submit-button').bind('click', submitSetting);
			
			// Query Address
			$('.query-form').submit(function(){
				queryAddr($('.input-text-address').val());
				return false;
			});
			$('.input-text-address').bind('focus', function(){$(this).removeClass('out-of-focus').addClass('in-focus').select()})
		},
		ajax: function() {
			var loading = function() {
				var messageStyle = {width:'300px', height:'100px', backgroundColor: '#eef5f5', textAlign: 'center', border: '2px solid #baccfa'};
				var overlayStyle = {cursor:'default'};
				$.blockUI({message:$('#loadingWrapper'), css:messageStyle, overlayCSS:overlayStyle});
			};
			var complete = function() {
				$.unblockUI();
			};
			$.ajaxSetup({
				beforeSend: loading,
				error: complete,
				success: complete,
				complete: complete
			});
		},
		getSettingQuery: function() {
			if (baseUrl.indexOf('?') > -1)
				settingQueryCallback();
		}
	};
	/**************************/
		
	/* Context Menu */
	var ContextMenu = {
		init: function(latlng) {
			var html = '<a href="javascript:void(0);">新增地標點</a><a href="javascript:void(0);">關閉選單</a>';
			var contextMenu = $('<div class="context-menu"></div>').html(html).appendTo($('body'));
			// Add New Marker
			$('a', contextMenu).eq(0).bind('click', function(){
				ContextMenu.close($('.context-menu'));
				if ($('#markerSection .marker-section .marker-content').length < 10) {
					Section.add(latlng);
				} else {
					alert('地標最多新增至十筆');
				}
			});
			// Close Context Menu
			$('a', contextMenu).eq(1).bind('click', function(){ContextMenu.close($('.context-menu'))});
		},
		show: function(latlng, element) {
			//var e = e || window.event;
			//var MouseObj = ContextMenu.getPos(e);
			var parentOffset = $('.wrapper').offset();
			var point = MAP.transformLatLngToContainerCoordinates(latlng);
			$(element).css({left:point.x+parentOffset.left, top:point.y+parentOffset.top});
			$(element).show();
		},
		close: function(element) {
			$(element).hide();
		}
	};
	/****************/
	
	/* Define Minimum And Maximum Of Map Size */
	var MapSize = {
		minWidth: 250,
		minHeight: 150,
		maxWidth: $('body').width() - $('.setting-form').width() - 73,
		maxHeight: 500,
		reset: function() {
			$('.setup-size :text').each(function() {
				$(this).removeClass().addClass('input-setup-size');
			});
			var errorSpan = $('.setting-form').find('span.size-error-msg');
			errorSpan.html('');
			errorSpan.parent().hide();
		},
		validate: function(width, height) {
			MapSize.reset();
			var isValidW = false;
			var isValidH = false;
			var errorMsg = '';
			if (width >= MapSize.minWidth && width <= MapSize.maxWidth) {
				isValidW = true;
			} else {
				isValidW = false;
				$('.setup-size :text').eq(0).removeClass().addClass('input-size-error');
				errorMsg += '寬： >= ' + MapSize.minWidth + 'px and <=' + MapSize.maxWidth + 'px<br />';	
			}
			if (height >= MapSize.minHeight && height <= MapSize.maxHeight) {
				isValidH = true;
			} else {
				isValidH = false;
				$('.setup-size :text').eq(1).removeClass().addClass('input-size-error');
				errorMsg += '高： >= ' + MapSize.minHeight + 'px and <= ' + MapSize.maxHeight + 'px';	
			}
			return {isValidW:isValidW, isValidH:isValidH, errorMsg:errorMsg};
		},
		showError: function(errorMsg) {
			var errorSpan = $('.setting-form').find('span.size-error-msg');
			errorSpan.html(errorMsg);
			errorSpan.parent().show();
		}
	};
	/*****************************************/
	
	/* Set Style Of Map */
	var MapStyle = {
		get: function() {
			var currentClass = $('.map-container div').eq(0).attr('className');
			var currentStyle = currentClass.split('-')[0];
			return currentStyle;
		},
		set: function(currentStyle, newStyle) {
			$('.map-container div').each(function(){
				var currentClass = $(this).attr('className');
				if (currentClass != '' && currentClass.match(currentStyle) != null) {
					var newClass = currentClass.replace(currentStyle, newStyle);
					$(this).removeClass().addClass(newClass);
				}
			});
		}
	};
	/********************/
	
	/* Setting */
	var Setting = {
		selectEvent: function() {
			if ($(this).val() == 'setup') {
				$('.setup-size').css('display', 'inline-block');
			} else {
				$('.setup-size').css('display', 'none');
				eval('sizeArray = new Array(' + $(this).val() + ')');
				Setting.setMapSize(sizeArray);
			}
		},
		keyEvent: function(e) {
			if (e.keyCode == 13) {
				var sizeArray = [];
				$('.setup-size :text').each(function(i) {
					sizeArray[i] = $(this).val();
				});
				Setting.setMapSize(sizeArray);
			}
		},
		changeEvent: function() {
			var sizeArray = [];
			$('.setup-size :text').each(function(i) {
				sizeArray[i] = $(this).val();
			});
			Setting.setMapSize(sizeArray);
		},
		setMapSize: function(sizeArray) {
			if (sizeArray.length > 2) return;
			var width = parseInt(sizeArray[0]);
			var height = parseInt(sizeArray[1]);
			var widthSpan = $('.map-container div:nth-child(2)').width() - $('#map').width();
			var heightSpan = $('.map-container div:nth-child(2)').height() - $('#map').height();
			var containerW = width + widthSpan;
			var containerH = height + heightSpan;
			var validObj = MapSize.validate(width, height);
			if (validObj.isValidW || validObj.isValidH) {
				if (validObj.isValidW) {
					$('.map-container').width(containerW);
					$('#map').width(width);
					var wrapperW = $('.body-left').width() + $('.body-right').width();
					$('.wrapper').width(wrapperW);
				}
				if (validObj.isValidH) {
					$('.map-container').height(containerH);
					$('#map').height(height);
				}	
				var centerLatLng = MAP.getCenter();
				MAP.checkResize();
				MAP.centerMap(centerLatLng);
			}
			if (!validObj.isValidW || !validObj.isValidH)
				MapSize.showError(validObj.errorMsg);	
		},
		getMapSize: function() {
			var mapSize = '&w=' + parseInt($('#map').width()) + ',h=' + parseInt($('#map').height());
			return mapSize;
		},
		showMapSize: function(width, height) {
			var containerW = width + 10;
			var containerH = height + 10;
			$('.map-container').css('width', containerW).css('height', containerH);
			$('#map').css('width', width).css('height', height);
			MAP.checkResize();
		},
		setZoomController: function() {
			$('#zoomController :radio').attr('checked', false);
			MAP.removeControl(U_FULLZOOM_CONTROL);
			MAP.removeControl(U_MINIZOOM_CONTROL);
			$(this).attr('checked', true);
			if ($(this).val() == '0')
				MAP.addControl();
			else if ($(this).val() == '1')
				MAP.addControl(U_FULLZOOM_CONTROL);
			else
				MAP.addControl(U_MINIZOOM_CONTROL);
		},
		getZoomController: function() {
			var zoomController = '';
			$('#zoomController :radio').each(function(){
				if ($(this).attr('checked'))
					zoomController = $(this).val();
			});
			return zoomController;
		},
		getMapZoomLevel: function() {
			var zoomLevel = MAP.getZoomLevel();
			return zoomLevel;
		},
		showZoomController: function(value) {
			if (value == '0')
				MAP.addControl();
			else if (value == '1')
				MAP.addControl(U_FULLZOOM_CONTROL);
			else
				MAP.addControl(U_MINIZOOM_CONTROL);
		},
		setTypeController: function() {
			$('#typeController :radio').attr('checked', false);
			MAP.removeControl(U_TYPE_CONTROL);
			$(this).attr('checked', true);
			if ($(this).val() == '0')
				MAP.addControl();
			else
				MAP.addControl(U_TYPE_CONTROL);
		},
		getTypeController: function() {
			var typeController = '';
			$('#typeController :radio').each(function(){
				if ($(this).attr('checked'))
					typeController = $(this).val();
			});
			return typeController;
		},
		showTypeController: function(type, mapType) {
			// Set Map Type
			if (mapType == '400')
				MAP.setMapType(U_MAP_TYPE);
			else if (mapType == '401')
				MAP.setMapType(U_SATELLITE_TYPE);
			else if (mapType == '402')
				MAP.setMapType(U_HYBRID_TYPE);
			// Add Map Type Controller
			if (type == '0') {
				MAP.addControl();
			} else {
				MAP.addControl(U_TYPE_CONTROL);
			}
		},
		setStyleController: function() {
			$('#styleController :radio').attr('checked', false);
			$(this).attr('checked', true);
			var currentStyle = MapStyle.get();
			var newStyle = $(this).val();
			MapStyle.set(currentStyle, newStyle);
			var sizeArray = [$('#map').width(), $('#map').height()];
			Setting.setMapSize(sizeArray);
		},
		getStyleController: function() {
			var styleValue = '';
			$('#styleController :radio').each(function(){
				if ($(this).attr('checked'))
					styleValue = $(this).val();
			});
			return styleValue;
		},
		showStyleController: function(value) {
			var currentStyle = MapStyle.get();
			var newStyle = value;
			MapStyle.set(currentStyle, newStyle);
		}
	};
	/**********/
	
	
	/* Marker Section */
	var Section = {
		add: function(latlng) {
			if ($('#markerSection').find('.marker-section .marker-content:visible')) {
				var visibleMarkerSectionDiv = $('#markerSection .marker-section .marker-content:visible');
				visibleMarkerSectionDiv.slideUp('slow');
				visibleMarkerSectionDiv.parent().css('cursor', 'pointer');
			}
			// Append Marker Section
			$('#markerSection').append($('#markerWrapper').html());
			// Get The Last Marker Section
			var markerSectionDiv = $('#markerSection .marker-section:last-child');
			$('.marker-content', markerSectionDiv).slideDown('slow');
			// Get Default Checked
			$('[name="markerController"] :radio', markerSectionDiv).eq(0).attr('checked', true);
			// Add Marker
			var marker = new UMarker(latlng);
			marker.sectionDiv = markerSectionDiv;
			marker.icon.image = defaultIcon.image;
			setMarkerIcon(marker);
			$(markerSectionDiv).data('marker', marker);
			var infoWindowOptions = new UInfoWindowOptions();
			var initInfoWindow = function() {
				var html = '<span class="label">' + marker.label + '</span><p class="description">' + marker.desc + '<p><a class="delete-link" href="javascript:void(0);">刪除地標點</a>';
				var element = $('<div></div>').addClass('info-window').html(html).get(0);
				infoWindowOptions.content = element;
				$('a', $(element)).bind('click', function(){
					if (confirm('您確定刪除此地標？'))
						Section.del(marker);
					return false;
				});
			};
			var showInfoWindow = function() {
				var element = $(infoWindowOptions.content);
				var label = element.find('.label').html(marker.label);
				var desc = element.find('.description').html(marker.desc);
				infoWindowOptions.content = element.get(0);
				marker.openInfoWindow(infoWindowOptions);
			};
			initInfoWindow();
			
			var resetSrcError = function() {
				$('[name="markerSrc"] :text', markerSectionDiv).removeClass().addClass('input-text-marker');
				var errorSpan = $(markerSectionDiv).find('span.src-error-msg');
				$(errorSpan).html('');
				$(errorSpan).parent().hide();
			};
			var iconSelected = function() {
				MAP.closeInfoWindow();
				resetSrcError();
				// Initialize Icon Options
				$('[name="markerController"] :radio', markerSectionDiv).attr('checked', false);
				// Get The Option Checked
				$(this).attr('checked', true);
				// Show/Hide Icon Input
				if ($(this).val() == '0') { // Default Icon
					$('[name="markerSrc"]', markerSectionDiv).hide();
					$('[name="markerLabel"]', markerSectionDiv).show();
					$('[name="markerDescription"]', markerSectionDiv).show();
					marker.icon.image = defaultIcon.image;
					setMarkerIcon(marker);
					MAP.addOverlay(marker);
				} else { // Personalized Icon
					$('[name="markerSrc"]', markerSectionDiv).show();
					$('[name="markerLabel"]', markerSectionDiv).show();
					$('[name="markerDescription"]', markerSectionDiv).show();
					if ($('[name="markerSrc"] :text', markerSectionDiv).val() != '') {
						marker.icon.image = $('[name="markerSrc"] :text', markerSectionDiv).val();
						setMarkerIcon(marker);
					}
					MAP.addOverlay(marker);
				}
			};
			var srcInput = function() {
				MAP.closeInfoWindow();
				resetSrcError();
				var value = $(this).val();
				var errorSpan = $(markerSectionDiv).find('span.src-error-msg');
				if (value != '') {
					var pattern = new RegExp('\.(bmp|jpg|jpeg|png|gif|BMP|JPG|JPEG|PNG|GIF)$');
					if (pattern.test(value)) {
						$(this).removeClass().addClass('input-text-marker');
						marker.icon.image = value;
					} else {
						$(this).removeClass().addClass('input-text-error');
						$(errorSpan).html('您輸入的格式錯誤');
						$(errorSpan).parent().show();
					}
				} else {
					$(this).removeClass().addClass('input-text-error');
					$(errorSpan).html('請輸入圖示路徑');
					$(errorSpan).parent().show();
				}
				setMarkerIcon(marker);
			};
			var labelInput = function() {
				marker.label = $(this).val();
				setupMouseonInfo(marker);
				showInfoWindow();
			};
			var descriptionInput = function() {
				marker.desc = $(this).val();
				setupMouseonInfo(marker);
				showInfoWindow();
			};
			// Select Default Icon/Personalized Icon/None
			$('[name="markerController"] :radio', markerSectionDiv).bind('click', iconSelected);
			// Input Marker Icon Src
			$('[name="markerSrc"] :text', markerSectionDiv).bind('blur', srcInput);
			// Input Marker Label
			$('[name="markerLabel"] :text', markerSectionDiv).bind('blur', labelInput);
			// Input Marker Description
			$('[name="markerDescription"] :input', markerSectionDiv).bind('blur', descriptionInput);
			// Delete Section & Marker
			$('.delete-button', markerSectionDiv).bind('click', function(){
				if (confirm('您確定刪除此地標？'))
					Section.del(marker);
			});
			// Marker Events
			marker.addListener('mouseover', function(){setupMouseonInfo(marker)});
			marker.addListener('dragging', function(){MAP.closeInfoWindow()});
			marker.addListener('dragend', function(){showInfoWindow();});
			marker.addListener('click', function(){
				MAP.removeListener('moveend', WriteAnchorUrl);
				showInfoWindow();
				setTimeout(function(){
					MAP.addListener('moveend', WriteAnchorUrl);
				}, 500);
			});
			marker.enableDragging();
			// Add Marker Onto The Map
			MAP.addOverlay(marker);
			$(markerSectionDiv).bind('click', function(){
				if ($('.marker-content', markerSectionDiv).is(':visible'))
					return false;
				if (!$('.marker-content', markerSectionDiv).is(':visible')) {
					var visibleMarkerSectionDiv = $('#markerSection .marker-section .marker-content:visible');
					visibleMarkerSectionDiv.slideUp('slow');
					visibleMarkerSectionDiv.parent().css('cursor', 'pointer');
					$('.marker-content', markerSectionDiv).slideDown('slow');
					markerSectionDiv.css('cursor', 'default');
					return false;
				}
			});
		},
		edit: function() {
			
		},
		del: function(marker) {
			MAP.closeInfoWindow();
			var markerSectionDiv = marker.sectionDiv;
			$(markerSectionDiv).remove();
			MAP.removeOverlay(marker);
		},
		show: function(markerObj) {
			var icon = new UIcon({
				image: 'http://maps.urmap.com/api/img/marker.gif',
				iconWidth: 16,
				iconHeight: 16,
				iconAnchor: new UPoint(8, 8),
				infoWindowAnchor: new UPoint(8, 0)
			});
			if (markerObj.iconType == '1') // Personalized Icon
				icon.image = markerObj.image;
			var marker = new UMarker(markerObj.latlng, icon, markerObj.label, markerObj.description);
			var infoWindowOptions = new UInfoWindowOptions();
			setMarkerIcon(marker);
			var showInfoWindow = function() {
				var html = '<span class="label">' + marker.label + '</span><p class="description">' + marker.desc + '<p>';
				var element = $('<div></div>').addClass('info-window').html(html).get(0);
				infoWindowOptions.content = element;
				marker.openInfoWindow(infoWindowOptions);
			};
			marker.addListener('mouseover', function(){setupMouseonInfo(marker)});
			marker.addListener('click', function(){
				MAP.removeListener('moveend', WriteAnchorUrl);
				showInfoWindow();
				setTimeout(function(){
					MAP.addListener('moveend', WriteAnchorUrl);
				}, 500);
			});
			MAP.addOverlay(marker);
			tmpMrks.push(marker);
		}
	};	
	/******************/
		
	/* Set Marker Icon */
	var setMarkerIcon = function(marker) {
		var markerSectionDiv = marker.sectionDiv;
		var icon = marker.icon;
		var img = new Image();
		img.src = icon.image;
		img.onload = function() {
			icon.iconWidth = img.width;
			icon.iconHeight = img.height;
			icon.iconAnchor = new UPoint(img.width/2, img.height/2);
			icon.infoWindowAnchor = new UPoint(img.width/2, 0);
			marker.setIcon(icon);
		}
		img.onerror = function() {
			/*$('[name="markerSrc"] :text', markerSectionDiv).removeClass()
														   .addClass('input-text-error')
														   .val('圖示路徑錯誤');*/
		}
	};
	/*******************/
	
	/* Mouseover Marker */
	var setupMouseonInfo = function(marker) {
		marker.setMouseonInfo(marker.label, marker.desc);
	};
	/********************/
	
	
	/* Get Markers On The Map */
	var getMarkers = function() {
		var markers = '';
		$('#markerSection .marker-section').each(function(){
			if ($(this).children().length != 0) {
				var markerSectionDiv = $(this);
				var icon = '';
				$('[name="markerController"] :radio', markerSectionDiv).each(function(){
					if ($(this).attr('checked'))
						icon = $(this).val();
				});
				var image = $('[name="markerSrc"] :text', markerSectionDiv).val();
				var label = encodeURIComponent($('[name="markerLabel"] :text', markerSectionDiv).val());
				var description = encodeURIComponent($('[name="markerDescription"] :input', markerSectionDiv).val());
				var latlng = $(markerSectionDiv).data('marker').getPoint().ec();
				markers += 'icon=' + icon + '|image=' + image + '|label=' + label + '|description=' + description + '|latlng=' + latlng + '||';
			}
		});
		if (markers != '')
			markers = markers.substring(0, markers.length-1);
		return markers;
	};
	/**************************/
	
	/* Submit Setting Form */
	var submitSetting = function() {
		var messageStyle = {width:'450px', height:'120px', backgroundColor: '#eef5f5', textAlign: 'left', border: '2px solid #baccfa'};
		var overlayStyle = {cursor:'default'};
		$.blockUI({message:$('.url-container'), css:messageStyle, overlayCSS:overlayStyle});
		if ($('.url-container:visible')) {
			$('.url-container :text').focus(function(){$(this).select()});
			$('#close-button').bind('click', function(){$.unblockUI()});
		}
		var centerLatlng = 'centerLatlng=' + MAP.getCenter().ec();
		var zoomLevel = '&zoomLevel=' + Setting.getMapZoomLevel();
		var mapSize = Setting.getMapSize();
		var zoomController = '&zoom=' + Setting.getZoomController();
		var typeController = '&type=' + Setting.getTypeController();
		var mapType = '&mapType=' + MAP.getCurrentMapType();
		var styleController = '&style=' + Setting.getStyleController();
		var markers = '&' + getMarkers();
		var parameters = centerLatlng + zoomLevel + mapSize + zoomController + typeController + mapType + styleController + markers;
		var url = embedUrl + '?' + parameters;
		$('.url-container :text').eq(0).val(url);
		var width = parseInt($('.map-container').width());
		var height = parseInt($('.map-container').height());
		var iframeString = '<iframe width="' + width + '" height="' + height + '" frameborder="no" scrolling="no" marginheight="0" marginwidth="0" src="' + url + '"></iframe>';
		$('.url-container :text').eq(1).val(iframeString);
		$('.url-container a').attr('href', url);
	};
	/***********************/
	
	/* Split Parameters Of Map Setting Query */
	var settingQueryCallback = function() {
		//var queryString = baseUrl.substr(baseUrl.indexOf('?')+1).toLowerCase();
		var queryString = baseUrl.substr(baseUrl.indexOf('?')+1);
		var tempArray = queryString.split('&');
		var centerLatlng = tempArray[0].split('=')[1];
		if (centerLatlng.search(',') >= 0) {
			var tempCenter = centerLatlng.split(',');
			if (tempCenter[0] == 'latlng')
				centerLatlng = new ULatLng(parseFloat(tempCenter[1]), parseFloat(tempCenter[2]));
			else if (tempCenter[0] == 'xy')
				centerLatlng = new ULatLng(parseFloat(tempCenter[1]), parseFloat(tempCenter[2]), U_TM2_COORDSYS);
		} else {
			centerLatlng = new ULatLng(centerLatlng, 'DES');
		}
		var zoomLevel = parseInt(tempArray[1].split('=')[1]);
		var tempSizeArray = tempArray[2].split(',');
		var width = parseInt(tempSizeArray[0].split('=')[1]);
		var height = parseInt(tempSizeArray[1].split('=')[1]);
		var size = {width:width, height:height};
		var zoom = tempArray[3].split('=')[1];
		var type = tempArray[4].split('=')[1];
		var mapType = tempArray[5].split('=')[1];
		var style = tempArray[6].split('=')[1];
		if (tempArray[7] != '') {
			var tempMarkerArray = tempArray[7].split('||');
			for (var i=0; i<tempMarkerArray.length; i++) {
				var markerObj = {};
				var markerArray = tempMarkerArray[i].split('|');
				markerObj['iconType'] = markerArray[0].split('=')[1];
				markerObj['image'] = markerArray[1].split('=')[1];
				markerObj['label'] = decodeURIComponent(markerArray[2].split('=')[1]);
				markerObj['description'] = decodeURIComponent(markerArray[3].split('=')[1]);
				var latlng = markerArray[4].split('=')[1];
				if (latlng.search(',') >= 0) {
					var tempLatlng = latlng.split(',');
					if (tempLatlng[0] == 'latlng')
						markerObj['latlng'] = new ULatLng(parseFloat(tempLatlng[1]), parseFloat(tempLatlng[2]));
					else if (tempLatlng[0] == 'xy')
						markerObj['latlng'] = new ULatLng(parseFloat(tempLatlng[1]), parseFloat(tempLatlng[2]), U_TM2_COORDSYS);
				} else {
					markerObj['latlng'] = new ULatLng(latlng, 'DES');
				}
				Section.show(markerObj);
			}
		}
		Setting.showMapSize(width, height);
		Setting.showZoomController(zoom);
		Setting.showTypeController(type, mapType);
		Setting.showStyleController(style);
		MAP.centerAndZoom(centerLatlng, zoomLevel);
		// find the marker nearest the center marker and open its infowindow
		var centerMarker = tmpMrks[0];
		var dist = centerMarker.getPoint().distanceTo(centerLatlng);
		if (tmpMrks.length > 1) {
			for (var j=1; j<tmpMrks.length; j++) {
				var mrk = tmpMrks[j];
				if (mrk.getPoint().distanceTo(centerLatlng) < dist) {
					dist = mrk.getPoint().distanceTo(centerLatlng);
					centerMarker = mrk;
				}
			}
		}
		centerMarker.triggerEvent('click');
	};	
	/*****************************************/
	
	/* Write Anchor Href To UrMap.com */
	var WriteAnchorUrl = function() {
		var url = toMapUrl + '?center=' + MAP.getCenter().toUrlString() + '&zoom=' + MAP.getZoomLevel();
		$('#toMapAnchor').attr('href', url);
	};	
	
	var encodeUrLatlng = function(num) {
		var str = num + '';
		var output = '';
		for(var i=0; i<str.length; i++){
			var cha = str.charCodeAt(i) + 49;
			cha = String.fromCharCode(cha);
			output += cha;
		}
		return (output);
	};
	
	var decodeUrLatlng = function(str) {
		var str = str + '';
		var output = '';
		for(var i=0; i<str.length; i++){
			var cha = str.charCodeAt(i) - 49;
			cha = String.fromCharCode(cha);
			output += cha;
		}
		return (output);
	};
	/**********************************/
	
	var queryAddr = function(qs){
		qs = encodeURI(qs);
		//var src = "queryAddress.jsp?qs="+qs+"&callback=Uindex.searchCallback";
		var src = queryAddressUrl + '?qs=' + qs + '&callback=Uindex.searchCallback';
		$.getScript(src);
	};
	
	var searchCallback = function (data){
		if(typeof data !== 'object')
			return;
		var record = data['api-data-root']['records']['record'];
		var status = parseInt(record.status_code);
		if(status){
			var lat = parseFloat(record.latitude);
			var lng = parseFloat(record.longitude);
			var latlng = new ULatLng(lat, lng);
			var addr = record.address;
			var msg = record.msg;
			searchMarker.setPoint(latlng);
			MAP.centerMap(latlng);
			setTimeout(function(){
				openSearchMarkerInfoWindow(searchMarker, addr, msg);
			}, 200);
			
		}else{
			alert('無法定位！');
		}
		searchMarker.searchRecord = record;
	};
	
	var searchMarkerClicked = function(e, marker, latlng){
		var searchRecord = marker.searchRecord;
		var addr = searchRecord.address;
		var msg = searchRecord.msg;
		openSearchMarkerInfoWindow(marker, addr, msg);
	};
	
	var openSearchMarkerInfoWindow = function(marker, addr, msg){
		var element = document.createElement('DIV');
		element.className = 'info-window';
		var html = '<p class="description">您查詢的地址：<span class="highlighted">' + addr + '</span></p><br /><p class="description">' + msg + '</p>';
		element.innerHTML = html;
		marker.openInfoWindow(element);
	};
	
	(function(){
		for(var i in Init){
			Init[i]();
		}
	})();
	
	this.searchCallback = searchCallback;
};