/**
 * @author Kirk Ouimet
 * @website http://www.yougetsignal.com/tools/network-location/
 * @copyright 2008 Kirk Ouimet Design. All rights reserved.
 */

function changeNav(div) {
	document.getElementById(div).style.background = "url('/img/link_bg_selected.gif') no-repeat";
}

/* AJAX request to initialize the Google Map to the default remote address
-------------------------------------------------------------------*/
var map;
function loadMap() {
	if(GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		gKeyboardHandler = new GKeyboardHandler(map);
		//updateMap(""); // Empty string puts the location to the user's IP
		// Fix the page scroll on zoom issue
		GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
		map.getContainer().onmousewheel = wheelevent; 				
                updateMap(document.getElementById('remoteAddress').value);
	}
}

/* AJAX request to locate a new location on the Google Map
-------------------------------------------------------------------*/
var centerSet = false; // Used for special start case
var oldLatLng;
var gLatLng;
var distanceInMiles = "0";
var ipJsonData;
var geoSource = "";
var ajaxUpdater = new Ajax.Request('', {});
function updateMap(remoteAddress) {
		// Notify the user a request is in process
		document.getElementById('networkLoaderStatus').innerHTML = "Locating target network...";
		document.getElementById('networkInfo').innerHTML = "Waiting for target lock...";
		new Effect.Appear('networkLoaderStatus', { duration: .5 });

		// Perform the request
		//url = "/tools/network-location/php/get-network-location-json.php";
		url = "/wp-content/themes/wpthemegen/ipLocationBackend.php";
		geoSource = getCheckedValue(document.forms['sourceForm'].elements['source']);
		ajaxUpdater.transport.abort(); // Cancel the previous request		
		ajaxUpdater = new Ajax.Request(url, {
		method: 'get',
		parameters: {'remoteAddress': remoteAddress, 'geoSource': geoSource},
		onFailure: function(transport) {
			document.getElementById('networkLoaderStatus').innerHTML = "<p>&nbsp;<span style=\"color: #DF454B;\">Service currently unavailable (Failure).</span></p>";
		},
		onException: function(transport) {
			document.getElementById('networkLoaderStatus').innerHTML = "<p>&nbsp;<span style=\"color: #DF454B;\">Service currently unavailable (Exception).</span></p>";
		},				
		onSuccess: function(transport) {
			ipJsonData = transport.responseText.evalJSON(); // Place the results into JSON
			if(ipJsonData.status == "Fail" || ipJsonData.latitude == "Unknown") {
				document.getElementById('networkLoaderStatus').innerHTML = "<span style=\"color: #DF454B;\">Unable to locate network.</span>";
				document.getElementById('networkInfo').innerHTML = ipJsonData.message;
			}
			else {
				gLatLng = new GLatLng(ipJsonData.latitude, ipJsonData.longitude); // Create a new Google point
				// Special start case
				if(centerSet == false) {
					map.setCenter(new GLatLng(ipJsonData.latitude, ipJsonData.longitude), 7);
					centerSet = true;
				}
				// Regular case
				else {
					// Find the distance from the last point in miles
					distanceInMiles = gLatLng.distanceFrom(oldLatLng) * 0.000621371192237334;
					distanceInMiles = distanceInMiles.toFixed(1); // Round to first decimal

					if(distanceInMiles < 5) {
						map.setZoom(12);
					}
					else if(distanceInMiles < 10) {
						map.setZoom(11);
					}
					else if(distanceInMiles < 50) {
						map.setZoom(10);
					}
					else if(distanceInMiles < 100) {
						map.setZoom(9);
					}
					else {
						map.setZoom(7);
					}
					
					// Pan to the point on the map
					map.panTo(gLatLng);
					
					// Draw a polyline from the last point
					//map.addOverlay(new GPolyline([gLatLng, oldLatLng], "#ff0000", 4));
				}
				
				// Create a marker
				markerHTML = ipJsonData.ipAddress + "<br />" + ipJsonData.baseDomain + "<br />" + ipJsonData.city + ", " + ipJsonData.region + "<br />"  + ipJsonData.countryName + "&nbsp;" + ipJsonData.countryFlag;
				placeMarker(gLatLng, markerHTML);
				
				// Notify the user the request has finished
				document.getElementById('networkLoaderStatus').innerHTML = "Location identified.";
				document.getElementById('networkInfo').innerHTML = "Found!";
				setTimeout("updateNetworkInfo()", 400);
				new Effect.Fade('networkLoaderStatus', { duration: 1.5 });
				
				// Set the new point to the old point
				oldLatLng = gLatLng;
			}
		}
	});
}
function updateNetworkInfo() {
	if(geoSource != "hostip") {
	var networkInfo = "<p>IP Address<br /><b>" + ipJsonData.ipAddress + "</b></p>" +
		"<p>Base Domain<br /><b>" + ipJsonData.baseDomain + "</b></p>" +
		"<p>Country<br /><b>" + ipJsonData.countryName + " " + ipJsonData.countryFlag + "</b></p>" +
		"<p>Region<br /><b>" + ipJsonData.region + "</b></p>" +
		"<p>City<br /><b>" + ipJsonData.city + "</b></p>" +
		"<p>Latitude<br /><b>" + ipJsonData.latitude + "</b></p>" +				
		"<p>Longitude<br /><b>" + ipJsonData.longitude + "</b></p>" +
		"<p>Area Code<br /><b>" + ipJsonData.areaCode + "</b></p>" +				
		"<p>Postal Code<br /><b>" + ipJsonData.postalCode + "</b></p>" +
		"<p>Distance from Last<br />(as the crow flies)<br /><b>" + distanceInMiles + " miles</b></p>" +
		"<p>Source<br /><a href=\"http://www.maxmind.com/\" target=\"_blank\"><b>MaxMind</b></a></p>"
	;
	}
	else {
	var networkInfo = "<p>IP Address<br /><b>" + ipJsonData.ipAddress + "</b></p>" +
		"<p>Base Domain<br /><b>" + ipJsonData.baseDomain + "</b></p>" +
		"<p>Latitude<br /><b>" + ipJsonData.latitude + "</b></p>" +				
		"<p>Longitude<br /><b>" + ipJsonData.longitude + "</b></p>" +
		"<p>Distance from Last<br />(as the crow flies)<br /><b>" + distanceInMiles + " miles</b></p>" +
		"<p>Source<br /><a href=\"http://hostip.info/\" target=\"_blank\"><b>Hostip.info</b></a></p>"		
	;		
	}

	document.getElementById('networkInfo').innerHTML = networkInfo;
}

/* Function to place a new marker on the map
-------------------------------------------------------------------*/
function placeMarker(point, html) {
	var gMarker = new GMarker(gLatLng);
	map.addOverlay(gMarker);	
	GEvent.addListener(gMarker, "click", function() {
		gMarker.openInfoWindowHtml(html);
	});
}

/* Submit AJAX request using enter key
-------------------------------------------------------------------*/
function submitUsingEnter(e) {
	var characterCode;
	if(e && e.which){ // If which property of event object is supported (NN4)
		e = e;
		characterCode = e.which // Character code is contained in NN4's which property
	}
	else {
		e = event;
		characterCode = e.keyCode; // Character code is contained in IE's keyCode property
	}
	
	if(characterCode == 13){ // If generated character code is equal to ASCII 13 (the enter key)
		updateMap(document.getElementById('remoteAddress').value);
		return false
	}
	else {
		return true
	}
}

/* Function to fix the page scroll issue with map zoom
-------------------------------------------------------------------*/
function wheelevent(e) {
	if (!e){
		e = window.event
	}
	if (e.preventDefault){
		e.preventDefault()
	}
	e.returnValue = false;
}

/* Function to get the value of the checked radio button
-------------------------------------------------------------------*/
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

