
var map;
var lati = 1;
var longi = 1;
var array = [];
var tit = 0;
var markers = [];

$('#selectDevice').scombobox({
	invalidAsValue: true,
	fullMatch: true
});

$(document).ready(function () {
	
	$("#send").click(function () {
		if ($("#nameZone").val()) {
			if (markers.length >= 3) {

				let toPost = convertToPoint($("#nameZone").val());
				var req = $.ajax({
					type: "POST",
					data: JSON.stringify(toPost),
					url: "/Home/Zone/Overwiev?handler=Save",
					headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function (response) {
						location.reload();
					},
					failure: function () {
						alert("fail")
					}
				});
			} else {
				alert("At least 3 points required.")
			};
		} else {
			alert("Set name");
		}
	});
	
});

function clearMap() {
	array = [];
	markers.forEach(item => {
		item.setMap(null);
	})
	markers = [];
	$("#nameZone").val("");
	$("#selectDevice").prop('selectedIndex', 0);
}

function convertToPoint(name) {
	let points = [];
	array.forEach(item => {
		points.push(Marker = {
			IdMarker: 0,
			Latitude: item[1],
			Longitude: item[2],
			Action: "create",
			DateTime: new Date(),
			LocationName: ""
		})
	});
	var iden = '';
	if ($("#selectDevice option:selected").val().toString() !== "null") {
		iden = $("#selectDevice option:selected").val().toString();
	}
	var ret = {
		Name: name,
		Identificator: iden,
		Points: points
	}
	console.log(ret);
	return ret;
}

function getLocation() {
	if (navigator.geolocation) {
		lati = navigator.geolocation.getCurrentPosition(showPosition);
	}
}
function showPosition(position) {
	lati = position.coords.latitude;
	longi = position.coords.longitude;
	console.log(lati + " " + longi);
	initMap();
}
function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: { lat: lati, lng: longi },
		zoom: 16
	});
	console.log(document.getElementById('map'));
	map.addListener('click', function (e) {
		placeMarkerAndPanTo(e.latLng, map);
	});
}

function placeMarkerAndPanTo(latLng, map) {
	var marker = new google.maps.Marker({
		position: latLng,
		map: map,
		draggable: true,
		title: tit.toString(),
	});

	marker.addListener('position_changed', function () {
		changedPositionOfMarker(marker)
	});
	marker.addListener('dblclick', function () {
		deleteMarker(marker)
	})
	array.push([tit.toString(), marker.position.lat(), marker.position.lng()]);
	markers.push(marker);
	tit++;
	map.panTo(latLng);
}

function changedPositionOfMarker(marker) {
	array.forEach(element => {
		if (element[0] === marker.title) {
			element[1] = marker.position.lat();
			element[2] = marker.position.lng();
		}
	});
	console.log(array);
}

function deleteMarker(marker) {
	var position;
	console.log(array);
	for (let index = 0; index < array.length; index++) {
		const element = array[index];
		if (element[0] === marker.title) {
			position = index;
			markers[index].setMap(null);
			markers.splice(index, 1);
		}
	}
	array.splice(position, 1);
	console.log(array);
	console.log(markers);
}

function printMarkers() {
	console.log(array);
}



function deleteZone(idZone) {
	$.ajax({
		type: "POST",
		data: JSON.stringify({ Value: idZone }),
		url: "/Home/Zone/Overwiev?handler=DeleteZone",
		headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (response) {
			location.reload();
		},
	})
}

$("#zoneTable").fancyTable({
	sortCsortColumn: 1,
	sortable: true,
	pagination: true,
	searchable: true,
	globalSearch: true,
	perPage: 10,
})

$(document).ready(function () {
	$("#partID").text("Zones");
	$("#sectionID").text("Overview");
})