/* 
Gmaps script
------------
Script to include location maps and directions to contacts using the google maps api - JC
05/09/2008 - Now includes transport information using the bus via transport direct - 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 PublicTransport;
    PublicTransport="<form method=\"post\" id=\"TransportDirectPlanningForm\" target=\"_blank\" action=\"http://www.transportdirect.info/web2/journeyplanning/jpLandingPage.aspx\">\n";
PublicTransport+="<table width=\"230px\" cellspacing=\"0\" style=\"margin: 1em;\">\n";
PublicTransport+="<tr bgcolor=\"#330099\">\n";
PublicTransport+="<td>\n";
PublicTransport+="<p style=\"margin: 2px 2px 2px 4px\">\n";
PublicTransport+="<img alt=\"Transport Direct (External link)\" src=\"http://www.transportdirect.info/Web2/App_Themes/TransportDirect/images/gifs/misc/TDLogo38.gif\" /></p>\n";
PublicTransport+="</td>\n";
PublicTransport+="</tr>\n";
PublicTransport+="<tr bgcolor=\"#99ccff\">\n";
PublicTransport+="<td>\n";
PublicTransport+="<p style=\"font-family: verdana, arial, helvetica, sans-serif; font-size: 12px; text-align: left;\n";
PublicTransport+="margin: 5px 5px 5px 5px;\">\n";
PublicTransport+="Get directions by public transport and car with <a href=\"http://www.transportdirect.info/web2/Home.aspx\"\n";
PublicTransport+="target=\"_blank\">Transport Direct (External link)</a>.</p>\n";
PublicTransport+="<p style=\"font-family: verdana, arial, helvetica, sans-serif; font-size: 12px; text-align: left;\n";
PublicTransport+="margin: 5px 5px 5px 5px;\">\n";
PublicTransport+="Enter your postcode</p>\n";
PublicTransport+="</td>\n";
PublicTransport+="</tr>\n";
PublicTransport+="<tr bgcolor=\"#99ccff\">\n";
PublicTransport+="<td>\n";
PublicTransport+="<p style=\"font-family: verdana, arial, helvetica, sans-serif; font-size: 12px; text-align: left;\n";
PublicTransport+="margin: 5px 5px 5px 5px;\">\n";
PublicTransport+="<input type=\"text\" id=\"txtOrigin\" name=\"o\" style=\"width: 80px; border-color: lightgrey;\n";
PublicTransport+="border-width: 1px; border-style: solid; font-size: 12px; font-family: verdana, arial, helvetica, sans-serif;\n";
PublicTransport+="background-color: white; height: 16px;\" />\n";
PublicTransport+="<input type=\"submit\" id=\"btnSubmit\" value=\"Go\" style=\"color: #264266; background-color: #ebebeb;\n";
PublicTransport+="font-family: verdana, arial, helvetica, sans-serif; font-weight: bold; font-size: 12px;\n";
PublicTransport+="text-align: center; text-decoration: none; border-bottom-color: #808080; border-top-color: #C0C0C0;\n";
PublicTransport+="border-right-color: #808080; border-left-color: #C0C0C0; border-width: 1px; border-style: solid;\n";
PublicTransport+="cursor: pointer; cursor: hand; width: auto; overflow: visible; padding: 0px 3px 1px 3px;\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"oo\" value=\"p\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"et\" value=\"jp\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"m\" value=\"m\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"do\" value=\"p\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"d\" id=\"destinationData\" value=\"" + postcode + "\" />";
PublicTransport+="<input type=\"hidden\" name=\"dn\" value=\"" + postcode + "\" />";
PublicTransport+="<input type=\"hidden\" name=\"p\" value=\"1\" />\n";
PublicTransport+="<input type=\"hidden\" name=\"id\" value=\"BusinessLinks\" />\n";
PublicTransport+="</p>\n";
PublicTransport+="</td>\n";
PublicTransport+="</tr>\n";
PublicTransport+="</table>\n";
PublicTransport+="</form>\n";
    var NewAddress = marker.openInfoWindowTabsHtml([new GInfoWindowTab('Address',address.replace(/,/g, ",<br>") + postcode), new GInfoWindowTab("Transport",PublicTransport)]);
}
/*
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();
    }
}


function MapLoadRSS(location,mapid,name){
   if (GBrowserIsCompatible()) {
   
        //alert("Hello World");
        // Set the holding div elements size, as a default is set so it cannot be seen untill required
        //alert(location)
        var coords = location.split(/[, ]+/)
        /*if(coords.length == 1){
           coords = location.split(",")
        }*/
        //alert(coords[0]);
        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(coords[0], coords[1]), 13);
        // Looks up postcode for contact and places icon and bubble with address details on map.
        var point = new GLatLng(coords[0], coords[1]);
        var marker = new GMarker(point);
        map[name].addOverlay(marker);
        
      }
      
       /*
       // 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=" + location + "'>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);
    */
    document.getElementById("maphide" + name).style.visibility = "visible"
    
    return;
 }
 

 
 function MapHide(position){
      //alert("mapholder" + position);
      var divMap = document.getElementById("mapholder" + position);
      var divHideMap = document.getElementById("maphide" + position);
      
      
      //alert(divMap.Id);
      
      if(divMap != null){
                  //alert("Here");
                  divMap.innerHTML ="";
                  divMap.style.width = "95%";
                  divMap.style.height = "0px";
           
      }
     
      if(divHideMap != null){
                  //alert("Here2");
                  divHideMap.style.visibility = "hidden";
                  divMap.style.width = "95%";
                  divMap.style.height = "0px";
     }
     
      
      return false;
 
 }
