/*
 * Let's GO!
 */

var myMap;
var categories = Array();
var points = Array();
var markers; // Используется для кластеризации
var layer;
var layers = Array();
var defaultZoom = 13;

categories.simplepoint = L.icon({
	iconUrl: '/ico/simplepoint.png',
	iconSize: [13, 13],
	iconAnchor: [7, 7],
	popupAnchor: [7, 7]
});

categories.targetpoint = L.icon({
	iconUrl: '/ico/infogreen.png',
	iconSize: [32, 37],
	iconAnchor: [16, 37],
	popupAnchor: [0, 1]
});


// -----------------------------------------------------------------------------

/**
 * Инициализируем яндекс-карты и узнаём расположение пользователя.
 */
ymaps.ready(function () {
	lat = ymaps.geolocation.latitude;
	lng = ymaps.geolocation.longitude;

	init(pointLat, pointLng);
});

/**
 * Инициализируем переменные и подгружаем данные.
 * @returns true
 */
function init(lat, lng) {
	myMap = L.map('map', {zoomControl: true}).setView([lat, lng], defaultZoom);
	markers = new L.MarkerClusterGroup({showCoverageOnHover: false, maxClusterRadius: 45});

	layers['quest'] = L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18});

	setLayer('quest');

	initPoints()

	myMap.on('click', function (e) {
		if (!myMap._popup) {
			closePopup();
		}
	});

	return true;
}

/**
 * Создаёт точку для карты - Placemark.
 * @param {Array} data
 * @returns {Array}
 */
function constructPoint(data)
{
	id = data['id'];

	icon = (id == pointId)?categories.targetpoint:categories.simplepoint;

	points[id] = L.marker(
			[data['lat'], data['lng']], {icon: icon, title: data['name'], id: id, categoryId: data['categoryId']}
	).on('click', function (e) {
		window.location.href = "/page/point/id/"+e.target.options.id;
	});

	return points[id];
}

/**
 * Загружает точки с сервера.
 * @returns {Boolean}
 */
function initPoints()
{
	$.ajax({
		url: "/json/points/",
		success: function (data) {
			for(var i=0; i<data.length; i++) {
				if (data[i].id == pointId) {
					constructPoint(data[i]);
					points[data[i].id].addTo(myMap);
				} else {
					markers.addLayer(constructPoint(data[i]));
				}
			}
			myMap.addLayer(markers);
		}
	});

	return true;
}

function setLayer(name)
{
	if (layer)
		myMap.removeLayer(layers[layer])

	layer = name;
	myMap.addLayer(layers[layer]);
}
