;(function () {
	
	'use strict';

	var mobileMenuOutsideClick = function() {

		$(document).click(function (e) {
	    var container = $("#fh5co-offcanvas, .js-fh5co-nav-toggle");
	    if (!container.is(e.target) && container.has(e.target).length === 0) {

	    	if ( $('body').hasClass('offcanvas') ) {

    			$('body').removeClass('offcanvas');
    			$('.js-fh5co-nav-toggle').removeClass('active');
	    	}
	    }
		});

	};

	var offcanvasMenu = function() {

		$('#page').prepend('<div id="fh5co-offcanvas" />');
		$('#page').prepend('<a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle fh5co-nav-white"><i></i></a>');
		var clone1 = $('.menu-1 > ul').clone();
		$('#fh5co-offcanvas').append(clone1);
		var clone2 = $('.menu-2 > ul').clone();
		$('#fh5co-offcanvas').append(clone2);

		$('#fh5co-offcanvas .has-dropdown').addClass('offcanvas-has-dropdown');
		$('#fh5co-offcanvas')
			.find('li')
			.removeClass('has-dropdown');

		// Hover dropdown menu on mobile
		$('.offcanvas-has-dropdown').mouseenter(function(){
			var $this = $(this);

			$this
				.addClass('active')
				.find('ul')
				.slideDown(500, 'easeOutExpo');				
		}).mouseleave(function(){

			var $this = $(this);
			$this
				.removeClass('active')
				.find('ul')
				.slideUp(500, 'easeOutExpo');				
		});


		$(window).resize(function(){

			if ( $('body').hasClass('offcanvas') ) {

    			$('body').removeClass('offcanvas');
    			$('.js-fh5co-nav-toggle').removeClass('active');
				
	    	}
		});
	};

	var burgerMenu = function() {

		$('body').on('click', '.js-fh5co-nav-toggle', function(event){
			var $this = $(this);


			if ( $('body').hasClass('overflow offcanvas') ) {
				$('body').removeClass('overflow offcanvas');
			} else {
				$('body').addClass('overflow offcanvas');
			}
			$this.toggleClass('active');
			event.preventDefault();

		});
	};

	var contentWayPoint = function() {
		var i = 0;
		$('.animate-box').waypoint( function( direction ) {

			if( direction === 'down' && !$(this.element).hasClass('animated-fast') ) {
				
				i++;

				$(this.element).addClass('item-animate');
				setTimeout(function(){

					$('body .animate-box.item-animate').each(function(k){
						var el = $(this);
						setTimeout( function () {
							var effect = el.data('animate-effect');
							if ( effect === 'fadeIn') {
								el.addClass('fadeIn animated-fast');
							} else if ( effect === 'fadeInLeft') {
								el.addClass('fadeInLeft animated-fast');
							} else if ( effect === 'fadeInRight') {
								el.addClass('fadeInRight animated-fast');
							} else {
								el.addClass('fadeInUp animated-fast');
							}

							el.removeClass('item-animate');
						},  k * 200, 'easeInOutExpo' );
					});
					
				}, 100);
				
			}

		} , { offset: '85%' } );
	};

	var dropdown = function() {

		$('.has-dropdown').mouseenter(function(){

			var $this = $(this);
			$this
				.find('.dropdown')
				.css('display', 'block')
				.addClass('animated-fast fadeInUpMenu');

		}).mouseleave(function(){
			var $this = $(this);

			$this
				.find('.dropdown')
				.css('display', 'none')
				.removeClass('animated-fast fadeInUpMenu');
		});

	};

	var testimonialCarousel = function(){
		var owl = $('.owl-carousel-fullwidth');
		owl.owlCarousel({
			items: 1,
			loop: true,
			margin: 0,
			responsiveClass: true,
			nav: false,
			dots: true,
			smartSpeed: 800,
			autoHeight: true,
		});
	};

	var goToTop = function() {

		$('.js-gotop').on('click', function(event){
			
			event.preventDefault();

			$('html, body').animate({
				scrollTop: $('html').offset().top
			}, 500, 'easeInOutExpo');
			
			return false;
		});

		$(window).scroll(function(){

			var $win = $(window);
			if ($win.scrollTop() > 200) {
				$('.js-top').addClass('active');
			} else {
				$('.js-top').removeClass('active');
			}

		});
	
	};

	var addField = async function() {
		$('.js-addField').on('click', async function(event){
			
			event.preventDefault();

			// Container <div> where dynamic content will be placed
			var container = document.getElementById("js-attentants");
			// Clear previous contents of the container
			// while (container.hasChildNodes()) {
			// 	container.removeChild(container.lastChild);
			// }
			//container.appendChild()

			// Append a node with a random text
			//container.appendChild(document.createTextNode("Member"));
			var outerDiv = document.createElement("div");
			outerDiv.style="padding-top: 20px;";

			var firstNameDiv = document.createElement("div");
			firstNameDiv.classList.add('col-md-5');
			firstNameDiv.classList.add('col-sm-5');
			var formGroupDiv = document.createElement("div");
			formGroupDiv.classList.add('form-group');
			firstNameDiv.appendChild(formGroupDiv);

			//Label
			var labelElement = document.createElement("label");
			labelElement.setAttribute("for","firstname");
			labelElement.classList.add('sr-only');
			labelElement.innerHTML = "Vorname";
			formGroupDiv.appendChild(labelElement);
			
			//Input
			var inputElement = document.createElement("input");
			inputElement.setAttribute("type","firstname");
			inputElement.classList.add('form-control');
			inputElement.classList.add('js-form-input');
			inputElement.setAttribute("id","firstname");
			inputElement.setAttribute("data-i18n","firstname");
			inputElement.setAttribute("data-i18n-attr","placeholder");
			let firstname_placeholder = await translator.getTranslationByKey(document.documentElement.lang,"firstname");
			inputElement.setAttribute("placeholder", firstname_placeholder);
			formGroupDiv.appendChild(inputElement);

			outerDiv.appendChild(firstNameDiv);
			

			var lastNameDiv = document.createElement("div");
			lastNameDiv.classList.add('col-md-5');
			lastNameDiv.classList.add('col-sm-5');
			var lastnameFormGroupDiv = document.createElement("div");
			lastnameFormGroupDiv.classList.add('form-group');
			lastNameDiv.appendChild(lastnameFormGroupDiv);

			//Label
			var lastNamelabelElement = document.createElement("label");
			lastNamelabelElement.setAttribute("for","lastname");
			lastNamelabelElement.classList.add('sr-only');
			lastNamelabelElement.innerHTML = "Nachname";
			lastnameFormGroupDiv.appendChild(lastNamelabelElement);

			//Input
			var firstNameInputElement = document.createElement("input");
			firstNameInputElement.setAttribute("type","lastname");
			firstNameInputElement.classList.add('form-control');
			firstNameInputElement.classList.add('js-form-input');
			firstNameInputElement.setAttribute("id","lastname");
			firstNameInputElement.setAttribute("data-i18n","lastname");
			firstNameInputElement.setAttribute("data-i18n-attr","placeholder");
			let lastname_placeholder = await translator.getTranslationByKey(document.documentElement.lang,"lastname");
			firstNameInputElement.setAttribute("placeholder", lastname_placeholder);
			lastnameFormGroupDiv.appendChild(firstNameInputElement);

			outerDiv.appendChild(lastNameDiv);	

			let underTwelveDiv = document.createElement("div");
			underTwelveDiv.classList.add('col-md-2');
			underTwelveDiv.classList.add('col-sm-2');

			let underTwelveInnerDiv = document.createElement("div");
			underTwelveInnerDiv.classList.add('undertwelve');

			let underTwelveLabel = document.createElement("label");
			underTwelveLabel.setAttribute("for","undertwelve");
			underTwelveLabel.setAttribute("data-i18n","undertwelve");
			underTwelveLabel.innerHTML = await translator.getTranslationByKey(document.documentElement.lang,"undertwelve");

			underTwelveInnerDiv.appendChild(underTwelveLabel);

			let underTwelveInput = document.createElement("input");
			underTwelveInput.classList.add('js-undertwelve');
			underTwelveInput.classList.add('js-form-input');
			underTwelveInput.setAttribute("type","checkbox");
			underTwelveInput.setAttribute("name","undertwelve");

			underTwelveInnerDiv.appendChild(underTwelveInput);
			underTwelveDiv.appendChild(underTwelveInnerDiv);
			outerDiv.appendChild(underTwelveDiv);

			container.appendChild(outerDiv);
			
			return false;
		});
	}

	// Loading page
	var loaderPage = function() {
		$(".fh5co-loader").fadeOut("slow");
	};

	var counter = async function() {
		let res = await fetch("https://rismer.de:9999/family/familycount", {
			method: "GET",
			headers: {
				'Content-Type': 'application/json'
			}
			//body: JSON.stringify(data)
		});
		let json = await res.json();
		$('.js-counter').countTo({
			from: 0,
			to: json,
			speed: 5000,
			 formatter: function (value, options) {
	      return value.toFixed(options.decimals);
	    },
		});
	};

	var counterWayPoint = function() {
		if ($('#fh5co-counter').length > 0 ) {
			$('#fh5co-counter').waypoint( function( direction ) {
										
				if( direction === 'down' && !$(this.element).hasClass('animated') ) {
					setTimeout( counter , 400);					
					$(this.element).addClass('animated');
				}
			} , { offset: '90%' } );
		}
	};

	// Parallax
	var parallax = function() {
		$(window).stellar({ horizontalScrolling: false });
	};

	var defaultUncheckedInputCheckboxes = function() {
		var inputs = document.getElementsByTagName('input');

		for (var i=0; i<inputs.length; i++)  {
		if (inputs[i].type == 'checkbox')   {
			inputs[i].checked = false;
		}
		}
	}

	var changeLanguage = function() {
		$('.change-language-js').on('click', function(event){
			
			event.preventDefault();

			if(document.documentElement.lang == "de")
			{
				translator.load("hr");
				$(".js-flag-image").attr("srcset","flags/4x3/de.svg");
				$(".js-flag-image").attr("src","flags/4x3/de.svg");
			} else
			{
				translator.load("de");
				$(".js-flag-image").attr("srcset","flags/4x3/hr.svg");
				$(".js-flag-image").attr("src","flags/4x3/hr.svg");
			}
			
			return false;
		});
	}
	
	$(function(){
		mobileMenuOutsideClick();
		parallax();
		offcanvasMenu();
		burgerMenu();
		contentWayPoint();
		dropdown();
		testimonialCarousel();
		goToTop();
		loaderPage();
		counter();
		counterWayPoint();
		addField();
		defaultUncheckedInputCheckboxes();
		changeLanguage();
	});
}());


document.getElementById("js-submitbtn").addEventListener("click", async function () {
	event.preventDefault();

	let inputs = document.querySelectorAll('.js-form-input');

	console.log(inputs);
	let from = inputs[0].value;
 	let message = inputs[1].value;

	if(StringLengthLT2(from))
	{
		SubmitError("Name too short!");
		return;
	}

	if(StringLengthLT2(message))
	{
		SubmitError("message too short!");
		return;
	}

	let contact = {
				from: from,
				email: "none",
				message: message,
		};

	const response = await fetch("https://rismer.de:9999/contact", {
		method: 'POST', // *GET, POST, PUT, DELETE, etc.
		mode: 'cors', // no-cors, *cors, same-origin
		cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
		//credentials: 'same-origin', // include, *same-origin, omit
		headers: {
		'Content-Type': 'application/json'
		// 'Content-Type': 'application/x-www-form-urlencoded',
		},
		redirect: 'follow', // manual, *follow, error
		referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
		body: JSON.stringify(contact) // body data type must match "Content-Type" header
	}).catch(function (timeout) { SubmitError("API error. Call the phone number."); });

	console.log("Request: " + JSON.stringify(contact));

	if(response.ok)
	{
		let jsonResponse = await response.json();
		console.log("Response: " + jsonResponse);
		SubmitSuccess();
	}
	else
	{
		SubmitError();
	}
});

// document.getElementById("js-submitbtn").addEventListener("click", async function () {
// 	//document.getElementById("js-attentants").elements["foo"]
// 	let inputs = document.querySelectorAll('.js-form-input');

// 	console.log(inputs);

// 	let firstname = inputs[0].value;
// 	let lastname = inputs[1].value;
// 	let telephonenumber = inputs[2].value;
// 	let eMail = inputs[3].value;

// 	if(StringLengthLT2(firstname))
// 	{
// 		SubmitError("Firstname too short!");
// 		return;
// 	}

// 	if(StringLengthLT2(lastname))
// 	{
// 		SubmitError("Lastname too short!");
// 		return;
// 	}

// 	if(StringLengthLT2(telephonenumber))
// 	{
// 		SubmitError("Telephonenumber too short!");
// 		return;
// 	}

// 	if(!OnlyNumbersInString(telephonenumber))
// 	{
// 		SubmitError("Telephonenumber can only contain numbers!");
// 		return;	
// 	}

// 	if(StringLengthLT2(eMail))
// 	{
// 		SubmitError("E-Mail too short!");
// 		return;
// 	}

// 	let overnightRequired = false;

// 	if ($('.overnight-js').is(":checked")) {
// 		overnightRequired = true;
// 	}

// 	let family = {
// 		name: lastname,
// 		overnight: overnightRequired,
// 		telephonenumber: telephonenumber,
// 		email: eMail,
// 		members: []
// 	  };

// 	let familyMember = {
// 		name: firstname + " " + lastname,
// 		isChild: false
// 	}

// 	family.members.push(familyMember);

// 	for (let i = 4; i < inputs.length; i+=3) 
// 	{
// 		let firstname = inputs[i].value;
// 		let lastname = inputs[i+1].value;
// 		let isChild = inputs[i+2].checked;
// 		console.log("IsChild" + isChild);
// 		if(StringLengthLT2(firstname))
// 		{
// 			SubmitError("Firstname of accompaniment too short!");
// 			return;
// 		}
// 		if(StringLengthLT2(lastname))
// 		{
// 			SubmitError("Lastname of accompaniment too short!");
// 			return;
// 		}
// 		let familyMember = {
// 			name: firstname + " " + lastname,
// 			isChild: isChild
// 		}

// 		family.members.push(familyMember);
// 	}

// 	console.log("Request: " + JSON.stringify(family));

	
// 	const response = await fetch("https://rismer.de:9999/family", {
// 		method: 'POST', // *GET, POST, PUT, DELETE, etc.
// 		mode: 'cors', // no-cors, *cors, same-origin
// 		cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
// 		//credentials: 'same-origin', // include, *same-origin, omit
// 		headers: {
// 		  'Content-Type': 'application/json'
// 		  // 'Content-Type': 'application/x-www-form-urlencoded',
// 		},
// 		redirect: 'follow', // manual, *follow, error
// 		referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
// 		body: JSON.stringify(family) // body data type must match "Content-Type" header
// 	  }).catch(function (timeout) { SubmitError("API error. Call the phone number."); });
// 	if(response.ok)
// 	{
// 		let jsonResponse = await response.json();
// 		console.log("Response: " + jsonResponse);
// 		SubmitSuccess();
// 	}
// 	else
// 	{
// 		SubmitError();
// 	}
// 	  //TODO: Refresh attentats count
//   });

  function OnlyNumbersInString(string)
  {
	  return /^\d+$/.test(string);
  }

  function StringLengthLT2(string)
  {  
	  return string.length < 2;
  }

  async function SubmitError(reason) {
	  let errorText = "Something went wrong...";
	  if(reason)
	  {
		errorText = reason;
	  }
	swal({
		type: 'error',
		title: 'Oops...',
		text: errorText,
	}).then(function () {
		//  swal( 'Ready?!', 'Your form is going to be submitted.' 'success');
		//document.querySelector('#myfrm').submit(); // manully submit 
	}).catch(function (timeout) { });
	return;
  }

  async function SubmitSuccess() {
	let title = 'Rückgemeldet';
	let text = "Nun gibt es kein zurück mehr!";
	title = await translator.getTranslationByKey(document.documentElement.lang,"success_title");
	text = await translator.getTranslationByKey(document.documentElement.lang,"success_text");

	swal({
		title: title,
		text: text,
		type: 'success',
		showConfirmButton: false,
		timer: 2000
	}).then(function () {
		//  swal( 'Ready?!', 'Your form is going to be submitted.' 'success');
		//document.querySelector('#myfrm').submit(); // manully submit 
	}).catch(function (timeout) { });

	document.getElementById("js-submitbtn").disabled = 'true';
	document.getElementById("js-submitbtn").textContent = await translator.getTranslationByKey(document.documentElement.lang,"already_participating");
	return;
  }

  class Translator {
	constructor(options = {}) {
	  this._options = Object.assign({}, this.defaultConfig, options);
	  this._elements = document.querySelectorAll("[data-i18n]");
	  this._cache = new Map();
  
	  if (this._options.detectLanguage) {
		let detectLanguage = this._detectLanguage();
		if(this._options.languages.includes(detectLanguage))
		{
			this._options.defaultLanguage = detectLanguage;
		}
	  }



	  document.documentElement.lang = this._options.defaultLanguage;
  
	  if (
		this._options.defaultLanguage &&
		typeof this._options.defaultLanguage == "string"
	  ) {
		this._getResource(this._options.defaultLanguage);
	  }

	  this.load(document.documentElement.lang);
	}
  
	_detectLanguage() {
	  var stored = localStorage.getItem("language");
  
	  if (this._options.persist && stored) {
		return stored;
	  }
  
	  var lang = navigator.languages
		? navigator.languages[0]
		: navigator.language;
  
	  return lang.substr(0, 2);
	}
  
	_fetch(path) {
	  return fetch(path)
		.then(response => response.json())
		.catch(() => {
		  console.error(
			`Could not load ${path}. Please make sure that the file exists.`
		  );
		});
	}
  
	async _getResource(lang) {
	  if (this._cache.has(lang)) {
		return JSON.parse(this._cache.get(lang));
	  }
  
	  var translation = await this._fetch(
		`${this._options.filesLocation}/${lang}.json`
	  );
  
	  if (!this._cache.has(lang)) {
		this._cache.set(lang, JSON.stringify(translation));
	  }
  
	  return translation;
	}
  
	async load(lang) {
	  if (!this._options.languages.includes(lang)) {
		return;
	  }

	  this._elements = document.querySelectorAll("[data-i18n]");
	  
	  document.documentElement.lang = lang;

	  this._translate(await this._getResource(lang));
  
	  if (this._options.persist) {
		localStorage.setItem("language", lang);
	  }
	}
  
	async getTranslationByKey(lang, key) {
	  if (!key) throw new Error("Expected a key to translate, got nothing.");
  
	  if (typeof key != "string")
		throw new Error(
		  `Expected a string for the key parameter, got ${typeof key} instead.`
		);
  
	  var translation = await this._getResource(lang);
  
	  return this._getValueFromJSON(key, translation, true);
	}
  
	_getValueFromJSON(key, json, fallback) {
	  var text = key.split(".").reduce((obj, i) => obj[i], json);
  
	  if (!text && this._options.defaultLanguage && fallback) {
		let fallbackTranslation = JSON.parse(
		  this._cache.get(this._options.defaultLanguage)
		);
  
		text = this._getValueFromJSON(key, fallbackTranslation, false);
	  } else if (!text) {
		text = key;
		console.warn(`Could not find text for attribute "${key}".`);
	  }
  
	  return text;
	}
  
	_translate(translation) {
	  var zip = (keys, values) => keys.map((key, i) => [key, values[i]]);
	  var nullSafeSplit = (str, separator) => (str ? str.split(separator) : null);
  
	  var replace = element => {
		var keys = nullSafeSplit(element.getAttribute("data-i18n"), " ") || [];
		var properties = nullSafeSplit(
		  element.getAttribute("data-i18n-attr"),
		  " "
		) || ["innerHTML"];
  
		if (keys.length > 0 && keys.length !== properties.length) {
		  console.error(
			"data-i18n and data-i18n-attr must contain the same number of items"
		  );
		} else {
		  var pairs = zip(keys, properties);
		  pairs.forEach(pair => {
			const [key, property] = pair;
			var text = this._getValueFromJSON(key, translation, true);
  
			if (text) {
			  element[property] = text;
			  element.setAttribute(property, text);
			} else {
			  console.error(`Could not find text for attribute "${key}".`);
			}
		  });
		}
	  };
	  
	  this._elements.forEach(replace);
	}
  
	get defaultConfig() {
	  return {
		persist: false,
		languages: ["de"],
		defaultLanguage: "",
		detectLanguage: true,
		filesLocation: "/i18n"
	  };
	}
  }
  
  var translator = new Translator({
	persist: false,
	languages: ["hr", "de"],
	defaultLanguage: "hr",
	detectLanguage: true,
	filesLocation: "/i18n"
  });

if (document.documentElement.lang == "de") {
	$(".js-flag-image").attr("src","flags/4x3/hr.svg");
	$(".js-flag-image").attr("srcset","flags/4x3/hr.svg");
}
else {
	$(".js-flag-image").attr("srcset","flags/4x3/de.svg");
	$(".js-flag-image").attr("src","flags/4x3/de.svg");
}

	//translator.load(translator._options.detectLanguage);
