var slideshow;
var lastValidScroll;

$(document).ready(function () {
	initButtons();
	noWindowShade();

	var isHome = $("#paper").hasClass("home");
	slideshow = $("#images");

	if ($("html").hasClass("touch")) {
		$("#scroll-images").css("bottom", 150);
	}
	if (isHome) {
		if ($("html").hasClass("touch")) {
			$("#canvas").css("bottom", 100);
		}
		slideshow.on("cycle-resume", function (event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
			// slideshow.cycle('next');
		});
		slideshow.on("cycle-after", function (event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
			if ($(incomingSlideEl).attr("id") == "print") {
				$("#print img").fadeTo(2000, 0.75);
				$("#print").addClass("scaledDown");
			}
			if ($(outgoingSlideEl).attr("id") == "print") {
				$("#print img").fadeTo(1000, 0);
				$("#print").removeClass("scaledDown");
			}
		});
	}

	slideshow.cycle({
		slides: ">div",
		speed: 6000,
		timeout: 1,
		fx: "fadeout",
		paused: isHome,
	});

	$("#mobile-images:visible").cycle({
		slides: ">div",
		speed: 6000,
		timeout: 1,
		fx: "fadeout",
	});

	slideshow.on("cycle-before", function (event, opts) {
		calculateLayout();
	});

	if ($("html").hasClass("touch")) {
		$("#toggle-nav").click(function () {
			$("#header").toggleClass("show-nav");
		});
		$(window).on("scroll", $.debounce(50, closeNav));
		function closeNav() {
			$("#header").removeClass("show-nav");
		}
	}

	$("#fake-poster").click(function () {
		$("#fake-poster").fadeOut();

		var player = $("iframe");
		var url = window.location.protocol + player.attr("src").split("?")[0];
		var data = { method: "play" };
		var message = JSON.stringify(data);
		player[0].contentWindow.postMessage(data, url);
	});

	$("#photog-credit .hover-link").click(function (e) {
		e.preventDefault();
		if ($("#photog-credit .photo-text:visible").length > 0) $("#photog-credit .photo-text").stop().fadeOut();
		else $("#photog-credit .photo-text").stop().fadeIn();
		if ($(window).width() < 781) $("html,body").animate({ scrollTop: $("html").height() - 300 });
		return false;
	});

	$("#contact-button .hover-link").click(function (e) {
		e.preventDefault();
		if ($("#contact-button .contact-text:visible").length > 0) $("#contact-button .contact-text").stop().fadeOut();
		else $("#contact-button .contact-text").stop().fadeIn();
		if ($(window).width() < 781) $("html,body").animate({ scrollTop: $("html").height() - 300 });
		return false;
	});

	$("#photog-credit .photo-text").hover(
		function () {},
		function () {
			$("#photog-credit .photo-text").fadeOut();
		}
	);

	$("#contact-button .contact-text").hover(
		function () {},
		function () {
			$("#contact-button .contact-text").fadeOut();
		}
	);

	initReservations();
	// if(!$('html').hasClass('touch')&&$(window).width()>780) initHistory();
	if ($(window).width() > 780) initHistory();
	if ($(".text-area").length > 0) {
		$('.text-area:not(".no-big-cap")').each(function (i) {
			var string = $(this).text().replace(/\W/g, "");
			$(this).attr("data-content", string[0]);
		});
	}

	$(window).keyup(function (e) {
		if (e.keyCode == 68) initDraggable();
	});

	$(".reveal-link").click(function (e) {
		e.preventDefault();
		$("#reveal-text").removeClass("hidden");
		$(this).addClass("hidden");
		return false;
	});

	$("a.drop-down").click(function (e) {
		e.preventDefault();
		$(this).closest("div").find(".text-body").toggleClass("hidden");
		$(this).find("span").toggleClass("hidden");
		$(this).find("i").toggleClass("hidden");
		return false;
	});

	$("#scroll-images .img-holder img").click(function (i) {
		var src = $(this).attr("src");
		$("#big-images .big-image").css("background-image", 'url("' + src + '")');
		$("#big-images").fadeIn();
		$(window).on("scroll", leaveBigImages);
	});

	$("#big-images").click(function () {
		leaveBigImages();
	});

	function leaveBigImages() {
		$("#big-images").fadeOut();
		$(window).off("scroll", leaveBigImages);
	}

	$(window).resize(calculateLayout);
	calculateLayout();
});

function initReservations() {
	$(".tour-date-label").click(function () {
		var main = $(this).closest(".tour-date");
		if (main.hasClass("selected")) {
			$(".selected").removeClass("selected");
			return;
		}
		$(".selected").removeClass("selected");
		main.addClass("selected");
		if (main.find("form").length < 1) {
			$.ajax({
				url: "https://carolands.org/index.php/site/tour-form/" + $(".selected").data("occurrence-id"),
				success: function (formHtml) {
					$(".selected .form-holder").html(formHtml);
					initForm();
				},
				dataType: "html",
			});
		}
	});
}

function initForm() {
	var main = $(".selected");
	main.find(".add-guest").click(function (e) {
		e.preventDefault();
		var main = $(this).closest(".tour-date");
		main.find(".hidden").eq(0).removeClass("hidden");
		if (main.find(".hidden").length < 1) main.find(".add-guest").html(main.find(".add-guest").data("disabled-text"));
		return false;
	});

	main.find("form").ajaxForm({
		success: function (returnData) {
			if (returnData.success) {
				$(".selected .form-holder").fadeOut(function () {
					$(".selected .form-holder").html('<span class="response">Thank you for entrying the tour lottery. You will hear back from us within five days after this lottery closes. Thank you for your patience.</span>');
					$(".selected .form-holder").fadeIn();
					// $.ajax({
					// 	url:'https://carolands.org/index.php/site/get-order-count/'+returnData.entry_id,
					// 	success:function(returnStr){
					// 		count=1;
					// 		names = returnStr.split('|||');
					// 		for (var i = 0; i<names.length-1; i++) {
					// 			if(names[i].trim()!="") count++;
					// 		};
					// 		console.log('https://carolands.org/index.php/site/reduce-by-1/'+names[names.length-1]+'/'+count);
					// 		$.ajax({
					// 			url:'https://carolands.org/index.php/site/reduce-by-1/'+names[names.length-1]+'/'+count,
					// 			success:function(returnStr){
					// 				console.log('reduced!');
					// 			}
					// 		});
					// 	}
					// });
				});
			} else {
				// console.log(returnData.errors);
				$(".selected .form-holder input").each(function () {
					if (returnData.errors[$(this).attr("name")]) {
						$(this).addClass("required");
					} else {
						$(this).removeClass("required");
					}
				});
			}
		},
	});

	main.find("form #freeform_key").attr("value", (Math.random() + " ").substring(2, 10) + (Math.random() + " ").substring(2, 10));

	// $('.selected form input[name="key"]').val($('input[name="XID"]').val());
}

function initDraggable() {
	$(".draggable form").ajaxForm({
		dataType: "json",
		error: function (data) {
			console.log(data);
		},
		success: function (data) {
			console.log(data);
			if (data.success) {
				alert("You successfully added a new entry with entry_id " + data.entry_id);
			} else {
				alert("Failed with the following errors: " + data.errors.join(", "));
			}
		},
	});

	var x = 0,
		y = 0;
	interact(".draggable")
		.draggable({
			onstart: function (event) {
				var t = $(event.target);
				x = 0;
				y = 0;
			},
			onmove: function (event) {
				x += event.dx;
				y += event.dy;
				event.target.style.webkitTransform = event.target.style.transform = "translate(" + x + "px, " + y + "px)";
			},
			onend: function (event) {
				var winW = $("#header").width() * 0.005;
				var t = $(event.target);
				var newL = (parseInt(t.attr("data-origxperc")) * winW + x) / winW;
				event.target.style.webkitTransform = event.target.style.transform = "";
				t.attr("data-origxperc", newL);
				t.find("form .input-left").val(Math.round(newL));
				t.find("form .input-top").val(Math.round(y) + parseInt(t.css("top")));
				t.css("left", newL + "%");
				t.toggleClass("left-right-offset", newL < 0);
				t.css("top", Math.round(y) + parseInt(t.css("top")));
				t.find("form").ajaxSubmit();
				resizeHistoryLines();
			},
		})
		.inertia(true);
}

var sWidth, sHeight;
var cWidth, cHeight;
var windowWidth;
function calculateLayout() {
	windowWidth = $(window).width();
	if ($("#paper").hasClass("home")) {
		sWidth = $("#canvas").width();
		sHeight = $("#canvas").height();
		$("#images>div").each(function (i) {
			canvasLayout($(this));
		});
	} else if ($("#paper").hasClass("history")) {
		resizeHistoryLines();
	}
}

var yearMarks;
function resizeHistoryLines() {
	$(".event:contains(rule)").each(function () {
		var event = $(this);
		var len = parseInt(event.css("left"));
		var rule = event.find(".rule");
		rule.width(Math.abs(len) + (len < 0 ? -2 : -5));
		if (len < 0) rule.css("left", "100%").css("right", "auto");
		else rule.css("right", "100%").css("left", "auto");

		var myYear = rule.data("year");
		var lastMark;
		yearMarks.each(function (i) {
			if ($(this).data("year") > myYear) {
				if (!lastMark) return false;
				else {
					var idealMark = lastMark.offset().top + (($(this).offset().top - lastMark.offset().top) * (myYear - lastMark.data("year"))) / ($(this).data("year") - lastMark.data("year"));
					rule.css("top", idealMark - event.offset().top + 14);
					return false;
				}
			} else {
				lastMark = $(this);
			}
		});
	});
}

function initHistory() {
	yearMarks = $("#spine .year-mark");
	$("#paper").height($("#spine").height());
	$("#spine").height($("#paper").height() - 150);
	$.stellar.scrollProperty.history = {
		getLeft: function ($element) {
			return parseInt($element.css("margin-left"), 10) * -1;
		},
		getTop: function ($element) {
			return $(window).scrollTop();
		},
	};
	$.stellar.positionProperty.transform = {
		setPosition: function ($elem, left, startingLeft, top, startingTop) {
			$elem[0].style[prefixedTransform] = "translate3d(" + ($elem.hasClass("context-event") ? 0 : left - startingLeft) + "px, " + (top - startingTop) + "px, 0)";
		},
	};

	// Returns a function which adds a vendor prefix to any CSS property name
	(vendorPrefix = (function () {
		var prefixes = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/,
			style = $("script")[0].style,
			prefix = "",
			prop;

		for (prop in style) {
			if (prefixes.test(prop)) {
				prefix = prop.match(prefixes)[0];
				break;
			}
		}

		if ("WebkitOpacity" in style) {
			prefix = "Webkit";
		}
		if ("KhtmlOpacity" in style) {
			prefix = "Khtml";
		}

		return function (property) {
			return prefix + (prefix.length > 0 ? property.charAt(0).toUpperCase() + property.slice(1) : property);
		};
	})()),
		(prefixedTransform = vendorPrefix("transform")),
		$("#stage").stellar({
			scrollProperty: "history",
			positionProperty: "transform",
			hideDistantElements: false,
		});

	function scrollToLeftWing() {
		$("#stage").css({ "margin-left": "0%" });
	}
	function scrollToCenter() {
		$(".extra-holder").fadeOut(200, function () {
			$(".extra-holder").html("");
			$("#stage").css({ "margin-left": "-100%" });
		});
	}
	function scrollToRightWing() {
		$("#stage").css({ "margin-left": "-200%" });
	}

	$(window).keyup(onKeyUp);
	function onKeyUp(e) {
		if (e.keyCode == 39) scrollToRightWing();
		else if (e.keyCode == 37) scrollToLeftWing();
		else if (e.keyCode == 38) window.location.hash = "";
	}

	$(window).on("hashchange", timelineHashChange);
	timelineHashChange();
	function timelineHashChange() {
		if (window.location.hash == "#" || window.location.hash == "") scrollToCenter();
		else {
			var id = window.location.hash.substring(1);
			if ($("#event-" + id).data("origxperc") > 0) scrollToRightWing();
			else scrollToLeftWing();
			$.ajax({
				url:
					"https://carolands.org/index.php/history-extras/" +
					$("#event-" + id)
						.find("a.learn-more")
						.data("url-title"),
				success: function (extraHtml) {
					$($("#event-" + id).data("origxperc") > 0 ? "#right-wing" : "#left-wing").html(extraHtml);
					// $(window).on('mousewheel', $.debounce( 10, onExtraScroll));
					// $(window).on('mousewheel', updateValidScroll);
					// $(window).on('mousewheel', limitScroll);
					// $(window).on('mousewheel', preventCompletely);
					$(".extra-images").cycle({
						speed: 6000,
						timeout: 1,
						delay: 2000,
						fx: "fade",
					});
					var origPaperHeight = $("#paper").height();

					$(".timeline-return").click(function (e) {
						e.preventDefault();
						scrollToCenter();
						if (history && history.pushState) {
							history.pushState("", document.title, window.location.pathname);
							$("#paper").height(origPaperHeight);
						}
					});
					$(".extra-holder").css("margin-top", $(window).scrollTop() + 00);
					$(".timeline-return").css("margin-top", ($(window).height() - 280) * 0.5);
					$(".extra-holder").delay(1000).fadeIn();
					lastValidScroll = $(".extra-holder").offset().top;

					// var articleHeightDifference = -($('#paper').height() - (lastValidScroll+$('.extra-holder').height()));
					// console.log($('.extra-holder').height(), lastValidScroll, articleHeightDifference);

					$("#paper").height(8500);
				},
				dataType: "html",
			});
		}
	}
}
function preventCompletely(e) {
	var extraHolder = $(e.target).closest(".extra-holder");
	if (extraHolder.length == 0 || extraHolder.scrollTop() < 0) e.preventDefault();
}
function limitScroll(e) {
	if (!isScrolledIntoView($(".extra-holder"))) {
		console.log("hi");
		e.preventDefault();
		$("html, body")
			.stop(false, false)
			.animate(
				{
					scrollTop: $(window).scrollTop() - 10,
				},
				200
			);
	}
}
function updateValidScroll(e) {
	if (isScrolledIntoView($(".extra-holder"))) {
		lastValidScroll = $(window).scrollTop();
	} else {
		e.preventDefault();
	}
}
function onExtraScroll() {
	if (!isScrolledIntoView($(".extra-holder"))) {
		$("html, body").stop(true, true).animate(
			{
				scrollTop: lastValidScroll,
			},
			200
		);
	}
}

function isScrolledIntoView(elem) {
	var docViewTop = $(window).scrollTop() + 300;
	var docViewBottom = docViewTop + $(window).height() - 400;

	var elemTop = $(elem).offset().top;
	var elemBottom = elemTop + $(elem).height();

	return elemBottom >= docViewBottom && elemTop <= docViewTop;
}

function canvasLayout(img) {
	var ratio = (img.data("width") + 12) / (img.data("height") + 12);

	if (ratio > sWidth / sHeight) img.height(sHeight).width(sHeight * ratio);
	else img.width(sWidth).height(sWidth / ratio);

	img.css("marginLeft", (sWidth - img.width()) * 0.5);
	img.css("marginTop", (sHeight - img.height()) * 0.5);

	if (img.hasClass("crop-bottom")) img.css("marginTop", (sHeight - img.height()) * 0.3);
}

function noWindowShade() {
	$("#images")
		.imagesLoaded()
		.always(function (instance) {})
		.done(function (instance) {
			if ($("#paper").hasClass("home")) {
				slideshow.cycle("resume");
			}
		})
		.fail(function () {})
		.progress(function (instance, image) {
			$(image.img).addClass("isLoaded");
			calculateLayout();
		});
}

function initButtons() {
	$("#next-button, #images").click(function () {
		nextImage();
		return false;
	});
	$("#prev-button").click(function () {
		prevImage();
		return false;
	});
	$("#pause-button").click(function () {
		pauseSlideshow();
		return false;
	});
	$("#play-button").click(function () {
		playSlideshow(true);
		return false;
	});

	$(window).keyup(onKeyUp);
}

function onKeyUp(e) {
	if (e.keyCode == 39) nextImage();
	else if (e.keyCode == 37) prevImage();
	else if (e.keyCode == 27) window.location.hash = "#";
}

function nextImage() {
	slideshow.cycle("next");
	pauseSlideshow();
}

function prevImage() {
	slideshow.cycle("prev");
	pauseSlideshow();
}

function pauseSlideshow() {
	$("#pause-button").addClass("hidden");
	$("#play-button").removeClass("hidden");
	slideshow.cycle("pause");
}

function playSlideshow(advanceOnPlay) {
	$("#play-button").addClass("hidden");
	$("#pause-button").removeClass("hidden");
	if (advanceOnPlay) slideshow.cycle("next");
	slideshow.cycle("resume");
}
