var centerLat = 25.013068400;
var centerLong = 121.529376148;
var mapCenterCrosshair;
var mapObj;
var mapJSONObject;
var now = new Date();
var lastMoveTime = now.getTime();
var searchMod = 'MoveMap';

// Recenter map
function BtnRecenterMap_OnClick() {
	mapObj.centerMap(new ULatLng(centerLat, centerLong));
}

// Center map to hotspot
function LinkHotspot_OnClick(hotspotLon, hotspotLat) {
	var latLon = new ULatLng(hotspotLat, hotspotLon);
	mapObj.centerMap(latLon);
	repositionCenterMarker(latLon);
}
// Resposition map center
function repositionCenterMarker(latLng)
{
	// Remove old center
	if (mapCenterCrosshair != null)
		mapObj.removeOverlay(mapCenterCrosshair);
	// Add new center crosshair mark
	var iconCenter = new UIcon();
	iconCenter.image = '../images/crosshair.gif';
	iconCenter.iconWidth = 16;
	iconCenter.iconHeight = 16;
	iconCenter.iconAnchor = new UPoint(7, 0);
	var centerPoint = new ULatLng(latLng.lat(), latLng.lng()); 
	var centerMarker = new UMarker(centerPoint, iconCenter);
	mapCenterCrosshair = centerMarker;
	mapObj.addOverlay(centerMarker);
}

// Setting the default Button for a TextBox
function clickButton(e, buttonid){ 
	var bt = document.getElementById(buttonid); 
	if (typeof bt == 'object'){ 
		if(navigator.appName.indexOf("Netscape")>(-1)){ 
			if (e.keyCode == 13){ 
					bt.click(); 
					return false; 
			} 
		} 
		if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){ 
			if (event.keyCode == 13){ 
					bt.click(); 
					return false; 
			} 
		} 
	} 
} 

function CopyLocationToClipboard()
{
	var CopiedTxt = '<a href="http://www.qon.com.tw/hotsearch/wifly/default.aspx?lon=' + mapObj.getCenter().lng() +
				'&lat=' + centerLat + '&addr=' + encodeURIComponent(document.Form1.TextBoxAddrToSearch.value) + 
				'">這個位置附近可無線上網的地點</a>';
	clipboardData.setData('Text',CopiedTxt);
	alert('「' + CopiedTxt + '」已經複製到剪貼簿。你可以把此超連結貼到網頁來分享給朋友。');
}

// AJAX
var xmlHttp,xmlHttp2,xmlHttp3; 
var requestURL = 'GetWiflyHotspots.aspx'; 
//var requestURL = 'http://localhost:100/CMSNew/PriorityCompany_NewGrid.aspx'; 
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
//netscape, safari, mozilla behave the same??? 
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 


function ShowHotspotsTable(center)
{
	// Only show geographic objects for zoom level > 9
	if (mapObj.getZoomLevel() < 9)
		return;
 				
	// Get map size
	//--------------------------------------------------------------
	var bounds = mapObj.getBounds();
	var mapWidth = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
	var mapHeight = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
	
	if (mapWidth == 0)
	{
		mapWidth = 0.015838846062564471;
		mapHeight = 0.010741243142408763;
	}
	var minLong  = center.lng() - mapWidth / 2;
	var maxLong  = center.lng() + mapWidth / 2;
	var minLat  = center.lat() - mapHeight / 2;
	var maxLat  = center.lat() + mapHeight / 2;

	//--------------------------------------------------------------
	var query = document.getElementById("txtQuery").value;
	var rows = document.getElementById("txtRows").value;
	var sortExpr = document.getElementById("txtSort").value;
	var page = document.getElementById("txtPage").value;
	
	query =	"SELECT TOP 200 ID, Name, GeoAddress, Type, IsFree, Longitude, Latitude, QonLevel FROM PublishedHotspots WHERE " +
			"(Longitude BETWEEN " + minLong + " AND " + maxLong + ") AND (Latitude BETWEEN " + minLat + " AND " + maxLat + ") " +
			"AND (WISP LIKE '%wifly%' OR WISP LIKE '%安源%') ORDER BY QonLevel DESC, IsFree DESC, Longitude, Latitude, Name";

	//Append the name to search for to the requestURL 
	var url = "GetWiflyHotspotTable.aspx?query=" + escape(query) + 
			  "&rows=" + rows + "&gridpage=" + page + "&expression=" + sortExpr;

	//Create the xmlHttp object to use in the request 
	//stateChangeHandler will fire when the state has changed, i.e. data is received back 
	// This is non-blocking (asynchronous) 
	xmlHttp2 = GetXmlHttpObject(hotspotsTableHandler); 
		
	//Send the xmlHttp get to the specified url 
	xmlHttp_Get(xmlHttp2, url); 
} 
// Process the HTTP Response when it is complete
function hotspotsTableHandler()
{
	if (xmlHttp2.readyState == 4)
	{
		if (xmlHttp2.status == 200)
		{
			var retval=xmlHttp2.responseText;
			if (document.getElementById("results")!=null)
			{
				document.getElementById("results").innerHTML = retval;
			}
			else
			{
				alert("Error retrieving data!");
			}
		}
	}
}
// Called when a column header is clicked
function sortGrid(sortExpr)
{
	document.getElementById("txtSort").value = sortExpr;
	ShowHotspotsTable(mapObj.getCenter());
}

// Called when the grid is paged
function pageGrid(page)
{
	document.getElementById("txtPage").value = page;
	ShowHotspotsTable(mapObj.getCenter());
}

function ShowHotspots(center)
{ 				
	// Only show geographic objects for zoom level > 9
	if (mapObj.getZoomLevel() < 9)
		return;

	var bounds = mapObj.getBounds();
	var width = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
	var height = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();

	//Append the name to search for to the requestURL 
	var url = requestURL + '?twd97Long=' + center.lng() + '&twd97Lat=' + center.lat() + 
				'&addrText=' + encodeURIComponent(document.Form1.TextBoxAddrToSearch.value) + 
				'&mapWidth=' + width + '&mapHeight=' + height;
		
	//Create the xmlHttp object to use in the request 
	//stateChangeHandler will fire when the state has changed, i.e. data is received back 
	// This is non-blocking (asynchronous) 
	xmlHttp = GetXmlHttpObject(stateChangeHandler); 
		
	//Send the xmlHttp get to the specified url 
	xmlHttp_Get(xmlHttp, url); 
	//document.body.style.cursor = 'wait';
	document.getElementById('searching').style.display = 'block';
} 

//stateChangeHandler will fire when the state has changed, i.e. data is received back 
// This is non-blocking (asynchronous) 
function stateChangeHandler() 
{ 
	//readyState of 4 or 'complete' represents that data has been returned 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		//document.body.style.cursor = 'auto';
		//Gather the results from the callback 
		var str = xmlHttp.responseText; 

		//Populate the innerHTML of the div with the results 
		//document.getElementById('serverTime').innerHTML = 'The time on the server is <b>' + str; 

		//alert(str);
		//var myJSONObject = eval('(' + str + ')');
		//alert(myJSONObject.HotspotInfo[0].ID + ' ' + myJSONObject.HotspotInfo[0].Name);
		//alert(myJSONObject.HotspotInfo[10].ID + ' ' + myJSONObject.HotspotInfo[10].Name);
		//alert(myJSONObject.HotspotInfo.length);
		//document.Form1.TextDebug.value += 'Get JSON text.\n';
		mapJSONObject = eval('(' + str + ')');
		//alert(testobj.test);
		if(mapJSONObject)
		{
			centerLat = mapJSONObject.twd97Lat;
			centerLong = mapJSONObject.twd97Long;
		}
		else
		{
			centerLong = mapObj.getCenter().lng();
			centerLat = mapObj.getCenter().lat();
		}
		if(mapJSONObject.IsErrorAddr == 0)
		{
			mapObj.centerMap(new ULatLng(centerLat, centerLong));
			searchMod='FinishSearch';
			mapObj.clearOverlays();
			ReDrawMap();

			// Get hotspot table
			//document.getElementById("txtPage").value = 1;
			//ShowHotspotsTable(mapObj.getCenter());
			document.getElementById('ErrorAddrText').style.display = 'none';
		}
		else
		{
			//alert('找不到您輸入的地址，請改用經緯度搜尋、或是「進階搜尋」。');
			document.getElementById('ErrorAddrText').style.display = 'block';
		}
		document.getElementById('searching').style.display = 'none';
	} 
} 

// Get longitude and latitude by UrMap API
function GetTWD97ByGeoAddressByUrmap()
{
	// Encode address is Big5
	//Dim encodedGeoAddr As String = HttpUtility.UrlEncode(geoAddr, enc)
	var uriString = "http://www.urmap.com/asp/yesturnkey/getxy.jsp?address="
					+ document.Form1.TextBoxAddrToSearch.value + "&encode=Big5";

	xmlHttp3 = GetXmlHttpObject(GetWD97); 
		
	//Send the xmlHttp get to the specified url 
	xmlHttp_Get(xmlHttp3, uriString); 
}

// Process the HTTP Response when it is complete
function GetWD97()
{
	if (xmlHttp3.readyState == 4)
	{
		if (xmlHttp3.status == 200)
		{
			var responseStr = xmlHttp3.responseText;
			// Parse longitude and latitude
			responseStr = responseStr.replace(/^\s+|\s+$/g, "");
			var coords = responseStr.split(",");
			var twd97long = coords[0];
			var twd97lat = coords[1];
			if (twd97long != 0 && twd97lat != 0)
			{
				LinkHotspot_OnClick(twd97long,twd97lat);
				//document.Form1.TextDebug.value += 'searching...\n';
				IsSearch = 0;
				ShowHotspots(mapObj.getCenter());
				
				// Get hotspot table
				//document.getElementById("txtPage").value = 1;
				//ShowHotspotsTable(mapObj.getCenter());
			}
			else
			{
				// Error address!
			}
		}
	}
}

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) { 
	xmlhttp.open('GET', url, true); 
	xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler) 
{ 
	var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

	//Depending on the browser, try to create the xmlHttp object 
	if (is_ie){ 
		//The object to create depends on version of IE 
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object 
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
			
		//Attempt to create the object 
		try{ 
			objXmlHttp = new ActiveXObject(strObjName); 
			objXmlHttp.onreadystatechange = handler; 
		} 
		catch(e){ 
		//Object creation errored 
			alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
			return; 
		} 
	} 
	else if (is_opera){ 
		//Opera has some issues with xmlHttp object functionality 
		alert('Opera detected. The page may not behave as expected.'); 
		return; 
	} 
	else{ 
		// Mozilla | Netscape | Safari 
		objXmlHttp = new XMLHttpRequest(); 
		objXmlHttp.onload = handler; 
		objXmlHttp.onerror = handler; 
	} 
		
	//Return the instantiated object 
	return objXmlHttp; 
} 

var IsSearch = 0;
function CheckIfSearch(check)
{
	//document.Form1.TextDebug.value += 'checking...\n';
	if (IsSearch == check)
	{
		//document.Form1.TextDebug.value += 'searching...\n';
		IsSearch = 0;
		ShowHotspots(mapObj.getCenter());
		
		// Get hotspot table
		//document.getElementById("txtPage").value = 1;
		//ShowHotspotsTable(mapObj.getCenter());
	}
}

// Initialize UrMap
function initAJAX() 
{
	//document.Form1.TextDebug.value += 'Initial map.\n';
	// Icon for unknown hotspot
	var iconUnknown = new UIcon();
	iconUnknown.image = '../images/UnknownHotspot.gif';
	iconUnknown.iconWidth = 16;
	iconUnknown.iconHeight = 16;
	iconUnknown.iconAnchor = new UPoint(9, 9);
	iconUnknown.infoWindowAnchor = new UPoint(16, 0);

	// Icon for free hotspot
	var iconFree = new UIcon();
	iconFree.image = '../images/wifly_icon.gif';
	iconFree.iconWidth = 16;
	iconFree.iconHeight = 16;
	iconFree.iconAnchor = new UPoint(9, 9);
	iconFree.infoWindowAnchor = new UPoint(16, 0);

	// Icon for for-fee hotspot
	var iconForFee = new UIcon();
	iconForFee.image = '../images/wifly_icon.gif';
	iconForFee.iconWidth = 16;
	iconForFee.iconHeight = 16;
	iconForFee.iconAnchor = new UPoint(9, 9);
	iconForFee.infoWindowAnchor = new UPoint(16, 0);

	// Icon for FON hotspot
	var iconFON = new UIcon();
	iconFON.image = '../images/FonHotspot.gif';
	iconFON.iconWidth = 16;
	iconFON.iconHeight = 16;
	iconFON.iconAnchor = new UPoint(9, 9);
	iconFON.infoWindowAnchor = new UPoint(16, 0);	

	// Create map
	var map;
	if (!mapJSONObject)
	{
		map = new UMap(document.getElementById('map'));
		map.setControlType(U_FULL_CONTROL);
		map.addControl(U_TYPE_CONTROL);
		map.centerAndZoom(new ULatLng(centerLat, centerLong), 9);
		mapObj = map;
	}
	else
	{
		map = mapObj;
	}
	
	// Crosshair icon for center
	var iconCenter = new UIcon();
	iconCenter.image = '../images/crosshair.gif';
	iconCenter.iconWidth = 16;
	iconCenter.iconHeight = 16;
	iconCenter.iconAnchor = new UPoint(7, 0);
	var centerPoint = new ULatLng(centerLat, centerLong); 
	var centerMarker = new UMarker(centerPoint, iconCenter);
	mapCenterCrosshair = centerMarker;
	map.addOverlay(centerMarker);

	// Get center coordinates after moving map
	map.addListener('moveend', function() {
		if(searchMod == 'MoveMap')
		{
			var center = map.getCenter();
			document.Form1.TextBoxAddrToSearch.value = center.lng() + ',' + center.lat();
			repositionCenterMarker(center);
			//alert('Move map!');
			// Test for AJAX
			//document.Form1.TextDebug.value += 'Move map.\n';
			//ShowHotspots(center);
			IsSearch++;
			setTimeout('CheckIfSearch('+IsSearch+')', 1000);
		}
		searchMod = 'MoveMap';
	});

	// Click to recenter map
	map.addListener('click', function(overlay, latLng) {
		if (latLng) {					
			map.centerMap(latLng);
			//repositionCenterMarker(latLng);
			//alert('Click map!');
			// Test for AJAX
			//document.Form1.TextDebug.value += 'Click map.\n';
			//ShowHotspots(map.getCenter());
		}
	});
	
	// Redraw geographical objects after zoom level is changed
	map.addListener('zoom', function() {
		// AJAX-call to show objects on map.
		searchMod = 'FirstSearch';
		ShowHotspots(map.getCenter());
	});

	// Add hotspot markers
	var bounds = map.getBounds();
	var width = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
	var height = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
	var hotspotName;
	var geoAddress;
	var telephone;
	var remark;

	// testing AJAX
	//alert('Getting new array values...');
	if (mapJSONObject)
	{
		//document.Form1.TextDebug.value += 'Drawing hotspot icons.\n';
		//alert(testobj.test);
		for (var i = 0; i < mapJSONObject.HotspotInfo.length; i++) {
			//alert(mapJSONObject.HotspotInfo[i].ID + ' ' + mapJSONObject.HotspotInfo[i].Name);
			hotspotName = '<B>' + mapJSONObject.HotspotInfo[i].Name + '</B>';
			geoAddress = mapJSONObject.HotspotInfo[i].GeoAddress;
			telephone = mapJSONObject.HotspotInfo[i].Telephone;
			remark = mapJSONObject.HotspotInfo[i].Remark;
			var point = new ULatLng(mapJSONObject.HotspotInfo[i].Latitude, 
									mapJSONObject.HotspotInfo[i].Longitude);
			var marker = createMarker(point, hotspotName, geoAddress, 
									  mapJSONObject.HotspotInfo[i].IsFree, 
									  mapJSONObject.HotspotInfo[i].OfferAC, 
									  telephone, remark, 
									  mapJSONObject.HotspotInfo[i].ID);
			map.addOverlay(marker);
		}
	}	
	// Save width & height
	document.Form1.mapWidth.value = width;
	document.Form1.mapHeight.value = height;
	
	//Initial hotspots on map and table.
	searchMod='FirstSearch';
	ShowHotspots(mapObj.getCenter());
}

function ReDrawMap()
{
	// Icon for unknown hotspot
	var iconUnknown = new UIcon();
	iconUnknown.image = '../images/UnknownHotspot.gif';
	iconUnknown.iconWidth = 16;
	iconUnknown.iconHeight = 16;
	iconUnknown.iconAnchor = new UPoint(9, 9);
	iconUnknown.infoWindowAnchor = new UPoint(16, 0);

	// Icon for free hotspot
	var iconFree = new UIcon();
	iconFree.image = '../images/wifly_icon.gif';
	iconFree.iconWidth = 16;
	iconFree.iconHeight = 16;
	iconFree.iconAnchor = new UPoint(9, 9);
	iconFree.infoWindowAnchor = new UPoint(16, 0);

	// Icon for for-fee hotspot
	var iconForFee = new UIcon();
	iconForFee.image = '../images/wifly_icon.gif';
	iconForFee.iconWidth = 16;
	iconForFee.iconHeight = 16;
	iconForFee.iconAnchor = new UPoint(9, 9);
	iconForFee.infoWindowAnchor = new UPoint(16, 0);

	// Icon for FON hotspot
	var iconFON = new UIcon();
	iconFON.image = '../images/FonHotspot.gif';
	iconFON.iconWidth = 16;
	iconFON.iconHeight = 16;
	iconFON.iconAnchor = new UPoint(9, 9);
	iconFON.infoWindowAnchor = new UPoint(16, 0);
	
	// Crosshair icon for center
	var iconCenter = new UIcon();
	iconCenter.image = '../images/crosshair.gif';
	iconCenter.iconWidth = 16;
	iconCenter.iconHeight = 16;
	iconCenter.iconAnchor = new UPoint(7, 0);
	var centerPoint = new ULatLng(centerLat, centerLong); 
	var centerMarker = new UMarker(centerPoint, iconCenter);
	mapCenterCrosshair = centerMarker;
	mapObj.addOverlay(centerMarker);

	// Create custom marker
	function createMarker(point, hotspotName, geoAddress, isFree, offerAcPower, telephone,
						  remark, hotspotID)
	{
		//document.Form1.TextDebug.value += '(' + hotspotID + ') createMarker.\n';

		var marker;
		var isFreeStr;
		var offerAcPowerStr;
		// Is free hotspot?
		if (isFree == '0') {
			marker = new UMarker(point, iconForFee, hotspotName, geoAddress);
			isFreeStr = '<FONT color="red">付費無線上網</FONT>';
		}
		else if (isFree == '1') {
			marker = new UMarker(point, iconFree, hotspotName, geoAddress);
			isFreeStr = '<FONT color="green">免費無線上網</FONT>';
		}
		else if (isFree == '2') {
			marker = new UMarker(point, iconFON, hotspotName, geoAddress);
			isFreeStr = '<FONT color="orange">FON無線上網</FONT>';
		}
		else {
			marker = new UMarker(point, iconUnknown, hotspotName, geoAddress);
			isFreeStr = '<FONT color="blue">無線上網未知是否需付費</FONT>';
		}
		// Offer AC power?
		if (offerAcPower == '0') {
			offerAcPowerStr = '<FONT color="gold">不提供電源插座</FONT>';
		}
		else if (offerAcPower == '1') {
			offerAcPowerStr = '<FONT color="gold">提供電源插座</FONT>';
		}
		else {
			offerAcPowerStr = '<FONT color="gold">未知是否提供電源插座</FONT>';
		}
			
		var html = '<B><FONT color="firebrick">' + hotspotName + '</FONT></B><BR>' + 
			geoAddress + '<BR>' + isFreeStr + '<BR>' + offerAcPowerStr + '<BR>' +
			'電話：' + telephone + '<BR><FONT color="navy">' +	remark + '</FONT><BR>' + 
			'<A href="../GuestBook.aspx?HotspotID=' + hotspotID + '" target="_blank">更多資訊...</A>';

		marker.addListener('click', function() {
			marker.openInfoWindow(html);
		});
		return marker;
	}

	// Add hotspot markers
	var bounds = mapObj.getBounds();
	var width = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
	var height = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
	var hotspotName;
	var geoAddress;
	var telephone;
	var remark;

	// AJAX: array from JSON text
	//alert('Getting new array values...');
	if (mapJSONObject)
	{
		//document.Form1.TextDebug.value += 'Redrawing hotspot icons.\n';
		//alert(testobj.test);
		for (var i = 0; i < mapJSONObject.HotspotInfo.length; i++) {
			//alert(mapJSONObject.HotspotInfo[i].ID + ' ' + mapJSONObject.HotspotInfo[i].Name);
			hotspotName = '<B>' + mapJSONObject.HotspotInfo[i].Name + '</B>';
			geoAddress = mapJSONObject.HotspotInfo[i].GeoAddress;
			telephone = mapJSONObject.HotspotInfo[i].Telephone;
			remark = mapJSONObject.HotspotInfo[i].Remark;
			var point = new ULatLng(mapJSONObject.HotspotInfo[i].Latitude, mapJSONObject.HotspotInfo[i].Longitude);
			var marker = createMarker(point, hotspotName, geoAddress, mapJSONObject.HotspotInfo[i].IsFree, mapJSONObject.HotspotInfo[i].OfferAC, telephone, remark, mapJSONObject.HotspotInfo[i].ID);
			mapObj.addOverlay(marker);
		}
	}	
}