<commit_before>/*global $, Modernizr, Handlebars, google */

String.prototype.repeat = function(num) {
    return new Array(num+1).join(this);
};

/* Maps map-canvas divs to google map objects */
var canvas_to_map = {};

/* The next appointments as a list */
var appointments = [];

/* Maps jumboroute divs to route data */
var jumboroute_to_route = {};

/* One Google Maps infoWindow instance for showing info on route stops */
var infowindow;

/* The object that the infowindow is currently opened for (e.g. a marker) */
var infowindowtrigger;

var Neverlate = {
    templates: {},
    API_CREDS: "&user=neverlate&pass=<PASSWORD>",
    COORD_FORMAT: "&epsg_in=wgs84&epsg_out=wgs84",
    DETAIL_LEVEL: "&detail=full",
    CORS: "http://www.corsproxy.com/"
};

//Load handlebar templates
$(function () {
    $(document.createElement("div")).load(
        "/static/handlebars-templates.html",
        function () {
            $(this).find("script").each(function (i, e) {
                Neverlate.templates[e.id] = e.innerHTML;
            });
        }
    );
});

Handlebars.registerHelper('times', function(n, block) {
    var accum = '';
    for(var i = 0; i < n; ++i)
        accum += block.fn(i);
    return accum;
});

/*
 * Generates a unique hash for an arbitrary object
*/
function hash(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
}
hash.current = 0;

Neverlate.getCurrentGeolocation = function() {
    function printCoords(location) {
        Neverlate.userCoords = location.coords;
    }
    if (Modernizr.geolocation) {
    navigator.geolocation.getCurrentPosition(printCoords);
  } else {
    console.log("no geolocation support");
  }
};

/*
 * Initializes the dashboard page
*/
Neverlate.initialize = function() {
    Neverlate.getCurrentGeolocation(); //Get user location from browser is possible
    console.log(Neverlate.loadAppointments());

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src  = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAoHieetxNcdqJ4PDij87fi2KH8tOhMK2Y&sensor=true&callback=gmap_loaded";
    $("head").append(s);
    window.gmap_loaded = function(){
        $(".map-canvas").each(function() {
            Neverlate.createMap($(this)[0]);
        });

        Neverlate.updateDashboardState();
    };
};

Neverlate.loadAppointments = function() {
    //Neverlate.getCurrentGeolocation(); //test
    console.log("Loading user appointments");
    var url= "/appointments";
    return $.get(url);
}

/*
 * Create a map, but don't do anything else with it yet.
*/
Neverlate.createMap = function(map_canvas) {
    console.log("drawed a map");
    var mapOptions = { // just some initial values until real data is available
        center: new google.maps.LatLng(60.188549397729, 24.833913340551),
        zoom: Neverlate.mapZoom(10)
    };
    canvas_to_map[hash(map_canvas)] = new google.maps.Map(map_canvas, mapOptions);; // store the map for later access
}

/*
 * Finds the coordinates for the given addresses using Reittiopas API
 * and calls loadRouteByCoordinate to get the actual route data and display it to the user.
*/
Neverlate.loadRouteByAddress = function(point1, point2, jumboroute, arrival, appointmentIndex) {
    var point1json = null;
    var point2json = null;

    $(document).ready(function () {
        var N = Neverlate; // faste to type
        var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;
        console.log("loading geocode")
        $.get(
            url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key="+point1+queryOptions,
            succes = function(response) {
            console.log("GOT RESPONSE FRON REITTIOPAS");
            point1json = JSON.parse(response);
            if (point2json != null) { // this in made in pieces because either call can finish first
                Neverlate.loadRouteByCoordinate(point1json[0]["coords"],point2json[0]["coords"],
                  jumboroute, arrival, appointmentIndex);
            }
        });
        $.get(
            url = N.CORS + "api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key=" + point2 + queryOptions,
                success = function (response) {
                    console.log("GOT RESPONSE FRON REITTIOPAS");
                    point2json = JSON.parse(response);
                    if (point1json != null) {// this in made in pieces because either call can finish first
                        Neverlate.loadRouteByCoordinate(point1json[0]["coords"], point2json[0]["coords"],
                          jumboroute, arrival, appointmentIndex);
                    };
        });
    });
};

Neverlate.zeroPad = function(number, zeros){
    return ('0'.repeat(zeros)+number.toString()).slice(-zeros);
};

/*
 * Fetches a route from Reittiopas.
 * Stores the route data for later use and display it to the user.
*/
Neverlate.loadRouteByCoordinate = function (point1coords, point2coords, jumboroute, arrival, appointmentIndex) {
    var N = Neverlate; // faster to type
    var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;

    var arrivalOptions = "";
    if (arrival) {
        var date = N.zeroPad(arrival.getYear(), 4)+N.zeroPad(arrival.getMonth(),2)+N.zeroPad(arrival.getDate(),2);
        var time = N.zeroPad(arrival.getHours(), 2) + N.zeroPad(arrival.getMinutes(), 2);
        arrivalOptions = "&time=" + time + + "&date=" + date + "&timetype=arrival";
    }

    $.get(
        url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=route&format=json&from="
          +point1coords+"&to="+point2coords+"&callback=?"+queryOptions+arrivalOptions,
        succes = function(response) {
        console.log("GOT ROUTE FRON REITTIOPAS");
        var routes = JSON.parse(response)[0];
        jumboroute_to_route[hash(jumboroute)] = routes; // store the route for later access
        if (typeof(appointmentIndex) != "undefined") {
            Neverlate.updateRoutePanel(jumboroute, appointments[appointmentIndex].fields, routes[0]);
        }
        Neverlate.showRoute(routes[0], jumboroute); // TODO: choose which of the route options to show
    });
};

/*
 * Shows the given route option to the user
 */
Neverlate.showRoute = function(data, jumboroute){
    var map = canvas_to_map[hash($(jumboroute).find(".map-canvas")[0])];
    Neverlate.loadMap(map, data);
    // TODO: call a function to show also the route info outside of the map
};

/*
 * Updates the given jumboroute div to show the route option at the given index.
 * The index can be in the range [0,2] or [0,4] depending on how many routes
 * were fetched from Reittiopas.
 */
Neverlate.updateRoute = function(jumboroute, routeIndex) {
    var route = jumboroute_to_route[hash(jumboroute)][routeIndex];<commit_msg>Showroute also updates panel if appointmentIndex is given<commit_after>/*global $, Modernizr, Handlebars, google */

String.prototype.repeat = function(num) {
    return new Array(num+1).join(this);
};

/* Maps map-canvas divs to google map objects */
var canvas_to_map = {};

/* The next appointments as a list */
var appointments = [];

/* Maps jumboroute divs to route data */
var jumboroute_to_route = {};

/* One Google Maps infoWindow instance for showing info on route stops */
var infowindow;

/* The object that the infowindow is currently opened for (e.g. a marker) */
var infowindowtrigger;

var Neverlate = {
    templates: {},
    API_CREDS: "&user=neverlate&pass=<PASSWORD>",
    COORD_FORMAT: "&epsg_in=wgs84&epsg_out=wgs84",
    DETAIL_LEVEL: "&detail=full",
    CORS: "http://www.corsproxy.com/"
};

//Load handlebar templates
$(function () {
    $(document.createElement("div")).load(
        "/static/handlebars-templates.html",
        function () {
            $(this).find("script").each(function (i, e) {
                Neverlate.templates[e.id] = e.innerHTML;
            });
        }
    );
});

Handlebars.registerHelper('times', function(n, block) {
    var accum = '';
    for(var i = 0; i < n; ++i)
        accum += block.fn(i);
    return accum;
});

/*
 * Generates a unique hash for an arbitrary object
*/
function hash(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
}
hash.current = 0;

Neverlate.getCurrentGeolocation = function() {
    function printCoords(location) {
        Neverlate.userCoords = location.coords;
    }
    if (Modernizr.geolocation) {
    navigator.geolocation.getCurrentPosition(printCoords);
  } else {
    console.log("no geolocation support");
  }
};

/*
 * Initializes the dashboard page
*/
Neverlate.initialize = function() {
    Neverlate.getCurrentGeolocation(); //Get user location from browser is possible
    console.log(Neverlate.loadAppointments());

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src  = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAoHieetxNcdqJ4PDij87fi2KH8tOhMK2Y&sensor=true&callback=gmap_loaded";
    $("head").append(s);
    window.gmap_loaded = function(){
        $(".map-canvas").each(function() {
            Neverlate.createMap($(this)[0]);
        });

        Neverlate.updateDashboardState();
    };
};

Neverlate.loadAppointments = function() {
    //Neverlate.getCurrentGeolocation(); //test
    console.log("Loading user appointments");
    var url= "/appointments";
    return $.get(url);
}

/*
 * Create a map, but don't do anything else with it yet.
*/
Neverlate.createMap = function(map_canvas) {
    console.log("drawed a map");
    var mapOptions = { // just some initial values until real data is available
        center: new google.maps.LatLng(60.188549397729, 24.833913340551),
        zoom: Neverlate.mapZoom(10)
    };
    canvas_to_map[hash(map_canvas)] = new google.maps.Map(map_canvas, mapOptions);; // store the map for later access
}

/*
 * Finds the coordinates for the given addresses using Reittiopas API
 * and calls loadRouteByCoordinate to get the actual route data and display it to the user.
*/
Neverlate.loadRouteByAddress = function(point1, point2, jumboroute, arrival, appointmentIndex) {
    var point1json = null;
    var point2json = null;

    $(document).ready(function () {
        var N = Neverlate; // faste to type
        var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;
        console.log("loading geocode")
        $.get(
            url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key="+point1+queryOptions,
            succes = function(response) {
            console.log("GOT RESPONSE FRON REITTIOPAS");
            point1json = JSON.parse(response);
            if (point2json != null) { // this in made in pieces because either call can finish first
                Neverlate.loadRouteByCoordinate(point1json[0]["coords"],point2json[0]["coords"],
                  jumboroute, arrival, appointmentIndex);
            }
        });
        $.get(
            url = N.CORS + "api.reittiopas.fi/hsl/prod/?request=geocode&format=json&key=" + point2 + queryOptions,
                success = function (response) {
                    console.log("GOT RESPONSE FRON REITTIOPAS");
                    point2json = JSON.parse(response);
                    if (point1json != null) {// this in made in pieces because either call can finish first
                        Neverlate.loadRouteByCoordinate(point1json[0]["coords"], point2json[0]["coords"],
                          jumboroute, arrival, appointmentIndex);
                    };
        });
    });
};

Neverlate.zeroPad = function(number, zeros){
    return ('0'.repeat(zeros)+number.toString()).slice(-zeros);
};

/*
 * Fetches a route from Reittiopas.
 * Stores the route data for later use and display it to the user.
*/
Neverlate.loadRouteByCoordinate = function (point1coords, point2coords, jumboroute, arrival, appointmentIndex) {
    var N = Neverlate; // faster to type
    var queryOptions = N.API_CREDS +N.COORD_FORMAT+N.DETAIL_LEVEL;

    var arrivalOptions = "";
    if (arrival) {
        var date = N.zeroPad(arrival.getYear(), 4)+N.zeroPad(arrival.getMonth(),2)+N.zeroPad(arrival.getDate(),2);
        var time = N.zeroPad(arrival.getHours(), 2) + N.zeroPad(arrival.getMinutes(), 2);
        arrivalOptions = "&time=" + time + + "&date=" + date + "&timetype=arrival";
    }

    $.get(
        url = N.CORS+"api.reittiopas.fi/hsl/prod/?request=route&format=json&from="
          +point1coords+"&to="+point2coords+"&callback=?"+queryOptions+arrivalOptions,
        succes = function(response) {
        console.log("GOT ROUTE FRON REITTIOPAS");
        var routes = JSON.parse(response)[0];
        jumboroute_to_route[hash(jumboroute)] = routes; // store the route for later access
        Neverlate.showRoute(routes[0], jumboroute, appointmentIndex); // TODO: choose which of the route options to show
    });
};

/*
 * Shows the given route option to the user
 */
Neverlate.showRoute = function(data, jumboroute, appointmentIndex){
    var map = canvas_to_map[hash($(jumboroute).find(".map-canvas")[0])];
    Neverlate.loadMap(map, data);
    if (typeof(appointmentIndex) != "undefined") {
        Neverlate.updateRoutePanel(jumboroute, appointments[appointmentIndex].fields, data);
    }
};

/*
 * Updates the given jumboroute div to show the route option at the given index.
 * The index can be in the range [0,2] or [0,4] depending on how many routes
 * were fetched from Reittiopas.
 */
Neverlate.updateRoute = function(jumboroute, routeIndex) {
    var route = jumboroute_to_route[hash(jumboroute)][routeIndex];
{'fraction_non_alphanumeric': 0.13430219820346162, 'fraction_numerical': 0.011611772438472213, 'mean_word_length': 3.0889817856076442, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '790531', 'n_tokens_mistral': 4376, 'n_tokens_neox': 4261, 'n_words': 988}