


var map;
var eMap;
var mgrOptions;
var mgr;
var blueIcon;
var countryBaseIcon;
var locationBaseIcon;
var siteBaseIcon;
var gdir;
var JSONLocations;
var JSONResellerSites;
var resellerGroupID_GG = 1;//globalgossip pc
var resellerGroupID_Connect = 2;//connect pc
var resellerGroupID_FijiConnect = 7;//fiji connect pc
var geocoder;
var countryMarkerMin = 1;
var locationMarkerMax = 12;
var locationMarkerMin = 4;
var siteMarkerMin = 13;
var manualZoomMin = 15;
var int32MinValue = -2147483648;
var decimalMinValue = -79228162514264337593543950335;
var icon1 = G_START_ICON;
var icon2 = G_PAUSE_ICON;
var icon3 = G_END_ICON;
var constPercent = 1.00005;
var lastLatLng;
var lastZoomLevel;

var active = [true, true];
var addresses = [];
var geoAddress;
var fMarker;
var tMarker;
var poly;
var paragraphs=0;//main map
var paras=0; //control map
var zoomButton;
var buttonBackColor;

var siteMarkerArray = new Array();
var locationMarkerArray = new Array();

// Create the marker and corresponding information window
function createMarker(dataObj, iconType, iconName) 
{
	var marker;
	if(iconType == "country")
	{
		var ggIcon = new GIcon(countryBaseIcon);
		ggIcon.image = iconName;
		markerOptions = { icon:ggIcon };
	}
	else if(iconType == "location")
	{
		markerOptions = { icon:defaultIcon, title:dataObj.countryID };
	}
	else if(iconType == "site")
	{
		var ggIcon;
		if(dataObj.groupID == resellerGroupID_GG)
			ggIcon = new GIcon(siteBaseIcon);
		else
			ggIcon = new GIcon(siteBaseConnectIcon);
			
		ggIcon.image = iconName;
		markerOptions = { icon:ggIcon, title:dataObj.locationID };
	}
	else if(iconType == "address")
	{
		markerOptions = { icon:addressIcon };
	}
	marker = new GMarker(dataObj.latlng, markerOptions);
	GEvent.addListener(
		marker, 
		"click",
		function()
		{
			MoveZoomDisplaySelection(dataObj);
		});
	GEvent.addListener(
		marker,
		"mouseover",
		function()
		{
			if(dataObj.name != undefined)
				Tip(dataObj.name);
		});
	return marker;
}
		

function SelectDropDownList(listName, value)
{
	var ddl = document.getElementById(listName);
	if(ddl)
	{
		for(i=0; i<ddl.length; i++)
		{
			if(ddl.options[i].value == value)
			{
				ddl.options[i].selected = true;
				break;
			}
					
		}
	}
}


function getCountryIDFromLocationID(locationID)
{
	for(i=0; i<JSONLocations.length; i++)
	{
		if(JSONLocations[i].location.ID == Number(locationID))
		{
			return JSONLocations[i].location.countryID;
			break;
		}
	}
}


function selectLocationByID(locationID, withZoom)
{
	for(i=0; i<JSONLocations.length; i++)
	{
		if(JSONLocations[i].location.ID == Number(locationID))
		{
			var lat = JSONLocations[i].location.latitude;
			var lng = JSONLocations[i].location.longitude;
			
			var dataObj = new Object();
			dataObj.latlng = new GLatLng(lat, lng);
			dataObj.countryID = JSONLocations[i].location.countryID;
			dataObj.locationID = JSONLocations[i].location.ID;
			dataObj.withZoom = withZoom;
			dataObj.countryName = JSONLocations[i].location.countryName;
//			dataObj.zoom = (JSONLocations[i].location.mapZoomLevel == decimalMinValue ? 14 : JSONLocations[i].location.mapZoomLevel);
			
			MoveZoomDisplaySelection(dataObj);
			break;
		}
	}
}


function selectSiteByID(siteID, withZoom, manualZoom)
{
	for(i=0; i<JSONResellerSites.length; i++)
	{
		if(JSONResellerSites[i].reseller.siteID == Number(siteID))
		{
			var lat = JSONResellerSites[i].reseller.latitude;
			var lng = JSONResellerSites[i].reseller.longitude;
			
			var dataObj = new Object();
			dataObj.latlng = new GLatLng(lat, lng);
			dataObj.locationID = JSONResellerSites[i].reseller.locationID;
			dataObj.countryName = JSONResellerSites[i].reseller.address.country;
			dataObj.siteID = JSONResellerSites[i].reseller.siteID;
			dataObj.withZoom = withZoom;
			dataObj.manualZoom = manualZoom;
			dataObj.zoom = 10;
			
			MoveZoomDisplaySelection(dataObj);
			break;
		}
	}
}

function getCountByID(siteID, locationID, countryID)
{
	this.count = 0;
	if(locationID != undefined)
	{
		for(i=0; i<JSONResellerSites.length; i++)
		{
			if(JSONResellerSites[i].reseller.locationID == Number(locationID))
			{
				this.count ++;
				this.id = JSONResellerSites[i].reseller.siteID;
			}
		}
	}
	if(countryID != undefined)
	{
		for(i=0; i<JSONLocations.length; i++)
		{
			if(JSONLocations[i].location.countryID == countryID)
			{
				this.count ++;
				this.id = JSONLocations[i].location.ID;
			}
		}
	}
	
	var returnObj = new Object();
	returnObj.count = this.count;
	returnObj.id = this.id;
	return returnObj;
}

function displayHideElement(listName, display)
{
	var list = document.getElementById(listName);
	list.style.display = (display == true ? "inline" : "none");
}
		
function createLocationList(countryID)
{
	var locationList = document.getElementById("locationList");
	ClearOptions(locationList);
	AddToOptionList(locationList, 0, 'Select location');
	var areaName;
	for(var i=0; i<JSONLocations.length; i++)
	{
		if(JSONLocations[i].location.countryID == Number(countryID) && JSONLocations[i].location.siteCount > 0)
		{
			AddToOptionList(locationList, JSONLocations[i].location.ID, JSONLocations[i].location.name + " (" + JSONLocations[i].location.siteCount + ")");
		}
	}
}

function HasGGRetailStore(locationID)
{
	this.yes = false;
	for(var x=0; x<JSONResellerSites.length; x++)
	{
		if(JSONResellerSites[x].reseller.locationID == Number(locationID) && JSONResellerSites[x].reseller.groupID == 1)
		{
			this.yes = true;
			break;
		}
	}
	return this.yes;
}

function ClearOptions(OptionList) 
{
	while (OptionList.firstChild)
	{
		OptionList.removeChild(OptionList.firstChild);
	}
}


function AddToOptionList(OptionList, OptionValue, OptionText) 
{
	var oOption = document.createElement('option');
	oOption.value = OptionValue;
	oOption.innerHTML = OptionText;
	oOption.style.fontWeight = (HasGGRetailStore(OptionValue) ? "bold" : "normal");
	OptionList.appendChild(oOption);
}

function JumpToLocation()
{
	var locationList = document.getElementById("locationList");
	var locationID = locationList.options[locationList.selectedIndex].value;
	selectLocationByID(locationID);
}

function selectCountryWithLatLng(lat, lng, id, zoom)
{
	var dataObj = new Object();
	dataObj.latlng = new GLatLng(Number(lat), Number(lng));
	dataObj.countryID = Number(id);
	dataObj.zoom = Number(zoom);
	
	MoveZoomDisplaySelection(dataObj);
}

function selectCountryByID(countryID, withZoom)
{
	for(i=0; i<JSONCountries.length; i++)
	{
		if(JSONCountries[i].country.ID == Number(countryID))
		{
			var lat = JSONCountries[i].country.latitude;
			var lng = JSONCountries[i].country.longitude;
			
			var dataObj = new Object();
			dataObj.latlng = new GLatLng(lat, lng);
			dataObj.countryID = JSONCountries[i].country.ID;
			dataObj.withZoom = withZoom;
			dataObj.countryName = JSONCountries[i].country.name;
//			dataObj.zoom = JSONCountries[i].country.mapZoomLevel;
			
			MoveZoomDisplaySelection(dataObj);
			break;
		}
	}
}

function getLocationIdByName(locationName)
{
    for(i=0; i<JSONLocations.length; i++)
	{
		if(JSONLocations[i].location.name.toLowerCase() == locationName.toLowerCase())
		{
		    return JSONLocations[i].location.ID;
		    break;
		}
	}
}


var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

// ====== Geocoding ======
function showAddress(address, getDirection)
{
	var findLocationErrorMsg = "We're sorry, we couldn't find a Global Gossip center near " + address + ". Try entering a different street address.";
	
	// ====== Perform the Geocoding ======
	geocoder.getLatLng(address, function (point)
	{ 
		// ===== If that was successful, plot the point and centre the map ======
		if (point)
		{
			var closestLocationID;
			var closestLocationPoint;
			var minLocationDist = Number.POSITIVE_INFINITY;
			var minSiteDist = Number.POSITIVE_INFINITY;
			var geoAddressAccuracy = 0;
							
			for(i=0; i<JSONLocations.length; i++)
			{
				locationPoint = new GLatLng(JSONLocations[i].location.latitude, JSONLocations[i].location.longitude);
				locationDist = distance_between_points(point, locationPoint);
				if(locationDist < minLocationDist)
				{				
					minLocationDist = locationDist;
					closestLocationID = JSONLocations[i].location.ID;
					closestLocationPoint = locationPoint;
				}
			}
			if(getDirection)
			{
				geocoder.getLocations(address, function (response)
				{
					if (!response || response.Status.code != 200) 
					{
						alert(findLocationErrorMsg);
						geoAddressAccuracy = 0;
					}
					else
						geoAddressAccuracy = response.Placemark[0].AddressDetails.Accuracy;

					if(geoAddressAccuracy >= 6) //6=street level 7=intersection level 8=address level
					{
						var closestSiteID;
						var closestSitePoint;	
						for(i=0; i<JSONResellerSites.length; i++)
						{
							if(JSONResellerSites[i].reseller.locationID == closestLocationID)
							{
								sitePoint = new GLatLng(JSONResellerSites[i].reseller.latitude, JSONResellerSites[i].reseller.longitude);
								siteDist = distance_between_points(point, sitePoint);
								if(siteDist < minSiteDist)
								{
									minSiteDist = siteDist;
									closestSiteID = JSONResellerSites[i].reseller.siteID;
									closestSitePoint = sitePoint;
								}
							}
						}
    					
    					if(minSiteDist < 2000000)
    					{
							var fromMarker = point;
							var toMarker = (closestSitePoint == undefined ? closestLocationPoint : closestSitePoint);
	    					
							var markerArray = new Array(0);
							doStart(fromMarker);
							doEnd(toMarker);
							directions(fromMarker.toUrlValue(6), toMarker.toUrlValue(6));
	    					
							markerArray[0] = point;
							markerArray[1] = toMarker;
	    					
							fit(markerArray);
							displayHideElement("divDirection", true);
							selectSiteByID(closestSiteID, true);
						}
						else
							alert(findLocationErrorMsg);
					}
					else
						alert(findLocationErrorMsg);
				});
			}
			else
			{
				var locationID = getLocationIdByName(address);
				if(locationID != undefined)
					selectLocationByID(locationID);
				else if(minLocationDist < 2000000)
					selectLocationByID(closestLocationID);
				else
					alert(findLocationErrorMsg);
			}
		}
		// ====== Decode the error status ======
		else 
		{
		  alert(findLocationErrorMsg);
		}
	});
}

Math.deg2rad=function(x)
{
	return x*(Math.PI/180.0);
}

var EARTH_RADIUS=6367000;
function distance_between_points(p1,p2)
{
	if(p1.x == p2.x && p1.y == p2.y)
		return 0;
	var a=Math.deg2rad(90-p1.y);
	var b=Math.deg2rad(90-p2.y);
	var theta=Math.deg2rad(p2.x-p1.x);
	var c=Math.acos(Math.cos(a)*Math.cos(b)+Math.sin(a)*Math.sin(b)*Math.cos(theta));
	return c*EARTH_RADIUS;
}

function directions(from, to)
{
	var fromto = "from: "+ from + " to: " + to;
	gdir.load(fromto, {getPolyline:true});
}

function createMarker2(point,i,icon) 
{
	var marker = new GMarker(point, {icon:icon});
	if(i == 0)
		fMarker = marker;
	if(i == 1)
		tMarker = marker;
		
	map.addOverlay(marker);
}

function doStart(point) 
{
	createMarker2(point,0,icon1);
}

function doEnd(point) 
{
	createMarker2(point,1,icon3);
}

function autoZoomToFit(locationID, countryID)
{
	var thisCount = 0;
	thisMarkerArray = new Array();
	
	if(locationID != undefined)
	{
		this.id = locationID;
		this.inputMarkerArray = siteMarkerArray;
	}
	if(countryID != undefined)
	{
		this.id = countryID
		this.inputMarkerArray = locationMarkerArray;
	}
	
	for(i=0; i<this.inputMarkerArray.length; i++)
	{
		if(this.inputMarkerArray[i].getTitle() == Number(this.id))
		{
			thisMarkerArray[thisCount] = this.inputMarkerArray[i];
			thisCount ++;
		}
	}
	fit(null, thisMarkerArray);
}

function fit(points, markers)
{
	var bounds = new GLatLngBounds();
	if(points != undefined && markers == undefined)
	{
		this.markerArray = points;
		this.isPoint = true;
	}
	else
	{
		this.markerArray = markers;
		this.isPoint = false;
	}
		
	for(var i=0;i<this.markerArray.length;i++)
	{
		bounds.extend((this.isPoint ? this.markerArray[i] : this.markerArray[i].getPoint()));
	}
	
	var center = bounds.getCenter();
	if(center.lat() == 0)
	{
	   map.setCenter(lastLatLng, lastZoomLevel);
	}
	else
	{
        var newBounds = getBestZoomLevel(bounds);
        var zoomLevel = map.getBoundsZoomLevel(newBounds)
        map.setCenter(center, zoomLevel);
        lastLatLng = center;
        lastZoomLevel = zoomLevel;
	}
}

function getBestZoomLevel(inputBounds)
{
	var southWest = inputBounds.getSouthWest();
	var northEast = inputBounds.getNorthEast();
	this.southWestLat = southWest.lat() * constPercent;
	this.southWestLng = southWest.lng() * constPercent;
	this.northEastLat = northEast.lat() * constPercent;
	this.northEastLng = northEast.lng() * constPercent;
	
	inputBounds.extend(new GLatLng(this.southWestLat,this.southWestLng));
	inputBounds.extend(new GLatLng(this.northEastLat,this.northEastLng));
	
	return inputBounds
}

/// map interconnection
function EMove()
{
	eMap.setCenter(map.getCenter(), map.getZoom()+1);
}

var lastCountryID;
function setBackgroundColor(countryID)
{
	if(lastCountryID != countryID)
	{
	    document.getElementById("divCountry_" + countryID).className = "highlight";
	
		if(lastCountryID)
		    document.getElementById("divCountry_" + lastCountryID).className = "";
			
		lastCountryID = countryID;
	}
}

function WheelEvent(e)
{
    if(true)
    {
		if (!e)
		{
			e = window.event
		}
		if (e.preventDefault)
		{
			e.preventDefault()
		}
		e.returnValue = false;
	}
}