var SHAPE_ROUTE_POST = HOST_URL + "/directions/v1/route?key=YOUR_KEY_HERE&callback=addShapeResults"
var SHAPE_POST = HOST_URL + "/directions/v1/routeshape?key=YOUR_KEY_HERE&callback=renderShapeResults"

var myMap;
var responses = new Array();
var shapeUrl;
var sessionId;
var colors = ['#FFFF00', '#0000FF', '#FF0000', '#FF00FF', '#00FFFF', '#0000FF'];

function initShape() {
    MQA.withModule('shapes', function() {
       myMap = new MQA.TileMap(document.getElementById('mapWindow'));
    });
    showShapeURL();
}

function doShape1() {
    var firstShapeUrl = SHAPE_ROUTE_POST;
    firstShapeUrl += '&from=' + document.getElementById('shapeFrom').value;
    firstShapeUrl += '&to=' + document.getElementById('shapeTo0').value;
    var foo = document.getElementById('shapeTo1').value;
    if (foo) {
        firstShapeUrl += '&to=' + foo;
    }
    foo = document.getElementById('shapeTo2').value;
    if (foo) {
        firstShapeUrl += '&to=' + foo;
    }
    foo = document.getElementById('shapeTo3').value;
    if (foo) {
        firstShapeUrl += '&to=' + foo;
    }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    var newURL = firstShapeUrl.replace('YOUR_KEY_HERE', APP_KEY);
    script.src = newURL;
    document.body.appendChild(script);
}

function addShapeResults(response) {
    if (response.info.statuscode && ((response.info.statuscode == 400) || (response.info.statuscode == 1))) {
        var text = "Whoops!  There was an error during the request:\n";
        if (response.info.messages) {
            for (i = 0; i < response.info.messages.length; i++) {
                text += response.info.messages[i] + "\n";
            }
        }
        alert(text);
        return;
    }
    
    if (response.collections) {
        var text = 'Whoops!  Ambiguous addresses detected.  Please use non-ambiguous locations.';
        text += '\n\nAmbiguous locations:\n\n';
        for (i = 0; i < response.collections.length; i++) {
            var collection = response.collections[i];
            if (collection.length == 1) {
                continue;
            }
            for (j = 0; j < collection.length; j++) {
                text += '    ' + (collection[j].adminArea5 || ' ');  
                text += ' ' + (collection[j].adminArea4 || ' ');  
                text += ' ' + (collection[j].adminArea3 || ' ');  
                text += ' ' + (collection[j].adminArea2 || ' ');  
                text += ' ' + (collection[j].adminArea1 || ' ');  
                text += '\n';
            }
        }
        alert(text);
        return;
    }
    sessionId = response.route.sessionId;
    if (!sessionId) {
       return;
    }
    responses[sessionId] = response;
    var select = document.getElementById('shapeSessionId');
    var now = "" + new Date();
    var pos = now.indexOf('GMT');
    if (pos >= 0) {
        now = now.substring(0, pos);
    }
    var newText = sessionId + " (" + now + ")";
    if (select[0].value == "") {
        select[0].value = sessionId;
        select[0].text = newText;
    } else {
        var option = document.createElement('option');
        option.value = sessionId;
        option.text = newText;
        try {
            select.add(option, null);  // For non-IE
        } catch (ex) {
            select.add(option); // IE
        }
        select.selectedIndex = select.options.length - 1;
    }
    showShapeURL();
}

function showShapeURL() {
    shapeUrl = SHAPE_POST;
    var block = document.getElementById('shapeControls');
    var select = document.getElementById('shapeSessionId');
    var selected = select[select.selectedIndex];
    // TODO:  Enable/disable run button appropriately.
    if (selected.value != "") {
        shapeUrl += '&json={';
        shapeUrl += 'sessionId: ' + selected.value;
        sessionId = selected.value;
        var boundingBox = responses[sessionId].route.boundingBox;
        myMap.removeShapeCollection("routeShapeCollection");
        myMap.zoomToRect(boundingBox);    
        var lat = (boundingBox.ul.lat + boundingBox.lr.lat) * 0.5;
        var lng = (boundingBox.ul.lng + boundingBox.lr.lng) * 0.5;
        shapeUrl += ', mapState:{width: ' + myMap.width + ', height:' + myMap.height;
        shapeUrl += ', scale:' + myMap.scale + ', center:{lat:' + lat + ', lng:' + lng + '}}';
        shapeUrl += '}';
        document.getElementById('shapeUrl').innerHTML = shapeUrl;
        block.style.display = "block";
    }
}

function doShape2() {
    myMap.zoomToRect(responses[sessionId].route.boundingBox);
    showShapeURL();
    var script = document.createElement('script');
    script.type = 'text/javascript';
    var newURL = shapeUrl.replace('YOUR_KEY_HERE', APP_KEY);
    script.src = newURL;
    document.body.appendChild(script);
}

function renderShapeResults(response) {
    var points = response.route.shape.shapePoints;
    if (!points) {
        alert('Hrmmm... No shapePoint data was returned.  Perhaps the sessionId is no longer valid?');
        return;
    }
    myMap.removeShapeCollection("routeShapeCollection");
    shapeCollection = new MQA.ShapeCollection();
    shapeCollection.setName("routeShapeCollection");
    var legIndexes = response.route.shape.legIndexes;
    var maneuverIndexes = response.route.shape.maneuverIndexes;
    var legIndex = 0;
    var numManeuvers = maneuverIndexes.length;
    var borderWidth = 2;
    for (maneuverIndex = 0; maneuverIndex < numManeuvers; maneuverIndex++) {
        var overlay = new MQA.LineOverlay();
        overlay.setBorderWidth(borderWidth);
        borderWidth += 2;
        overlay.setColor(colors[legIndex]);
        overlay.setFillColor(colors[legIndex + 1]);
        overlay.setColorAlpha(0.75);
        overlay.setKey('routeShape-' + maneuverIndex + '-' + new Date().getTime());
        
        //  Set the raw shape point for new toolkit (5.3 took an MQA.LatLngCollection())
        var legPoints;
        var start = maneuverIndexes[maneuverIndex];
        if (start >= legIndexes[legIndex]) {
            borderWidth = 2;
            legIndex++;
        }
        if (maneuverIndex == (maneuverIndexes.length - 1)) {
            legPoints = points.slice(start * 2);
        } else {
            var end = maneuverIndexes[maneuverIndex + 1] * 2; 
            legPoints = points.slice(start * 2, end);
        }
        overlay.setShapePoints(legPoints);
        shapeCollection.add(overlay);
    }
    myMap.addShapeCollection(shapeCollection);
}