// Load up our icon images. Array keys refer to values of 'type'
var icons = {
    FE:         "img/orange.png",
    Sponsored:  "img/cyan.png",
    Special:    "img/purple.png",
    University: "img/red.png",
    ACL:        "img/yellow.png",
    Default:    "img/green.png"
};

var labels = {      // should be plural
    FE:         "FE Colleges",
    Sponsored:  "Sponsored Organisations",
    Special:    "Specialist Colleges",
    University: "Universities",
    ACL:        "Adult and Community Learning",
    Default:    "Other"
};

//The URL of the XML file
var xmlUrl = 'norman.xml';

// Make a HTTP request for the map data, and if successful, create a map and list in the given elements
function replaceWithListAndMap(listElement,mapElement,width,height) {
    var request = GXmlHttp.create();
    request.open("GET", xmlUrl, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            createMapFromXML(parseSiteXML(request.responseXML),
                             listElement,
                             mapElement,
                             new GSize(width,height) );
        }
    }
    request.send(null);
}

// Replace elements with map and list generated from given data
function createMapFromXML (siteData,listElement,mapElement,mapGSize) {
    // Initialise the Googlemap component
    var map = new GMap2(document.getElementById(mapElement),{size:mapGSize});
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.setCenter(new GLatLng(54.85843, -1.528473), 9, G_SATELLITE_MAP);

    // Loop thru our data and add markers and list items
    var typeList = document.createElement('ul');
    for (var t in siteData) {
        if (t == 'NCL') {continue;}
        var typeItem = document.createElement('li');
        typeList.appendChild(typeItem);
        var iconImg = document.createElement('img');
        iconImg.src = getIconPath(t);
        iconImg.width = 16;        
        iconImg.height = 16;
        typeItem.appendChild(iconImg);
        typeItem.appendChild(document.createTextNode( mapLabel(t) ));
        var siteList = document.createElement('ul');
        typeItem.appendChild(siteList);
        for (var i in siteData[t]) {
            // skip if no valid long or lat
            if (isNaN(siteData[t][i]['lat']) || isNaN(siteData[t][i]['lng'])) { continue; }

            // Add a marker for our site
            var marker = markerForSite(siteData[t][i]);
            GEvent.addListener(marker, "click", makeInfoWindowOpener(marker,siteData[t][i]));
            map.addOverlay( marker );
            
            // Add a list item to the DOM
            var siteItem = document.createElement('li');
            siteItem.appendChild( document.createTextNode(siteData[t][i]['short']) );
            siteList.appendChild( siteItem );
            siteItem.onclick = makeInfoWindowOpener(marker,siteData[t][i]);
        }
    }
     
    // Clear old content from sitelist element and replace with our new list
    var siteListDiv = document.getElementById(listElement);
    while ( siteListDiv.hasChildNodes() ) {
        siteListDiv.removeChild(siteListDiv.firstChild);
    }           
    var introText = document.createElement('p');
    introText.appendChild(document.createTextNode('(Click names to show on map)'));
    siteListDiv.appendChild(introText);
    siteListDiv.appendChild(typeList);
}

// Closure function which returns a function to pass as a handler to things
function makeInfoWindowOpener(marker, site) {
    function inner() {
        return marker.openInfoWindowHtml("<b>" + site['name'] + "</b><br/>" + site['addr']);
    }
    return inner;
}

// Maps data org types to configured nice labels
function mapLabel(oldLabel) {
    var newLabel = labels['Default'];
    if (typeof(labels[oldLabel]) != 'undefined') {
        newLabel = labels[oldLabel];
    }
    return newLabel;
}

// Returns icon path from has for given type
function getIconPath(type) {
    var path = icons['Default'];
    if (typeof(icons[type]) != 'undefined') {
        path = icons[type];
    }
    return path;
}

// Returns a GMarker for the given site data
function markerForSite(site) {
    var iconPath = getIconPath( site['type'] );
    
    // Build a Google Icon for the marker
    var icon              = new GIcon();
    icon.image            = iconPath;
    icon.shadow           = "";
    icon.iconSize         = new GSize(16, 16);
    icon.shadowSize       = new GSize(0, 0);
    icon.iconAnchor       = new GPoint(8, 8);
    icon.infoWindowAnchor = new GPoint(8, 6);

    var point = new GLatLng(site['lat'],site['lng']);

    return new GMarker(point, icon);
}

// Function to parse the NorMAN XML data into a data structure:
function parseSiteXML(xmlDoc) {
    var siteData = new Array();
    var sites = xmlDoc.documentElement.getElementsByTagName("site");
    for (var i=0; i<sites.length; i++) {
        var type = sites[i].getAttribute("type");
        if (typeof(siteData[type]) == 'undefined') {
            siteData[type] = new Array();
        }
        var site = new Array();
        site['type']  = type;
        site['name']  = sites[i].getAttribute("name");
        site['short'] = sites[i].getAttribute("short");
        if ( site['short'] == null) site['short'] = site['name'];
        var address = sites[i].getElementsByTagName("address")[0];
        if ( address ) {
            site['lat'] = parseFloat(address.getAttribute("lat"));
            site['lng'] = parseFloat(address.getAttribute("lng"));
            site['addr'] = GXml.value(address);
        }
        siteData[type].push(site);
    }
    return siteData;
}

