// JavaScript Document
var map = null;
var geocoder = null;
var apIDForResultHandler = 0;
var flgNoQuery = false;
var windowOpen = false;
var minZoom = 5;
var clickMarker;
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
function initialize()
{
	if (GBrowserIsCompatible()) 
	{
		map = new GMap2(document.getElementById("map"));
		map.enableScrollWheelZoom();
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		var lat = gup( 'lat' );
		var lon = gup( 'lon' );
		var zoom = gup( 'zoom' );
		
		geocoder = new GClientGeocoder();
		GEvent.addListener(map, "moveend", function() {
			//alert('moveend');
			var swLat = map.getBounds().getSouthWest().lat();
			var swLng = map.getBounds().getSouthWest().lng();
			var neLat = map.getBounds().getNorthEast().lat();
			var neLng = map.getBounds().getNorthEast().lng();
			var categorie = createCatString();

			var zoom = map.getZoom();
			if (zoom < minZoom)
			{
				show('overlaymapzoom');
				map.clearOverlays();
				return;
			}
			else
			{
				hide('overlaymapzoom');	
			}
			//alert(flgNoQuery);
			if (!flgNoQuery)
			{
				makeRequestNum(swLat,swLng,neLat,neLng,categorie);
				makeRequestSpot(swLat,swLng,neLat,neLng,categorie);
			}
			//hide('updatemap');
		});
		GEvent.addListener(map, "dragstart", function() {
			if (!windowOpen)
			flgNoQuery = false;
		});
		GEvent.addListener(map, "infowindowclose", function() {
			//alert('infowindowclose');
			flgNoQuery = false;
			windowOpen = false;
		});
		GEvent.addListener(map, "infowindowopen", function() {
			//alert('infowindowclose');
			flgNoQuery = true;
			windowOpen = true;
		  });
		if (lat == '' && lon == '' && zoom == '')
		{
			map.setCenter(new GLatLng(23.885837699862005, -39.0234375), 2);
			hide('overlaymapzoom');	
		}
		else
		{
			map.setCenter(new GLatLng(parseFloat(lat), parseFloat(lon)), parseInt(zoom));
			GEvent.trigger(map, "moveend");	
		}
	}
}
function createCatString()
{
	var categorie = "";
	var chkFree = document.getElementById("chkFree");
	var chkCom = document.getElementById("chkCom");
	var chkAirport = document.getElementById("chkAirport");
	var chkCoffee = document.getElementById("chkCoffee");
	var chkGas = document.getElementById("chkGas");
	var chkTrain = document.getElementById("chkTrain");
	var chkHotels = document.getElementById("chkHotels");
	var chkOthers = document.getElementById("chkOthers");
	if (chkFree.checked) 
	{
		categorie = categorie += 'free,';
	}
	if (chkAirport.checked) 
	{
		categorie = categorie += 'airport,';
	}
	if (chkCoffee.checked) 
	{
		categorie = categorie += 'coffee,';
	}
	if (chkGas.checked) 
	{
		categorie = categorie += 'gas,';
	}
	if (chkTrain.checked) 
	{
		categorie = categorie += 'train,';
	}
	if (chkHotels.checked) 
	{
		categorie = categorie += 'hotels,';
	}
	if (chkOthers.checked) 
	{
		categorie = categorie += 'others,';
	}
	if (categorie != "")
	{
		categorie = categorie.substring(0,categorie.length - 1);
	}	
	return categorie;
}
function showCountryList()
{
	show('overlaymapcity');
	hide('overlaymapshowcountries');
}
function showAddress(address,zoom) {
	
	if (hideOverlayPaesi)
	{
		hide('overlaymapcity');
		show('overlaymapshowcountries');
		flgNoQuery = false;
	}
	else
	{
		//alert('passato');
		hideOverlayPaesi = true;	
		flgNoQuery = true;
	}
	
	if (geocoder)
	{
		geocoder.getLatLng(
			address,
		  	function(point) 
		  	{
				if (!point) 
				{
					if (address == '')
					{
						alert('Please, insert an address');
					}
					else
					{
						alert(address + " not found");
					}
				} 
				else 
				{
			  		//map.setCenter(point, zoom);
					map.setCenter(point,zoom);
					//var marker = new GMarker(point);
					//map.addOverlay(marker);
					//marker.openInfoWindowHtml(address);
				}
			}
		);
		geocoder.getLocations(address, addAddressToTB);
	}
}
function addAddressToTB(response) {
      if (!response || response.Status.code != 200) {
        //alert("Sorry, we were unable to geocode that address");
      } else {
        place = response.Placemark[0];
		xajax_setGeocodeAddress(place.address);
      }
    }
function goToMarker(markerID, lat, lng) {

	// Recenter map
	flgNoQuery = true;
    map.setCenter(new GLatLng(lat, lng), 15); 
    
	// Request the details for the marker
	var url = 'php_request_spot_details_whisher.php?apid=' + markerID;
	//alert(url);
	var httpRequest;
	if (window.XMLHttpRequest) 
	{ 
		// Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) 
		{
			httpRequest.overrideMimeType('text/xml');
		}
	} 
	else if (window.ActiveXObject) 
	{ 
		// IE
		try 
		{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
			
			}
		}
	}
	if (!httpRequest) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	httpRequest.onreadystatechange = function() { alertContentsMarkerDetails(httpRequest,markerID); };
	httpRequest.open('GET', url, true);
	httpRequest.send('');
}
function alertContentsMarkerDetails(httpRequest,markerID)
{
	if (httpRequest.readyState == 4) 
	{
		if (httpRequest.status == 200) 
		{
			//alert('passato');
			var xmlResponse = httpRequest.responseText;
			var arrayAP = eval('(' + xmlResponse + ')');
			infoContent = generateBalloon(arrayAP, markerID);
			
			// Pop open the info balloon
			map.openInfoWindow(map.getCenter(), infoContent);
			infoPopup = map.getInfoWindow();
			flgNoQuery = true;
			var nome = arrayAP[1];
			var categoria = arrayAP[6];
			var indirizzo = arrayAP[7];
			var city = arrayAP[8];
			//xajax_updateResultsDetails(nome,categoria,indirizzo,city);
		}
	}
}
function addAccessPointOnMap(aps) 
{	
	//alert('add access point on map');	
	//map.clearOverlays();
	pins = new Array();
	accessPoints = new Array();
	apCounter=0;
	pinID=0;	
	
	for (i=0; i<aps.length;i++) 
	{        
		var baseImage = new GIcon();
		var apsAM = aps[i].Category;
		//alert(apsAM);
		baseImage.image = 'php_request_image_filename_small.php?catid=' + apsAM;
		baseImage.iconSize = new GSize(32, 33);
		baseImage.iconAnchor = new GPoint(9, 5);
		baseImage.infoWindowAnchor = new GPoint(0, 0);
		//alert('passato');
		pin = new GMarker(new GLatLng(aps[i].Latitude, aps[i].Longitude), baseImage);  
		pin.accessPoint = aps[i];
		pin.id = aps[i].APId;
		
		//add eventhandler for mouseclick on AP icon                      
		GEvent.addListener(pin, "click", function() {	
			flgNoQuery = true;
			clickMarker = this;
			//show('updatemap');
			if (clickMarker.id)  {  	
				// show info window (DataAccess.js)             
				requestDetailsForAccessPoint(clickMarker.id); 
				tableClicked = false; 
			}
			else {
				clickMarker = null;
				tableClicked = false;                
			}            
			/*if (searching) 
			{
				map.removeControl(searching);
			}*/
		  });
		
		
		accessPoints[apCounter] = aps[i];
		accessPoints[apCounter].PinID = pinID;			                 
		apCounter++;          
		map.addOverlay(pin);                      
	}	
}
function getImageForAccessModifier(category) {
	//alert(category);
	/*switch (category){
		case 1:
			return IMG_SHARED;
		case 2:
			return IMG_AIRPORT;
		case 3:
			return IMG_GAS;
		case 4:
			return IMG_TRAIN;
		case 5:
			return IMG_COFFEE;
		case 6:
			return IMG_HOTEL;
		case 14:
			return IMG_OTHER;
		default:
			return IMG_OTHER;
	}*/
	return 'php_request_image_filename_small.php?catid=' + category;
	//return 'img/wifi_free.png';
}
function getLargeImageForAccessModifier(category) {
	switch (category){
		case 1:
			return IMG_SHARED_L;
		case 2:
			return IMG_AIRPORT_L;
		case 3:
			return IMG_GAS_L;
		case 4:
			return IMG_TRAIN_L;
		case 5:
			return IMG_COFFEE_L;
		case 6:
			return IMG_HOTEL_L;
		case 14:
			return IMG_OTHER_L;
		default:
			return IMG_OTHER_L;
	}
}
function requestDetailsForAccessPoint(apid) {
//alert('richiesta');
	var url = 'php_request_spot_details_whisher.php?apid='+apid;
	//xajax_setTemp(url);
	//alert(url);
	var httpRequest;
	if (window.XMLHttpRequest) 
	{ 
		// Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) 
		{
			httpRequest.overrideMimeType('text/xml');
		}
	} 
	else if (window.ActiveXObject) 
	{ 
		// IE
		try 
		{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
			
			}
		}
	}
	if (!httpRequest) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	httpRequest.onreadystatechange = function() { requestDetailsForAPResultHandler(httpRequest,apid); };
	httpRequest.open('GET', url, true);
	httpRequest.send(null);
}

function requestDetailsForAPResultHandler(httpRequest,apid) {
	if (httpRequest.readyState == 4) 
	{
		if (httpRequest.status == 200) 
		{
			//alert('pass');
			/*
			try {
				if (netscape.security.PrivilegeManager.enablePrivilege) {
					netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
				}
			}
			catch (ex) {}
			*/	
			//alert(apIDForResultHandler);
			var xmlResponse = httpRequest.responseText;
							            
            var arrayAP = eval('(' + xmlResponse + ')');
			//alert(arrayAP);
			accessPoints[apIDForResultHandler].APId = apid;
			accessPoints[apIDForResultHandler].APName = arrayAP[1];		
			/*if (arrayAP[1] != '') {
				accessPoints[apIDForResultHandler].Description = arrayAP[1];
			} else {
				accessPoints[apIDForResultHandler].Description = "";
			}*/
			accessPoints[apIDForResultHandler].OwnerName = arrayAP[2];
			accessPoints[apIDForResultHandler].Category = arrayAP[6];
			/////////////////////
						/////////////////////
									/////////////////////
												/////////////////////
															/////////////////////
															//GESTIONE IMMAGINI
															
			accessPoints[apIDForResultHandler].Picture = 'php_request_image_filename.php?catid=' + arrayAP[6];
			//accessPoints[apIDForResultHandler].Picture = WIFI_PICTURES_URL + "?" + arrayAP[6];
			accessPoints[apIDForResultHandler].Description = arrayAP[3];
			//xajax_setTemp('php_request_image_filename.php?catid=' + arrayAP[6]);
			//alert('categoria = ' + arrayAP[5]);
			//xajax_setTemp('php_request_image_filename.php?catid=' + arrayAP[6]);
			//alert(accessPoints[apIDForResultHandler].Category);
			/*if (accessPoints[apIDForResultHandler].Category == 1) {
				accessPoints[apIDForResultHandler].Picture = AP_PICTURES_URL + "?" + accessPoints[apIDForResultHandler].APId;
			}
			else {
				accessPoints[apIDForResultHandler].Picture = getLargeImageForAccessModifier(accessPoints[apIDForResultHandler].Category);
				//accessPoints[apIDForResultHandler].Picture = 'img/wifi_airport.png';
				accessPoints[apIDForResultHandler].Description = "WiFi Out Enabled Hotspot";
			}*/
			//if (xmlResponse.getElementsByTagName('ownersite')[0].childNodes[0]) {
			//	accessPoints[apIDForResultHandler].HomeSite = xmlResponse.getElementsByTagName('ownersite')[0].childNodes[0].nodeValue;
			//} else {
			//	accessPoints[apIDForResultHandler].HomeSite = "";
			//}
			//if (xmlResponse.getElementsByTagName('ownerskypename')[0].childNodes[0]) {
			//	accessPoints[apIDForResultHandler].OwnerSkypeName = xmlResponse.getElementsByTagName('ownerskypename')[0].childNodes[0].nodeValue;
			//} else {
			//	accessPoints[apIDForResultHandler].OwnerSkypeName = "";
			//}
			if (arrayAP[7] != '') {
				accessPoints[apIDForResultHandler].Address = arrayAP[7];
			} else {
				accessPoints[apIDForResultHandler].Address = "";
			}
			if (arrayAP[8] != '') {
				accessPoints[apIDForResultHandler].City = arrayAP[8]
			} else {
				accessPoints[apIDForResultHandler].City = "";
			}			
			accessPoints[apIDForResultHandler].Latitude = arrayAP[4];
			accessPoints[apIDForResultHandler].Longitude = arrayAP[5];
			
			accessPoints[apIDForResultHandler].hasCompleteInfo = true;
            
            //create html info popup for an AP in utils.js
			//alert(accessPoints);
            resultHtml = buildAPDetailsPopupContent(accessPoints[apIDForResultHandler]);            						                  
            //AP on map clicked
            if (clickMarker) { 
                tableClicked = true;       
                map.openInfoWindow(clickMarker.getPoint(), resultHtml);  
                infoPopup=map.getInfoWindow();     
                clickMarker = null;
                //remove Search result
			    //document.getElementById("apAddress").innerHTML = "-";

            }
            //link in result table clicked
            else 
            {                                                               
                bigResult = "";
                bigResult = resultHtml;            
                map.openInfoWindow(map.getCenter(), bigResult);
                infoPopup=map.getInfoWindow();
				//map.openInfoWindow(map.getCenter(), resultHtml);
				//remove Search result
			    document.getElementById("apAddress").innerHTML = "-";
            }           
            
            /*if (searching) 
            {
	            map.removeControl(searching);
	        }*/          
		} 
	}
}
function getLocation()
{
	document.info.textsearch.value = '<?=$location?>';
	if (document.info.textsearch.value != '')
	{
		submitForm();
	}
}