/*
 * Config
 *
 */
var googleAnalyticsID = "UA-00000000-0";
var matomoBaseUrl = 'https://www.kvg.de/piwik/';
var matomoSiteID = '';
// Zum Online-Gang aktivieren
var matomoSiteID = 2;

switch (window.location.hostname) {
	case 'www.kvg.de':
		matomoSiteID = 2;
		break;
	case 'kvg.de':
		matomoSiteID = 2;
		break;
	case 'www.125-jahre-kvg.de':
		matomoSiteID = 26;
		break;
	case '125-jahre-kvg.de':
		matomoSiteID = 26;
		break;
	default:
	  console.log(window.location.hostname);
	  break;
}



/*
 * Module
 *
 */


swe.slider("slider", ".slider", {
  // Options ...
    prevNextButtons: false
});

swe.slider('newsSlider', '.news-slider', {
  prevNextButtons: true,
  pageDots: true,
  groupCells: true,
  draggable: '>2',
  wrapAround: false,
  //autoPlay: 5000,
  //fade: true
});

swe.slider('newsSliderAutoplay', '.news-slider-autoplay', {
  prevNextButtons: true,
  pageDots: false,
  groupCells: true,
  draggable: '>2',
  wrapAround: false,
  autoPlay: 5000,
  fade: true
});


swe.checkForm("#demoCheck", "#kontakt-form");


swe.mobileNav(".mobile", {
  buttonsSelector: "nav.desktop button.open-nav",
  slidingSide: "right",
});


swe.lightbox(".lightbox", {
  // String or HTML for the navigation buttons
  navText: ["&lsaquo;", "&rsaquo;"],

  // String or HTML for the close button
  closeText: "&times;",

  // String or HTML for the zoom icon
  zoomText: "<i class=\"fa fa-expand\" aria-hidden=\"true\"></i>",
});


swe.googleAnalytics(googleAnalyticsID);
swe.smoothScroll(".nav-container");
swe.lazyLoad();
swe.loadMap();
swe.accordion();
swe.counter('bounceIn');
swe.up("#top", ".top");
swe.fixedNav();


swe.sameHeight(".equal-height");

// News Slider auf der Startseite
swe.sameHeight(".equal-height-6990 .news-content");
swe.sameHeight(".equal-height-7032 .news-content");
swe.sameHeight(".equal-height-6993 .news-content");
swe.sameHeight(".equal-height-7191 .news-content");




//
var changeURL = function(image, inputField, defaultValue, set) {
  var str = "&pw=600&co=80&convert=png&ac=695810F7BB5685E9E158B45AC4DF6230",
      setValue = encodeURIComponent(document.querySelector(inputField).value);

  if (setValue === "") {
    setValue = defaultValue;
  }

  newURL = "https://www.bildperso.de/DSMO/streamimage.aspx?set=" + set + "&t=" + setValue + str;

  document.querySelector(image).setAttribute("src", newURL);
};




/*
 * Scroll event
 *
 */
var scrollTicking = false;

window.addEventListener("scroll", function () {
  if (!scrollTicking) {
    window.requestAnimationFrame(function () {
      // ...



      scrollTicking = false;
    });
  }
  scrollTicking = true;
});




/*
 * Resize event
 *
 */
var resizeTicking = false;

window.addEventListener("resize", function () {
  if (!resizeTicking) {
    window.requestAnimationFrame(function () {
      // ...



      resizeTicking = false;
    });
  }
  resizeTicking = true;
});

function openNews(element) {
    document.querySelector('#'+element+' .button-center').style.display = "none";
    document.querySelector('#'+element+' .body-text').style.display = "block";
    document.querySelector('#'+element+' .news-img-wrap .caption').style.display = "block";
    return false;
}

function closeNews(element) {
  document.querySelector('#'+element+' .button-center').style.display = "block";
  document.querySelector('#'+element+' .body-text').style.display = "none";
  document.querySelector('#'+element+' .news-img-wrap .caption').style.display = "none";
  document.getElementById(element).scrollIntoView({
	behavior: 'smooth'
  });
  return false;
}

/* Verbindungssuche */
var verbindungDate = swe.datetimepicker("fp", "#date", {
  dateFormat: 'd.m.Y H:i',
  enableTime: true,
  defaultDate: new Date(),
  minDate: Date.now(),
  maxDate: new Date().fp_incr(21),
  minuteIncrement: 1,
  onChange: function (selectedDates, dateStr, instance) {
    var selectedTime = document.querySelector('#selectedTime');
    if (!selectedTime) return;

    if (dateStr.length > 0) {
      selectedTime.innerText = dateStr;
      instance.input.value = dateStr;
      return;
    }

    selectedTime.innerText = 'Jetzt';
  },
});

if (document.getElementById("changeDirection") !== null) {
    document.getElementById("changeDirection").addEventListener("click", function() {
      let form = document.querySelector('#verbindungssuche');
      if (!form) return;

      let startElement = form.querySelector('[name="start"]'),
        destinationElement = form.querySelector('[name="ziel"]');

      if (!startElement || !destinationElement) return;

      let start = startElement.value.trim(),
        destination = destinationElement.value.trim();

      startElement.value = destination;
      destinationElement.value = start;
    });
}
if (document.getElementById("selectTime") !== null) {
    document.getElementById("selectTime").addEventListener("click", function() {
      if (!verbindungDate) return;
      verbindungDate.toggle();
    });
}
if (document.getElementById("resetSettings") !== null) {
    document.getElementById("resetSettings").addEventListener("click", function() {
      if (verbindungDate) {
        verbindungDate.clear();
      }

      var form = document.querySelector('#verbindungssuche');
      if (!form) return;

      var start = form.querySelector('[name="start"]'),
        destination = form.querySelector('[name="ziel"]');

      if (!start || !destination) return;
      start.value = '';
      destination.value = '';
    });
}

if (document.getElementById("verbindung-start") !== null) {
  document.getElementById("verbindung-start").addEventListener("click", function() {
    if (this.value.length > 0) return
    this.value = 'Kassel ';
  });
}

if (document.getElementById("verbindung-ziel") !== null) {
  document.getElementById("verbindung-ziel").addEventListener("click", function() {
    if (this.value.length > 0) return
    this.value = 'Kassel ';
  });
}

/**
 * Get the date string of the current date in format dd.mm.yyy
 *
 * @return {string}
 */
function getCurrentDateString () {
  let currentDate = '',
    today = new Date(),
    currentDateArray = [
      today.getDate(),
      today.getMonth() + 1,
      today.getFullYear(),
    ]

  if (currentDateArray[0] < 10) currentDateArray[0] = '0' + currentDateArray[0]
  if (currentDateArray[1] < 10) currentDateArray[1] = '0' + currentDateArray[1]

  currentDate = currentDateArray.join('.')

  return currentDate
}

// region Hafas Autocomplete

/**
 * Creates the url for the map
 *
 * Diese Funktion ist von der NVV übernommen und nur etwas angepasst um ohne jQuery und mit unseren Klassen/IDs zu
 * funktionieren.
 *
 * [04.09.2019] [Luca Braun] TODO: Die elemente "Date" und "Time" müssen noch angelegt werden. Bei der NVV sind sie
 *                                hidden und haben das aktuelle datum und 'now' als value.
 */
function createHafasUrl () {
  let form = document.querySelector('#verbindungssuche')

  if (!form) return

  let submit = form.querySelector('[type="submit"]'),
    startElement = form.querySelector('[name="start"]'),
    destinationElement = form.querySelector('[name="ziel"]'),
    dateElement = form.querySelector('#selectedTime')

  if (!submit || !startElement || !destinationElement) return

  submit.addEventListener('click', function (event) {
    event.stopPropagation()
    event.preventDefault()

    let start = startElement.value.trim(),
      destination = destinationElement.value.trim(),
      dateValue = dateElement.innerText.trim(),
      currentDate = getCurrentDateString(),
      date = currentDate,
      time = 'now'

    // If a time was selected
    if (!isNaN(dateValue.substr(0, 1))) {
      let dateArray = dateValue.split(' ')
      date = dateArray[0]
      time = dateArray[1]
    }

    // Check if input fields contain values. If not clear destination and start parameter
    let paramString = {
      start: '!S|' + start,
      destination: '!Z|' + destination,
      date: '!date|' + date,
      time: '!time|' + time,
    }

    if (!start) paramString.start = ''
    if (!destination) paramString.destination = ''

    let url = form.getAttribute('action').split('?').shift()
    url += '?VAR='
    url += paramString.start
    url += paramString.destination
    url += paramString.date
    url += paramString.time

    window.open(url, '_self')
  })
}

// Die Variable "hafWebappUrl" muss global sein und darf nicht umbenannt werden.
// Sie wird in den Hafas Scripts ebenfalls verwendet.
var hafWebappUrl = 'https://auskunft.nvv.de/'; // Wird auch bei NVV verwendet

// New link - E-Mail Hr. Aue vom 15.10.2021
//hafWebappUrl = 'https://demo.hafas.de/webapp/nvv/preview_edc95a6446b2a094b28e543b84419c83/';

if (window.location.hostname == 'www.kvg.de') {

  // Fügt automatisch das Script für Hafas ein, das alle anderen notwendigen Scripte lädt.
  (function() {
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = hafWebappUrl + 'js/build/_external/hafas_external_suggest.js';
    document.getElementsByTagName('head')[0].appendChild(script);
  })()

  createHafasUrl(); 
}

// endregion

/**
 * Get the given parameters for the Fahrplan-map with the leading hashtag (#).
 *
 * @return {string}
 */
function getVerbindungParameter () {
  let queryString = window.location.search.replace('?', ''),
    queries = queryString.split('&'),
    result = '#'

  for (let i = 0; i < queries.length; i += 1) {
    if (queries[i].substr(0, 3) !== 'VAR') continue
    result += queries[i]
  }

  if (result.length === 1) result = ''

  return result
}

if (document.querySelector('#Fahrplanauskunft')) {
  let iframe = document.querySelector('#Fahrplanauskunft'),
    src = iframe.getAttribute('data-src').split('#')[0]

  src += getVerbindungParameter()

  iframe.setAttribute('src', src)
}

/* -- Webticker -- */
/* --------------- */
if ($("#ticker ul").length) {
  $("#ticker ul").show();
  $("#ticker ul").webTicker();
  $('#ticker .mask').append('<div id="leftMask"></div><div id="rightMask"></div>');
}

if (document.getElementById("btn-search-mobile") !== null) {
  document.getElementById("btn-search-mobile").addEventListener("click", function() {
    window.location.href = "/suche";
  });
}

if (document.getElementById("tx-indexedsearch-searchbox-button-open") !== null) {
  document.getElementById("tx-indexedsearch-searchbox-button-open").addEventListener("click", function() {
    document.querySelector('#tx-indexedsearch-searchbox-button-open~.hiddenSearch').style.display = "block";
    document.querySelector('#tx-indexedsearch-searchbox-button-open>i').style.display = "none";
  });
}


// DCE Darksite
if (document.querySelector('.dce-darksite') !== null) {
  var callButtonClose = document.querySelector('#close-darksite');
  
  callButtonClose.addEventListener('click', function(event) {
      document.querySelector('.dce-darksite').style.display = "none";
  });
  
  let darkSiteCookie = swe.getCookie('cookieDarkSiteKVG');
  
  if (darkSiteCookie === 'Set') {
    document.querySelector('.dce-darksite').style.display = "none";
  } else {
    document.cookie = 'cookieDarkSiteKVG=Set; expires=; path=/';
    document.querySelector('.dce-darksite').style.display = "block";
  }
}
                                     
/*
 * Datenschutzhinweis
 */
if (document.querySelector(".dce-privacy") !== null) {
  let privacyContainer = document.querySelector(".dce-privacy"),
    noteTriggerAllCookies = document.querySelector(".note button.allcookies"),
    noteTriggerSaveCookies = document.querySelector(".note button.savecookies"),
    noteTriggerEditCookies = document.querySelector(".editCookies"),
    noteContainer = document.querySelector(".note"),
    checkboxElements = noteContainer.querySelectorAll("input"),
    infoButtons = noteContainer.querySelectorAll(".privacy-info"),
    bodyContainer = document.querySelector("body");

  [].forEach.call(infoButtons, function(button) {
    button.addEventListener("click", function () {
      if (this.classList.contains("open")) {
        this.classList.remove("open");
      } else {
        this.classList.add("open");
      }
    });
  });

  if (noteTriggerEditCookies) {
    noteTriggerEditCookies.addEventListener("click", function () {
      let cookie = swe.getCookie('cookieBanner2019');

      if (cookie === 'Set') {
        [].forEach.call(checkboxElements, function(element) {
          switch (element.name) {
            case "googleanalytics":
              if (swe.getCookie('cookieGoogleanaltytics') === 'Set') {
                element.checked = true;
              }
              break;
            case "matomo":
              if (swe.getCookie('cookieMatomo') === 'Set') {
                element.checked = true;
              }
              break;
            case "googlemaps":
              if (swe.getCookie('cookieGooglemaps') === 'Set') {
                element.checked = true;
              }
              break;
            case "youtube":
              if (swe.getCookie('cookieYoutube') === 'Set') {
                element.checked = true;
              }
              break;
            default:
              console.log("Element "+element.name+ " unbekannt");
          }
        });
        privacyContainer.style.display = "block";
      } else {
        privacyContainer.style.display = "block";
      }
    });
  }

  noteTriggerAllCookies.addEventListener("click", function () {
    [].forEach.call(checkboxElements, function(element) {
      switch (element.name) {
        case "googleanalytics":
          swe.setCookie('cookieGoogleanaltytics', 'Set', 365);
          swe.googleAnalytics(googleAnalyticsID);
          break;
        case "matomo":
          swe.setCookie('cookieMatomo', 'Set', 365);
          swe.matomo(matomoBaseUrl, matomoSiteID);
          break;
        case "googlemaps":
          swe.setCookie('cookieGooglemaps', 'Set', 365);
          swe.loadMap();
          break;
        case "youtube":
          swe.setCookie('cookieYoutube', 'Set', 365);
          swe.loadIframes();
          swe.responsiveIframe();
          break;
        default:
          console.log("Element "+element.name+ " unbekannt");
      }
    });

    swe.setCookie('cookieBanner2019', 'Set', 365);
    privacyContainer.style.display = "none";
  });

  noteTriggerSaveCookies.addEventListener("click", function () {
    [].forEach.call(checkboxElements, function(element) {
      if (element.checked) {
        switch (element.name) {
          case "googleanalytics":
            swe.setCookie('cookieGoogleanaltytics', 'Set', 365);
            swe.googleAnalytics(googleAnalyticsID);
            break;
          case "matomo":
            swe.setCookie('cookieMatomo', 'Set', 365);
            swe.matomo(matomoBaseUrl, matomoSiteID);
            break;
          case "googlemaps":
            swe.setCookie('cookieGooglemaps', 'Set', 365);
            swe.loadMap();
            break;
          case "youtube":
            swe.setCookie('cookieYoutube', 'Set', 365);
            swe.loadIframes();
            swe.responsiveIframe();
            break;
          default:
            console.log("Element "+element.name+ " unbekannt");
        }
      } else {
        switch (element.name) {
          case "googleanalytics":
            swe.setCookie('cookieGoogleanaltytics', '');
            document.cookie = '_gid=; Path=/; Domain=.domain.tld; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
            document.cookie = '_gat=; Path=/; Domain=.domain.tld; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
            document.cookie = '_ga=; Path=/; Domain=.domain.tld; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
            break;
          case "matomo":
            swe.setCookie('cookieMatomo', '');
            break;
          case "googlemaps":
            swe.setCookie('cookieGooglemaps', '');
            break;
          case "youtube":
            swe.setCookie('cookieYoutube', '');
            break;
          default:
            console.log("Element "+element.name+ " unbekannt");
        }
      }
    });

    swe.setCookie('cookieBanner2019', 'Set', 365);
    privacyContainer.style.display = "none";
  });

  let cookie = swe.getCookie('cookieBanner2019');

  if (cookie === 'Set') {
    if (swe.getCookie('cookieGoogleanaltytics') === 'Set') {
      swe.googleAnalytics(googleAnalyticsID);
    }

    if (swe.getCookie('cookieMatomo') === 'Set') {
      swe.matomo(matomoBaseUrl, matomoSiteID);
    }

    if (swe.getCookie('cookieGooglemaps') === 'Set') {
      swe.loadMap();
    }

    // Iframes
    if (swe.getCookie('cookieYoutube') === 'Set') {
      swe.loadIframes();
      swe.responsiveIframe();
    }
  } else {
    if (bodyContainer.classList.contains("nobanner")) {
      privacyContainer.style.display = "none";
    } else {
      privacyContainer.style.display = "block";
    }
  }
}

// Ticket Accordion Anker Open
(function NavigateAndOpenAccordion() {
    let url = window.location.href.split('#')
    let id = url[1]

	if (!id) return

    let tab = document.querySelector('#' + id)
	
	if (!tab) return

    if (tab.parentElement.parentElement.classList.contains('toplevel')) {
        tab.parentElement.parentElement.firstElementChild.click()
        tab.firstElementChild.firstElementChild.click()
    } else if (tab.parentElement.parentElement.parentElement.parentElement.parentElement.classList.contains('toplevel')) {
        tab.parentElement.parentElement.parentElement.parentElement.parentElement.firstElementChild.click()
        tab.parentElement.parentElement.firstElementChild.click()
        tab.firstElementChild.firstElementChild.click()
    } else if (tab.firstElementChild.firstElementChild.classList.contains('toplevel')) {
        tab.firstElementChild.firstElementChild.firstElementChild.click()
    } else {
		tab.firstElementChild.firstElementChild.click()
	}
})();

                                     
/*
 * Carousel
 *
 */

if(document.querySelector(".carousel") !== null) {
  var sliders = document.querySelectorAll(".carousel");

  // Slider options
  var options = {
    // enable keyboard navigation, pressing left & right keys
    accessibility: true,

    // set carousel height to the selected slide
    adaptiveHeight: false,

    // advances to the next cell
    // if true, default is 3 seconds
    // or set time between advances in milliseconds
    // i.e. `autoPlay: 1000` will advance every 1 second
    autoPlay: true,

    pauseAutoPlayOnHover: true,

    // alignment of cells, 'center', 'left', or 'right'
    // or a decimal 0-1, 0 is beginning (left) of container, 1 is end (right)
    cellAlign: 'left',

    // specify selector for cell elements
    cellSelector: ".carousel-cell",

    // will contain cells to container
    // so no excess scroll at beginning or end
    // has no effect if wrapAround is enabled
    contain: false,

    // enables dragging & flicking
    draggable: true,

    // number of pixels a user must scroll horizontally to start dragging
    // increase to allow more room for vertical scroll for touch devices
    dragThreshold: 3,

    // enables content to be freely scrolled and flicked
    // without aligning cells
    freeScroll: false,

    // smaller number = easier to flick farther
    //friction: 0.2,

    // group cells together in slides
    groupCells: false,

    // zero-based index of the initial selected cell
    initialIndex: 0,

    // enable lazy-loading images
    // set img data-flickity-lazyload="src.jpg"
    // set to number to load images adjacent cells
    lazyLoad: false,

    // sets positioning in percent values, rather than pixels
    // Enable if items have percent widths
    // Disable if items have pixel widths, like images
    percentPosition: false,

    // creates and enables buttons to click to previous & next cells
    prevNextButtons: true,

    // create and enable page dots
    pageDots: false,

    // listens to window resize events to adjust size & positions
    resize: true,

    // enables right-to-left layout
    rightToLeft: false,

    // sets the height of gallery
    // disable if gallery already has height set with CSS
    setGallerySize: true,

    // watches the content of :after of the element
    // activates if #element:after { content: 'flickity' }
    watchCSS: false,

    // at end of cells, wraps-around to first for infinite scrolling
    wrapAround: true,


    imagesLoaded: true,
  };

  [].forEach.call(sliders, function(slider, index) {
    slider.setAttribute("data-slider", "carousel-" + index);

    // Init Flickity
    swe.slider("carousel-" + index, '[data-slider="carousel-' + index + '\"]', options);
  });
}

                                     