function initSmoothScrolling() {
	$('#header a.nav-link[href*=\\#]:not([href=\\#])').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

			var offset = $(this).attr("data-offset");

			if (offset > 0) {
				offset = offset;  
			} else {
				offset = 0;  
			}

			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top - offset + 1
				}, 1000);
				return false;
			}
		}
	});
}

function validateForm(theForm) {
	// $(document).off('submit').on('submit', theForm, function(e) {
	// 	e.preventDefault();
	// 	return false;
	// });

	// theForm.trigger("submit");

	if (!theForm[0].checkValidity()) {
		alert("Bitte teilen Sie uns Ihre Daten mit");
		return false;
	} else {
		return true;
	}
}

function initScrollReveal() {
	// window.sr = ScrollReveal({ reset: true });
	// sr.sync() for async
	//sr.reveal('.wow', { container: '#modalRemote' });
	// sr.reveal('.wow', {});
}

function initFullPage() {
	var $isAnimatedFirst = $('#section3 .is-animated'),
		$isAnimatedSecond = $('#section4 .is-animated'),
		$isAnimatedThird = $('#section5 .is-animated');

	var myFullpage = new fullpage('#fullpage', {
		//Navigation
		menu: '#menu',
		lockAnchors: false,
		// anchors:['firstPage', 'secondPage'],
		navigation: true,
		navigationPosition: 'right',
		navigationTooltips: [],
		showActiveTooltip: false,
		slidesNavigation: true,
		slidesNavPosition: 'bottom',

		//Scrolling
		css3: true,
		scrollingSpeed: 700,
		autoScrolling: true,
		fitToSection: true,
		fitToSectionDelay: 1000,
		scrollBar: false,
		easing: 'easeInOutCubic',
		easingcss3: 'ease',
		loopBottom: false,
		loopTop: false,
		loopHorizontal: true,
		continuousVertical: false,
		continuousHorizontal: false,
		scrollHorizontally: false,
		interlockedSlides: false,
		dragAndMove: false,
		offsetSections: false,
		resetSliders: false,
		fadingEffect: false,
		normalScrollElements: '#element1, .element2',
		scrollOverflow: false,
		scrollOverflowReset: false,
		scrollOverflowOptions: null,
		touchSensitivity: 15,
		normalScrollElementTouchThreshold: 5,
		bigSectionsDestination: null,

		//Accessibility
		keyboardScrolling: true,
		animateAnchor: true,
		recordHistory: true,

		//Design
		controlArrows: true,
		verticalCentered: true,
		sectionsColor : ['#ccc', '#fff'],
		paddingTop: '3em',
		paddingBottom: '10px',
		fixedElements: '#header, #page-footer',
		responsiveWidth: 0,
		responsiveHeight: 0,
		responsiveSlides: false,
		parallax: false,
		parallaxOptions: {type: 'reveal', percentage: 62, property: 'translate'},

		//Custom selectors
		sectionSelector: '.section',
		slideSelector: '.slide',

		lazyLoading: true,
		//events
		onLeave: function(index, nextIndex, direction) {

      /**
      * use the following condition: 
      *
      *   if( index == 1 && direction == 'down' ) {
      *
      * if you haven't enabled the dot navigation
      * or you aren't interested in the animations that occur 
      * when you jump (using the dot navigation) 
      * from the first section to another sections 
      */
      
      index = index.index;
      nextIndex = nextIndex.index;

      console.log("Index " + index);
      console.log("Next Index " + nextIndex);

      // first animation
      if( index == 1 && nextIndex == 2 ) { 
      	$isAnimatedFirst.addClass('animated fadeInUp'); 
      	$isAnimatedFirst.eq(0).css('animation-delay', '.3s');
      	$isAnimatedFirst.eq(1).css('animation-delay', '.6s');
      	$isAnimatedFirst.eq(2).css('animation-delay', '.9s');
      }

    /**
      * use the following condition: 
      *
      *   else if( index == 2 && direction == 'down' ) {
      *
      * if you haven't enabled the dot navigation
      * or you aren't interested in the animations that occur 
      * when you jump (using the dot navigation) from the first section to the third one 
      */
      
      // second animation
      else if( ( index == 1 || index == 2 ) && nextIndex == 3 ) {
      	$isAnimatedSecond.addClass('animated fadeInUp'); 
      	$isAnimatedSecond.eq(0).css('animation-delay', '.3s');
      	$isAnimatedSecond.eq(1).css('animation-delay', '.6s');
      	$isAnimatedSecond.eq(2).css('animation-delay', '.9s');
      	// $isAnimatedThirdSingle.addClass('animated bounceInDown').css('animation-delay', '1.2s');
      }

      
     /**
      * use the following condition:
      *
      *   else if( index == 3 && direction == 'down' ) {
      *
      * if you haven't enabled the dot navigation
      * or you aren't interested in the animations that occur 
      * when you jump (using the dot navigation) 
      * from the first or second section to the fourth one 
      */
      
      // third animation
      else if( ( index == 1 || index == 2 || index == 3 ) && nextIndex == 4 ) {
      	$isAnimatedThird.addClass('animated zoomIn').css('animation-delay', '.6s');
      	// $isAnimatedFourthSingle.addClass('animated lightSpeedIn').css('animation-delay', '1.2s');
      	// $isAnimatedFourthSingle.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      		// $(this).removeClass('lightSpeedIn').addClass('zoomOutDown');
      	// });
      }},
		afterLoad: function(origin, destination, direction) {
			initScrollReveal();
		},
		afterRender: function() {
			initScrollReveal();
		},
		afterResize: function(width, height) {
			initScrollReveal();
		},
		afterResponsive: function(isResponsive) {
			initScrollReveal();
		},
		afterSlideLoad: function(section, origin, destination, direction){
			initScrollReveal();
		},
		onSlideLeave: function(section, origin, destination, direction) {
			initScrollReveal();
		}
	});
}

function handleSubmit(theForm) {
	$(document).off('submit').on('submit', theForm, function(e) {
		var $form = $(e.target);
		var formData = new FormData(e.target);
		formData.append('ajax', 'true');

		if ($form.find('input[name="ajax-target"]').length) {
			var target = $form.find('input[name="ajax-target"]').val();
			var $parent = $(document).find(target).first();
		} else {
			// var $parent = $form.closest('.modal-content').first();
			var $parent = $form.find('.modal-body').first();
		}

		$parent.html('<div class="loader m-x-auto block"><div class="double-bounce1"></div><div class="double-bounce2"></div></div>');

		$.ajax({
			method: "POST",
			// url: $form.attr('action'),
			url: 'modules/sendAnswersToKlicktipp.php',
			data: formData,
			async: true,
			cache: false,
			contentType: false,
			processData: false,
			success: function(data, success, jqXHR) {
				console.log(data);
				$parent.html(data);

				$('#confirmCalculator').addClass("d-none");
				$('#closeCalculator').removeClass("d-none");

				try {
					$parent.closest('.modal').modal('handleUpdate');
				} catch (e) {
					console.log("Catched in success");
					console.log(e);
					console.log($parent.closest('.modal'));
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				console.log(jqXHR);
				console.log(textStatus);
				console.log(errorThrown);
				$parent.html('Es ist ein Fehler aufgetreten.');
			}
		});

		e.preventDefault();
		return false;
	});
}

function contactForm() {
	if ($('#contact-form').length <= 0) {
		return false;
	}

	$(document).off('submit').on('submit', $('#contact-form'), function(e) {
		var $form = $(e.target);
		var formData = new FormData(e.target);
		formData.append('ajax', 'true');

		if ($form.find('input[name="ajax-target"]').length) {
			var target = $form.find('input[name="ajax-target"]').val();
			var $parent = $(document).find(target).first();
		} else {
			var $parent = $form.closest('.modal-content').first();
		}

		$('#contact-form-result').html('<div class="loader m-x-auto block"><div class="double-bounce1"></div><div class="double-bounce2"></div></div>');

		$.ajax({
			method: "POST",
			url: $form.attr('action'),
			data: formData,
			async: true,
			cache: false,
			contentType: false,
			processData: false,
			success: function(data, success, jqXHR) {
				$parent.html(data);
				try {
					// console.log(data);
					$('#contact-form-result').html(data);
					return true;
				} catch (e) {
					console.log("Caught in success");
					console.log(e);
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				console.log(jqXHR);
				console.log(textStatus);
				console.log(errorThrown);
				$('#contact-form-result').html('Es ist ein Fehler aufgetreten.');
			}
		});

		e.preventDefault();
		return false;
	});
}

function collectFields() {
	$(document).find('#optinModal input').each(function(i, obj) {
		if ($(obj).attr('name').startsWith('hidden_')) { 
			// skip
			return true;
		}

		if ($('#hidden_' + $(obj).attr('name')).length > 0) {
			if (!$(obj).is(':checked') && ($(obj).attr("type") == "radio") || $(obj).attr("type") == "checkbox") {
				return true;
			} else {
				$('#hidden_' + $(obj).attr('name')).val($(obj).val());
			}
		} else {
			if (!$(obj).is(':checked') && ($(obj).attr("type") == "radio") || $(obj).attr("type") == "checkbox") {
				return true;
			} else {
				$('#optinModal form').first().append('\
					<input type="hidden" id="hidden_' + $(obj).attr('name') + '" name="hidden_' + $(obj).attr('name') + '" value="' + $(obj).val() + '">\
				');
			}
		}
	});
}

function optinModal() {
	// $("#optinModal").on('hide.bs.modal', function(e) {
	$("#optinModal").on('hidden.bs.modal', function(e) {
		$("#startCalculator").attr("disabled", false);
		// $("#startCalculator").removeClass("d-none");
		$("#startCalculator").addClass("d-none");
		$("#confirmCalculator").addClass("d-none");
		// $("#closeCalculator").addClass("d-none");
		currentPosition = 1;
		percent = 0;

		page_id = "";

		if (document.body.id) {
			page_id = document.body.id;
		} else {
			page_id = "landing";
		}

		$(document).find("#optinModal .modal-body").first().load("/module.php?module=questions&page_id=" + page_id);
	});

	$("#confirmCalculator").on("click", function(e) {
		collectFields();

		theForm = $(document).find("#optinModal form").first();
		isValid = validateForm(theForm);

		if (isValid) {
			handleSubmit(theForm);
			theForm.trigger("submit");
		}
	});

	$("#startCalculator").on("click", function() {
		collectFields();

		$("#optinModal").find(".modal-body").html('\
			<div class="progress">\
			  <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100" style="width: 30%"></div>\
			</div>\
		');

		$progressbar = $("#optinModal").find('.progress-bar');

		var i = 0;
		var steps = 30;
		var percent = 30;
		var n = 0;
		var once = 0;

		$("#startCalculator").val("Wird berechnet");
		$("#startCalculator").attr("disabled", true);

		// while (Number($progressbar.attr("aria-valuenow")) < Number($progressbar.attr("aria-valuemax"))) {
		while (i < 4) {
			(function(i) {
				setTimeout(function() {
					$progressbar.css("width", async function() {
						percent = percent + steps;

						if (percent > 100) {
							percent = 100;
						}

						$(this).attr("aria-valuenow", percent);
						$(this).attr("style", "width: " + percent + "%");

						setTimeout(function(){

							if (percent == 100) {
								if (once > 0) {
									return false;
								}

								once = 1;

								// $("#optinModal").find(".modal-body").html('\
								// 	<p>Vielen Dank! Sie erhalten Ihr persönliches Ergebnis in spätestens 24 Stunden.</p>\
								// ');

								$("#confirmCalculator").addClass("d-none");
								$("#closeCalculator").removeClass("d-none");

								theForm = $(document).find("#optinModal form").first();
								handleSubmit(theForm);
								theForm.trigger("submit");

								currentPosition = 0;
								percent = 0;
								return true;
							}
						}, 1000);

					});
				}, 700 * i);
			})(i++);
		}
	});
}

function addTrackingPixel(klicktipp_pixel_id) {
	if (!klicktipp_pixel_id) {
		return false;
	}

	var pixel = document.createElement("IMG");
	pixel.setAttribute("src", "https://www.klick-tipp.com/pix/" + klicktipp_pixel_id);
	pixel.setAttribute("height", "1");
	pixel.setAttribute("width", "1");
	document.body.appendChild(pixel);
}

function optinModalRide() {
	currentPosition = 1;

	// $(document).on("change", '.answer-label.input-radio', function() {
	$(document).on("change", 'input.form-check-input[type=radio]', function(e) {
		addTrackingPixel($(this).data("klicktipp-pixel-id"));

		collectFields();
		$(this).parents('.question-form-group').removeClass('active');
		currentPosition++;

		$('#questionnaire-progress').css("width", function() {
			return (currentPosition * $(this).data("step-size")) + "%";
		});

		group_counter = $(this).parents('.question-form-group').parent().find('.question-form-group').length;
		group_with_conditons_counter = $(this).parents('.question-form-group').parent().find('.question-form-group.has-condition').length;

		if (group_with_conditons_counter > 0) {
			relevant_group_counter = group_counter - group_with_conditons_counter + 1;
		} else {
			relevant_group_counter = group_counter;
		}

		// console.log("Current Position " + currentPosition.toString());
		// console.log("Group counter " + group_counter.toString());
		// console.log("Group with Conditions counter " + group_with_conditons_counter.toString());
		// console.log("Relevant Group Counter " + relevant_group_counter.toString());

		if (currentPosition == relevant_group_counter) {
			// $('#startCalculator').removeClass("d-none");
			$('#confirmCalculator').removeClass("d-none");
			$('#closeCalculator').addClass("d-none");
		}

		$(document).find('.question-form-group').each(function(index, value) {
			if (typeof $(this).data('conditions') !== 'undefined') {
				conditions_arr = $(this).data('conditions').split(',');
				answer_cache = $('#hidden_question_answer_' + conditions_arr[1]);

				if (answer_cache.val() == conditions_arr[2]) {
					$(this).addClass('condition-resolved');
				}
			}
		});

		if ($(document).find('.question-form-group-position-' + currentPosition).first()) {
			calculate = (currentPosition - 1) * 100;
			$('#question-row').css("transform", "translate(-" + calculate + "%)");
			// element = $(document).find('.question-form-group-position-' + currentPosition).first();
			// element.addClass('active');

			// element.parent().children().each(function(index, element) {
			// 	currentElement = $(this);

			// 	// offset = Number(currentPosition) - Number(currentElement.data("position"));
			// 	offset = Number(currentPosition) - 1;
			// 	calculate = offset * 100;
			// 	currentElement.css("transform", "translate(-" + calculate + "%)");
			// });

			window.location.hash = currentPosition;
		}
	});

}

$(document).ready(function() {
	initSmoothScrolling();
	initScrollReveal();
	// initFullPage();
	contactForm();
	optinModalRide();
	optinModal();
});