523 lines
13 KiB
JavaScript
523 lines
13 KiB
JavaScript
/*
|
||
* Приложение
|
||
*/
|
||
|
||
// ------------ Система статусов приложения ------------------------------------
|
||
var statusReady = 0; // Обычный режим. Просмотр точек, навигация по карте и прочее.
|
||
var statusHunting = 1; // Курсор-прицел. Поиск места для добавления точки.
|
||
var statusReHunting = 2; // КУрсор прицел. Переопределение координат точки.
|
||
var statusAdd = 3; // Открыто окно добавления точки - форма.
|
||
var statusEdit = 4; // Открыто окно редактирования точки. В нём информация о существующей точке, включая ID.
|
||
var statusSendingToServer = 5; // Отправлен запрос на сервер - ждём, не даём жать кнопку повторно, отвлекаем пользователя.
|
||
var statusMovingInHistory = 6;
|
||
|
||
var status = statusReady;
|
||
var statusPrev = statusReady;
|
||
|
||
/**
|
||
* Устанавливает новое значение статуса.
|
||
* @returns {undefined}
|
||
*/
|
||
function setStatus(value)
|
||
{
|
||
statusPrev = status;
|
||
status = value;
|
||
}
|
||
|
||
/**
|
||
* Меняет значение статуса на предыдущее.
|
||
* @returns {undefined}
|
||
*/
|
||
function resetStatus()
|
||
{
|
||
tmp = status;
|
||
status = statusPrev;
|
||
statusPrev = tmp;
|
||
}
|
||
|
||
// -------------------------------- Libs ---------------------------------------
|
||
|
||
/**
|
||
* Возвращает GET параметр
|
||
* @param string name
|
||
* @returns string
|
||
*/
|
||
function getURLParameter(name) {
|
||
return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
|
||
}
|
||
|
||
// ----------------- Работа с правым блоком (BOX) ------------------------------
|
||
|
||
function openBox(type, keepOpen)
|
||
{
|
||
newTab = $('#box'+type).css('display') == 'none';
|
||
keepOpen = keepOpen == true;
|
||
|
||
if (!newTab && !keepOpen)
|
||
{
|
||
return closeBox();
|
||
}
|
||
|
||
$('div','#control').removeClass('active');
|
||
$('#box').children('div').css('display', 'none');
|
||
|
||
$('.boxButton'+type).addClass('active');
|
||
$('#box'+type).css('display', 'block');
|
||
$('body').addClass('openBox');
|
||
}
|
||
|
||
function closeBox()
|
||
{
|
||
$('body').removeClass('openBox');
|
||
$('div','#control').removeClass('active');
|
||
$('#box').children('div').css('display', 'none');
|
||
|
||
return true;
|
||
}
|
||
|
||
function showImage(id)
|
||
{
|
||
point = pointsSources[id];
|
||
photos = [];
|
||
|
||
if( typeof($('.fotorama').data('fotorama')) != 'undefined' )
|
||
{
|
||
$('.fotorama').data('fotorama').destroy();
|
||
}
|
||
|
||
$('#imageModalLabel').text(point.name);
|
||
$('#imageModalImg').hide();
|
||
$('.fotorama').show();
|
||
|
||
if (typeof(point.images) == 'object')
|
||
{
|
||
point.images.forEach(function(entry) {
|
||
if (true || window.devicePixelRatio > 1) {
|
||
photos.push({img: '/photos/big/'+entry, thumb: '/photos/small/'+entry});
|
||
} else {
|
||
photos.push({img: '/photos/middle/'+entry, thumb: '/photos/small/'+entry});
|
||
}
|
||
});
|
||
} else {
|
||
photos.push({img: point.img, thumb: point.img});
|
||
}
|
||
|
||
initFotorama('.fotorama', photos);
|
||
$('#imageModal').modal('show');
|
||
}
|
||
|
||
function addRemoveFavorite(id)
|
||
{
|
||
if (user != '0')
|
||
{
|
||
$.ajax({
|
||
url: "/json/addRemoveFavorites/id/" + id,
|
||
success: function(data) {
|
||
if (data){
|
||
// Тут переключалку классов звёздочки
|
||
$('#myFavoritesButton').toggleClass('glyphicon glyphicon-star-empty').toggleClass('glyphicon glyphicon-star');
|
||
}
|
||
}});
|
||
} else {
|
||
$('#loginModal').modal('show');
|
||
}
|
||
}
|
||
|
||
function addRemoveLike(id)
|
||
{
|
||
if (user != '0')
|
||
{
|
||
$.ajax({
|
||
url: "/json/addRemoveLike/id/" + id,
|
||
success: function(data) {
|
||
if (data){
|
||
$('#myLikesButton').toggleClass('glyphicon-thumbs-up').toggleClass('glyphicon-ok');
|
||
}
|
||
}});
|
||
} else {
|
||
$('#loginModal').modal('show');
|
||
}
|
||
}
|
||
|
||
window.addEventListener('popstate', function(e)
|
||
{
|
||
if (typeof(e.state) == 'object' && e.state != null)
|
||
{
|
||
setStatus(statusMovingInHistory);
|
||
if (e.state.hasOwnProperty('pointId'))
|
||
{
|
||
showInfo(e.state.pointId, false, true);
|
||
} else
|
||
if (e.state.hasOwnProperty('zoom'))
|
||
{
|
||
lat = e.state.lat;
|
||
lng = e.state.lng;
|
||
zoom = e.state.zoom;
|
||
|
||
myMap.setView([lat, lng], zoom);
|
||
} else
|
||
if (e.state.hasOwnProperty('route'))
|
||
{
|
||
loadRouteJSON(e.state.route);
|
||
}
|
||
}
|
||
}, false);
|
||
|
||
function getTime() {
|
||
return Math.floor(Date.now() / 1000);
|
||
}
|
||
|
||
function showRandomPoint()
|
||
{
|
||
roundIndex = Math.floor(Math.random() * points.length);
|
||
runner = 0;
|
||
for (var key in points)
|
||
{
|
||
if (runner++ >= roundIndex)
|
||
return showInfo(key);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Загружает с сервера список категорий точек.
|
||
* @returns {Boolean}
|
||
*/
|
||
function initCategories()
|
||
{
|
||
data = JSON.parse(categoryArray);
|
||
for (var k in data) {
|
||
categories[data[k]['id']] = L.icon({
|
||
iconUrl: data[k]['icon'],
|
||
iconSize: [32, 37],
|
||
iconAnchor: [16, 37],
|
||
popupAnchor: [0, 1]
|
||
});
|
||
}
|
||
|
||
if (isAdmin == 0) {
|
||
initPoints(true);
|
||
}
|
||
|
||
return initPoints();
|
||
}
|
||
|
||
/**
|
||
* Производит поиск по адресу или координатам, введённым в соответствующее поле.
|
||
* @returns {undefined}
|
||
*/
|
||
function searchAdderess()
|
||
{
|
||
$.ajax({
|
||
url: "/json/geocoding",
|
||
data: {
|
||
search: $('#addressField').val()
|
||
},
|
||
success: function (data)
|
||
{
|
||
if (data.lat && data.lng)
|
||
{
|
||
myMap.setView([data.lat, data.lng], defaultZoom);
|
||
L.popup()
|
||
.setLatLng([data.lat, data.lng])
|
||
.setContent('Координаты: lat:' + data.lat + ' lng:' + data.lng)
|
||
.openOn(myMap);
|
||
} else
|
||
{
|
||
alert('Ничего не найдено.');
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Активирет добавление точки - ждёт выбор координат, меняет курсор на прицел.
|
||
* @returns {Boolean}
|
||
*/
|
||
function activateAddPoint()
|
||
{
|
||
$('#addPointButton').toggleClass('active');
|
||
if ($('#addPointButton').hasClass('active'))
|
||
{
|
||
$('.extraImage', '#imgsContainer').remove();
|
||
addNewImage();
|
||
$('#map').css('cursor', 'crosshair');
|
||
setStatus(statusHunting)
|
||
}
|
||
else
|
||
{
|
||
$('#map').css('cursor', 'arrow');
|
||
setStatus(statusReady)
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* Отправляет данные о точке на сервер.
|
||
* @returns {Boolean}
|
||
*/
|
||
function addPoint()
|
||
{
|
||
$('.form-group').removeClass('has-error');
|
||
if (status != statusSendingToServer)
|
||
{
|
||
setStatus(statusSendingToServer)
|
||
id = $('#addPointId').length ? $('#addPointId').val() : 0;
|
||
hasImages = false;
|
||
$("input[name='imgs[]']", '#addPointForm').each(function () {
|
||
if ($(this).val().length > 10)
|
||
hasImages = true;
|
||
});
|
||
$("input[name='photos[]']", '#addPointForm').each(function () {
|
||
if ($(this).val().length > 5)
|
||
hasImages = true;
|
||
})
|
||
$.ajax({
|
||
type: "POST",
|
||
url: "/json/addpoint/",
|
||
data: {
|
||
name: $('#addPointName').val(),
|
||
img: hasImages ? 1 : 0,
|
||
description: $('#addPointDescription').val(),
|
||
categoryId: $('#addPointCategoryId').val(),
|
||
source: $('#addPointSource').val(),
|
||
lat: $('#addPointLat').val(),
|
||
lng: $('#addPointLng').val(),
|
||
status: $('#moderate').val(),
|
||
id: id
|
||
},
|
||
success: function (data) {
|
||
if ($("input[name='photos[]']").length > 0 || $("input[name='imgs[]']").length > 0)
|
||
{
|
||
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(data);
|
||
$('#addPointForm').submit();
|
||
}
|
||
|
||
text = id ? 'Точка успешно отредактирована!' : 'Точка успешно добавлена!';
|
||
if (id)
|
||
{
|
||
markers.removeLayer(points[id]);
|
||
}
|
||
|
||
text = '<center><img src="/img/loading.gif" style="height: 89px; width: 89px;" /><br/><br/><b style="font-size: 1.2em;">Подождите пожалуйста!</b><br/>Изображения загружаются на сайт...</center>'
|
||
balloon = L.popup()
|
||
.setLatLng([$('#addPointLat').val(), $('#addPointLng').val()])
|
||
.setContent(text)
|
||
.openOn(myMap);
|
||
// setTimeout(function () {
|
||
// balloon._close();
|
||
// delete balloon;
|
||
// }, 2000);
|
||
|
||
obj = {};
|
||
obj.id = data;
|
||
obj.name = $('#addPointName').val();
|
||
obj.lat = $('#addPointLat').val();
|
||
obj.lng = $('#addPointLng').val();
|
||
obj.categoryIcon = categories[$('#addPointCategoryId').val()].icon;
|
||
obj.categoryId = $('#addPointCategoryId').val();
|
||
|
||
setTimeout(function () {
|
||
markers.addLayer(constructPoint(obj));
|
||
}, 2000);
|
||
|
||
$('#addPointModal').modal('hide');
|
||
|
||
// Clear form
|
||
$('#addPointForm input').val('');
|
||
$('#addPointForm textarea').val('');
|
||
$('.form-group').removeClass('has-error');
|
||
$('#addPointButton').removeClass('active');
|
||
$('#addPointId').remove();
|
||
$('#map').css('cursor', 'arrow');
|
||
setStatus(statusReady);
|
||
|
||
return true;
|
||
},
|
||
error: function (data) {
|
||
response = data.responseJSON;
|
||
message = '';
|
||
for (var k in response) {
|
||
if (typeof response[k] !== 'function') {
|
||
if (k == 1)
|
||
$('#addPointName').parent().addClass('has-error');
|
||
else
|
||
if (k == 2)
|
||
{
|
||
$('.extraImage', '#addPointForm').addClass('has-error');
|
||
}
|
||
else
|
||
if (k == 3)
|
||
$('#addPointDescription').parent().addClass('has-error');
|
||
else
|
||
message += response[k] + '; ';
|
||
}
|
||
}
|
||
|
||
if (message != '')
|
||
alert(message);
|
||
|
||
resetStatus();
|
||
return false;
|
||
}
|
||
});
|
||
}
|
||
else
|
||
{
|
||
alert('Точка добавляется, нужно немного подождать.');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Включает режим редактирования точки.
|
||
* @param int id
|
||
* @returns {undefined}
|
||
*/
|
||
function editPoint(id)
|
||
{
|
||
$('#addPointId').remove();
|
||
$('<input type="hidden" id="addPointId" name="id"/>').appendTo('#addPointForm').val(id);
|
||
$('#addPointName').val(pointsSources[id].name);
|
||
$('#addPointDescription').val(pointsSources[id].description);
|
||
$("#addPointCategoryId option").attr('selected', null);
|
||
$("#addPointCategoryId option[value='" + pointsSources[id].categoryId + "']").attr('selected', 'selected');
|
||
$('#addPointSource').val(pointsSources[id].source);
|
||
$('#addPointLat').val(pointsSources[id].lat);
|
||
$('#addPointLng').val(pointsSources[id].lng);
|
||
$('#moderate').val(pointsSources[id].status);
|
||
|
||
$('.extraImage', '#imgsContainer').remove();
|
||
$('.extraParam', '#extraParamsContainer').remove();
|
||
if (pointsSources[id].images != undefined && pointsSources[id].images.length > 0)
|
||
{
|
||
for (var i = 0; i < pointsSources[id].images.length; i++)
|
||
{
|
||
addNewImage(pointsSources[id].images[i]);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
addNewImage(pointsSources[id].img);
|
||
}
|
||
|
||
if (pointsSources[id].extraParams != undefined)
|
||
{
|
||
for( var paramKey in pointsSources[id].extraParams )
|
||
{
|
||
addNewExtraParam(pointsSources[id].extraParams[paramKey][0], pointsSources[id].extraParams[paramKey][1])
|
||
}
|
||
}
|
||
|
||
closePopup();
|
||
$('#addPointModal').modal('show');
|
||
setStatus(statusEdit);
|
||
}
|
||
|
||
function editSetNewCoords()
|
||
{
|
||
$('#addPointModal').modal('hide');
|
||
$('#map').css('cursor', 'crosshair');
|
||
setStatus(statusReHunting)
|
||
}
|
||
|
||
function closePopup()
|
||
{
|
||
if (myMap._popup)
|
||
myMap._popup._close();
|
||
}
|
||
|
||
function filter()
|
||
{
|
||
var selected = new Array();
|
||
$('.filterSelector:checked').each(function (i, e) {
|
||
selected.push($(e).val());
|
||
});
|
||
|
||
for (var key in points)
|
||
{
|
||
if (selected.length == 0 || points[key].options.categoryId == undefined || selected.indexOf(points[key].options.categoryId) != -1)
|
||
{
|
||
markers.addLayer(points[key]);
|
||
}
|
||
else
|
||
{
|
||
markers.removeLayer(points[key]);
|
||
}
|
||
}
|
||
}
|
||
|
||
$(document).ready(function(){
|
||
if ($('.dfotorama').length >= 1) {
|
||
initFotorama('.dfotorama');
|
||
|
||
$(window).on("orientationchange", function (event) {
|
||
// $('.dfotorama').data('fotorama').destroy();
|
||
// initFotorama('.dfotorama');
|
||
// myMap.invalidateSize();
|
||
});
|
||
}
|
||
});
|
||
|
||
function initFotorama(selector, data){
|
||
width = $(window).width() < 585 ? $(window).width()-10 : 555;
|
||
height = $(window).width() < 585 ? ((450/555)*($(window).width()-10)) : 450;
|
||
|
||
ww = $(window).width();
|
||
wh = $(window).height();
|
||
|
||
if (ww >= 1200 && wh >= 1080) {
|
||
width = 1110;
|
||
height = 900;
|
||
} else if (ww < 585) {
|
||
width = ww - 10;
|
||
height = ((450 / 555) * width);
|
||
} else {
|
||
width = 555;
|
||
height = 450;
|
||
}
|
||
|
||
if ($(window).height() < height) {
|
||
height = $(window).height();
|
||
width = (555 / 450) * height;
|
||
}
|
||
|
||
width = Math.round(width);
|
||
height = Math.round(height);
|
||
|
||
if (typeof data !== 'undefined') {
|
||
$(selector).fotorama({
|
||
data: data,
|
||
width: width,
|
||
height: height,
|
||
allowfullscreen: true,
|
||
startindex: 0
|
||
});
|
||
} else {
|
||
$(selector).fotorama({
|
||
width: width,
|
||
height: height,
|
||
startindex: 0
|
||
}).on('fotorama:fullscreenenter', function (e, fotorama) {
|
||
fotorama.setOptions({
|
||
nav: 'dots'
|
||
});
|
||
}).on('fotorama:fullscreenexit', function (e, fotorama) {
|
||
fotorama.setOptions({
|
||
nav: 'thumbs'
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
function showArticle(id)
|
||
{
|
||
$.ajax({
|
||
url: "/json/article/id/" + id,
|
||
success: function (data) {
|
||
$('#articleModal').modal('hide').remove();
|
||
$('body').append($(data));
|
||
$('#articleModal').modal('show');
|
||
}
|
||
});
|
||
}
|