﻿/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function to create a google map object and create on overlay marker for the hospital
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadMap() {
    // get the lable to use if we run into an error
    var lblError = document.getElementById("lblDirectionsError");
    var placeNode = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_hidNode");
    var placeNodeStr = placeNode.value
    var destinationAddress = "3901+Rainbow+Blvd,+Kansas+City,+KS+66160";
    //var kmlUrl = "http://www.kumed.com/kumedplaces.kml";
    if (GBrowserIsCompatible()) {
        function createMarker(point, html) {
            var marker = new GMarker(point);
            GEvent.addListener(marker, "click",
		        function() {
		            marker.openInfoWindowHtml(html);
		        }
		    );
            return marker;
        }

        // 1' = 0.0166667 deg, 1" = 0.000278
        // KUMC =  Lat: 39° 3'20.95"N (39 + 0.05 + 0.0058241), long:  94°36'35.97"W (94 + 0.6 + 0.009917)
        //var centerCoor = new GLatLng(39.0558241, -94.609917);
        // Figure out which placemark, we need to load the center for
        var destinationNode = findKMLPlaceMark(kmlDom, placeNodeStr);
        //alert("placeNodeStr = "+placeNodeStr+", destinationNode = "+destinationNode);
        // if we can find the destination node, then create a centerCoor object and move map to there
        // otherwise show an error
        if (destinationNode != null) {
            // get the coordinates, should only be one node so we'll grab the first
            var coordinatesNode = destinationNode.getElementsByTagName("coordinates")[0];
            var coordinatesStringPair = "";
            if (coordinatesNode != null) {
                if (coordinatesNode.text != undefined) // Check for IE XML DOM, or compliant DOM
                {
                    coordinatesStringPair = coordinatesNode.text;
                }
                else {
                    coordinatesStringPair = coordinatesNode.textContent;
                }
                // split pair into two floats, remembering that in a kml coordinates element, the pairs are reverse the order of the
                // GLatLng initialization elements
                var coordinatesPair = coordinatesStringPair.split(',');
                var latFloat = parseFloat(coordinatesPair[1]);
                var longFloat = parseFloat(coordinatesPair[0]);
                //var centerCoor = new GLatLng(39.056600, -94.608800);
                var centerCoor = new GLatLng(latFloat, longFloat);
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                // Once the zoom metadata attribute is added we can activate this code
                //var zoomLevel = document.getElementById("hidZoom");
                map.setCenter(centerCoor, 15);
                //map.setMapType(G_SATELLITE_MAP);
                //map.setMapType(G_HYBRID_MAP);
                map.setMapType(G_NORMAL_MAP);

                // setup overlay using the GGeoXml object and a .kml file
                var geoXml = new GGeoXml(kmlUrl);
                map.addOverlay(geoXml);
            }
            else {
                // if we cannot find the destination address in the kml file, show an error
                lblError.innerHTML = "<p style='color: Red;'>Unable to determine the map to show," +
                    " please contact the <a href='mailto:webteam@kumc.edu'>web master</a> for help</p>";
            }
        }
        else {
            // if we cannot find the destination address in the kml file, show an error
            lblError.innerHTML = "<p style='color: Red;'>Unable to determine the map to show," +
                " please contact the <a href='mailto:webteam@kumc.edu'>web master</a> for help</p>";
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construct a url to google maps to get the user directions from a location they specify to the current
// location.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getDirections(placeNodeStr) {
    // Get the place node
    var placeNode = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_hidNode");
    var placeNodeStr = placeNode.value
    // get the lable to use if we run into an error
    var lblError = document.getElementById("lblDirectionsError");
    // search kml placemarks for the id value in placeNode
    var destinationNode = findKMLPlaceMark(kmlDom, placeNodeStr);
    // if we found a placemark node with that id, then we extract the address
    // Otherwise we use the default, which is the hospital address
    if (destinationNode != null) {
        // get the address element of the placemark
        var destinationAddressNode = destinationNode.getElementsByTagName("address")[0];
        if (destinationAddressNode != null) {
            if (destinationAddressNode.text != undefined) // check for IE XML DOM or compliant XML DOM
            {
                destinationAddress = destinationAddressNode.text.replace(/ /g, '+');
            }
            else {
                destinationAddress = destinationAddressNode.textContent.replace(/ /g, '+');
            }

            var startAddress = "";
            var tbStreet = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_tbStreet");
            var tbCity = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_tbCity");
            var ddlState = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_ddlState");
            var selectedState = ddlState.selectedIndex;
            var tbZipCode = document.getElementById("ctl00_MyContentPlaceHolder_ctl01_tbZipCode");

            startAddress += tbStreet.value.replace(/ /g, '+');
            startAddress += "+" + tbCity.value.replace(/ /g, '+');
            startAddress += "+" + ddlState.options[selectedState].text.replace(/ /g, '+');
            startAddress += "+" + tbZipCode.value.replace(/ /g, '+');

//            var googleMapsUrl = "http://maps.google.com/maps?daddr=" + destinationAddress +
//                "&dirflg=&saddr=" + startAddress;
//            window.open(googleMapsUrl);

            //dirDiv.style.visibility = "visible";
            //dirDiv.style.overflow = "scroll"; //overflow: scroll;
            GEvent.addListener(gdir, "load", onGDirectionsLoad);
            GEvent.addListener(gdir, "error", handleErrors);

            var locale = "en_US";
            gdir.load("from: " + startAddress + " to: " + destinationAddress,
                { "locale": locale });

        }
        else {
            // if we cannot find the destination address in the kml file, show an error
            lblError.innerHTML = "<p style='color: Red;'>Unable to determine the destination address to direct you to," +
                " please contact the <a href='mailto:webteam@kumc.edu'>web master</a> for help</p>";
        }
    }
    else {
        // if we cannot find the destination address in the kml file, show an error
        lblError.innerHTML = "<p style='color: Red;'>Unable to determine the destination address to direct you to," +
            " please contact the <a href='mailto:webteam@kumc.edu'>web master</a> for help</p>";
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Gets info about the directions loaded to verify that it worked ok
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function onGDirectionsLoad()
{
    //var status = document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Handles errors related to getting directions
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function handleErrors()
{

    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Loads a local or internet kml file and returns an xml dom object containing it
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadKMLFile() {
    var xmlDoc;
    // Create the xml dom object
    try //Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    }
    catch (e) {
        try //Firefox, Mozilla, Opera, etc.
        {
            xmlDoc = document.implementation.createDocument("", "", null);
        }
        catch (e) {
            alert("Could not create kml doc: " + e);
        }
    }

    // load the kml file
    try {
        xmlDoc.async = false;
        xmlDoc.load(kmlUrl);
    }
    catch (e) {
        alert("Could not load kml doc: " + e);
    }

    return xmlDoc;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Find a node in the list of placemarks with a particular id
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function findKMLPlaceMark(kmlDom, nodeID) {
    var placemarkNodes = kmlDom.getElementsByTagName("Placemark");
    // find the node with the id equal to the nodePlace variable
    var destinationPlaceMark = null;
    for (nodeNdx = 0; nodeNdx < placemarkNodes.length; nodeNdx++) {
        var thisNode = placemarkNodes[nodeNdx];
        // Search thru attribute array for the id node
        for (nodeAttrNdx = 0; nodeAttrNdx < thisNode.attributes.length; nodeAttrNdx++) {
            var thisAttr = thisNode.attributes[nodeAttrNdx];
            if (thisAttr.name == "id") {
                // see if this is the correct node
                if (thisAttr.value == nodeID) {
                    destinationPlaceMark = thisNode;
                    break;
                }
            }
        }
        // if we found the place mark id in the inner loop, break out of the outter loop
        if (destinationPlaceMark != null) {
            break;
        }
    }

    return destinationPlaceMark;
}

