"use strict";

/**
 * @version 1.2
 */

var gallery; // globální reprezentace objektu PhotoSwipe galerie

$(function () {
	// Zobrazení celého popisu na mobilní verzi
	$('.hoteldiv').each(function () {
		$(this).find('.hotel-popis')
			.find('.hotel-ajax-cely-popis').click(function (e) {
			e.preventDefault();

			var parent = $(this).parent(),
				text = parent.find('.hotel-ajax-popis').text();

			parent.append(document.createTextNode(text));
			parent.find('.hotel-ajax-popis, .hotel-ajax-tecky, .hotel-ajax-cely-popis').remove();
		})
	});

	//pomocný div pro prevenci kliknutí na odkaz pod galerií (jinak je snadné se překliknout)
	$("#fotoDialogContainer").hide();

	// Posun na zvýrazněný hotel
	var selectedHotel = $('.hoteldiv.highlighted');

	if (selectedHotel.length > 0) {
		var hashId = "hotel" + window.location.hash.replace("#", "");

		if (selectedHotel.attr("id") === hashId || selectedHotel.attr("data-lastminute-id") === hashId)
			$(window).scrollTop($(selectedHotel[0]).offset().top - 50);
	}

	$(window).on('hashchange', function (e) {
		e.preventDefault();

		// zavření galerie
		if ((window.location.hash.indexOf('galerie') === -1 && window.location.hash.indexOf('cenik') === -1)
			&& gallery instanceof PhotoSwipe)
			gallery.close();

		return false;
	});
});

function toggleCalendar(id, from, to)
{
	console.log(id);
	var calendar = $('#kalendar_' + id);

	if (calendar.hasClass('kalendar-expand'))
	{
		calendar.removeClass('kalendar-expand');
		$('#hotel_' + id).html(zobrazKalendar);
		hideKalendar(id);
	}
	else
	{
		calendar.addClass('kalendar-expand');
		$('#hotel_' + id).html(skrytKalendar);
		Kalendar(id, from, to);
	}
}

// zobrazení termínu v kalendáři
function Kalendar(id, from, to) {
	var element = $("#kalendar_" + id);
	if (!element.hasClass('visible')) {
		element.addClass('visible')
			.show()
			.flatpickr({
				mode: 'range',
				inline: true,
				monthSelectorType: 'static',
				minDate: element.data('calendarStart'),
				maxDate: element.data('calendarEnd'),
				appendTo: element[0],
				defaultDate: [element.data('calendarStart'), element.data('calendarEnd')],
			});
		element.parent()
			.slideDown();
	}
}

function hideKalendar(id) {
	var element = $("#kalendar_" + id);
	element.removeClass('visible')
		.parent().slideUp(function () {
			element.hide();
		});
}

// pro testování na lokálu, kde nejsou všechny fotky
var bTestOnServer = false;

function getPhotoLink(slozka, n) {
	return (bTestOnServer ? 'https://www.ceskehory.cz' : '') + photoBase + slozka + "/x" + n + ".jpg";
}

function createPhotoObjects(slozka, foto_string, n) {
	var pages = foto_string.toString().split('').map(function (item) {
		return Number(item);
	});

	var objects = {
		count: pages.length - n,
		data: []
	};

	for (var i = 0; i < pages.length - 1; i++) {

		var addPage = {
			src: getPhotoLink(slozka, i + 1),
			w: 0,
			h: 0
		};

		objects.data.push(addPage);
	}

	return objects;
}

function uniqid(a, b) {
	a = a || "";
	b = b && false;

	var c = Date.now() / 1000;
	var d = c.toString(16).split(".").join("");
	while (d.length < 14) {
		d += "0";
	}
	var e = "";
	if (b) {
		e = ".";
		e += Math.round(Math.random() * 100000000);
	}
	return a + d + e;
}

var highlightTimeout = 2000;

function addActionHighlight(id) {
	var highlighId = uniqid();

	$('.highlighted').removeClass('highlighted');
	$("#hotel" + id).addClass('action-highlight')
		.addClass('action-highlight_' + highlighId);

	removeAllOtherHighLights(highlighId);

	return highlighId;
}

function removeAllOtherHighLights(exclusionId) {
	var excludeClass = '.action-highlight_' + exclusionId;
	$('.action-highlight:not(' + excludeClass + ')').removeClass('action-highlight');

}

function removeActionHighlight(highlightId) {
	var selector = typeof highlightId === "undefined" ? ".action-highlight" : ".action-highlight_" + highlightId;

	setTimeout(function () {
		$(selector).removeClass('action-highlight')
			.removeClass('action-highlight_' + highlightId);
	}, highlightTimeout);
}

function initializePhotoSwipe(items, highlightId) {
	var containerElement = $('.pswp')[0];

	var options = {
		history: false,
		focus: false,
		index: 0,
		shareEl: false // schování share buttonu
	};

	gallery = new PhotoSwipe(containerElement, PhotoSwipeUI_Default, items, options);
	gallery.listen('close', function () {
		if (window.location.hash.indexOf('galerie') !== -1)
			window.history.back();

		removeActionHighlight(highlightId);
	});
	// https://github.com/dimsemenov/PhotoSwipe/issues/796
	gallery.listen('gettingData', function(index, item) {
		if (item.w < 1 || item.h < 1) { // unknown size
			var img = new Image();
			img.onload = function() {
				item.w = this.width;
				item.h = this.height;
				gallery.invalidateCurrItems();
				gallery.updateSize(true);
			};
			img.src = item.src;
		}
	});

	gallery.init();

}

function showMorePhotos(slozka, foto_string, n, id) {
	$('#fotoDialogContainer').show();

	var highlightId = addActionHighlight(id);

	var photoObjects = createPhotoObjects(slozka, foto_string, n);
	initializePhotoSwipe(photoObjects.data, highlightId);

	if (window.location.hash.indexOf('galerie') === -1)
		window.location.hash += 'galerie';
}

var xmlHttp = new XMLHttpRequest();

function sendRequestCenikHR(id, route, mutace) {
	const highlight = addActionHighlight(id);

	fetch(route)
		.then(response => response.text())
		.then(response => showPricesDialog(response, highlight));
}

function sendRequestCenik(id, mutace, postfix) {
	var highlightId = addActionHighlight(id);

	if (xmlHttp) {
		xmlHttp.open("GET", "/share/ajax/ajax_cenik_3R.php?id=" + id + "&mutace=" + mutace + "&postfix=" + postfix + '&highlightId=' + highlightId, true);
		xmlHttp.onreadystatechange = function () {
			showPrices(highlightId);
		};
		xmlHttp.send(null);
	}


	if (window.location.hash.indexOf('cenik') === -1)
		window.location.hash += 'cenik';
}

function showPrices(highlightId) {
	if (xmlHttp.readyState === 4) {
		if (xmlHttp.status === 200) {
			var ajaxReturn = xmlHttp.responseText;
			showPricesDialog(ajaxReturn, highlightId);
		}

		else
			$(".action-highlight_" + highlightId).removeClass('action-highlight action-highlight_' + highlightId);
	}
}

function closeCenik(highlightId) {
	removeActionHighlight(highlightId);

	var toRemove = $("#simple-popup, #simple-popup-backdrop");
	toRemove.fadeOut('fast', function () {
		toRemove.remove();
	});

	history.back();
}

function showPricesDialog(text, highlightId) {
	var options = {
		type: "html",
		htmlSelector: "#cenik-container",
		afterClose: function () {
			if (window.location.hash.indexOf('cenik') !== -1)
				window.history.back();

			removeActionHighlight(highlightId);
		}
	};

	$("#cenik-container").html(text);
	$(document).simplePopup(options);
}
