var localSearch = new GlocalSearch();
var theMap;
var rangeLat;
var rangeLng;
var origLat;
var origLng;
var details;
var distanceList = [];
var zoomLevel = 14;
var iconCovered = "no";
var markersID = [];
var centerPoint;

// saving important vars as global 
var HsearchRadius;
var Haddress;
var Hcity;
var Hpostcode;
var Hcountry;

// used for displaying the info window when the request comes from "Browes" with a certain hotspot.
var Hssid;
var HlocationType;
var Hprice;

// for logging
var logMapFound = "";
var logMappedHotspots = "";
var logWithoutGeos = "";
var tool = "Web find";

var jsHotspots;


/////////////////////////////////////////////////////////////////////////////
// Main function, directing to the correct position functionn 
// The name, ssid, locationType, fsGeoLat and fsGeoLng are used just when the request comes from "Browse" with a certain hotspot.
function getRadiusHospots(searchRange, address, city, postCode, country, name, ssid, locationType, fsGeoLat, fsGeoLng, fsPrice){
	if(searchRange == 1){
		zoomLevel = 13;
	}
	if(searchRange == 2){
		 zoomLevel = 13;
	}
	if(searchRange == 5){
		 zoomLevel = 12;
	}
	if(searchRange == 10){
		 zoomLevel = 11;
	}	
	
	HsearchRadius = searchRange;
 	Haddress = address;
 	Hcity = city;
 	Hpostcode = postCode;
 	Hcountry = country;
		
	rangeLat = searchRange * 0.009;
	rangeLng = searchRange * 0.012;
	
	if(name != ""){ // when the search came from "Browse" with an address (without geos)
		tool = "Web Browse search";
	}
	
	if(fsGeoLat != ""){ // in case the request came form "Browse" and with known hotspot geos
		origLat = fsGeoLat;
		origLng = fsGeoLng;
		logMapFound = "yes";
		tool = "Web Browse pointed";
		
		// The hotspot is covered by the "i'm here" icon.		
		iconCovered = "yes";
		Hssid = ssid;
		HlocationType = locationType;
		Hname = name;
		Hprice = fsPrice;
			
		ajaxCalculateNearby();
	}
	else{
		if(country == "United Kingdom" || country == "Royaume Uni" || country == "Het Verenigd Koninkrijk"){
			// when google maps is getting both an address and a postcode for the UK, it doesn't return any geo point. 
			// It does return the correct point if we use the address and postcode separately. If the user uses both address and postcode we choose the addres
			if(address && postCode){
				postCode = "";
			}
			var fullAddressUK = address + ", " + postCode + ", " + city + ", " + country;
			AJAXgetPosition(fullAddressUK);
		}
		else{
			var fullAddress = address;
			getNormalPosition(fullAddress);
		}
	}
} 





////////////////////////////////////////////////////////////////////////////
// getting the current position geocode 
function getNormalPosition(fullAddress){
	var geocoder = new GClientGeocoder();
	geocoder.getLocations(fullAddress, getGeo);	
}

function getGeo(response) {
  if (!response || response.Status.code != 200) {
  	logMapFound = "no";
  	//logIt();
	showErrorPage("", "map");
  } 
  else {
    var place = response.Placemark[0];
    origLat = place.Point.coordinates[1];
    origLng = place.Point.coordinates[0];
    logMapFound = "yes";
    ajaxCalculateNearby();     
  }
}


////////////////////////////////////////////////////////////////////////
// getting the current position using AJAX api
function AJAXgetPosition(fullAddress) {
	localSearch.setSearchCompleteCallback(null, 
		function() {
			if (localSearch.results[0] && localSearch.results[0].lat)
			{		
				origLat = localSearch.results[0].lat;
				origLng = localSearch.results[0].lng;
    			logMapFound = "yes";
    			ajaxCalculateNearby();
			}
			else{
				logMapFound = "no";
  				//logIt();
				showErrorPage("", "map");
			}			
		});	
		
	localSearch.execute(fullAddress);
}


///////////////////////////////////////////////////////////////////////////
// Free style field
// when the user enters an address in the "free style" search field (i.e 16 la Buffa, 06000, Nice)
function freeStyleRadiusSearch(fullAddress, short_lang){
	// previously, the function was as simple as GClientGeocoder.getLocations(fullAddress, getFreeStyleDeatils)
    // but a bug in the google maps API prevents receiving the "address" in the language requested
    // using the "hl" parameter in the "<script>" tag... so the (ugly) fix is to use a simple proxy.
    // Refer to simple_proxy.php for additionnal information about the following code.
    
    if (typeof short_lang == "undefined") {
        short_lang = "en";
    }
    
    var ajaxRequest;  
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Error processing the request. Please try again");
				return false;
			}
		}
	}
	
	// receiving the response JSON string
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			//alert(ajaxRequest.responseText);
            var details = eval('(' + ajaxRequest.responseText + ')');
            getFreeStyleDeatils(details);
		}
	};
    var url = "/simple_proxy.php?q=" + fullAddress + "&short_lang=" + short_lang;
	ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null); 
}

function getFreeStyleDeatils(response){
  if (!response || response.Status.code != 200) {
	showErrorPage("", "sideimage"); 
  } 
  else { 
    var place = response.Placemark[0];
    var freeUrl = "/hotspots/";
	freeUrl += place.AddressDetails.Country.CountryName.replace("'", "`") + "/";
    
    try {
        // if it exist, the city name will be the SubAdministrativeArea.Locality.LocalityName
        freeUrl +=  place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName + "/";
    } catch (e) {
        try {
            // the SubAdministrativeArea.Locality.LocalityName doesn't exist, try with AdministrativeArea.Locality.LocalityName
            freeUrl +=  place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName + "/";
        } catch (e) {
            // no way to find the city name
            freeUrl += "_/";
        }
    }
	
	var addressParts = place.address.split(",", 5);
	if(addressParts.length > 1){
			for(var x=0; x < addressParts.length; x++){
				freeUrl += "_" + addressParts[x].replace(" ", "_"); 
			} 
			freeUrl += "_address";
		}
	}
    window.location = freeUrl;
}

/////////////////////////////////////////////////////////////////////////////////
// an Ajax function that uses countryNameFromCode.php to get the country name from the code we found
// in the google decoder response
// In countryNameFromCode.php we also set $_SESSION['radius'] to 10km.
//
// should now not be used anymore (20/10/2008) as the getFreeStyleDeatils function
// isn't using it anymore (hotspot locator is now fully localized
function getCountryNameFromCode(countryCode, url){
	var ajaxRequest;  
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Error processing the request. Please try again");
				return false;
			}
		}
	}
	
	// receiving the response JSON string
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var details = eval('(' + ajaxRequest.responseText + ')');		  
			var freeCountryName = details.country[0].name;	
			freeCountryName = freeCountryName.replace(/ /g, "_");
			var freeUrl = "/hotspots/" + freeCountryName + url;
			window.location = freeUrl;
		}
	};
	var varString = "?ccode=" + countryCode;
	ajaxRequest.open("GET", "/countryNameFromCode.php" + varString, true);
	ajaxRequest.send(null); 
}



////////////////////////////////////////////////////////////////////////////
// an Ajax function that uses the nearbyQuery.php file to retrieve the nearby list.
// This is the main function that uses most of the other functions in the file.
function ajaxCalculateNearby(){
	var ajaxRequest;  
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Error processing the request. Please try again");
				return false;
			}
		}
	}
	// receiving the response JSON string
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			// adding the map
			theMap = new GMap2(document.getElementById("map"));
	    	theMap.addControl(new GSmallMapControl());
			theMap.addControl(new GMapTypeControl());
			theMap.addControl(new GScaleControl()); 
			
			
			centerPoint = new GLatLng(origLat, origLng);
			theMap.setCenter(centerPoint, zoomLevel);
			
			// creating a hotspot's icon
			var icon = new GIcon();
			icon.image = "/images/trustive-icon.png";
			icon.iconSize = new GSize(20, 40);
			icon.iconAnchor = new GPoint(10, 40);
			icon.infoWindowAnchor = new GPoint(10, 40);
			
			// adding the "I'm here marker"
			var imHereIcon = new GIcon();
			imHereIcon.image = "/images/trustive-icon-here.png";
			imHereIcon.iconSize = new GSize(20, 40);
			imHereIcon.iconAnchor = new GPoint(10, 40);
			imHereIcon.infoWindowAnchor = new GPoint(10, 40);
			
						
			// adding a scroll wheel zoom. 
			theMap.enableContinuousZoom();
			theMap.enableScrollWheelZoom();
			
			// getting the hotspot's details from the JSON and adding the markers
			details = eval('(' + ajaxRequest.responseText + ')');
			
			/*
			var rangeArray = new Array(1,2,5,10);
			if(details.rangedHotspots.length == 0 && HsearchRadius < 10){
				alert(HsearchRadius);
				for(var r=0; r> rangeArray.length ; r++){
					if(rangeArray[r] == HsearchRadius){
						var newRange = rangeArray[++r];
						break;
					}
				}			
				rangeLat = newRange * 0.009;
				rangeLng = newRange * 0.012;
				alert(newRange);
				ajaxCalculateNearby();
			}
			else{
			*/
			
			// for logging
			logMappedHotspots = details.rangedHotspots.length;
			var ic = 0; var imHereAdded = false;
			distanceList = [];
			markersID = [];
			for(var i=0;i<details.rangedHotspots.length;i++){  
				var lat = details.rangedHotspots[i].geoLat;
				var lng = details.rangedHotspots[i].geoLng;
				var name = details.rangedHotspots[i].hotspot;
				var SSID = details.rangedHotspots[i].SSID;
				var Address = details.rangedHotspots[i].Address;
				var postCode = details.rangedHotspots[i].postCode;
				var locationType = details.rangedHotspots[i].locationType;	
				var price = details.rangedHotspots[i].price;
				
				if(price == null || price == 0){
					price = 0.05;
				}	
				
				var posn = new GLatLng(lat, lng); 
				if(lat != origLat && lng != origLng){
					var newMarker = createMarker(posn, name, SSID, Address, postCode, locationType, price, icon);
				}
				else{
					var newMarker = createMarker(posn, name, SSID, Address, postCode, locationType, price, imHereIcon);	
					imHereAdded = true;
				}

				theMap.addOverlay(newMarker);		
				var hdist = calcdDistance(lat, lng);
				distanceList.push(new Array(name, hdist, locationType, price, newMarker, Address, postCode, SSID, lat, lng));
			}
					
			
			if(!imHereAdded){
				var imHereMarker = new GMarker(centerPoint, imHereIcon);
				theMap.addOverlay(imHereMarker);
			}		
			
			distanceList.sort(sortDistancelist); // sorting the distance list by km.
			// adding the distance list
			var distanceListHtml = getListHtml();
			var rl = document.getElementById("hotspotsresultstable");
			rl.innerHTML = distanceListHtml;
            
            // fill in the number of hotspots mapped, and display the radius dropdown and GO button
            document.getElementById("hotspots-count").innerHTML = logMappedHotspots;
            document.getElementById("radiush5").selectedIndex = document.getElementById("radius").selectedIndex;
            document.getElementById("hotspots-list-title").style.display = "block";
            document.getElementById("findnearbyhotspots-h5").style.display = "inline";
            
			stopLoadingDiv();
			//logIt();	
			//} end the else
		}
	};

	var varString = "?GeoLat=" + origLat + "&GeoLng=" + origLng + "&rangeLat=" + rangeLat + "&rangeLng=" + rangeLng;
	//window.location = "/nearbyQuery.php" + varString; // for testing
	ajaxRequest.open("GET", "/nearbyQuery.php" + varString, true);
	ajaxRequest.send(null); 
}


///////////////////////////////////////////////////////////////////////
// poping up an info window of a marker
function openMarkerWindow(mID){
	for(var i=0; i<markersID.length; i++){
		markersID[i].show();
	}
	
	if(markersID[mID]){
		if(zoomLevel == 1){ 
			theMap.setZoom(2);
		}
		
		
		
		var clickedMarker = markersID[mID];
		GEvent.trigger(clickedMarker, "click");
	}
}



///////////////////////////////////////////////////////////////////////////
// creating a marker and its infoWindow
function createMarker(posn, name, SSID, Address, postCode, locationType, price, icon){  
	var marker = new GMarker(posn, icon);
	
	var descriptionInfo = "";
	if (Address.indexOf("|") != -1)
	{
		descriptionInfo = "<tr><td valign=\"top\"><b>Description:</b></td><td>" + Address.substring(Address.indexOf("|") + 1) + "</td></tr>";
		Address = Address.substring(0, Address.indexOf("|"));
	}
	
	GEvent.addListener(marker, "click", function(){    
		marker.openInfoWindowHtml("<table id=\"mapInfoWindow\" border=0><tr><td><b>Name:</b></td><td>" + name + "</td></tr>" + 
									"<tr><td><b>Network&nbsp;name:</b></td><td>" + SSID + "</td></tr>" + 
									"<tr><td><b>Address:</b></td><td>" + Address + "</td></tr>" +
									descriptionInfo +
									"<tr><td><b>Postcode:</b></td><td>" + postCode + "</td></tr>" +
									"<tr><td><b>Location type:</b></td><td>" + locationType + "</td></tr>" +
									"<tr><table id=\"mapInfoWindow\"><tr><td id=\"upperLine\" colspan=2></td></tr>" +
												"<tr><td align=left><b>Pre-Paid:</b></td><td>" + price + " &euro; p/min</td><td><a href=\"https://secure.trustive.com/buy/pre-paid/\" target=\"_blank\">buy now</a></td></tr>" +
												"<tr><td><b>World:</b></td><td>included</td><td><a href=\"https://secure.trustive.com/buy/world/\" onclick=\"return openNewWin(this);\">buy now</a></td></tr>" +
												"</table></tr>" +
									"</table>");
	});  
return marker;
}


//////////////////////////////////////////////////////////////////////////
// calulating the distance from the center point
function calcdDistance(lat, lng){
	
	var latDist = (Math.abs(origLat-lat)) * 0.009;
	var lngDist = (Math.abs(origLng-lng)) * 0.009;
	var hdist = (Math.sqrt((latDist*latDist) + (lngDist*lngDist)))*9000;	
	return hdist;
}

//////////////////////////////////////////////////////////////////////////
function sortDistancelist(a, b) {
    var x = a[1];
    var y = b[1];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}


//////////////////////////////////////////////////////////////////////////
// returns an html string of the hotspots' list 
function getListHtml(){
	var counter = 0; 
	var tempListString = "";
	if(distanceList.length > 0){	
        tempListString += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"hotspotsresultstableheader\">"+
				"<thead>"+
					"<tr align=\"left\" valign=\"middle\">"+
						"<td width=\"212\" colspan=3>Hotspot name</td>"+
						"<td width=\"70\">Distance</td>"+
						"<td width=\"96\">Location type</td>"+
						"<td align=\"center\" width=\"83\">Pre-Paid<br /><a href=\"https://secure.trustive.com/buy/pre-paid/\">&raquo; buy now</a></td>"+
						"<td align=\"center\" width=\"62\">World<br /><a href=\"https://secure.trustive.com/buy/world/\">&raquo; buy now</a></td>"+
					"</tr>"+
				"</thead>"+
			"</table>"+	
			
            "<div class=\"hotspotresultslist\" id=\"nearbyresults\">"+
			"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"hotspots\" id=\"hotspotstable\">" ;	
        
		for(var x=0; x<distanceList.length; x++){
			markersID[x] = distanceList[x][4];
			
			var zigzag = "odd";
			if (((counter++) % 2) == 0){
					zigzag = "even";
			}
			if(x == 0){
			    zigzag = zigzag + " active";
			}
				  
            tooltip = distanceList[x][0];
            tooltip+= ", " + distanceList[x][5] + ", " + distanceList[x][6];
            tooltip+= " - SSID: " + distanceList[x][7];

			 tempListString += "<tbody>" +		 
			 "<tr class=\""+ zigzag + "\">" +
			 	"<td width=\"190\" class=\"hotspotname\" title=\"" + tooltip + "\"><a href=# onclick=\"mapSingleHotspot('" + distanceList[x][5] + "', 'City','" + distanceList[x][6] + "','" + distanceList[x][0].replace(/'/g, "\\'") + "','" + distanceList[x][7] + "','" + distanceList[x][2] + "','" + distanceList[x][8] + "','" + distanceList[x][9] + "','" + distanceList[x][3] + "'); return false;\">" + distanceList[x][0] + "</a></td>" +
				"<td width=\"16\" class=\"hotspotmap\"><a href=# onclick=\"mapSingleHotspot('" + distanceList[x][5] + "', 'City','" + distanceList[x][6] + "','" + distanceList[x][0].replace(/'/g, "\\'") + "','" + distanceList[x][7] + "','" + distanceList[x][2] + "','" + distanceList[x][8] + "','" + distanceList[x][9] + "','" + distanceList[x][3] + "') \" onmouseover=\"hoverImgOver(this);\" onmouseout=\"hoverImgOut(this);\"><img src=\"/images/icon.map.gif\"></a></td>" +
				/*"<td width=\"16\" class=\"hotspotinfoicon\"><a href=# onclick=\"openMarkerWindow(" + x + ")\" onmouseover=\"hoverImgOver(this);\" onmouseout=\"hoverImgOut(this);\"><img src=\"/images/icon.info.gif\"></a></td>" + */
			 "<td width=\"70\" class=\"hotspotdistance\">" + distanceList[x][1].toFixed(2)	+ " km</td>" +
			 "<td width=\"96\" class=\"hotspotdistance2\">" + distanceList[x][2]	+ "</td>" + 
			 "<td width=\"83\" align=\"center\" class=\"hotspotppm\">" + distanceList[x][3]	+ " &euro; p/min</td><td align=center width=\"62\" class=\"hotspotincluded\">included</td>" +
			 "</tr>"+
			 "</tbody>";
			 	 
		}
		tempListString += "</table></div>";
		
	}
	else{
		if(HsearchRadius < 10){
			var tempStrInc = "Please try increasing the search radius";
		}
		else{
			var tempStrInc = "";
		}
		tempListString += "<tr id=\"noListMessage\"><td>No mapped hotspots were found. " + tempStrInc + " </td></tr>";
	}
	
	tempListString += "</tbody></table>";
	
	return tempListString;
}



///////////////////////////////////////////////////////////////////////////
// stoping the loading div image
function stopLoadingDiv(){
	if (document.getElementById("loadingdiv"))
	{
		document.getElementById("loadingdiv").style.display = "none";
	}
}


///////////////////////////////////////////////////////////////////////////
// Checking if the result is a correct one. Matching the city and country to avoid "San Francisco" addresses or other 
// wrong one. Returns the result if correct and FALSE if not.
function checkSearchResult(lcResult, city, country){ 	
	city = city.toLowerCase();
	country = country.toLowerCase();
	var foundCity = lcResult.city.toLowerCase();
	var foundAddress = lcResult.streetAddress.toLowerCase();
		
	//alert(foundAddress + " - " + city + " | " + foundCity + " - " + country); // for testing
	if(foundAddress.match(city)){
		return lcResult;
	}	
	else if(foundAddress.match(city) && foundCity.match(" "+country)){
		return lcResult;
	}			
	return false;
}



////////////////////////////////////////////////////////////////////////////////
//	Showing an error page
//  Checking if the result is wrong due to to more than one search parameters
function showErrorPage(errorStr, divName){  

    var er = document.getElementById(divName);
    var erHtmlString = "<div id=\"searchError\">" +
    						"<br /><div><img src=\"/images/locator_error_logo.gif\"/></div><br />" + 
    				   		"<div id=\"eBody\">We're sorry, but the location you are trying " +
    				   			 "to search could not be mapped. " +
    				   			 errorStr + "</div>" +
    				   "</div>";
	er.innerHTML = erHtmlString;
				
	stopLoadingDiv(); 
}


///////////////////////////////////////////////////////////////////////////////
//	logging the search details to HotspotLocatorLog in db.
//
function logIt(){
	//alert(Haddress +", "+ Hpostcode+", "+ Hcity+", "+ Hcountry+", "+ HsearchRadius+", "+ logMapFound+", "+ logMappedHotspots+", "+ logWithoutGeos);
	logSearch(Haddress, Hpostcode, Hcity, Hcountry, HsearchRadius, logMapFound, logMappedHotspots, logWithoutGeos, tool);
}

var globalNewMarker = null;

///////////////////////////////////////////////////////////////////////////
//	mapping a single known hotspot 
//
function mapSingleHotspot(address, city, postCode, name, ssid, locationType, fsGeoLat, fsGeoLng, price){
	//alert(address + " - " + city + " - " + postCode + " - " + name + " - " + ssid + " - " + locationType + " - " + fsGeoLat + " - " + fsGeoLng + " - " + price);
	if (document.getElementById("map"))
	{
		theMap = new GMap2(document.getElementById("map"));
		theMap.addControl(new GSmallMapControl());
		theMap.addControl(new GMapTypeControl());
		theMap.addControl(new GScaleControl()); 
						
		centerPoint = new GLatLng(fsGeoLat, fsGeoLng);
		theMap.setCenter(centerPoint, 15);
		
		// creating a hotspot's icon
		var icon = new GIcon();
		icon.image = "/images/trustive-icon.png";
		icon.iconSize = new GSize(20, 40);
		icon.iconAnchor = new GPoint(10, 40);
		icon.infoWindowAnchor = new GPoint(10, 40);
									
		// adding a scroll wheel zoom. 
		theMap.enableContinuousZoom();
		theMap.enableScrollWheelZoom();
		 
		var newMarker = createMarker(centerPoint, name, ssid, address, postCode, locationType, price, icon);
		markersID = [];
	
		theMap.addOverlay(newMarker);
		globalNewMarker = newMarker;
		setTimeout("GEvent.trigger(globalNewMarker, 'click')", 1000);
	}
}


////////////////////////////////////////////////////////
//	start the nearby query with a choosen radius
//
function startGetNearby(mAddress, mCity, mPostalCode, mCountry, mName, mSSID, mLocationType, mGeoLat, mGeoLng, mPrice){
	var radiusFromForm = document.getElementById("radius").value;
	
	//alert(radiusFromForm + " - " + mAddress + " - " + mCity + " - " + mPostalCode + " - " + mName + " - " + mSSID + " - " + mLocationType + " - " + mGeoLat + " - " + mGeoLng + " - " + mPrice);
	getRadiusHospots(radiusFromForm, mAddress, mCity, mPostalCode, mCountry, mName, mSSID, mLocationType, mGeoLat, mGeoLng, mPrice);	
}

///////////////////////////////////////////////////////////////
//	getting a different radius in a map that was created from an address
//
function startGetNearbyFromLocation(radiusFromForm){
	if (typeof radiusFromForm == "undefined") {
        radiusFromForm = document.getElementById("radius").value;
    }
	getRadiusHospots(radiusFromForm, Haddress, Hcity, Hpostcode, Hcountry, "", "", "", "", "", "");
}

//////////////////////////////////////////////////////////
//
//
function createHotspotsMap(){	
	theMap = new GMap2(document.getElementById("map"));
	theMap.addControl(new GSmallMapControl());
	theMap.addControl(new GMapTypeControl());
	theMap.addControl(new GScaleControl());			
	centerPoint = new GLatLng(origLat, origLng);
	
	theMap.setCenter(centerPoint, zoomLevel);
	
	// creating a hotspot's icon
	var icon = new GIcon();
	icon.image = "/images/trustive-icon.png";
	icon.iconSize = new GSize(20, 40);
	icon.iconAnchor = new GPoint(10, 40);
	icon.infoWindowAnchor = new GPoint(10, 40);
								
	// adding a scroll wheel zoom. 
	theMap.enableContinuousZoom();
	theMap.enableScrollWheelZoom();
    var bounds = new GLatLngBounds();
    
	for(var i=0; i< jsHotspots.length; i++){
		//alert(jsHotspots[i]);
		var tLat = jsHotspots[i][7];
		var tLng = jsHotspots[i][8];
		var posn = new GLatLng(tLat	, tLng );
		
		// the jsHotspots array -- (posn, name, address, postCode, locationType, price, icon)
		var newMarker = createMarker(posn, jsHotspots[i][0], jsHotspots[i][1], jsHotspots[i][2], jsHotspots[i][5], jsHotspots[i][6], jsHotspots[i][9], icon);
		theMap.addOverlay(newMarker);
		markersID[i] = newMarker;
        if (posn != new GLatLng(0, 0)) {
            bounds.extend(posn);
        }
	}
    if (!bounds.isEmpty()) {
        theMap.setZoom(theMap.getBoundsZoomLevel(bounds));
        theMap.setCenter(bounds.getCenter());
    }
}

// finding the map center point and calling the createHotspotsMap function
function startCreateHotspotsMap(jsHotspotsTemp, fullAddress, zoom){
	jsHotspots = jsHotspotsTemp;
	
	if(zoom == "worldZoom"){
		zoomLevel = 1;
	}
	else if(zoom == "countryZoom"){
		zoomLevel = 5;
	}
	else if(zoom == "cityZoom"){
		zoomLevel = 13;
	}
	else{
		zoomLevel = 14;
	}
	///////////////////////////

	if(fullAddress == "europe"){
		origLat = 50.7920470;
  		origLng = 5.1855468;
		createHotspotsMap();
	}
	else if(fullAddress == "world"){
		origLat = 39.315125;
  		origLng = -43.59375;
		createHotspotsMap();
	}
	else{
		var geocoder = new GClientGeocoder();
		geocoder.getLocations(fullAddress, getCenter);
	}
}

// get the geos from the google result or set fixed geos for a region.
function getCenter(response){
	if (!response || response.Status.code != 200) {
		showErrorPage("", "map");
  	} 
  	else {
   		place = response.Placemark[0];
   		 origLat = place.Point.coordinates[1];
  		origLng = place.Point.coordinates[0]; 
		createHotspotsMap();
  	}
}

// open an info window for a hotspot that couldn't be mapped
function openDetailsWindow(name, ssid, address, postCode, locationType, price){
	
	for(var i=0; i<markersID.length; i++){
		markersID[i].hide();
	}
	
	if(theMap.getZoom() == 1){
			theMap.setCenter(new GLatLng(39.315125, -43.59375), 1);
			centerPoint = new GLatLng(-10.315125, -43.59375);
	}

	// creating a not-mapped icon
	var icon = new GIcon();
	icon.image = "/images/notMappedMessage.png";
	icon.iconSize = new GSize(250, 50);
	icon.iconAnchor = new GPoint(125, 0);
	icon.infoWindowAnchor = new GPoint(80, 5);
	
	var newMarker = createMarker(centerPoint, name, ssid, address, postCode, locationType, price, icon);
	
	GEvent.addListener(newMarker, "infowindowclose", function(){   
		newMarker.hide();
		if(theMap.getZoom() == 1){
			theMap.panTo(new GLatLng(39.315125, -43.59375));
		}
	});  
	
	
	theMap.addOverlay(newMarker);
	GEvent.trigger(newMarker, "click");
	
}

/** \function
 * Display a "loading" icon and text, instead of the map and results table
 */
function displayMapLoading() {
    var loading_div = "<div id='loadingdiv' style='text-align: center; font-weight: bold; color:#336699;'><br /><br /><img src='/images/loading_map.gif' alt=''/><br /><br />Loading...</div>";
    document.getElementById("map").innerHTML = loading_div;
    document.getElementById("hotspotsresultstable").innerHTML = loading_div;
}
