// Copyright (c) 2008-09 David Ng (http://nudge.id.au/)
// cellsite.js Version 1.0



/* CountryInfo object constructor method */
function CountryInfo( mnc, name ) {
    this.mnc = mnc;
    this.name = name;
};

/* LocationInfo object constructor method */
function LocationInfo( mnc, name, lat, lon, zoom ) {
    this.mnc = mnc;
    this.name = name;
    this.lat = lat;
    this.lon = lon;
    this.zoom = zoom;
};

/* Define global variables */
var map; // Google Maps object
var mgr; // Google Maps MarkerManager object
var csCountry = new Array();  // Define a country array
var csLocation = new Array();  // Define a location array

/* Populate country array */
csCountry[0] = new CountryInfo(505, "Australia");
csCountry[1] = new CountryInfo(230, "Czech Republic");
/* Populate location array */
csLocation[0]  = new LocationInfo(505, "Melbourne", -37.814429, 144.962668, 15);
csLocation[1]  = new LocationInfo(505, "Sydney",    -33.867921, 151.206551, 15);
csLocation[2]  = new LocationInfo(505, "Canberra",  -35.2925,   149.127302, 14);
csLocation[3]  = new LocationInfo(505, "Brisbane",  -27.468336, 153.026333, 16);
csLocation[4]  = new LocationInfo(505, "Perth",     -31.95584,  115.861344, 15);
csLocation[5]  = new LocationInfo(505, "Adelaide",  -34.928762, 138.600383, 15);
csLocation[6]  = new LocationInfo(505, "Darwin",    -12.4604,   130.840237, 15);
csLocation[7]  = new LocationInfo(505, "Hobart",    -42.880807, 147.325201, 15);
csLocation[8]  = new LocationInfo(230, "Prague",     50.088208,  14.418097, 15);
csLocation[9]  = new LocationInfo(230, "Brno",       49.191184,  16.611586, 15);
csLocation[10] = new LocationInfo(230, "Ostrava",    49.838813,  18.284383, 15);


function setMapLocation(mnc, location_name)
{
    for( cidx=0 ; cidx<csCountry.length ; cidx++ )
    {
        if (csCountry[cidx].mnc == mnc)
        {
            break;
        }
    }

    for( lidx=0 ; lidx<csLocation.length ; lidx++ )
    {
        if
        (
            csLocation[lidx].mnc == mnc
            &&
            csLocation[lidx].name == location_name
        )
        {
            break;
        }
    }

    map.setCenter
    (
        new GLatLng
        (
            csLocation[lidx].lat,
            csLocation[lidx].lon
        ),
        csLocation[lidx].zoom
    );
}

/* Marker click handler to retreive information using AJAX call */
function getMarkerInfo(marker) {
    var towersDesc = "";

    /* Get country id from drop down box */
    countryid = document.getElementById("country").value;

    /* Do AJAX request */
    var urlstr="celltowers-xmlutil.php?action=getSiteInfo&siteid="+marker.siteid+"&country="+countryid;
    var request = GXmlHttp.create();  
    request.open('GET', urlstr , true);	// request XML from PHP with AJAX call

    request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			siteDesc = xmlDoc.documentElement.getAttribute("description");
			towers = xmlDoc.documentElement.getElementsByTagName("tower");
			if (towers.length){
				for (var i = 0; i < towers.length; i++) { // cycle thru locations
					towersDesc = "<div class='GMPopupTowerRecord'>" +
						towersDesc +
						towers[i].getAttribute("carrier")+ ": " + towers[i].getAttribute("name") + " (" + towers[i].getAttribute("cid") + ")" +
						"</div>";
				}
				marker.openInfoWindowHtml
				(
					"<div class='GMPopupSiteHeader'>" + siteDesc + "</div>" +
					towersDesc
				);
			}
		}
	}
	request.send(null);
}

/* Get site data for the given country using AJAX call */
function refreshMarkers(countryid) {
    /* Do AJAX request */
    var urlstr="celltowers-xmlutil.php?action=getMarkers&country="+countryid;
    var request = GXmlHttp.create();
    request.open('GET', urlstr , true);	// request XML from PHP with AJAX call

    /* Clear markers from MarkerManager object */
    mgr.clearMarkers();  

    request.onreadystatechange = function () {
        if (request.readyState == 4) {
           var xmlDoc = request.responseXML;
           sites = xmlDoc.documentElement.getElementsByTagName("site");
            markers = [];
           if (sites.length) {
                for (var i = 0; i < sites.length; i++) { // cycle thru locations
                    markers[i] =
                        new GMarker
                        (
                            new GLatLng
                            (
                                sites[i].getAttribute("lat"),
                                sites[i].getAttribute("lon")
                            )
                        );
                    /* Store the siteid of the location the marker represents. */
                    markers[i].siteid = sites[i].getAttribute("id");
                }

                mgr.addMarkers(markers, 12);
                mgr.refresh();
            }
        }
    }
    request.send(null);
}

function populateCountryDropDown()
{
    countryelem = document.getElementById("country");
    countryelem.options.length = 0;
    for( cidx=0 ; cidx<csCountry.length ; cidx++ )
    {
        countryelem.options[cidx] =
            new Option(csCountry[cidx].name, csCountry[cidx].mnc);
    }
}

/* Populate the Location dropdown list */
function populateLocationDropDown(mnc) {
    locationelem = document.getElementById("location");
    locationelem.options.length = 0;
    for( lidx=0 ; lidx<csLocation.length ; lidx++ )
    {
        if (csLocation[lidx].mnc == mnc)
        {
            locationelem.options[locationelem.options.length] =
                new Option(csLocation[lidx].name, csLocation[lidx].name);
        }
    }
}

/* Load country specific markers and populate the Location dropdown list */
function updateCountry() {
    /* Load markers for the selected country from the dropdown list */
    countryelem = document.getElementById("country");
    /* Update the Location dropdown list */
    populateLocationDropDown(countryelem.value);
    refreshMarkers(countryelem.value);
    updateLocation();
}

/* Move map to the specified location */
function updateLocation() {
   countryelem = document.getElementById("country");
   locationelem = document.getElementById("location");
   setMapLocation(countryelem.value, locationelem.value);
}


/* This function is called on page load to initialise the map and markers */
function load() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.enableScrollWheelZoom();
    
    setMapLocation(505, "Melbourne");
        
    mgr = new MarkerManager(map);
    
    map.addMapType(G_PHYSICAL_MAP);
    
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());     
    map.addControl(new GScaleControl());
    
    // bind a search control to the map, suppress result list
    map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));
       

    /* Initialise drop down boxes */
    populateCountryDropDown();
    populateLocationDropDown(505);
              
    /* Initialise default location */
    refreshMarkers(505);
                            
    GEvent.addListener(map, "click", function(overlay, point)
    {
        if (overlay)
        {
            // marker clicked
            getMarkerInfo(overlay);
        }
        else if (point)
        { // background clicked
        }
    }
    );

  }
}
