/* 
Gmaps script
------------
Script to include location maps and directions to contacts using the google maps api - JC
*/
/* 
Global Functions
*/
var map = new Array();
var directions = new Array();
var localSearch = new GlocalSearch();
var localSearch2 = new GlocalSearch();
/* 
This function looks up a postcode returns the latitude and longitude
*/
function usePointFromPostcode(postcode, callbackFunction, address, name) {
    // Sets the action for when the local search has been completed
    localSearch.setSearchCompleteCallback(null,
    function() {
        if (localSearch.results[0]) {
            // Result is found
            // Latitude location of result
            var resultLat = localSearch.results[0].lat;
            // Longitude location of result
            var resultLng = localSearch.results[0].lng;
            // Puts the Longitude and Latitude into a format google prefers
            var point = new GLatLng(resultLat, resultLng);
            // calls placeMarkerAtPoint with information
            callbackFunction(point, postcode, address, name);
        } else {
            // No Results
            // Places alert box to inform user
            alert("Address not found!");
        }
    });
    // Starts geocoding search for postcode.
    localSearch.execute(postcode + ", UK");
}
/*
Puts location of address on map.
*/
function placeMarkerAtPoint(point, postcode, address, name) {
    // Centres map on address
    map[name].setCenter(point, 15);
    // Creates the marker object for address
    var marker = new GMarker(point);
    // Places marker on map
    map[name].addOverlay(marker);
    // Centres map on address
    map[name].setCenter(point, 15);
    // Adds information bubble to map to display marker information. Replaces commas with breaklines for display purposes.
    var NewAddress = marker.openInfoWindowHtml(address.replace(/,/g, ",<br>") + postcode);
}
/*
This function is called from a button on the page, it will display directions from a specified postcode to the contact address.
*/
function doDirections(directionDiv, name, postcode) {
    // Select panel to place directions
    directionsPanel = document.getElementById(directionDiv);
    // Select the users entered postcode
    directionsStart = document.getElementById("from" + name).value;
    // Check if directions object for address exisits.
    if (!directions[name]) {
        // Directions object doesn't exisit
        // Create new directions object
        directions[name] = new GDirections(map[name], directionsPanel);
        // Add disclaimer text 
        directionsPanel.innerHTML = directionsPanel.innerHTML + "<p style=\"font-size: 75%\">These directions are for planning purposes only. You may find that construction projects, traffic, or other events may cause road conditions to differ from the map results.<\/p>";
        // Add print option
        directionsPanel.innerHTML = directionsPanel.innerHTML + "<a href=\"javascript:PrintDirections(" + name + ")\">Print directions to " + postcode + "<\/a>";
    }
    // Sets the action for when the local search for start has been completed
    localSearch2.setSearchCompleteCallback(null,
    function() {
        if (localSearch2.results[0]) {
            // Start address found
            // Sets the action for when the local search for contact has been completed
            localSearch.setSearchCompleteCallback(null,
            function() {
                if (localSearch.results[0]) {
                    // Both address found
                    // Clear exisiting directions if required.
                    directions[name].clear();
                    // Request directions, and load onto page
                    directions[name].load(localSearch2.results[0].lat + "," + localSearch2.results[0].lng + " to " + localSearch.results[0].lat + "," + localSearch.results[0].lng + "");
                } else {
                    // End address not found
                    alert("Address not found!");
                }
            });
            // Search end address
            localSearch.execute(postcode + ", UK");
        } else {
            // Start postcode not found
            alert("Start address not found!");
        }
    });
    // Search start address
    localSearch2.execute(directionsStart + ", UK");
}
/*
Function to initilise the map, run when user clicks "Location of X"
*/
function mapLoad(postcode, address, mapid, name) {
    //Checks browser is compatible
    if (GBrowserIsCompatible()) {
        // Set the holding div elements size, as a default is set so it cannot be seen untill required
        document.getElementById(mapid).style.width = "95%";
        document.getElementById(mapid).style.height = "400px";
        // Creates the map object
        map[name] = new GMap2(document.getElementById(mapid));
        // Adds zoom and movement tools
        map[name].addControl(new GLargeMapControl());
        // Adds map type options
        map[name].addControl(new GMapTypeControl());
        // Zooms to townhall as a default location.
        map[name].setCenter(new GLatLng(53.54826350153167, -2.629680633544922), 13);
        // Looks up postcode for contact and places icon and bubble with address details on map.
        usePointFromPostcode(postcode, placeMarkerAtPoint, address, name);
    }
    // Checks large map div has been created
    if (!document.getElementById(mapid + "link")) {
        // Creates new div element for large map div.
        var newDiv = document.createElement("div");
        // sets the id for the new div
        newDiv.setAttribute("id", mapid + "link");
        // sets contents for the new div
        newDiv.innerHTML = "<p><a href='http://maps.google.co.uk/maps?q=" + postcode + "'>View Large Map for " + postcode + " (external link)<\/a><\/p>";
        // selects the maps div 
        var mapDiv = document.getElementById(mapid);
        // selects the parent element for the map div
        var parentDiv = mapDiv.parentNode;
        // Inserts the new div before the element after the map div.
        parentDiv.insertBefore(newDiv, mapDiv.nextSibling);
        // Creates new div element for directions.
        var newDiv2 = document.createElement("div");
        // sets the id for the new div
        newDiv2.setAttribute("id", mapid + "direction");
        // sets contents for the new div
        newDiv2.innerHTML = "<label for=\"from" + name + "\">Enter your postcode<\/label> <input type=\"text\" id=\"from" + name + "\" style=\"width: 100px\"> <a href='javascript:doDirections(\"" + mapid + "direction\",\"" + name + "\",\"" + postcode + "\"); '>Get Directions to " + postcode + "<\/a>";
        newDiv2.style.width = "95%";
        // selects the largemap div 
        var parentDiv = newDiv.parentNode;
        // Inserts the new div before the element after the large map div.
        parentDiv.insertBefore(newDiv2, newDiv.nextSibling);
    }
}
/*
Function to print the directions generated.
*/
function PrintDirections(name) {
    try {
        // Tries to put directions in the div and print.
        // Selects print iframe
        var oIframe = document.getElementById('ifrmPrint');
        // Selects directions div
        var oContent = document.getElementById("mapholder" + name + "direction").innerHTML;
        // puts div contents into iframe and prints.
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.write("<html><head><title>title<\/title>");
        oDoc.write("<\/head><body onload='this.focus(); this.print();'>");
        oDoc.write(oContent + "<\/body><\/html>");
        oDoc.close();
    } catch(e) {
        // If all else fails prints all the page
        self.print();
    }
}