text:
var host;

// Deployment-scripts can insert host here.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// We know that you love 'free', we love it too :)! And so our entire software stack is free and even Open Source!
// Our routing service is also free for certain applications or smaller volume. Be fair, grab an API key and support us:
// https://graphhopper.com/#directions-api Misuse of API keys that you don't own is prohibited and you'll be blocked.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (!host) {
    if (location.port === '') {
        host = location.protocol + '//' + location.hostname;
    } else {
        host = location.protocol + '//' + location.hostname + ":" + location.port;
    }
}

var ghRequest = new GHRequest(host);
var tmpArgs = parseUrlWithHisto();
var bounds = {};

var nominatimURL = "https://nominatim.openstreetmap.org/search";
var nominatimReverseURL = "https://nominatim.openstreetmap.org/reverse";
var routingLayer;
var map;
var menuStart;
var menuIntermediate;
var menuEnd;
var browserTitle = "GraphHopper Maps - Driving Directions";
var defaultTranslationMap = null;
var enTranslationMap = null;
var routeSegmentPopup = null;
var elevationControl = null;
var activeLayer = '';
var i18nIsInitialized;

var iconFrom = L.icon({
    iconUrl: './img/marker-icon-green.png',
    shadowSize: [50, 64],
    shadowAnchor: [4, 62],
    iconAnchor: [12, 40]
});

var iconTo = L.icon({
    iconUrl: './img/marker-icon-red.png',
    shadowSize: [50, 64],
    shadowAnchor: [4, 62],
    iconAnchor: [12, 40]
});

var iconInt = L.icon({
    iconUrl: './img/marker-icon-blue.png',
    shadowSize: [50, 64],
    shadowAnchor: [4, 62],
    iconAnchor: [12, 40]
});

$(document).ready(function (e) {
    // fixing cross domain support e.g in Opera
    jQuery.support.cors = true;

    if (isProduction())
        $('#hosting').show();

    var History = window.History;
    if (History.enabled) {
        History.Adapter.bind(window, 'statechange', function () {
            // No need for workaround?
            // Chrome and Safari always emit a popstate event on page load, but Firefox doesn't
            // https://github.com/defunkt/jquery-pjax/issues/143#issuecomment-6194330

            var state = History.getState();
            log(state);
            initFromParams(state.data, true);
        });
    }

    $('#locationform').submit(function (e) {
        // no page reload
        e.preventDefault();
        mySubmit();
    });

    $('#gpxExportButton a').click(function (e) {
        // no page reload
        e.preventDefault();
        exportGPX();
    });

    $('#settings-btn').click(function(e){
        $('.collapse').collapse('toggle');
    });

    var urlParams = parseUrlWithHisto();
    $.when(ghRequest.fetchTranslationMap(urlParams.locale), ghRequest.getInfo())
            .then(function (arg1, arg2) {
                // init translation retrieved from first call (fetchTranslationMap)
                var translations = arg1[0];

                // init language
                // 1. determined by Accept-Language header, falls back to 'en' if no translation map available
                // 2. can be overwritten by url parameter
                ghRequest.setLocale(translations["locale"]);
                defaultTranslationMap = translations["default"];
                enTranslationMap = translations["en"];
                if (!defaultTranslationMap)
                    defaultTranslationMap = enTranslationMap;

                i18nIsInitialized = true;
                initI18N();

                // init bounding box from getInfo result
                var json = arg2[0];
                var tmp = json.bbox;
                bounds.initialized = true;
                bounds.minLon = tmp[0];
                bounds.minLat = tmp[1];
                bounds.maxLon = tmp[2];
                bounds.maxLat = tmp[3];
                // Additional configuration of the nominatum URL for the bounding box
                nominatum.remote.url = nominatum.remote.url + "&bounded=1&viewbox=" + bounds.minLon + "," + bounds.maxLat + "," + bounds.maxLon + "," + bounds.minLat;

                var vehiclesDiv = $("#vehicles");
                function createButton(vehicle) {
                    var button = $("<button class='vehicle-btn' title='" + tr(vehicle) + "'/>");
                    button.attr('id', vehicle);
                    button.html("");
                    button.click(function () {
                        ghRequest.initVehicle(vehicle);
                        resolveAll()
                        routeLatLng(ghRequest);
                    });
                    return button;
                }

                if (json.features) {
                    ghRequest.features = json.features;

                    var vehicles = Object.keys(json.features);
                    if (vehicles.length > 0)
                        ghRequest.initVehicle(vehicles[0]);

                    for (var key in json.features) {
                        vehiclesDiv.append(createButton(key.toLowerCase()));
                    }
                }

                initMap(urlParams.layer);

                // execute query
                initFromParams(urlParams, true);
            }, function (err) {
                log(err);
                $('#error').html('GraphHopper API offline? Refresh'
                        + '
Status: ' + err.statusText + '
' + host);

                bounds = {
                    "minLon": -180,
                    "minLat": -90,
                    "maxLon": 180,
                    "maxLat": 90
                };
                initMap();
            });

    $(window).resize(function () {
        adjustMapSize();
    });
    $("#locationpoints").sortable({
        items: ".pointDiv",
        cursor: "n-resize",
        containment: "parent",
        handle: ".pointFlag",
        update: function (event, ui) {
            var origin_index = $(ui.item[0]).data('index');
            sortable_items = $("#locationpoints > div.pointDiv");
            $(sortable_items).each(function (index) {
                var data_index = $(this).data('index');
                if (origin_index === data_index) {
                    //log(data_index +'>'+ index);
                    ghRequest.route.move(data_index, index);
                    if (!routeIfAllResolved())
                        checkInput();
                    return false;
                }
            });
        }
    });

    $('#locationpoints > div.pointAdd').click(function () {
        ghRequest.route.add(new GHInput());
        checkInput();
    });

    checkInput();
});

function initFromParams(params, doQuery) {
    ghRequest.init(params);
    var fromAndTo = params.from && params.to,
            routeNow = params.point && params.point.length >= 2 || fromAndTo;

    if (routeNow) {
        if (fromAndTo)
            resolveCoords([params.from, params.to], doQuery);
        else
            resolveCoords(params.point, doQuery);
    } else if (params.point && params.point.length === 1) {
        ghRequest.from = new GHInput(params.point[0]);
        resolve("from", ghRequest.from);
        focus(ghRequest.from, 15, true);
    }
}

function resolveCoords(pointsAsStr, doQuery, inputsStr) {
	for (var i = 0, l = pointsAsStr.length; i < l; i++) {
        var pointStr = pointsAsStr[i];
        var coords = ghRequest.route.getIndex(i);
        if (!coords || pointStr !== coords.input || !coords.isResolved())
            ghRequest.route.set(pointStr, i, true);
    }

    checkInput();

    if (ghRequest.route.isResolved()) {
        resolveAll(inputsStr);
        routeLatLng(ghRequest, doQuery);
    } else {
        // at least one text input from user -> wait for resolve as we need the coord for routing
        $.when.apply($, resolveAll(inputsStr)).done(function () {
            routeLatLng(ghRequest, doQuery);
        });
    }
}

function checkInput() {
    var template = $('#pointTemplate').html(),
            len = ghRequest.route.size();

    // remove deleted points
    if ($('#locationpoints > div.pointDiv').length > len) {
        $('#locationpoints > div.pointDiv:gt(' + (len - 1) + ')').remove();
    }

    // properly unbind previously click handlers
    $("#locationpoints .pointDelete").off();

    // console.log("## new checkInput");
    for (var i = 0; i < len; i++) {
        var div = $('#locationpoints > div.pointDiv').eq(i);
        // console.log(div.length + ", index:" + i + ", len:" + len);
        if (div.length === 0) {
            $('#locationpoints > div.pointAdd').before(nanoTemplate(template, {id: i}));
            div = $('#locationpoints > div.pointDiv').eq(i);
        }

        var toFrom = getToFrom(i);
        div.data("index", i);
        div.find(".pointFlag").attr("src",
                (toFrom === FROM) ? 'img/marker-small-green.png' :
                ((toFrom === TO) ? 'img/marker-small-red.png' : 'img/marker-small-blue.png'));
        if (len > 2) {
            div.find(".pointDelete").click(function () {
                var index = $(this).parent().data('index');
                ghRequest.route.removeSingle(index);
                routingLayer.clearLayers();
                routeLatLng(ghRequest, false);
            }).show();
        } else {
            div.find(".pointDelete").hide();
        }

       setupTypeAhead(i);

    }

    adjustMapSize();
}
function setupTypeAhead(i) {
	$('#'+i+'_searchBox')
	existing_typeahead = $("#locationpoints > #"+i+"_Div > span.twitter-typeahead");
	if (existing_typeahead.size()==0) {
		$('#'+i+'_searchBox').typeahead(
				{
					highlight : true
				},
				{
					name : 'Address',
					displayKey : 'address_line',
					source : places.ttAdapter(),
					templates : {
						empty : [ '
',
								'No Results', '
' ].join('\n'),
						header : '
OS Places - Address
'
					}
//				},
//				{
//					name : 'Nominatum',
//					displayKey : 'address_line',
//					source : nominatum.ttAdapter(),
//					templates : {
//						empty : [ '
',
//								'No Results', '
' ].join('\n'),
//						header : '
OpenStreetMap Nominatum
'
//					}

				}
				);
	$('#'+i+'_searchBox').on(
				'typeahead:selected',
				function(e, datum) {
					e.target.data = {
							x: datum.longitude,
							y: datum.latitude,
							latitude: datum.latitude,
							longitude: datum.longitude,
							address_line: datum.address_line};
				});
	}

}
function nanoTemplate(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
        var keys = key.split("."), v = data[keys.shift()];
        for (i = 0, l = keys.length; i < l; _i++)
            v = v[this];
        return (typeof v !== "undefined" && v !== null) ? v : "";
    });
}

function adjustMapSize() {
    var mapDiv = $("#map");
    var width = $(window).width() - 295;
    if (width < 400) {
        width = 290;
        mapDiv.attr("style", "position: relative; float: right;");
    } else {
        mapDiv.attr("style", "position: absolute; right: 0;");
    }
    var height = $(window).height();
    mapDiv.width(width).height(height);
    $("#input").height(height);
    // reduce info size depending on how heigh the input_header is and reserve space for footer
    $("#info").css("max-height", height - $("#input_header").height() - 58);
}

function initMap(selectLayer) {
    adjustMapSize();
    log("init map at " + JSON.stringify(bounds));

    var osmAttr = '© OpenStreetMap contributors';
    // provider
    //@see http://leaflet-extras.github.io/leaflet-providers/preview/index.html
    var osmAttr = '© OpenStreetMap contributors';

    var tp = "ls";
    if (L.Browser.retina)
        tp = "lr";

    /** Define the layer type
 *  GEOGRAPHICALGRIDSYSTEMS.MAPS
 *  GEOGRAPHICALGRIDSYSTEMS.MAPS.SCAN-EXPRESS.CLASSIQUE
 *  GEOGRAPHICALGRIDSYSTEMS.MAPS.SCAN-EXPRESS.STANDARD
 */
var layerOSZoom = "Zoom Map Auto";

// The WMTS URL
var url = "http://gwccluster2-env.elasticbeanstalk.com/service/wmts";

function getTopLeftCorners() {
	/**
	 * the matrixIdsBNG represents the projection
	 * for in the OS WMTS for BNG coordinates.
	 */
	var topLeftCorners = new Array(14);
	var i=0;
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, -238375.0);
	/*
	topLeftCorners[i++] = new L.LatLng(1376256.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1376256.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1347584.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1347584.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1347584.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	topLeftCorners[i++] = new L.LatLng(1344000.0, 0.0);
	*/
	return topLeftCorners;
}

	// The WMTS URL
	var url = "https://dte-wmts.eu-west-1.elasticbeanstalk.com/service/wmts";

    var osRoad = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Road%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
       tileSize: 256,
       continuousWorld: true,
       attribution: '© Ordnance Survey '
    });

    var osOutdoor = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Outdoor%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
        tileSize: 256,
        continuousWorld: true,
        attribution: '© Ordnance Survey '
     });

    var osLight = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Light%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
            tileSize: 256,
            continuousWorld: true,
            attribution: '© Ordnance Survey '
         });

    var osNight = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Night%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
                tileSize: 256,
                continuousWorld: true,
                attribution: '© Ordnance Survey '
             });

    var osLeisure = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Leisure%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
        tileSize: 256,
        continuousWorld: true,
        attribution: '© Ordnance Survey '
     });

     var osImagery = new L.TileLayer(url + '?height=256&width=256&tilematrixSet=EPSG%3A27700&version=1.0.0&style=&layer=Imagery%2027700&SERVICE=WMTS&REQUEST=GetTile&format=image/png&TileMatrix=EPSG:27700:{z}&TileRow={y}&TileCol={x}',{
             tileSize: 256,
             continuousWorld: true,
             attribution: '© Ordnance Survey '
          });

    var lyrk = L.tileLayer('https://tiles.lyrk.org/' + tp + '/{z}/{x}/{y}?apikey=6e8cfef737a140e2a58c8122aaa26077', {
        attribution: osmAttr + ', Lyrk',
        subdomains: ['a', 'b', 'c']
    });

    var mapquest = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', MapQuest',
        subdomains: ['otile1', 'otile2', 'otile3', 'otile4']
    });

    var mapquestAerial = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', MapQuest',
        subdomains: ['otile1', 'otile2', 'otile3', 'otile4']
    });

    var openMapSurfer = L.tileLayer('http://openmapsurfer.uni-hd.de/tiles/roads/x={x}&y={y}&z={z}', {
        attribution: osmAttr + ', GIScience Heidelberg'
    });

    // not an option as too fast over limit
//    var mapbox= L.tileLayer('https://{s}.tiles.mapbox.com/v4/peterk.map-vkt0kusv/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoicGV0ZXJrIiwiYSI6IkdFc2FJd2MifQ.YUd7dS_gOpT3xrQnB8_K-w', {
//        attribution: osmAttr + ', © MapBox'
//    });

    var sorbianLang = L.tileLayer('http://map.dgpsonline.eu/osmsb/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', © Alberding GmbH, CC-BY-SA'
    });

    var thunderTransport = L.tileLayer('http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', Thunderforest Transport',
        subdomains: ['a', 'b', 'c']
    });

    var thunderCycle = L.tileLayer('http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', Thunderforest Cycle',
        subdomains: ['a', 'b', 'c']
    });

    var thunderOutdoors = L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', Thunderforest Outdoors',
        subdomains: ['a', 'b', 'c']
    });

    var wrk = L.tileLayer('http://{s}.wanderreitkarte.de/topo/{z}/{x}/{y}.png', {
        attribution: osmAttr + ', WanderReitKarte',
        subdomains: ['topo4', 'topo', 'topo2', 'topo3']
    });

    var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: osmAttr
    });

    var osmde = L.tileLayer('http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png', {
        attribution: osmAttr,
        subdomains: ['a', 'b', 'c']
    });

    var baseMaps = {
    	"OS Road": osRoad,
    	"OS Outdoor": osOutdoor,
    	"OS Light": osLight,
    	"OS Night": osNight,
    	"OS Leisure": osLeisure,
    	"OS Imagery": osImagery
    };

    var defaultLayer = baseMaps[selectLayer];
    if (!defaultLayer)
        defaultLayer = osRoad
	var epsg27700 = "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894 +datum=OSGB36 +units=m +no_defs";
    var crs = new L.Proj.WMTSCRS(
    		'EPSG:27700',
    		epsg27700,
    		{
    			topLeftCorners: getTopLeftCorners(),
    			resolutions : [ 896.0, 448.0, 224.0, 112.0, 56.0, 28.0, 14.0, 7.0, 3.5, 1.75, 0.875, 0.4375, 0.21875, 0.109375 ]
    		});

    // default
    map = L.map('map', {
    	crs: crs,
        layers: [defaultLayer],
        contextmenu: true,
        contextmenuWidth: 145,
        contextmenuItems: [{
                separator: true,
                index: 3,
                state: ['set_default']
            }, {
                text: 'Show coordinates',
                callback: function (e) {
                    alert(e.latlng.lat + "," + e.latlng.lng);
                },
                index: 4,
                state: [1, 2, 3]
            }, {
                text: 'Center map here',
                callback: function (e) {
                    map.panTo(e.latlng);
                },
                index: 5,
                state: [1, 2, 3]
            }],
        zoomControl: false,
        loadingControl: false,
        maxZoom: 13,
        minZoom: 0
    });

    var _startItem = {
        text: 'Set as start',
        callback: setStartCoord,
        disabled: false,
        index: 0
    };
    var _intItem = {
        text: 'Set intermediate',
        callback: setIntermediateCoord,
        disabled: true,
        index: 1
    };
    var _endItem = {
        text: 'Set as end',
        callback: setEndCoord,
        disabled: false,
        index: 2
    };
    menuStart = map.contextmenu.insertItem(_startItem, _startItem.index);
    menuIntermediate = map.contextmenu.insertItem(_intItem, _intItem.index);
    menuEnd = map.contextmenu.insertItem(_endItem, _endItem.index);

    var zoomControl = new L.Control.Zoom({position: 'topleft'}).addTo(map);

    new L.Control.loading({
        zoomControl: zoomControl
    }).addTo(map);

    map.contextmenu.addSet({
        name: 'markers',
        state: 2
    });

    map.contextmenu.addSet({
        name: 'path',
        state: 3
    });

    L.control.layers(baseMaps/*, overlays*/).addTo(map);

    map.on('baselayerchange', function (a) {
        if (a.name) {
            activeLayer = a.name;
            $("#export-link a").attr('href', function (i, v) {
                return v.replace(/(layer=)([\w\s]+)/, '$1' + activeLayer);
            });
        }
    });

    L.control.scale().addTo(map);

    map.fitBounds(new L.LatLngBounds(new L.LatLng(bounds.minLat, bounds.minLon),
            new L.LatLng(bounds.maxLat, bounds.maxLon)));

    if (isProduction())
        map.setView(new L.LatLng(0, 0), 2);

    map.attributionControl.setPrefix('');

    var myStyle = {
        "color": 'black',
        "weight": 2,
        "opacity": 0.3
    };
    var geoJson = {
        "type": "Feature",
        "geometry": {
            "type": "LineString",
            "coordinates": [
                [bounds.minLon, bounds.minLat],
                [bounds.maxLon, bounds.minLat],
                [bounds.maxLon, bounds.maxLat],
                [bounds.minLon, bounds.maxLat],
                [bounds.minLon, bounds.minLat]]
        }
    };

    if (bounds.initialized)
        L.geoJson(geoJson, {
            "style": myStyle
        }).addTo(map);

    routingLayer = L.geoJson().addTo(map);
    routingLayer.options = {
        style: {color: "#ED1A5E", "weight": 5, "opacity": 0.6}, // route color and style
        contextmenu: true,
        contextmenuItems: [{
                text: 'Route ',
                disabled: true,
                index: 0,
                state: 3
            }, {
                text: 'Set intermediate',
                callback: setIntermediateCoord,
                index: 1,
                state: 3
            }, {
                separator: true,
                index: 2,
                state: 3
            }],
        contextmenuAtiveState: 3
    };
    /*
     routingLayer.options = {style: {color: "#1F40C4", "weight": 5, "opacity": 0.6}, onEachFeature: function (feature, layer) {
     layer.on('contextmenu', function (e) {
     alert('The GeoJSON layer has been clicked');
     });
     }}; // route color and style
     */
}

function setToStart(e) {
    var latlng = e.target.getLatLng(),
            index = ghRequest.route.getIndexByCoord(latlng);
    ghRequest.route.move(index, 0);
    routeIfAllResolved();
}

function setToEnd(e) {
    var latlng = e.target.getLatLng(),
            index = ghRequest.route.getIndexByCoord(latlng);
    ghRequest.route.move(index, -1);
    routeIfAllResolved();
}

function setStartCoord(e) {
    ghRequest.route.set(e.latlng, 0);
    resolveFrom();
    routeIfAllResolved();
}

function setIntermediateCoord(e) {
    var index = ghRequest.route.size() - 1;
    ghRequest.route.add(e.latlng, index);
    resolveIndex(index);
    routeIfAllResolved();
}

function deleteCoord(e) {
    var latlng = e.target.getLatLng();
    ghRequest.route.removeSingle(latlng);
    routingLayer.clearLayers();
    routeLatLng(ghRequest, false);
}

function setEndCoord(e) {
    var index = ghRequest.route.size() - 1;
    ghRequest.route.set(e.latlng, index);
    resolveTo();
    routeIfAllResolved();
}

function routeIfAllResolved() {
    if (ghRequest.route.isResolved()) {
        routeLatLng(ghRequest);
        return true;
    }
    return false;
}

function makeValidLng(lon) {
    if (lon < 180 && lon > -180)
        return lon;
    if (lon > 180)
        return (lon + 180) % 360 - 180;
    return (lon - 180) % 360 + 180;
}

var FROM = 'from', TO = 'to';
function getToFrom(index) {
    if (index === 0)
        return FROM;
    else if (index === (ghRequest.route.size() - 1))
        return TO;
    return -1;
}

function setFlag(coord, index) {
    if (coord.lat) {
        var toFrom = getToFrom(index),
                marker = L.marker([coord.lat, coord.lng], {
                    icon: ((toFrom === FROM) ? iconFrom : ((toFrom === TO) ? iconTo : iconInt)),
                    draggable: true,
                    contextmenu: true,
                    contextmenuItems: [{
                            text: 'Marker ' + ((toFrom === FROM) ?
                                    'Start' : ((toFrom === TO) ? 'End' : 'Intermediate ' + index)),
                            disabled: true,
                            index: 0,
                            state: 2
                        }, {
                            text: 'Set as ' + ((toFrom !== TO) ? 'End' : 'Start'),
                            callback: (toFrom !== TO) ? setToEnd : setToStart,
                            index: 2,
                            state: 2
                        }, {
                            text: 'Delete from Route',
                            callback: deleteCoord,
                            index: 3,
                            state: 2,
                            disabled: (toFrom !== -1 && ghRequest.route.size() === 2) ? true : false // prevent to and from
                        }, {
                            separator: true,
                            index: 4,
                            state: 2
                        }],
                    contextmenuAtiveState: 2
                }).addTo(routingLayer).bindPopup(((toFrom === FROM) ?
                'Start' : ((toFrom === TO) ? 'End' : 'Intermediate ' + index)));
        // intercept openPopup
        marker._openPopup = marker.openPopup;
        marker.openPopup = function () {
            var latlng = this.getLatLng(),
                    locCoord = ghRequest.route.getIndexFromCoord(latlng),
                    content;
            if (locCoord.resolvedList && locCoord.resolvedList[0] && locCoord.resolvedList[0].locationDetails) {
                var address = locCoord.resolvedList[0].locationDetails;
                content =
                        ((address.road) ? address.road + ', ' : '') +
                        ((address.postcode) ? address.postcode + ', ' : '') +
                        ((address.city) ? address.city + ', ' : '') +
                        ((address.country) ? address.country : '')
                        ;
                // at last update the content and update
                this._popup.setContent(content).update();
            }
            this._openPopup();
        };
        var _tempItem = {
            text: 'Set as Start',
            callback: setToStart,
            index: 1,
            state: 2
        };
        if (toFrom === -1)
            marker.options.contextmenuItems.push(_tempItem);// because the Mixin.ContextMenu isn't initialized
        marker.on('dragend', function (e) {
            routingLayer.clearLayers();
            // inconsistent leaflet API: event.target.getLatLng vs. mouseEvent.latlng?
            var latlng = e.target.getLatLng();
            hideAutoComplete();
            ghRequest.route.getIndex(index).setCoord(latlng.lat, latlng.lng);
            resolveIndex(index);
            // do not wait for resolving and avoid zooming when dragging
            ghRequest.do_zoom = false;
            routeLatLng(ghRequest, false);
        });
    }
}

function resolveFrom() {
    return resolveIndex(0);
}

function resolveTo() {
    return resolveIndex((ghRequest.route.size() - 1));
}

function resolveIndex(index, inputsStr) {
    setFlag(ghRequest.route.getIndex(index), index);
    if (index === 0) {
        if (!ghRequest.to.isResolved())
            map.contextmenu.setDisabled(menuStart, true);
        else
            map.contextmenu.setDisabled(menuStart, false);
    } else if (index === (ghRequest.route.size() - 1)) {
        if (!ghRequest.from.isResolved())
            map.contextmenu.setDisabled(menuEnd, true);
        else
            map.contextmenu.setDisabled(menuEnd, false);
    }

    return resolve(index, ghRequest.route.getIndex(index), inputsStr);
}

function resolveAll(inputsStr) {
    var ret = [];
    for (var i = 0, l = ghRequest.route.size(); i < l; i++) {
        ret[i] = resolveIndex(i, inputsStr);
    }
    return ret;
}

function flagAll() {
    for (var i = 0, l = ghRequest.route.size(); i < l; i++) {
        setFlag(ghRequest.route.getIndex(i), i);
    }
}

function resolve(index, locCoord, inputsStr) {
    var div = $('#locationpoints > div.pointDiv').eq(index);
    $(div).find(".pointFlag").hide();
    $(div).find(".pointIndicator").show();
//    if (inputsStr) {
//    	$(div).find(".pointInput").val(inputsStr[index]);
//    }
//    else {
//	$(div).find(".pointInput").val(locCoord.input);
    var ttinput = $(div).find(".tt-input");
    ttinput.val(locCoord.input);
    var tthint = $(div).find(".tt-hint");
    tthint.val('');

    return createAmbiguityList(locCoord, ttinput).always(function () {
        var errorDiv = $(div).find(".pointResolveError");
        errorDiv.empty();

        if (locCoord.error) {
            errorDiv.show();
            errorDiv.text(locCoord.error).fadeOut(5000);
            locCoord.error = '';
        }

        $(div).find(".pointIndicator").hide();
        $(div).find(".pointFlag").show();
        return locCoord;
    });
}

/**
 * Returns a defer object containing the location pointing to a resolvedList with all the found
 * coordinates.
 */
function createAmbiguityList(locCoord, ttinput) {
    locCoord.error = "";
    locCoord.resolvedList = [];
    var timeout = 3000;

    if (locCoord.isResolved()) {
        // if we changed only another location no need to look this up again
        var tmpDefer = $.Deferred();
        tmpDefer.resolve([locCoord]);
        return tmpDefer;
    } else if (locCoord.lat && locCoord.lng) {
        locCoord.error = "Nominatum reverse geocode not supported";
        var tmpDefer = $.Deferred();
        tmpDefer.resolve([locCoord]);
        return tmpDefer;
    } else {
        var tmpDefer = $.Deferred();
        var enteredValue = ttinput.val();
    	places.get(enteredValue, function(suggestions) {
    		var resolved = false;
    		jQuery.each(suggestions, function (index, item) {
    			if (item.address_line===enteredValue) {
    				locCoord.lat = item.latitude;
    				locCoord.lng = item.longitude;
    	            resolved = true;
    				return false;
    			}
    	    });
    		if(!resolved) {
	            locCoord.error = "Failed to resolve entered value";
				tmpDefer.resolve([locCoord]);
    		}
    		else {
    			tmpDefer.resolve([locCoord]);
    		}
    	});
        return tmpDefer;
    }
}

function insComma(textA, textB) {
    if (textA.length > 0)
        return textA + ", " + textB;
    return textB;
}

function formatLocationEntry(address) {
    var locationDetails = {};
    var text = "";
    if (!address)
        return locationDetails;
    if (address.road) {
        text = address.road;
        if (address.house_number) {
            if (text.length > 0)
                text += " ";
            text += address.house_number;
        }
        locationDetails.road = text;
    }

    if (address.postcode)
        locationDetails.postcode = address.postcode;
    locationDetails.country = address.country;

    if (address.city || address.suburb || address.town
            || address.village || address.hamlet || address.locality) {
        text = "";
        if (address.locality)
            text = insComma(text, address.locality);
        if (address.hamlet)
            text = insComma(text, address.hamlet);
        if (address.village)
            text = insComma(text, address.village);
        if (address.suburb)
            text = insComma(text, address.suburb);
        if (address.city)
            text = insComma(text, address.city);
        if (address.town)
            text = insComma(text, address.town);
        locationDetails.city = text;
    }

    text = "";
    if (address.state)
        text += address.state;

    if (address.continent)
        text = insComma(text, address.continent);

    locationDetails.more = text;
    return locationDetails;
}

function doGeoCoding(input, limit, timeout) {
    // see https://trac.openstreetmap.org/ticket/4683 why limit=3 and not 1
    if (!limit)
        limit = 10;
    var url = nominatimURL + "?format=json&addressdetails=1&q=" + encodeURIComponent(input) + "&limit=" + limit;
    if (bounds.initialized) {
        // minLon, minLat, maxLon, maxLat => left, top, right, bottom
        url += "&bounded=1&viewbox=" + bounds.minLon + "," + bounds.maxLat + "," + bounds.maxLon + "," + bounds.minLat;
    }

    return $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        timeout: timeout
    }).fail(
            createCallback("[nominatim] Problem while looking up location " + input)
            );
}

function createCallback(errorFallback) {
    return function (err) {
        log(errorFallback + " " + JSON.stringify(err));
    };
}

function focusWithBounds(coord, bbox, index) {
    routingLayer.clearLayers();
    // bbox needs to be in the none-geojson format!?
    // [[lat, lng], [lat2, lng2], ...]
    map.fitBounds(new L.LatLngBounds(bbox));
    setFlag(coord, index);
}

function focus(coord, zoom, index) {
    if (coord.lat && coord.lng) {
        if (!zoom)
            zoom = 11;
        routingLayer.clearLayers();
        map.setView(new L.LatLng(coord.lat, coord.lng), zoom);
        setFlag(coord, index);
    }
}
function routeLatLng(request, doQuery) {
    // do_zoom should not show up in the URL but in the request object to avoid zooming for history change
    var doZoom = request.do_zoom;
    request.do_zoom = true;

    var urlForHistory = request.createHistoryURL() + "&layer=" + activeLayer;

    // not enabled e.g. if no cookies allowed (?)
    // if disabled we have to do the query and cannot rely on the statechange history event
    if (!doQuery && History.enabled) {
        // 2. important workaround for encoding problems in history.js
        var params = parseUrl(urlForHistory);
        log(params);
        params.do_zoom = doZoom;
        // force a new request even if we have the same parameters
        params.mathRandom = Math.random();
        History.pushState(params, browserTitle, urlForHistory);
        return;
    }

    $("#info").empty();
    $("#info").show();
    var descriptionDiv = $("
");
    $("#info").append(descriptionDiv);

    if (elevationControl)
        elevationControl.clear();

    routingLayer.clearLayers();
    flagAll();

    map.contextmenu.setDisabled(menuIntermediate, false);

    $("#vehicles button").removeClass("selectvehicle");
    $("button#" + request.vehicle.toLowerCase()).addClass("selectvehicle");

    var urlForAPI = request.createURL();
    descriptionDiv.html(' Search Route ...');
    request.doRequest(urlForAPI, function (json) {
        descriptionDiv.html("");
        if (json.error) {
            var tmpErrors = json.error;
            log(tmpErrors);
            if (json.hints)
                for (var m = 0; m < json.hints.length; m++) {
                    descriptionDiv.append("
" + json.hints[m].message + "
");
                }
            return;
        }
        var path = json.paths[0];
        var geojsonFeature = {
            "type": "Feature",
            // "style": myStyle,
            "geometry": path.points
        };

        if (request.hasElevation()) {
            if (elevationControl === null) {
                elevationControl = L.control.elevation({
                    position: "bottomright",
                    theme: "white-theme", //default: lime-theme
                    width: 450,
                    height: 125,
                    yAxisMin: 0, // set min domain y axis
                    // yAxisMax: 550, // set max domain y axis
                    forceAxisBounds: false,
                    margins: {
                        top: 10,
                        right: 20,
                        bottom: 30,
                        left: 50
                    },
                    useHeightIndicator: true, //if false a marker is drawn at map position
                    interpolation: "linear", //see https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-area_interpolate
                    hoverNumber: {
                        decimalsX: 3, //decimals on distance (always in km)
                        decimalsY: 0, //deciamls on height (always in m)
                        formatter: undefined //custom formatter function may be injected
                    },
                    xTicks: undefined, //number of ticks in x axis, calculated by default according to width
                    yTicks: undefined, //number of ticks on y axis, calculated by default according to height
                    collapsed: false    //collapsed mode, show chart on click or mouseover
                });
                elevationControl.addTo(map);
            }

            elevationControl.addData(geojsonFeature);
        }

        routingLayer.addData(geojsonFeature);
        if (path.bbox && doZoom) {
            var minLon = path.bbox[0];
            var minLat = path.bbox[1];
            var maxLon = path.bbox[2];
            var maxLat = path.bbox[3];
            var tmpB = new L.LatLngBounds(new L.LatLng(minLat, minLon), new L.LatLng(maxLat, maxLon));
            map.fitBounds(tmpB);
        }

        var tmpTime = createTimeString(path.time);
        var tmpDist = createDistanceString(path.distance);
        descriptionDiv.append(tr("routeInfo", [tmpDist, tmpTime]));

        $('.defaulting').each(function (index, element) {
            $(element).css("color", "black");
        });

        if (path.instructions) {
            var instructionsElement = $("
");

            var partialInstr = path.instructions.length > 100;
            var len = Math.min(path.instructions.length, 100);
            for (var m = 0; m < len; m++) {
                var instr = path.instructions[m];
                var lngLat = path.points.coordinates[instr.interval[0]];
                addInstruction(instructionsElement, instr, m, lngLat);
            }
            $("#info").append(instructionsElement);

            if (partialInstr) {
                var moreDiv = $("<button id='moreButton'>" + tr("moreButton") + "..</button>");
                moreDiv.click(function () {
                    moreDiv.remove();
                    for (var m = len; m < path.instructions.length; m++) {
                        var instr = path.instructions[m];
                        var lngLat = path.points.coordinates[instr.interval[0]];
                        addInstruction(instructionsElement, instr, m, lngLat);
                    }
                });
                instructionsElement.append(moreDiv);
            }

            var hiddenDiv = $("
");
            hiddenDiv.hide();

            var toggly = $("<button id='expandDetails'>+</button>");
            toggly.click(function () {
                hiddenDiv.toggle();
            });
            $("#info").append(toggly);
            var infoStr = "took: " + round(json.info.took / 1000, 1000) + "s"
                    + ", points: " + path.points.coordinates.length;

            hiddenDiv.append("" + infoStr + "");

            var exportLink = $("#export-link a");
            exportLink.attr('href', urlForHistory);
            var osmRouteLink = $("
view on OSM");

            var osmVehicle = "bicycle";
            if (request.vehicle.toUpperCase() === "FOOT") {
                osmVehicle = "foot";
            }
            osmRouteLink.attr("href", "http://www.openstreetmap.org/directions?engine=graphhopper_" + osmVehicle + "&route=" + encodeURIComponent(request.from.lat + "," + request.from.lng + ";" + request.to.lat + "," + request.to.lng));
            hiddenDiv.append(osmRouteLink);

            var osrmLink = $("OSRM");
            osrmLink.attr("href", "http://map.project-osrm.org/?loc=" + request.from + "&loc=" + request.to);
            hiddenDiv.append("
Compare with: ");
            hiddenDiv.append(osrmLink);
            var googleLink = $("Google ");
            var addToGoogle = "";
            var addToBing = "";
            if (request.vehicle.toUpperCase() === "FOOT") {
                addToGoogle = "&dirflg=w";
                addToBing = "&mode=W";
            } else if ((request.vehicle.toUpperCase().indexOf("BIKE") >= 0) ||
                    (request.vehicle.toUpperCase() === "MTB")) {
                addToGoogle = "&dirflg=b";
                // ? addToBing = "&mode=B";
            }

            googleLink.attr("href", "https://maps.google.com/?saddr=" + request.from + "&daddr=" + request.to + addToGoogle);
            hiddenDiv.append(googleLink);
            var bingLink = $("Bing ");
            bingLink.attr("href", "https://www.bing.com/maps/default.aspx?rtp=adr." + request.from + "~adr." + request.to + addToBing);
            hiddenDiv.append(bingLink);
            $("#info").append(hiddenDiv);
        }
    });
}

function createDistanceString(dist) {
    if (dist < 900)
        return round(dist, 1) + tr2("mAbbr");

    dist = round(dist / 1000, 100);
    if (dist > 100)
        dist = round(dist, 1);
    return dist + tr2("kmAbbr");
}

function createTimeString(time) {
    var tmpTime = round(time / 60 / 1000, 1000);
    var resTimeStr;
    if (tmpTime > 60) {
        if (tmpTime / 60 > 24) {
            resTimeStr = floor(tmpTime / 60 / 24, 1) + tr2("dayAbbr");
            tmpTime = floor(((tmpTime / 60) % 24), 1);
            if (tmpTime > 0)
                resTimeStr += " " + tmpTime + tr2("hourAbbr");
        } else {
            resTimeStr = floor(tmpTime / 60, 1) + tr2("hourAbbr");
            tmpTime = floor(tmpTime % 60, 1);
            if (tmpTime > 0)
                resTimeStr += " " + tmpTime + tr2("minAbbr");
        }
    } else
        resTimeStr = round(tmpTime % 60, 1) + tr2("minAbbr");
    return resTimeStr;
}

function addInstruction(main, instr, instrIndex, lngLat) {
    var sign = instr.sign;
    if (instrIndex === 0)
        sign = "marker-icon-green";
    else if (sign === -3)
        sign = "sharp_left";
    else if (sign === -2)
        sign = "left";
    else if (sign === -1)
        sign = "slight_left";
    else if (sign === 0)
        sign = "continue";
    else if (sign === 1)
        sign = "slight_right";
    else if (sign === 2)
        sign = "right";
    else if (sign === 3)
        sign = "sharp_right";
    else if (sign === 4)
        sign = "marker-icon-red";
    else if (sign === 5)
        sign = "marker-icon-blue";
    else if (sign === 6)
        sign = "roundabout";
    else
        throw "did not found sign " + sign;
    var title = instr.text;
    if (instr.annotation_text) {
        if (!title)
            title = instr.annotation_text;
        else
            title = title + ", " + instr.annotation_text;
    }
    var distance = instr.distance;
    var str = "" + title + "	";

    if (distance > 0) {
        str += " "
                + createDistanceString(distance) + "
"
                + createTimeString(instr.time) + "	";
    }

    if (sign !== "continue") {
        var indiPic = "";
        str = "" + indiPic + "	" + str;
    } else
        str = "" + str;
    var instructionDiv = $("
");
    instructionDiv.html(str);
    if (lngLat) {
        instructionDiv.click(function () {
            if (routeSegmentPopup)
                map.removeLayer(routeSegmentPopup);

            routeSegmentPopup = L.popup().
                    setLatLng([lngLat[1], lngLat[0]]).
                    setContent(title).
                    openOn(map);
        });
    }
    main.append(instructionDiv);
}

function getCenter(bounds) {
    var center = {
        lat: 0,
        lng: 0
    };
    if (bounds.initialized) {
        center.lat = (bounds.minLat + bounds.maxLat) / 2;
        center.lng = (bounds.minLon + bounds.maxLon) / 2;
    }
    return center;
}

function parseUrlWithHisto() {
    if (window.location.hash)
        return parseUrl(window.location.hash);

    return parseUrl(window.location.search);
}

function parseUrlAndRequest() {
    return parseUrl(window.location.search);
}

function parseUrl(query) {
    var index = query.indexOf('?');
    if (index >= 0)
        query = query.substring(index + 1);
    var res = {};
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var indexPos = vars[i].indexOf("=");
        if (indexPos < 0)
            continue;

        var key = vars[i].substring(0, indexPos);
        var value = vars[i].substring(indexPos + 1);
        value = decodeURIComponent(value.replace(/\+/g, ' '));
        if (value === "")
            continue;

        if (key === "point" && !res[key]) {
            res[key] = [value];
        } else if (typeof res[key] === "string") {
            var arr = [res[key], value];
            res[key] = arr;
        } else if (typeof res[key] === "undefined") {
            if (value === 'true') {
                res[key] = true;
            } else if (value === 'false') {
                res[key] = false;
            } else {
                var tmp = Number(value);
                if (isNaN(tmp))
                    res[key] = value;
                else
                    res[key] = Number(value);
            }
        } else {
            res[key].push(value);
        }
    }
    return res;
}

function mySubmit() {
    var fromStr,
            toStr,
            viaStr,
            allStr = [],
            inputsStr = [],
            inputOk = true;

    if (osplacesurl && osplacesurl.indexOf('OS_PLACES_KEY')>-1) {
    	alert('Configuration error. You must configure your OS Places license key.');
    	return;
    }

//    var location_points = $("#locationpoints > div.pointDiv > input.pointInput");
    var location_points = $("#locationpoints > div.pointDiv > span.twitter-typeahead > input.tt-input");

    var len = location_points.size();
    $.each(location_points, function (index) {
    	var latLonString;
    	var address;
    	if (this.data) {
    		latLonString = this.data.latitude + ', ' + this.data.longitude;
    		address = this.data.address_line;
    	}

        if (index === 0) {
            fromStr = $(this).val();
            // We haven't looked up an address so assume it is a lat lon
        	if (!this.data) {
        		latLonString = fromStr;
        		address = latLonString;
        	}
            if (fromStr !== tr("fromHint") && fromStr !== "") {
                allStr.push(latLonString);
                inputsStr.push(address);
            }
            else {
                inputOk = false;
            }
        } else if (index === (len - 1)) {
            toStr = $(this).val();
            // We haven't looked up an address so assume it is a lat lon
        	if (!this.data) {
        		latLonString = toStr;
        		address = latLonString;
        	}
            if (toStr !== tr("toHint") && toStr !== "") {
                allStr.push(latLonString);
                inputsStr.push(address);
            }
            else {
                inputOk = false;
            }
        } else {
            viaStr = $(this).val();
            // We haven't looked up an address so assume it is a lat lon
        	if (!this.data) {
        		latLonString = viaStr;
        		address = latLonString;
        	}
            if (viaStr !== tr("viaHint") && viaStr !== "") {
                allStr.push(latLonString);
                inputsStr.push(address);
            }
            else {
                inputOk = false;
            }
        }
    });
    if (!inputOk) {
        // TODO print warning
        return;
    }
    if (fromStr === tr("fromHint")) {
        // no special function
        return;
    }

    if (toStr === tr("toHint")) {
        // lookup area
        ghRequest.from.setStr(fromStr);
        $.when(resolveFrom()).done(function () {
            focus(ghRequest.from, null, 0);
        });
        return;
    }
    // route!
    if (inputOk)
        resolveCoords(allStr, false, inputsStr);
}

function floor(val, precision) {
    if (!precision)
        precision = 1e6;
    return Math.floor(val * precision) / precision;
}

function round(val, precision) {
    if (precision === undefined)
        precision = 1e6;
    return Math.round(val * precision) / precision;
}

function tr(key, args) {
    return tr2("web." + key, args);
}

function tr2(key, args) {
    if (key === null) {
        log("ERROR: key was null?");
        return "";
    }
    if (defaultTranslationMap === null) {
        log("ERROR: defaultTranslationMap was not initialized?");
        return key;
    }
    key = key.toLowerCase();
    var val = defaultTranslationMap[key];
    if (!val && enTranslationMap)
        val = enTranslationMap[key];
    if (!val)
        return key;

    return stringFormat(val, args);
}

function stringFormat(str, args) {
    if (typeof args === 'string')
        args = [args];

    if (str.indexOf("%1$s") >= 0) {
        // with position arguments ala %2$s
        return str.replace(/\%(\d+)\$s/g, function (match, matchingNum) {
            matchingNum--;
            return typeof args[matchingNum] !== 'undefined' ? args[matchingNum] : match;
        });
    } else {
        // no position so only values ala %s
        var matchingNum = 0;
        return str.replace(/\%s/g, function (match) {
            var val = typeof args[matchingNum] !== 'undefined' ? args[matchingNum] : match;
            matchingNum++;
            return val;
        });
    }
}

function initI18N() {
    $('#searchButton').attr("value", tr("searchButton"));
    location_points = $("#locationpoints > div.pointDiv > input.pointInput");
    var j = location_points.size();
    $(location_points).each(function (index) {
        if (index === 0)
            $(this).attr("placeholder", tr("fromHint"));
        else if (index === (j - 1))
            $(this).attr("placeholder", tr("toHint"));
        else
            $(this).attr("placeholder", tr("viaHint"));
    });
    $('#gpxExportButton').attr("title", tr("gpxExportButton"));
    // Populate the placeholder text for the typeahead inputs
    typeahead_points = $("#locationpoints > div.pointDiv > span.twitter-typeahead > input.tt-input");
    var l = typeahead_points.size();
    $(typeahead_points).each(function (index) {
        if (index === 0)
            $(this).attr("placeholder", tr("fromHint"));
        else if (index === (l - 1))
            $(this).attr("placeholder", tr("toHint"));
        else
            $(this).attr("placeholder", tr("viaHint"));
    });

}

function exportGPX() {
    if (ghRequest.route.isResolved())
        window.open(ghRequest.createGPXURL());
    return false;
}

function getAutoCompleteDiv(index) {
    return null;//$('#locationpoints > div.pointDiv').eq(index).find(".pointInput");
}

function hideAutoComplete() {
//    $(':input[id$="_Input"]').autocomplete().hide();
}

function formatValue(orig, query) {
    var pattern = '(' + $.Autocomplete.utils.escapeRegExChars(query) + ')';
    return orig.replace(new RegExp(pattern, 'gi'), '$1<\/strong>');
}

function setAutoCompleteList(index) {
    var myAutoDiv = getAutoCompleteDiv(index);

    var options = {
        containerClass: "autocomplete",
        /* as we use can potentially use jsonp we need to set the timeout to a small value */
        timeout: 1000,
        /* avoid too many requests when typing quickly */
        deferRequestBy: 5,
        minChars: 2,
        maxHeight: 510,
        noCache: true,
        /* this default could be problematic: preventBadQueries: true, */
        triggerSelectOnValidInput: false,
        autoSelectFirst: false,
        paramName: "q",
        dataType: ghRequest.dataType,
        onSearchStart: function (params) {
            // query server only if not a parsable point (i.e. format lat,lon)
            var val = new GHInput(params.q).lat;
            return val === undefined;
        },
        serviceUrl: function () {
            // see https://graphhopper.com/#directions-api
            return ghRequest.createGeocodeURL(host, index - 1);
        },
        transformResult: function (response, originalQuery) {
            response.suggestions = [];
            if (response.hits)
                for (var i = 0; i < response.hits.length; i++) {
                    var hit = response.hits[i];
                    response.suggestions.push({value: dataToText(hit), data: hit});
                }
            return response;
        },
        onSearchError: function (element, q, jqXHR, textStatus, errorThrown) {
            // too many errors if interrupted console.log(element + ", " + JSON.stringify(q) + ", textStatus " + textStatus + ", " + errorThrown);
        },
        formatResult: function (suggestion, currInput) {
            // avoid highlighting for now as this breaks the html sometimes
            return dataToHtml(suggestion.data, currInput);
        },
        onSelect: function (suggestion) {
            options.onPreSelect(suggestion);
        },
        onPreSelect: function (suggestion) {
            var req = ghRequest.route.getIndex(index);

            myAutoDiv.autocomplete().disable();

            var point = suggestion.data.point;
            req.setCoord(point.lat, point.lng);

            req.input = suggestion.value;
            if (!routeIfAllResolved(true))
                focus(req, 15, index);

            myAutoDiv.autocomplete().enable();
        }
    };

    myAutoDiv.autocomplete(options);

    // with the following more stable code we cannot click on suggestions anylonger
//    $("#" + fromOrTo + "Input").focusout(function() {
//        myAutoDiv.autocomplete().disable();
//        myAutoDiv.autocomplete().hide();
//    });
//    $("#" + fromOrTo + "Input").focusin(function() {
//        myAutoDiv.autocomplete().enable();
//    });
}

function dataToHtml(data, query) {
    var element = "";
    if (data.name)
        element += "
" + formatValue(data.name, query) + "
";
    var addStr = "";
    if (data.postcode)
        addStr = data.postcode;
    if (data.city)
        addStr = insComma(addStr, data.city);
    if (data.country)
        addStr = insComma(addStr, data.country);

    if (addStr)
        element += "
" + formatValue(addStr, query) + "
";

    if (data.osm_key === "highway") {
        // ignore
    }
    if (data.osm_key === "place") {
        element += "" + data.osm_value + "";
    } else
        element += "" + data.osm_key + "";
    return element;
}

function dataToText(data) {
    var text = "";
    if (data.name)
        text += data.name;

    if (data.postcode)
        text = insComma(text, data.postcode);

    // make sure name won't be duplicated
    if (data.city && text.indexOf(data.city) < 0)
        text = insComma(text, data.city);

    if (data.country && text.indexOf(data.country) < 0)
        text = insComma(text, data.country);
    return text;
}

function isProduction() {
    return host.indexOf("graphhopper.com") > 0;
}


text:
namespace fnx {

	RWLock::RWLock(){
		int retval = pthread_rwlock_init(&theLock, NULL);
		switch (retval) {
			case 0:
				return;
				break;
			case EAGAIN:
				throw GenericException("Not enough resources to instantiate rw-lock");
				break;
			case ENOMEM:
				throw GenericException("Not enough memory to instantiate rw-lock");
				break;
			case EPERM:
				throw GenericException("Not enough privileges to instantiate rw-lock");
				break;
			case EINVAL:
				throw GenericException("Invalid rw-lock attributes assigned, can't create rw-lock.");
			default:
				throw GenericException("Can't create rw-lock");
				break;
		}
	}

	RWLock::~RWLock(){
		pthread_rwlock_destroy(&theLock);
	}

	void RWLock::readLock(){
		int retval = pthread_rwlock_rdlock(&theLock);
		if(retval != 0){
			std::stringstream errmsg;
			errmsg << "Unable to read-lock, error: " << retval;
			throw GenericException(errmsg.str());
		}
	}

	void RWLock::unlock(){
		int retval = pthread_rwlock_unlock(&theLock);
		if(retval != 0){
			std::stringstream errmsg;
			errmsg << "Unable to unlock rw-lock, error: " << retval;
			throw GenericException(errmsg.str());
		}
	}

	void RWLock::writeLock(){
		int retval = pthread_rwlock_wrlock(&theLock);
		if(retval != 0){
			std::stringstream errmsg;
			errmsg << "Unable to write-lock, error: " << retval;
			throw GenericException(errmsg.str());
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.drools.compiler.builder.impl;

import org.kie.api.io.Resource;

public interface ResourceBuilder {
    public void addResource(Resource resource);
}


text:
#include "../TreeNode.h"
#include <iostream>
#include <queue>
using namespace std;

/*
 * Approach: use level order traversal to get the parent and depth of each input node in the Binary Tree.
 * Then, check to make sure that the depth of the two nodes is the same and that the two nodes have different parents.
 *
 * Time complexity: O(n) [where n is the number of nodes in the Binary Tree]
 * Space complexity: O(n)
 */

int getNodeLevel(TreeNode* root, const int & number)
{
    queue<TreeNode*> Q;

    Q.push(root);

    int level=0;

    bool done=false;

    while(!Q.empty())
    {
        int qSize=int(Q.size());

        for(int count=0;count<qSize;++count)
        {
            TreeNode* current=Q.front();

            Q.pop();

            if(current->val==number)
            {
                done=true;
            }

            if(current->left!=nullptr)
            {
                Q.emplace(current->left);
            }

            if(current->right!=nullptr)
            {
                Q.emplace(current->right);
            }
        }

        if(done)
        {
            break;
        }

        level++;
    }

    return level;
}

void getNodeParent(TreeNode* root, TreeNode* & parent, const int & number)
{
    queue<TreeNode*> Q;

    Q.push(root);

    bool done=false;

    while(!Q.empty())
    {
        int qSize=int(Q.size());

        for(int count=0;count<qSize;++count)
        {
            TreeNode* current=Q.front();

            Q.pop();

            if(current->left!=nullptr)
            {
                if(current->left->val==number)
                {
                    parent=current;

                    done=true;
                }

                Q.emplace(current->left);
            }

            if(current->right!=nullptr)
            {
                if(current->right->val==number)
                {
                    parent=current;

                    done=true;
                }

                Q.emplace(current->right);
            }
        }

        if(done)
        {
            break;
        }
    }
}

bool isCousins(TreeNode* root, int x, int y)
{
    if(root==nullptr)
    {
        return false;
    }

    int xLevel=getNodeLevel(root, x);

    int yLevel=getNodeLevel(root, y);

    TreeNode* xParent=nullptr;

    getNodeParent(root, xParent, x);

    TreeNode* yParent=nullptr;

    getNodeParent(root, yParent, y);

    return xLevel==yLevel && xParent->val!=yParent->val;
}


text:
<?php
namespace Giosh94mhz\GeonamesBundle\Geocoder;

use Giosh94mhz\GeonamesBundle\Exception\InvalidArgumentException;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Allocate and load (delayed) an instance. Used to reduce code duplication.
 *
 * @author Giorgio Premi <giosh94mhz@agmail.com>
 * @internal
 */
class ResultLoader
{
    protected $om;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    /**
     * @return ResultAdapter
     */
    public function newInstance()
    {
        $result = new ResultAdapter();
        $callback = array($this, 'createFromId');
        $result->setLoaderClosure(function ($geonameid) use ($callback) {
            return call_user_func($callback, $geonameid);
        });

        return $result;
    }

    /**
     * @param integer $geonameid A geonameid to load.
     *
     * @return Toponym
     */
    public function createFromId($geonameid)
    {
        $toponym = $this->om->find('Giosh94mhzGeonamesBundle:Toponym', $geonameid);
        if (! $toponym )
            throw new InvalidArgumentException("Cannot load the Toponym with id '{$geonameid}'");

        return $toponym;
    }
}


text:
package org.apache.poi.hpsf;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 *
The Variant types as defined by Microsoft's COM. I
 * found this information in
 * http://www.marin.clara.net/COM/variant_type_definitions.htm.

 *
 *
In the variant types descriptions the following shortcuts are
 * used:  [V] - may appear in a VARIANT,
 * [T] - may appear in a TYPEDESC,
 * [P] - may appear in an OLE property set,
 * [S] - may appear in a Safe Array.

 *
 * @author Rainer Klute (klute@rainer-klute.de)
 */
public class Variant
{

    /**
     *
[V][P] Nothing, i.e. not a single byte of data.

     */
    public static final int VT_EMPTY = 0;

    /**
     *
[V][P] SQL style Null.

     */
    public static final int VT_NULL = 1;

    /**
     *
[V][T][P][S] 2 byte signed int.

     */
    public static final int VT_I2 = 2;

    /**
     *
[V][T][P][S] 4 byte signed int.

     */
    public static final int VT_I4 = 3;

    /**
     *
[V][T][P][S] 4 byte real.

     */
    public static final int VT_R4 = 4;

    /**
     *
[V][T][P][S] 8 byte real.

     */
    public static final int VT_R8 = 5;

    /**
     *
[V][T][P][S] currency. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_CY = 6;

    /**
     *
[V][T][P][S] date. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_DATE = 7;

    /**
     *
[V][T][P][S] OLE Automation string. How long is this? How is it
     * to be interpreted?

     */
    public static final int VT_BSTR = 8;

    /**
     *
[V][T][P][S] IDispatch *. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_DISPATCH = 9;

    /**
     *
[V][T][S] SCODE. How
     * long is this? How is it to be interpreted?

     */
    public static final int VT_ERROR = 10;

    /**
     *
[V][T][P][S] True=-1, False=0.

     */
    public static final int VT_BOOL = 11;

    /**
     *
[V][T][P][S] VARIANT *. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_VARIANT = 12;

    /**
     *
[V][T][S] IUnknown *. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_UNKNOWN = 13;

    /**
     *
[V][T][S] 16 byte fixed point.

     */
    public static final int VT_DECIMAL = 14;

    /**
     *
[T] signed char.

     */
    public static final int VT_I1 = 16;

    /**
     *
[V][T][P][S] unsigned char.

     */
    public static final int VT_UI1 = 17;

    /**
     *
[T][P] unsigned short.

     */
    public static final int VT_UI2 = 18;

    /**
     *
[T][P] unsigned int.

     */
    public static final int VT_UI4 = 19;

    /**
     *
[T][P] signed 64-bit int.

     */
    public static final int VT_I8 = 20;

    /**
     *
[T][P] unsigned 64-bit int.

     */
    public static final int VT_UI8 = 21;

    /**
     *
[T] signed machine int.

     */
    public static final int VT_INT = 22;

    /**
     *
[T] unsigned machine int.

     */
    public static final int VT_UINT = 23;

    /**
     *
[T] C style void.

     */
    public static final int VT_VOID = 24;

    /**
     *
[T] Standard return type. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_HRESULT = 25;

    /**
     *
[T] pointer type. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_PTR = 26;

    /**
     *
[T] (use VT_ARRAY in VARIANT).

     */
    public static final int VT_SAFEARRAY = 27;

    /**
     *
[T] C style array. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_CARRAY = 28;

    /**
     *
[T] user defined type. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_USERDEFINED = 29;

    /**
     *
[T][P] null terminated string.

     */
    public static final int VT_LPSTR = 30;

    /**
     *
[T][P] wide (Unicode) null terminated string.

     */
    public static final int VT_LPWSTR = 31;

    /**
     *
[P] FILETIME. The FILETIME structure holds a date and time
     * associated with a file. The structure identifies a 64-bit
     * integer specifying the number of 100-nanosecond intervals which
     * have passed since January 1, 1601. This 64-bit value is split
     * into the two dwords stored in the structure.

     */
    public static final int VT_FILETIME = 64;

    /**
     *
[P] Length prefixed bytes.

     */
    public static final int VT_BLOB = 65;

    /**
     *
[P] Name of the stream follows.

     */
    public static final int VT_STREAM = 66;

    /**
     *
[P] Name of the storage follows.

     */
    public static final int VT_STORAGE = 67;

    /**
     *
[P] Stream contains an object.  How long is this? How is it
     * to be interpreted?

     */
    public static final int VT_STREAMED_OBJECT = 68;

    /**
     *
[P] Storage contains an object.  How long is this? How is it
     * to be interpreted?

     */
    public static final int VT_STORED_OBJECT = 69;

    /**
     *
[P] Blob contains an object. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_BLOB_OBJECT = 70;

    /**
     *
[P] Clipboard format. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_CF = 71;

    /**
     *
[P] A Class ID.

     *
     *
It consists of a 32 bit unsigned integer indicating the size
     * of the structure, a 32 bit signed integer indicating (Clipboard
     * Format Tag) indicating the type of data that it contains, and
     * then a byte array containing the data.

     *
     *
The valid Clipboard Format Tags are:

     *
     *

     *
{@link Thumbnail#CFTAG_WINDOWS}

     *
{@link Thumbnail#CFTAG_MACINTOSH}

     *
{@link Thumbnail#CFTAG_NODATA}

     *
{@link Thumbnail#CFTAG_FMTID}

     *

     *
     *
typedef struct tagCLIPDATA {
     * // cbSize is the size of the buffer pointed to
     * // by pClipData, plus sizeof(ulClipFmt)
     * ULONG              cbSize;
     * long               ulClipFmt;
     * BYTE*              pClipData;
     * } CLIPDATA;

     *
     *
See
     * msdn.microsoft.com/library/en-us/com/stgrstrc_0uwk.asp.

     */
    public static final int VT_CLSID = 72;

    /**
     *
[P] simple counted array. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_VECTOR = 0x1000;

    /**
     *
[V] SAFEARRAY*. How
     * long is this? How is it to be interpreted?

     */
    public static final int VT_ARRAY = 0x2000;

    /**
     *
[V] void* for local use. How long is this? How is it to be
     * interpreted?

     */
    public static final int VT_BYREF = 0x4000;

    /**
     *
FIXME (3): Document this!

     */
    public static final int VT_RESERVED = 0x8000;

    /**
     *
FIXME (3): Document this!

     */
    public static final int VT_ILLEGAL = 0xFFFF;

    /**
     *
FIXME (3): Document this!

     */
    public static final int VT_ILLEGALMASKED = 0xFFF;

    /**
     *
FIXME (3): Document this!

     */
    public static final int VT_TYPEMASK = 0xFFF;

    /**
     *
Maps the numbers denoting the variant types to their corresponding
     * variant type names.

     */
    private static Map numberToName;

    private static Map numberToLength;

    /**
     *
Denotes a variant type with a length that is unknown to HPSF yet.

     */
    public static final Integer LENGTH_UNKNOWN = Integer.valueOf(-2);

    /**
     *
Denotes a variant type with a variable length.

     */
    public static final Integer LENGTH_VARIABLE = Integer.valueOf(-1);

    /**
     *
Denotes a variant type with a length of 0 bytes.

     */
    public static final Integer LENGTH_0 = Integer.valueOf(0);

    /**
     *
Denotes a variant type with a length of 2 bytes.

     */
    public static final Integer LENGTH_2 = Integer.valueOf(2);

    /**
     *
Denotes a variant type with a length of 4 bytes.

     */
    public static final Integer LENGTH_4 = Integer.valueOf(4);

    /**
     *
Denotes a variant type with a length of 8 bytes.

     */
    public static final Integer LENGTH_8 = Integer.valueOf(8);

    static
    {
        /* Initialize the number-to-name map: */
        Map tm1 = new HashMap();
        tm1.put(Long.valueOf(0), "VT_EMPTY");
        tm1.put(Long.valueOf(1), "VT_NULL");
        tm1.put(Long.valueOf(2), "VT_I2");
        tm1.put(Long.valueOf(3), "VT_I4");
        tm1.put(Long.valueOf(4), "VT_R4");
        tm1.put(Long.valueOf(5), "VT_R8");
        tm1.put(Long.valueOf(6), "VT_CY");
        tm1.put(Long.valueOf(7), "VT_DATE");
        tm1.put(Long.valueOf(8), "VT_BSTR");
        tm1.put(Long.valueOf(9), "VT_DISPATCH");
        tm1.put(Long.valueOf(10), "VT_ERROR");
        tm1.put(Long.valueOf(11), "VT_BOOL");
        tm1.put(Long.valueOf(12), "VT_VARIANT");
        tm1.put(Long.valueOf(13), "VT_UNKNOWN");
        tm1.put(Long.valueOf(14), "VT_DECIMAL");
        tm1.put(Long.valueOf(16), "VT_I1");
        tm1.put(Long.valueOf(17), "VT_UI1");
        tm1.put(Long.valueOf(18), "VT_UI2");
        tm1.put(Long.valueOf(19), "VT_UI4");
        tm1.put(Long.valueOf(20), "VT_I8");
        tm1.put(Long.valueOf(21), "VT_UI8");
        tm1.put(Long.valueOf(22), "VT_INT");
        tm1.put(Long.valueOf(23), "VT_UINT");
        tm1.put(Long.valueOf(24), "VT_VOID");
        tm1.put(Long.valueOf(25), "VT_HRESULT");
        tm1.put(Long.valueOf(26), "VT_PTR");
        tm1.put(Long.valueOf(27), "VT_SAFEARRAY");
        tm1.put(Long.valueOf(28), "VT_CARRAY");
        tm1.put(Long.valueOf(29), "VT_USERDEFINED");
        tm1.put(Long.valueOf(30), "VT_LPSTR");
        tm1.put(Long.valueOf(31), "VT_LPWSTR");
        tm1.put(Long.valueOf(64), "VT_FILETIME");
        tm1.put(Long.valueOf(65), "VT_BLOB");
        tm1.put(Long.valueOf(66), "VT_STREAM");
        tm1.put(Long.valueOf(67), "VT_STORAGE");
        tm1.put(Long.valueOf(68), "VT_STREAMED_OBJECT");
        tm1.put(Long.valueOf(69), "VT_STORED_OBJECT");
        tm1.put(Long.valueOf(70), "VT_BLOB_OBJECT");
        tm1.put(Long.valueOf(71), "VT_CF");
        tm1.put(Long.valueOf(72), "VT_CLSID");
        Map tm2 = new HashMap(tm1.size(), 1.0F);
        tm2.putAll(tm1);
        numberToName = Collections.unmodifiableMap(tm2);

        /* Initialize the number-to-length map: */
        tm1.clear();
        tm1.put(Long.valueOf(0), LENGTH_0);
        tm1.put(Long.valueOf(1), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(2), LENGTH_2);
        tm1.put(Long.valueOf(3), LENGTH_4);
        tm1.put(Long.valueOf(4), LENGTH_4);
        tm1.put(Long.valueOf(5), LENGTH_8);
        tm1.put(Long.valueOf(6), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(7), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(8), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(9), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(10), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(11), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(12), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(13), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(14), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(16), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(17), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(18), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(19), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(20), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(21), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(22), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(23), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(24), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(25), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(26), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(27), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(28), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(29), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(30), LENGTH_VARIABLE);
        tm1.put(Long.valueOf(31), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(64), LENGTH_8);
        tm1.put(Long.valueOf(65), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(66), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(67), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(68), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(69), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(70), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(71), LENGTH_UNKNOWN);
        tm1.put(Long.valueOf(72), LENGTH_UNKNOWN);
        tm2 = new HashMap(tm1.size(), 1.0F);
        tm2.putAll(tm1);
        numberToLength = Collections.unmodifiableMap(tm2);
    }

    /**
     *
Returns the variant type name associated with a variant type
     * number.

     *
     * @param variantType The variant type number
     * @return The variant type name or the string "unknown variant type"
     */
    public static String getVariantName(final long variantType)
    {
        final String name = (String) numberToName.get(Long.valueOf(variantType));
        return name != null ? name : "unknown variant type";
    }

    /**
     *
Returns a variant type's length.

     *
     * @param variantType The variant type number
     * @return The length of the variant type's data in bytes. If the length is
     * variable, i.e. the length of a string, -1 is returned. If HPSF does not
     * know the length, -2 is returned. The latter usually indicates an
     * unsupported variant type.
     */
    public static int getVariantLength(final long variantType)
    {
        final Long key = Long.valueOf((int) variantType);
        final Long length = (Long) numberToLength.get(key);
        if (length == null)
            return -2;
        return length.intValue();
    }

}


text:
package genericapiserver

import (
	"crypto/tls"
	"encoding/pem"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"regexp"
	goruntime "runtime"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/go-openapi/spec"
	"github.com/golang/glog"
	"github.com/pborman/uuid"
	"gopkg.in/natefinch/lumberjack.v2"

	"k8s.io/kubernetes/pkg/admission"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
	apiserverauthenticator "k8s.io/kubernetes/pkg/apiserver/authenticator"
	apiserverfilters "k8s.io/kubernetes/pkg/apiserver/filters"
	apiserveropenapi "k8s.io/kubernetes/pkg/apiserver/openapi"
	"k8s.io/kubernetes/pkg/apiserver/request"
	"k8s.io/kubernetes/pkg/auth/authenticator"
	"k8s.io/kubernetes/pkg/auth/authorizer"
	authorizerunion "k8s.io/kubernetes/pkg/auth/authorizer/union"
	authhandlers "k8s.io/kubernetes/pkg/auth/handlers"
	"k8s.io/kubernetes/pkg/auth/user"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/cloudprovider"
	apiserverauthorizer "k8s.io/kubernetes/pkg/genericapiserver/authorizer"
	genericfilters "k8s.io/kubernetes/pkg/genericapiserver/filters"
	"k8s.io/kubernetes/pkg/genericapiserver/mux"
	"k8s.io/kubernetes/pkg/genericapiserver/openapi/common"
	"k8s.io/kubernetes/pkg/genericapiserver/options"
	"k8s.io/kubernetes/pkg/genericapiserver/routes"
	genericvalidation "k8s.io/kubernetes/pkg/genericapiserver/validation"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/sets"
	"k8s.io/kubernetes/pkg/version"
	authenticatorunion "k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union"
)

const (
	// DefaultLegacyAPIPrefix is where the the legacy APIs will be located.
	DefaultLegacyAPIPrefix = "/api"

	// APIGroupPrefix is where non-legacy API group will be located.
	APIGroupPrefix = "/apis"
)

// Config is a structure used to configure a GenericAPIServer.
type Config struct {
	// Destination for audit logs
	AuditWriter io.Writer
	// Allow downstream consumers to disable swagger.
	// This includes returning the generated swagger spec at /swaggerapi and swagger ui at /swagger-ui.
	EnableSwaggerSupport bool
	// Allow downstream consumers to disable swagger ui.
	// Note that this is ignored if EnableSwaggerSupport is false
	EnableSwaggerUI bool
	// Allows api group versions or specific resources to be conditionally enabled/disabled.
	APIResourceConfigSource APIResourceConfigSource
	// allow downstream consumers to disable the index route
	EnableIndex     bool
	EnableProfiling bool
	// Requires generic profiling enabled
	EnableContentionProfiling bool
	EnableMetrics             bool
	EnableGarbageCollection   bool

	Version               *version.Info
	CorsAllowedOriginList []string
	Authenticator         authenticator.Request
	// TODO(roberthbailey): Remove once the server no longer supports http basic auth.
	SupportsBasicAuth bool
	Authorizer        authorizer.Authorizer
	AdmissionControl  admission.Interface
	// TODO(ericchiang): Determine if policy escalation checks should be an admission controller.
	AuthorizerRBACSuperUser string

	// LoopbackClientConfig is a config for a privileged loopback connection to the API server
	LoopbackClientConfig *restclient.Config

	// Map requests to contexts. Exported so downstream consumers can provider their own mappers
	RequestContextMapper api.RequestContextMapper

	// Required, the interface for serializing and converting objects to and from the wire
	Serializer runtime.NegotiatedSerializer

	// If specified, requests will be allocated a random timeout between this value, and twice this value.
	// Note that it is up to the request handlers to ignore or honor this timeout. In seconds.
	MinRequestTimeout int

	SecureServingInfo   *SecureServingInfo
	InsecureServingInfo *ServingInfo

	// DiscoveryAddresses is used to build the IPs pass to discovery.  If nil, the ExternalAddress is
	// always reported
	DiscoveryAddresses DiscoveryAddresses

	// The port on PublicAddress where a read-write server will be installed.
	// Defaults to 6443 if not set.
	ReadWritePort int

	// ExternalAddress is the host name to use for external (public internet) facing URLs (e.g. Swagger)
	ExternalAddress string

	// PublicAddress is the IP address where members of the cluster (kubelet,
	// kube-proxy, services, etc.) can reach the GenericAPIServer.
	// If nil or 0.0.0.0, the host's default interface will be used.
	PublicAddress net.IP

	// EnableOpenAPISupport enables OpenAPI support. Allow downstream customers to disable OpenAPI spec.
	EnableOpenAPISupport bool

	// OpenAPIConfig will be used in generating OpenAPI spec.
	OpenAPIConfig *common.Config

	// MaxRequestsInFlight is the maximum number of parallel non-long-running requests. Every further
	// request has to wait. Applies only to non-mutating requests.
	MaxRequestsInFlight int
	// MaxMutatingRequestsInFlight is the maximum number of parallel mutating requests. Every further
	// request has to wait.
	MaxMutatingRequestsInFlight int

	// Predicate which is true for paths of long-running http requests
	LongRunningFunc genericfilters.LongRunningRequestCheck

	// Build the handler chains by decorating the apiHandler.
	BuildHandlerChainsFunc func(apiHandler http.Handler, c *Config) (secure, insecure http.Handler)

	// LegacyAPIGroupPrefixes is used to set up URL parsing for authorization and for validating requests
	// to InstallLegacyAPIGroup
	LegacyAPIGroupPrefixes sets.String
}

type ServingInfo struct {
	// BindAddress is the ip:port to serve on
	BindAddress string
	// BindNetwork is the type of network to bind to - defaults to "tcp", accepts "tcp",
	// "tcp4", and "tcp6".
	BindNetwork string
}

type SecureServingInfo struct {
	ServingInfo

	// Cert is the main server cert which is used if SNI does not match. Cert must be non-nil and is
	// allowed to be in SNICerts.
	Cert *tls.Certificate

	// CACert is an optional certificate authority used for the loopback connection of the Admission controllers.
	// If this is nil, the certificate authority is extracted from Cert or a matching SNI certificate.
	CACert *tls.Certificate

	// SNICerts are the TLS certificates by name used for SNI.
	SNICerts map[string]*tls.Certificate

	// ClientCA is the certificate bundle for all the signers that you'll recognize for incoming client certificates
	ClientCA string
}

// NewConfig returns a Config struct with the default values
func NewConfig() *Config {
	longRunningRE := regexp.MustCompile(options.DefaultLongRunningRequestRE)

	config := &Config{
		Serializer:             api.Codecs,
		ReadWritePort:          6443,
		RequestContextMapper:   api.NewRequestContextMapper(),
		BuildHandlerChainsFunc: DefaultBuildHandlerChain,
		LegacyAPIGroupPrefixes: sets.NewString(DefaultLegacyAPIPrefix),

		EnableIndex:          true,
		EnableSwaggerSupport: true,
		OpenAPIConfig: &common.Config{
			ProtocolList:   []string{"https"},
			IgnorePrefixes: []string{"/swaggerapi"},
			Info: &spec.Info{
				InfoProps: spec.InfoProps{
					Title:   "Generic API Server",
					Version: "unversioned",
				},
			},
			DefaultResponse: &spec.Response{
				ResponseProps: spec.ResponseProps{
					Description: "Default Response.",
				},
			},
			GetOperationIDAndTags: apiserveropenapi.GetOperationIDAndTags,
		},
		LongRunningFunc: genericfilters.BasicLongRunningRequestCheck(longRunningRE, map[string]string{"watch": "true"}),
	}

	// this keeps the defaults in sync
	defaultOptions := options.NewServerRunOptions()
	// unset fields that can be overridden to avoid setting values so that we won't end up with lingering values.
	// TODO we probably want to run the defaults the other way.  A default here drives it in the CLI flags
	defaultOptions.AuditLogPath = ""
	return config.ApplyOptions(defaultOptions)
}

func (c *Config) ApplySecureServingOptions(secureServing *options.SecureServingOptions) (*Config, error) {
	if secureServing == nil || secureServing.ServingOptions.BindPort <= 0 {
		return c, nil
	}

	secureServingInfo := &SecureServingInfo{
		ServingInfo: ServingInfo{
			BindAddress: net.JoinHostPort(secureServing.ServingOptions.BindAddress.String(), strconv.Itoa(secureServing.ServingOptions.BindPort)),
		},
		ClientCA: secureServing.ClientCA,
	}

	serverCertFile, serverKeyFile := secureServing.ServerCert.CertKey.CertFile, secureServing.ServerCert.CertKey.KeyFile

	// load main cert
	if len(serverCertFile) != 0 || len(serverKeyFile) != 0 {
		tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
		if err != nil {
			return nil, fmt.Errorf("unable to load server certificate: %v", err)
		}
		secureServingInfo.Cert = &tlsCert
	}

	// optionally load CA cert
	if len(secureServing.ServerCert.CACertFile) != 0 {
		pemData, err := ioutil.ReadFile(secureServing.ServerCert.CACertFile)
		if err != nil {
			return nil, fmt.Errorf("failed to read certificate authority from %q: %v", secureServing.ServerCert.CACertFile, err)
		}
		block, pemData := pem.Decode(pemData)
		if block == nil {
			return nil, fmt.Errorf("no certificate found in certificate authority file %q", secureServing.ServerCert.CACertFile)
		}
		if block.Type != "CERTIFICATE" {
			return nil, fmt.Errorf("expected CERTIFICATE block in certiticate authority file %q, found: %s", secureServing.ServerCert.CACertFile, block.Type)
		}
		secureServingInfo.CACert = &tls.Certificate{
			Certificate: [][]byte{block.Bytes},
		}
	}

	// load SNI certs
	namedTlsCerts := make([]namedTlsCert, 0, len(secureServing.SNICertKeys))
	for _, nck := range secureServing.SNICertKeys {
		tlsCert, err := tls.LoadX509KeyPair(nck.CertFile, nck.KeyFile)
		namedTlsCerts = append(namedTlsCerts, namedTlsCert{
			tlsCert: tlsCert,
			names:   nck.Names,
		})
		if err != nil {
			return nil, fmt.Errorf("failed to load SNI cert and key: %v", err)
		}
	}
	var err error
	secureServingInfo.SNICerts, err = getNamedCertificateMap(namedTlsCerts)
	if err != nil {
		return nil, err
	}

	c.SecureServingInfo = secureServingInfo
	c.ReadWritePort = secureServing.ServingOptions.BindPort

	return c, nil
}

func (c *Config) ApplyInsecureServingOptions(insecureServing *options.ServingOptions) *Config {
	if insecureServing == nil || insecureServing.BindPort <= 0 {
		return c
	}

	c.InsecureServingInfo = &ServingInfo{
		BindAddress: net.JoinHostPort(insecureServing.BindAddress.String(), strconv.Itoa(insecureServing.BindPort)),
	}

	return c
}

func (c *Config) ApplyAuthenticationOptions(o *options.BuiltInAuthenticationOptions) *Config {
	if o == nil || o.PasswordFile == nil {
		return c
	}

	c.SupportsBasicAuth = len(o.PasswordFile.BasicAuthFile) > 0
	return c
}

func (c *Config) ApplyRBACSuperUser(rbacSuperUser string) *Config {
	c.AuthorizerRBACSuperUser = rbacSuperUser
	return c
}

// ApplyOptions applies the run options to the method receiver and returns self
func (c *Config) ApplyOptions(options *options.ServerRunOptions) *Config {
	if len(options.AuditLogPath) != 0 {
		c.AuditWriter = &lumberjack.Logger{
			Filename:   options.AuditLogPath,
			MaxAge:     options.AuditLogMaxAge,
			MaxBackups: options.AuditLogMaxBackups,
			MaxSize:    options.AuditLogMaxSize,
		}
	}

	c.CorsAllowedOriginList = options.CorsAllowedOriginList
	c.EnableGarbageCollection = options.EnableGarbageCollection
	c.EnableProfiling = options.EnableProfiling
	c.EnableContentionProfiling = options.EnableContentionProfiling
	c.EnableSwaggerUI = options.EnableSwaggerUI
	c.ExternalAddress = options.ExternalHost
	c.MaxRequestsInFlight = options.MaxRequestsInFlight
	c.MaxMutatingRequestsInFlight = options.MaxMutatingRequestsInFlight
	c.MinRequestTimeout = options.MinRequestTimeout
	c.PublicAddress = options.AdvertiseAddress

	return c
}

type completedConfig struct {
	*Config
}

// Complete fills in any fields not set that are required to have valid data and can be derived
// from other fields.  If you're going to `ApplyOptions`, do that first.  It's mutating the receiver.
func (c *Config) Complete() completedConfig {
	if len(c.ExternalAddress) == 0 && c.PublicAddress != nil {
		hostAndPort := c.PublicAddress.String()
		if c.ReadWritePort != 0 {
			hostAndPort = net.JoinHostPort(hostAndPort, strconv.Itoa(c.ReadWritePort))
		}
		c.ExternalAddress = hostAndPort
	}
	// All APIs will have the same authentication for now.
	if c.OpenAPIConfig != nil && c.OpenAPIConfig.SecurityDefinitions != nil {
		c.OpenAPIConfig.DefaultSecurity = []map[string][]string{}
		keys := []string{}
		for k := range *c.OpenAPIConfig.SecurityDefinitions {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			c.OpenAPIConfig.DefaultSecurity = append(c.OpenAPIConfig.DefaultSecurity, map[string][]string{k: {}})
		}
		if c.OpenAPIConfig.CommonResponses == nil {
			c.OpenAPIConfig.CommonResponses = map[int]spec.Response{}
		}
		if _, exists := c.OpenAPIConfig.CommonResponses[http.StatusUnauthorized]; !exists {
			c.OpenAPIConfig.CommonResponses[http.StatusUnauthorized] = spec.Response{
				ResponseProps: spec.ResponseProps{
					Description: "Unauthorized",
				},
			}
		}
	}
	if c.DiscoveryAddresses == nil {
		c.DiscoveryAddresses = DefaultDiscoveryAddresses{DefaultAddress: c.ExternalAddress}
	}

	// If the loopbackclientconfig is specified AND it has a token for use against the API server
	// wrap the authenticator and authorizer in loopback authentication logic
	if c.Authenticator != nil && c.Authorizer != nil && c.LoopbackClientConfig != nil && len(c.LoopbackClientConfig.BearerToken) > 0 {
		privilegedLoopbackToken := c.LoopbackClientConfig.BearerToken
		var uid = uuid.NewRandom().String()
		tokens := make(map[string]*user.DefaultInfo)
		tokens[privilegedLoopbackToken] = &user.DefaultInfo{
			Name:   user.APIServerUser,
			UID:    uid,
			Groups: []string{user.SystemPrivilegedGroup},
		}

		tokenAuthenticator := apiserverauthenticator.NewAuthenticatorFromTokens(tokens)
		c.Authenticator = authenticatorunion.New(tokenAuthenticator, c.Authenticator)

		tokenAuthorizer := apiserverauthorizer.NewPrivilegedGroups(user.SystemPrivilegedGroup)
		c.Authorizer = authorizerunion.New(tokenAuthorizer, c.Authorizer)
	}

	return completedConfig{c}
}

// SkipComplete provides a way to construct a server instance without config completion.
func (c *Config) SkipComplete() completedConfig {
	return completedConfig{c}
}

// New returns a new instance of GenericAPIServer from the given config.
// Certain config fields will be set to a default value if unset,
// including:
//   ServiceClusterIPRange
//   ServiceNodePortRange
//   MasterCount
//   ReadWritePort
//   PublicAddress
// Public fields:
//   Handler -- The returned GenericAPIServer has a field TopHandler which is an
//   http.Handler which handles all the endpoints provided by the GenericAPIServer,
//   including the API, the UI, and miscellaneous debugging endpoints.  All
//   these are subject to authorization and authentication.
//   InsecureHandler -- an http.Handler which handles all the same
//   endpoints as Handler, but no authorization and authentication is done.
// Public methods:
//   HandleWithAuth -- Allows caller to add an http.Handler for an endpoint
//   that uses the same authentication and authorization (if any is configured)
//   as the GenericAPIServer's built-in endpoints.
//   If the caller wants to add additional endpoints not using the GenericAPIServer's
//   auth, then the caller should create a handler for those endpoints, which delegates the
//   any unhandled paths to "Handler".
func (c completedConfig) New() (*GenericAPIServer, error) {
	if c.Serializer == nil {
		return nil, fmt.Errorf("Genericapiserver.New() called with config.Serializer == nil")
	}

	s := &GenericAPIServer{
		discoveryAddresses:     c.DiscoveryAddresses,
		LoopbackClientConfig:   c.LoopbackClientConfig,
		legacyAPIGroupPrefixes: c.LegacyAPIGroupPrefixes,
		admissionControl:       c.AdmissionControl,
		requestContextMapper:   c.RequestContextMapper,
		Serializer:             c.Serializer,

		minRequestTimeout:    time.Duration(c.MinRequestTimeout) * time.Second,
		enableSwaggerSupport: c.EnableSwaggerSupport,

		SecureServingInfo:   c.SecureServingInfo,
		InsecureServingInfo: c.InsecureServingInfo,
		ExternalAddress:     c.ExternalAddress,

		apiGroupsForDiscovery: map[string]metav1.APIGroup{},

		enableOpenAPISupport: c.EnableOpenAPISupport,
		openAPIConfig:        c.OpenAPIConfig,

		postStartHooks: map[string]postStartHookEntry{},
	}

	s.HandlerContainer = mux.NewAPIContainer(http.NewServeMux(), c.Serializer)

	s.installAPI(c.Config)

	s.Handler, s.InsecureHandler = c.BuildHandlerChainsFunc(s.HandlerContainer.ServeMux, c.Config)

	return s, nil
}

func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) (secure, insecure http.Handler) {
	generic := func(handler http.Handler) http.Handler {
		handler = genericfilters.WithCORS(handler, c.CorsAllowedOriginList, nil, nil, nil, "true")
		handler = genericfilters.WithPanicRecovery(handler, c.RequestContextMapper)
		handler = genericfilters.WithTimeoutForNonLongRunningRequests(handler, c.LongRunningFunc)
		handler = genericfilters.WithMaxInFlightLimit(handler, c.MaxRequestsInFlight, c.MaxMutatingRequestsInFlight, c.RequestContextMapper, c.LongRunningFunc)
		handler = apiserverfilters.WithRequestInfo(handler, NewRequestInfoResolver(c), c.RequestContextMapper)
		handler = api.WithRequestContext(handler, c.RequestContextMapper)
		return handler
	}
	audit := func(handler http.Handler) http.Handler {
		return apiserverfilters.WithAudit(handler, c.RequestContextMapper, c.AuditWriter)
	}
	protect := func(handler http.Handler) http.Handler {
		handler = apiserverfilters.WithAuthorization(handler, c.RequestContextMapper, c.Authorizer)
		handler = apiserverfilters.WithImpersonation(handler, c.RequestContextMapper, c.Authorizer)
		handler = audit(handler) // before impersonation to read original user
		handler = authhandlers.WithAuthentication(handler, c.RequestContextMapper, c.Authenticator, authhandlers.Unauthorized(c.SupportsBasicAuth))
		return handler
	}

	return generic(protect(apiHandler)), generic(audit(apiHandler))
}

func (s *GenericAPIServer) installAPI(c *Config) {
	if c.EnableIndex {
		routes.Index{}.Install(s.HandlerContainer)
	}
	if c.EnableSwaggerSupport && c.EnableSwaggerUI {
		routes.SwaggerUI{}.Install(s.HandlerContainer)
	}
	if c.EnableProfiling {
		routes.Profiling{}.Install(s.HandlerContainer)
		if c.EnableContentionProfiling {
			goruntime.SetBlockProfileRate(1)
		}
	}
	if c.EnableMetrics {
		if c.EnableProfiling {
			routes.MetricsWithReset{}.Install(s.HandlerContainer)
		} else {
			routes.DefaultMetrics{}.Install(s.HandlerContainer)
		}
	}
	routes.Version{Version: c.Version}.Install(s.HandlerContainer)
	s.HandlerContainer.Add(s.DynamicApisDiscovery())
}

func DefaultAndValidateRunOptions(options *options.ServerRunOptions) {
	genericvalidation.ValidateRunOptions(options)

	glog.Infof("Will report %v as public IP address.", options.AdvertiseAddress)

	// Set default value for ExternalAddress if not specified.
	if len(options.ExternalHost) == 0 {
		// TODO: extend for other providers
		if options.CloudProvider == "gce" || options.CloudProvider == "aws" {
			cloud, err := cloudprovider.InitCloudProvider(options.CloudProvider, options.CloudConfigFile)
			if err != nil {
				glog.Fatalf("Cloud provider could not be initialized: %v", err)
			}
			instances, supported := cloud.Instances()
			if !supported {
				glog.Fatalf("%q cloud provider has no instances.  this shouldn't happen. exiting.", options.CloudProvider)
			}
			hostname, err := os.Hostname()
			if err != nil {
				glog.Fatalf("Failed to get hostname: %v", err)
			}
			nodeName, err := instances.CurrentNodeName(hostname)
			if err != nil {
				glog.Fatalf("Failed to get NodeName: %v", err)
			}
			addrs, err := instances.NodeAddresses(nodeName)
			if err != nil {
				glog.Warningf("Unable to obtain external host address from cloud provider: %v", err)
			} else {
				for _, addr := range addrs {
					if addr.Type == v1.NodeExternalIP {
						options.ExternalHost = addr.Address
					}
				}
			}
		}
	}
}

func NewRequestInfoResolver(c *Config) *request.RequestInfoFactory {
	apiPrefixes := sets.NewString(strings.Trim(APIGroupPrefix, "/")) // all possible API prefixes
	legacyAPIPrefixes := sets.String{}                               // APIPrefixes that won't have groups (legacy)
	for legacyAPIPrefix := range c.LegacyAPIGroupPrefixes {
		apiPrefixes.Insert(strings.Trim(legacyAPIPrefix, "/"))
		legacyAPIPrefixes.Insert(strings.Trim(legacyAPIPrefix, "/"))
	}

	return &request.RequestInfoFactory{
		APIPrefixes:          apiPrefixes,
		GrouplessAPIPrefixes: legacyAPIPrefixes,
	}
}


text:
The `c1d3r` guide is built using the [Polymer](https://www.polymer-project.org/) application framework. This framework makes it easy to use the latest web technologies in a way that is portable and actually enjoyable to code.

This project relatively small size and clear focus makes it an excellent introduction to the Polymer framework. You should be up and running in no time.

# Prerequisite
Here are the tools and technologies needed to locally deploy `c1d3r`. Be aware that the commands will be run from a command line utility.

1. Install [Git](https://git-scm.com/downloads)
1. Install [Node.js](https://nodejs.org/en/download/) LTS version.
1. Install the latest version of Bower.

    npm install -g bower

1. Install Polymer CLI.

    npm install -g polymer-cli

### Updating libraries

Each time the guide is deployed, it's library should first be updated. The command to deploy the application locally will **not** perform a verification of library update status. Missing library will most of the time result in either weird behavior or an empty page. The libraries are updated by going to the root of the referential and running ``npm install`` and ``bower install``.

### Serving C1d3r

The `c1d3r` guide is now fully deployed using the Polymer CLI tools. It means that ``polymer serve`` is the only command needed for most situations. The command will output the full URL which can be used to access the application running locally.

## Running Tests

At this point, our regression testing suite is just a placeholder, but please do always run ``wct -l chrome`` to be warned if any of our tested assumptions are broken. Each developer is expected to run this before committing.

## Building and Deploying

Publishing the `c1d3r` application is a two step process. We first use the Polymer-cli project to analyse and minify our sources and dependencies using : ``gulp build``.

Then we can deploy our project on the web, by pushing these changes to the **gh-pages** branch of the repository. By doing so, we are making GitHub update our project page which is hosting the web accessible version of the application. This is done using : ``gulp deploy``.


text:
  <title>cf-pingdom</title>

  {{> authorize }}

  {{> apps}}

<template name="apps">

  {{#each result}}

    {{entity.name}}

    {{entity.state}}

  {{/each}}

</template>

<template name="authorize">
  <form class="auth-form">
    CF API server
      <input type="text" name="api" placeholder="api.cf-app.com" value="{{settings.api}}"/>

    Username
      <input type="text" name="username" placeholder="admin" value="{{settings.username}}" />

    Password
      <input type="password" name="password" placeholder="admin" value="{{settings.password}}" />

    <button type="submit">Submit</button>
  </form>
</template>