/*
UnivNautes
Copyright (C) 2014  Entr'ouvert

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function univnautes(bounds) {

    var redirectTimeout;
    var refreshMarkersTimeout;
    var redirectLink = '';
    var searchinput = $('input#search');

    var start_center = [46.5, 2.5];
    if (bounds) {
        var start_lat = (bounds[0][0] + bounds[1][0])/2;
        var start_lon = (bounds[0][1] + bounds[1][1])/2;
        start_center = [start_lat, start_lon];
    }

    var map = L.map('map', {
            center: start_center,
            zoom: 6,
            maxZoom: 16
    });
    L.tileLayer('/map/{z}/{x}/{y}.png').addTo(map);
    L.control.scale( { 'imperial': false, 'updateWhenIdle': true } ).addTo(map);

    map.attributionControl.setPrefix('');
    map.attributionControl.addAttribution('');

    var markers = new L.MarkerClusterGroup({
        spiderfyOnMaxZoom: true,
        showCoverageOnHover: false,
        zoomToBoundsOnClick: true,
        animateAddingMarkers: false,
        disableClusteringAtZoom: 50,
        maxClusterRadius: 25,
        spiderfyDistanceMultiplier: 3,
        singleMarkerMode: true,
    });

    /*
    geoinfos = [ {
        "entityid": "https://shib-idp-1.oru.se/idp/shibboleth", 
        "geo": [ [ 59.7065, 14.5473 ], [ 59.2547, 15.2485 ] ],
        "slug": "orebro-universitet"
    }, ... ]
    */

    function refreshMarkers() {
        var searchValue = searchinput.val().toLowerCase();
        var new_markers = new Array();
        for (var i=geoinfos.length-1; i>=0; i--) {
            var geoinfo = geoinfos[i];
            var slug = geoinfo['slug'];
            var listitem = $('#idp-' + slug);
            var name = geoinfo['name'];
            var entityid = geoinfo['entityid'];
            var geo = geoinfo['geo'];
            if (searchValue.length > 2) {
                if (name.toLowerCase().indexOf(searchValue) < 0) {
                    listitem.hide();
                    listitem.addClass('hidden');
                    continue;
                }
            } else {
                var show=false;
                for (var j=geo.length-1; j>=0; j--)
                    if (map.getBounds().contains(geo[j]))
                        show=true;
                if (!show) {
                    listitem.hide();
                    listitem.addClass('hidden');
                    continue;
                }
            }
            listitem.show();
            for (var j=geo.length-1; j>=0; j--) {
                var marker = new L.Marker(geo[j], {
                                    title: name,
                                    icon: new L.DivIcon({
                                        html: '<div><span></span></div>',
                                        className: 'marker-cluster marker-cluster-one',
                                        iconSize: new L.Point(40, 40) 
                                    })
                             });
                marker.entityid = entityid;
                marker.bindPopup('<p>' + name + '</p><p align="center"><a href="/authsaml2/sso?entity_id=' + entityid + '"><button class="connexion">Connexion</button></a></p>');
                new_markers.push(marker);
            }
        }
        markers.clearLayers();
        markers.addLayers(new_markers);
    }

    function delayRefresh(e) {
        clearTimeout(refreshMarkersTimeout);
        refreshMarkersTimeout = setTimeout(refreshMarkers, 500);
    }

    if (bounds) {
        map.fitBounds(bounds);
    }

    map.addLayer(markers);
    refreshMarkers();
    map.on('moveend', delayRefresh);

    searchinput.on('keyup webkitspeechchange speechchange', delayRefresh);

}
