$(function() {

var start_lat = (start_bounds[0][0] + start_bounds[1][0])/2;
var start_lon = (start_bounds[0][1] + start_bounds[1][1])/2;
var start_center = [start_lat, start_lon];

var redirectTimeout;
var refreshmarkersTimeout;
var redirectLink = '';
var mapstyle = 'cm-22677';
var searchinput = $('input#search');
var markers = new L.MarkerClusterGroup({
	spiderfyOnMaxZoom: true,
	showCoverageOnHover: false,
	zoomToBoundsOnClick: true,
	animateAddingMarkers: false,
	disableClusteringAtZoom: 50,
	maxClusterRadius: 25,
	spiderfyDistanceMultiplier: 3,
	singleMarkerMode: true,
});
var map = L.map('map', {
	center: start_center,
	zoom: start_zoom,
	maxZoom: 16,
});

L.tileLayer('/map/' + mapstyle + '/{z}/{x}/{y}.png', {}).addTo(map);
L.control.scale( { 'imperial': false, 'updateWhenIdle': true } ).addTo(map);

map.attributionControl.setPrefix('');
map.attributionControl.addAttribution('Données &copy; les contributeurs d’<a href="licences#osm">OpenStreetMap</a> — Imagerie <a href="licences#cloudmade">CloudMade</a> + <a href="licences#leaflet">Leaflet</a>');

function redirectTo(e) {
	map.closePopup();
	if (redirectLink != '') {
		window.location = redirectLink;
	}
}

function onIdPClick(e) {
	if (typeof disco_set != 'undefined') disco_set(e.target.entityid);
	redirectLink = '/sso?entity_id=' + e.target.entityid;
	redirectTimeout = setTimeout(redirectTo, 2000);
}

function noRedirect(e) {
	map.closePopup();
	clearTimeout(redirectTimeout);
}

$('a.idplink').click(function() {
	var a = $(this);
	if (typeof disco_set != 'undefined') disco_set(a.data('entityid'));
	setTimeout(function () { window.location.href = a.attr('href'); }, 2000);
	return false;
});

map.on('mousedown click popupclose', noRedirect);

function refreshmarkers() {
	var listItems = $('ul#idps').children();
	var searchValue = $('input#search').val().toLowerCase();
	var new_markers = new Array();
	for ( var i = listItems.length - 1; i >= 0; i-- ) {
		item = $(listItems[i]);
		idp = item.children('a');
		text = idp.data('filtertext');
		eid = idp.data('entityid');
		lat = idp.data('lat');
		lon = idp.data('lon');
		latlon = new L.LatLng(lat, lon);
		if (searchValue.length > 2) {
			if (text.toLowerCase().indexOf(searchValue) < 0) {
				// filtered by input#search : hide it and don't add to markers
				item.hide();
				item.addClass('hidden');
				continue;
			}
		} else if (! map.getBounds().contains(latlon)) {
			// marker is not on the map, hide it and don't add to markers
			item.hide();
			item.addClass('hidden');
			continue;
		}
		item.show();
		item.removeClass('hidden');
		marker = new L.Marker(latlon, { title: text,
			icon: new L.DivIcon({ 
				html: '<div><span></span></div>',
				className: 'marker-cluster marker-cluster-one',
				iconSize: new L.Point(40, 40) 
			})
		});
		marker.entityid = eid;
		marker.on('click', onIdPClick);
		marker.bindPopup('<p>' + text + '</p><p align="center"><strong><a href="sso?entity_id=' + eid + '"><i class="icon-time"></i> Connexion dans 2 secondes…</a></strong></p>');
		new_markers.push(marker);

	}
	markers.clearLayers();
	markers.addLayers(new_markers);
}

function delayRefresh(e) {
	clearTimeout(refreshmarkersTimeout);
	refreshmarkersTimeout = setTimeout(refreshmarkers, 500);
}

map.fitBounds(start_bounds);

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

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

// handle up/page-up and down/page-down keys

$('a#preferedidp').on('keydown', function(e) {
	if ((e.which == 40) || (e.which == 34)) { // down & page-down
		e.preventDefault();
		searchinput.focus();
	};
	if ((e.which == 38) || (e.which == 33)) { // up && page-up
		e.preventDefault();
		$('ul#idps li:not(.hidden):last a').focus();
	};
});

searchinput.on('keydown', function(e) {
	if ((e.which == 40) || (e.which == 34)) { // down & page-down
		e.preventDefault();
		$('ul#idps li:not(.hidden):first a').focus();
	}
	if ((e.which == 38) || (e.which == 33)) { // up && page-up
		e.preventDefault();
		$('a#preferedidp').focus();
	}
});

$('ul#idps').on('keydown', function(e) {
	if ((e.which == 40) || (e.which == 34)) { // down & page-down
		e.preventDefault();
		a = $('ul#idps a:focus').parent().nextAll('li:not(.hidden)').first().find('a');
		if (a.length == 0) {
			$('a#preferedidp').focus();
		} else {
			a.focus();
		}
	};
	if ((e.which == 38) || (e.which == 33)) { // up && page-up
		e.preventDefault();
		a = $('ul#idps a:focus').parent().prevAll('li:not(.hidden)').first().find('a');
		if (a.length == 0) {
			searchinput.focus();
		} else {
			a.focus();
		}
	};
});

// show eduspot logo in a tooltip
$('a.brand').tooltip({'html': true,
	'title':'<p><strong>eduspot</strong></p><p><img src="/static/univnautes/img/eduspot200x139.png" /></p>',
	'placement':'bottom',
	'trigger' : 'hover',
	'animation': true,
	'delay': 500}
);

});
