var OPTIMIZED_URL = HOST_URL + '/directions/v1/ACTION?key=YOUR_KEY_HERE&callback=renderOptimized';
var LOCATIONS = '{\n\
   locations:[\n\
      "Boalsburg, PA",\n\
      "York, PA",\n\
      "State College, PA",\n\
      "Lancaster, PA"\n\
   ]\n\
}';
OPTIMIZED_URL += '&json=' + LOCATIONS.replace(' ', '').replace('\n','');

var action = 'route';

function doOptimized() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    var newURL = OPTIMIZED_URL.replace('YOUR_KEY_HERE', 'Dmjtd%7Clu612007nq%2C20%3Do5-50zah');
    newURL = newURL.replace('ACTION', action);
    script.src = newURL;
    document.body.appendChild(script);
};

function showOptimizedURL() {
    action = document.getElementById('optimizedOn').checked ? "optimizedroute" : "route";
    var html = '<pre>';
    html += 'REQUEST URL:\n';
    html += '\n' + HOST_URL + '/directions/v1/';
    html += action;
    html += '?key=YOUR_KEY_HERE\n';
    html += '\nREQUEST BODY:\n';
    html += LOCATIONS;
    html += '</pre>\n';
    document.getElementById('optimizedSampleUrl').innerHTML = html;
}

function renderOptimized(response) {
    var legs = response.route.legs;
    var html = '';
    var i = 0;
    var j = 0;
    var trek;
    var maneuver;

    html += '<p>Final <code>locationSequence</code>:  ';
    var locationSequence = response.route.locationSequence;
    if (!locationSequence) {
        html += "[Not set...]";
    } else {
        for (i = 0; i < locationSequence.length; i++) {
            if (i > 0) {
                html += ',&nbsp;';
            }
            html += locationSequence[i];
        }
    }    
    
    if (response.route.distance) {
        html += "<p>Total distance for trip:  " + response.route.distance.toFixed(2) + " miles.</p>";
    }
    
    html += '<table><tr><th colspan=2>Narrative</th></tr><tbody>'
    for (i = 0; i < legs.length; i++) {
        for (j = 0; j < legs[i].maneuvers.length; j++) {
            maneuver = legs[i].maneuvers[j];
            
            html += '<tr>';
            html += '<td>&nbsp;';
            if (maneuver.iconUrl) {
                html += '<img src="' + maneuver.iconUrl + '">  '; 
            } 
            for (k = 0; k < maneuver.signs.length; k++) {
                var sign = maneuver.signs[k];
                if (sign && sign.url) {
                    html += '<img src="' + sign.url + '">  '; 
                }
            }
            
            html += '</td>'
            html += '<td>' + maneuver.narrative + '</td>'
            html += '</tr>';
        }
    }
    
    html += '</tbody></table>';
    
    document.getElementById('optimizedNarrative').innerHTML = html;
}
