﻿function SetupDirectionsPanel(){
    directionsPanel = document.getElementById("directionsDiv");
    directions = new GDirections(map,directionsPanel);
    GEvent.addListener(directions, "error", handleErrors);
    GEvent.addListener(directions,"load", function() {
        map.removeOverlay(MyLocationMarker);
        setTimeout('customPanel(map,"map",directions,directionsPanel)', 1);
    });
}

function ClearDirections(){
    if (directions != undefined){
        directions.clear();
    }
}

function ClearDirectionsAndReturnToMyLocation(){
    ClearDirections();
    map.addOverlay(MyLocationMarker);
    map.setZoom(MyLocationRepositionedZoom);
    setTimeout(function(){
        map.panTo(MyLocationRepositionedPoint);
    },500);
    document.getElementById("directionsDiv").innerHTML = "";
    document.getElementById("directionsDiv").style.display = "none";
    document.getElementById("LocationSetMessage").style.display = "block";
    document.getElementById("MapLegendHolder").style.display = "block";
}

function SetYourLocale(value){
    yourLocale = value;
}

function getDirectionsToHereFromHome(id, useLatLng){
    map.closeInfoWindow();
    document.getElementById("LocationSetMessage").style.display = "none";
    document.getElementById("MapLegendHolder").style.display = "none";
    document.getElementById("summaryHTML_Start").innerHTML = MyLocationAddress;
    document.getElementById("summaryHTML_End").innerHTML = BuildSummaryHTML(id);
    currLocID = id;
    dirTypeFlag = "to";
    if (useLatLng == "True"){
        useLatLngFlag = true;
        setDirections(MyLocationAddress,Array_LatitudeLongitude[id]);
    }else{
        useLatLngFlag = false;
        setDirections(MyLocationAddress,Array_FullAddress[id]);
    }
}

function getDirectionsFromHereToHome(id, useLatLng){
    map.closeInfoWindow();
    document.getElementById("LocationSetMessage").style.display = "none";
    document.getElementById("MapLegendHolder").style.display = "none";
    document.getElementById("summaryHTML_Start").innerHTML = BuildSummaryHTML(id);
    document.getElementById("summaryHTML_End").innerHTML = MyLocationAddress;
    currLocID = id;
    dirTypeFlag = "from";
    if (useLatLng == "True"){
        useLatLngFlag = true;
        setDirections(Array_LatitudeLongitude[id], MyLocationAddress);
    }else{
        useLatLngFlag = false;
        setDirections(Array_FullAddress[id], MyLocationAddress);
    }
}

function setDirections(fromAddress, toAddress) {
    directionsPanel.style.display = "none";
    directions.load("from " + fromAddress + " to " + toAddress);
}

function BuildSummaryHTML(id){
    var html;
    html = "<table class='summary'><tr><td colspan='2'>" + Array_HTML_Titles[id] + "</td></tr><tr><td width='50%'>" + Array_HTML_Address[id] + "</td><td width='50%'>" + Array_HTML_Hours[id] + "</td></tr></table>";
    if (Array_HTML_AMS[id] != undefined){
        html = html +  "<table id='summaryAMS' class='summary'><tr><td width='50%'>" + Array_HTML_AMS[id] + "</td><td width='50%' style='padding-top:20px'>" + Array_HTML_AMS_Hours[id] + "</td></tr></table>";
    }
    html = html + "";
    
    return html;
}

function handleErrors(){
   if (directions.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: " + directions.getStatus().code);
   else if (directions.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: " + directions.getStatus().code);
   
   else if (directions.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: " + directions.getStatus().code);

   else if (directions.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: " + directions.getStatus().code);

   else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
    
   else alert("An unknown error occurred.");  
}

// ============ custom direction panel ===============
function customPanel(map,mapname,dirn,div) {
    var html = "";
  
    // === waypoint banner ===
    function waypoint(point, type, address) {
        var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
        html += '<table class="waypoint_' + type + '" style="margin: 10px 0px; background-color: #e1e1e1; border-collapse: collapse; color: rgb(0, 0, 0);">';
        html += '  <tr style="cursor: pointer;" onclick='+target+'>';
        html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
        html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
        html += '    </td>';
        html += '    <td style="vertical-align: middle; width: 100%;">';
        html +=        address;
        html += '    </td>';
        html += '  </tr>';
        html += '</table>';
    }

    // === route distance ===
    function routeDistance(dist) {
        html += dist;
    }      

    // === step detail ===
    function detail(point, num, description, dist) {
        var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
        html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
        html += '  <tr style="cursor: pointer;" onclick='+target+'>';
        html += '    <td style="margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: center;">';
        if (description.indexOf("Turn <b>left</b>") > -1){
            html += '<img src="assets/images/arrow_left.gif" alt="Turn Left" />';
        }else if (description.indexOf("Turn <b>right</b>") > -1){
            html += '<img src="assets/images/arrow_right.gif" alt="Turn Right" />';
        }else if (description.indexOf("Slight <b>left</b>") > -1){
            html += '<img src="assets/images/arrow_left_slight.gif" alt="Slight Left" />';
        }else if (description.indexOf("Slight <b>right</b>") > -1){
            html += '<img src="assets/images/arrow_right_slight.gif" alt="Slight Right" />';
        }else if (description.indexOf("U-turn") > -1){
            html += '<img src="assets/images/arrow_uturn.gif" alt="U-Turn" />';
        }else if (description.indexOf("Continue straight") > -1){
            html += '<img src="assets/images/arrow_straight.gif" alt="Continue Straight" />';
        }else{
            html += '<img src="assets/images/arrow_blank.gif" alt="" />';
        }
        html += '    </td>';
        html += '    <td style="border-top: 2px solid #CCC; margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
        html += '      <a href="javascript:void(0)"> '+num+'. </a>';
        html += '    </td>';
        html += '    <td style="border-top: 2px solid #CCC; margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
        html +=        description;
        html += '    </td>';
        html += '    <td style="border-top: 2px solid #CCC; margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
        html +=        dist;
        html += '    </td>';
        html += '  </tr>';
        html += '</table>';
    }
    
    function ChangeDescription(desc){
        var descText = desc;
        alert(descText);
        var trLoc = descText.indexOf("Toll road");
        if (trLoc > -1){
            descText = descText.replace("Toll road","<font color='red'>Toll road</font>");
            alert(descText);
        }
        return descText;
    }

    // === Copyright tag ===
    function copyright(text) {
        html += '<div id="copyright" style="font-size: 0.86em;">' + text + "</div>";
    }

    // === read through the GRoutes and GSteps ===
    for (var i=0; i<dirn.getNumRoutes(); i++) {
        if (i==0) {
            var type="play";
        } else {
            var type="pause";
        }
        var route = dirn.getRoute(i);
        var geocode = route.getStartGeocode();
        var point = route.getStep(0).getLatLng();
        
        var routeText = "<div id='directionsPrint'><a href='javascript:void(0)' onclick='window.print();'><img src='assets/images/print.gif' alt='Print Directions' hspace='2' />Print</a></div><div id='directionsPrint'><a href='javascript:void(0)' onclick='ClearDirectionsAndReturnToMyLocation();'><img src='assets/images/clear.gif' alt='Clear Directions' hspace='2' />Clear</a>&nbsp;</div><div class='directionsTitle'>Driving Directions</div><div class='routeDistText'>";
        routeText = routeText + route.getDistance().html.replace("mi","miles");
        routeText = routeText +  " (about "+route.getDuration().html.replace("mins","minutes")+")</div>";
        
        routeDistance(routeText);
        html += "<div class='disclaimer'>Note that the following driving directions are correct based on the latest available mapping data. Road closures/additions, construction, and other factors may affect their accuracy. If you cannot find this location, we suggest you call the location for local directions.</div>"
        if (useLatLngFlag == true){
            if (dirTypeFlag == "from"){
                waypoint(point, type, Array_FullAddress[currLocID]);
            }else{
                waypoint(point, type, geocode.address);
            }
        }else{
            waypoint(point, type, geocode.address);
        }

        for (var j=0; j<route.getNumSteps(); j++) {
            var step = route.getStep(j);
            // === detail lines for each step ===
            detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
        }
    }
    
    // === the final destination waypoint ===   
    var geocode = route.getEndGeocode();
    var point = route.getEndLatLng();
    
    if (useLatLngFlag == true){
       if (dirTypeFlag == "to"){
            waypoint(point, "stop", Array_FullAddress[currLocID]);
        }else{
            waypoint(point, "stop", geocode.address);
        }
    }else{
        waypoint(point, "stop", geocode.address);
    }
             
    // === the copyright text ===
    copyright(dirn.getCopyrightsHtml());

    // === drop the whole thing into the target div
    div.innerHTML = html;
    div.style.display = "block";
    html = undefined;
    point = undefined;
    geocode = undefined;

}

// ============ end of customPanel function ===========