/* Minification failed. Returning unminified contents.
(130,13-14): run-time error JS1014: Invalid character: `
(130,14-15): run-time error JS1195: Expected expression: <
(130,14-15): run-time error JS1195: Expected expression: <
(130,14-15): run-time error JS1195: Expected expression: <
(130,88-89): run-time error JS1002: Syntax error: }
(130,95-96): run-time error JS1014: Invalid character: `
(139,43-44): run-time error JS1195: Expected expression: )
(139,45-46): run-time error JS1004: Expected ';': {
(142,6-7): run-time error JS1195: Expected expression: ,
(144,46-47): run-time error JS1004: Expected ';': {
(166,6-7): run-time error JS1195: Expected expression: ,
(168,33-34): run-time error JS1195: Expected expression: )
(168,35-36): run-time error JS1004: Expected ';': {
(236,6-7): run-time error JS1195: Expected expression: ,
(238,5-25): run-time error JS1197: Too many errors. The file might not be a JavaScript file: setFocusOnInputField
(172,13-19): run-time error JS1018: 'return' statement outside of function: return
(156,17-23): run-time error JS1018: 'return' statement outside of function: return
 */
var CookieWall = {
    tcData: null,
    consentIsGiven: false,
    ConsentForPersonalAds: undefined,
    remainingRetries: 5, // wait 5*500= 2,5 sec for GA to load

    isConsentGiven: function() {
        return CookieWall.consentIsGiven;
    },

    setConsentIsGiven: function() {

        CookieWall.consentIsGiven = true;
    },

    isCMPLoaded: function() {
        var result = false;

        try {
            result = typeof window.__tcfapi !== "undefined";
        } catch (error) {
            // ignore cause
        }

        return result;
    },

    checkConsent: function() {
        window.__tcfapi("getTCData",
            2,
            function(tcData, success) {
                window.__tcfapi("consentDataExist",
                    2,
                    function(consentGiven, success) {
                        if (success && consentGiven) {
                            CookieWall.setConsentIsGiven();
                        }
                    });
                if (success && CookieWall.consentIsGiven) {
                    CookieWall.setFocusOnInputField();

                    CookieWall.tcData = tcData;

                    const newConsentForPersonalAds = CookieWall.isPersonalizedContentAllowed(tcData);
                    if (CookieWall.ConsentForPersonalAds !== newConsentForPersonalAds) {
                        CookieWall.ConsentForPersonalAds = newConsentForPersonalAds;
                        CookieWall.loadAdvertisements(CookieWall.ConsentForPersonalAds,
                            CookieWall.isSavingAdvertisementsAllowed(tcData),
                            tcData);
                    }

                }
            });
    },

    isSavingAdvertisementsAllowed: function(tcData) {
        const result = tcData.purpose.consents[1] ||
            !tcData.gdprApplies;

        return result;
    },

    isPersonalizedContentAllowed: function(tcData) {

        const result = tcData.purpose.consents[1] &&
            tcData.purpose.consents[3] &&
            tcData.purpose.consents[4] ||
            !tcData.gdprApplies;

        return result;
    },

    loadAdvertisements: function(consentForPersonalAds, savingAdsAllowed, tcData) {

        try {
            window.googletag.cmd.push(function() {
                if (consentForPersonalAds === false) {
                    window.googletag.pubads().setPrivacySettings({
                        nonPersonalizedAds: true
                    });
                }


                AdvertisementUtils.refreshAllNormalAdSlots(savingAdsAllowed);
                AdvertisementUtils.fetchAdviceBannersForSelectedJourney(savingAdsAllowed);

                if (tcData && tcData.tcString) {
                    window.googletag.pubads()
                        .setTargeting('iab_string', [tcData.tcString]);
                }
            });

            AdvertisementUtils.showAdAbovePlannerBlockIfNeeded();
        } catch (error) {
            // ignore cause
        }
    },

    activateCMPFallBack: function() {

        if (!CookieWall.cookiesEnabled()) {
            CookieWall.showBlockedCookiesModal();
            return;
        }

        CookieWall.loadAdvertisements(false, false);

        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': "GA"
        });
    },

    cookiesEnabled: function() {
        return navigator.cookieEnabled;
    },

    showBlockedCookiesModal: function() {

        if ($(window)
            .width() <
            960) {
            $("#genericModal .modal-title")
                .removeClass("absolutePos");
            $("#genericModal .modal-header-image img")
                .addClass("noFloat");
        }

        const cookieBlockedMessage =
            `<div class="cookieblockedmessage">${$("body").data("cookieblockedmessage")}</div>`;
        $("#dataHolder")
            .html(cookieBlockedMessage);
        $("#genericModal .curtain")
            .hide();

        loadGenericModal($("#cookieWall"));
    },

    setConsentManagerVisibility: function() {

        window.__tcfapi("showConsentManager", 2, function(result) {});
    },

    registerClick: function(clickEventLabel) {

        if (typeof window.ga === "function") {
            window.ga("9292GATracker.send",
                {
                    hitType: "event",
                    eventCategory: "Consent",
                    eventAction: clickEventLabel,
                    eventLabel: clickEventLabel
                });
        } else {
            if (clickEventLabel === consentClickType.PrivacySettings)
                return; // "PrivacySettings" will not enable GA, so we don't need to wait for GA.

            if (CookieWall.remainingRetries > 0) {
                CookieWall.remainingRetries--;
                setTimeout(function() {
                        CookieWall.registerClick(clickEventLabel);
                    },
                    500);
            }
        }
    },

    enableCMPFeatures: function() {

        if (!CookieWall.isCMPLoaded()) {
            CookieWall.activateCMPFallBack();
            return;
        }

        cmp.onerror = function() {
            CookieWall.activateCMPFallBack();
        };

        window.__tcfapi("addEventListener",
            2,
            function() {
                CookieWall.setConsentIsGiven();
                CookieWall.checkConsent();
                CookieWall.registerClick(consentClickType.AcceptAll);
            },
            "acceptAllButtonClicked");

        window.__tcfapi("addEventListener",
            2,
            function() {
                CookieWall.setConsentIsGiven();
                CookieWall.checkConsent();
                CookieWall.registerClick(consentClickType.SaveExit);
            },
            "exitButtonClicked");

        window.__tcfapi("addEventListener",
            2,
            function() {
                CookieWall.setConsentIsGiven();
                CookieWall.checkConsent();
                CookieWall.registerClick(consentClickType.SaveExit);
            },
            "saveAndExitButtonClicked");

        window.__tcfapi("addEventListener",
            2,
            function() {
                CookieWall.registerClick(consentClickType.PrivacySettings);
            },
            "consentManagerAlreadyShown");

        window.__tcfapi("addEventListener",
            2,
            function() {
                CookieWall.checkConsent();
            },
            "cmpReady");

        window.__tcfapi("changeLanguage",
            2,
            null,
            $("html")
            .attr("lang")
        );

        window.__tcfapi('addEventListener',
            2,
            function(tcData, success) {
                if (success) {
                    if (tcData.eventStatus === 'useractioncomplete') {
                        location.reload();
                    }
                }
            });
    },

    setFocusOnInputField: function() {
        if ($("#van")
            .length >
            0 &&
            $("#van")
            .val()
            .length ===
            0) {
            $("#van")
                .focus();
        }
    }
};

var consentClickType = {
    AcceptAll: "AcceptAll",
    SaveExit: "SaveExit",
    PrivacySettings: "PrivacySettings"
};

$(document)
    .ready(function() {

        if (!CookieWall.cookiesEnabled()) {
            CookieWall.setConsentManagerVisibility(false);
            CookieWall.showBlockedCookiesModal();
        } else {
            CookieWall.enableCMPFeatures();
        }
    });;
var NavBarLocation = {
    GeoLocationError: "",
    GeoLocationIsNotSupported: "",
    GeoLocationUserDenied: "",
    GeoLocationInfoUnavailable: "",
    GeoLocationTimeOut: "",
    GeoLocationUnknownError: "",
    noMostUsedTextTemplate: "",
    nearbyTitle: "Nearby",
    mostUsedTitle: "Most Used",
    languageIsEnglish: false,

    init: function(geoErrorTextTranslation, noMostUsedTextTranslation, titleNearbyList, titleMostUsed, language) {
        GeoLocationError = geoErrorTextTranslation[0],
        GeoLocationIsNotSupported = geoErrorTextTranslation[1];
        GeoLocationUserDenied = geoErrorTextTranslation[2];
        GeoLocationInfoUnavailable = geoErrorTextTranslation[3];
        GeoLocationTimeOut = geoErrorTextTranslation[4];
        GeoLocationUnknownError = geoErrorTextTranslation[5];
        noMostUsedTextTemplate = noMostUsedTextTranslation;
        nearbyTitle = titleNearbyList;
        mostUsedTitle = titleMostUsed;
        languageIsEnglish = (language == "en-GB") ? true : false;
    },

    consolelog: function(str) {
        if (false) {
            console.log(str);
        }
    },

    showLoader: function() {
        $("#genericModal .curtain").show();
    },

    removeLoader: function() {
        $("#genericModal .curtain").hide();
    },

    positionOption: {
        //enableHighAccuracy: true,
        // Maximum length of time (in milliseconds) the device is allowed to return a position
        timeout: 5000,
        // Maximum age in milliseconds of a possible cached position that is acceptable
        maximumAge: 3000
    },

    getNeighborhoodStops: function() {

        if ($('#genericModal #modalBody-ul').length == 0) {
            $("<ul id='modalBody-ul' class='inDeBuurtUL'></ul>").appendTo('#genericModal #dataHolder');
            $('<h2 class="h6 fat m-b-0">' + nearbyTitle + '</h2>').insertBefore('#genericModal #modalBody-ul');
        }

        // Reset
        NavBarLocation.showLoader();
        $('#genericModal #modalBody-ul').empty();
        var error = {
            code: 77
        };

        NavBarLocation.consolelog("Function getNeighborhoodStops.");
        try {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(NavBarLocation.showPosition, NavBarLocation.showError, NavBarLocation.positionOption);
            } else {
                NavBarLocation.consolelog("Geolocation is not supported by this browser.");
                NavBarLocation.insertCustomFeedbackNode("modalBody-ul", GeoLocationIsNotSupported);
                NavBarLocation.removeLoader();
            }
        } catch (err) {
            NavBarLocation.consolelog("Geolocation is not supported by this browser. Error: " + err.message);
            NavBarLocation.showError(error);
        }

        //Patch for Bug 7838:Locations modal (WinPhone) - modal hangt als "locations" is uitgeschakeld
        setTimeout(function() {
            if ($("#genericModal .curtain").is(':visible')) {
                NavBarLocation.showError(error);
            }
        }, 6000);

    },

    showPosition: function(position) {
        NavBarLocation.consolelog("Function showPosition: Latitude: " + position.coords.latitude + "; Longitude: " + position.coords.longitude);
        NavBarLocation.getNearby(position);
    },

    showError: function(error) {
        NavBarLocation.consolelog("Function showError");
        var errorMssg = "";

        switch (error.code) {
            case error.PERMISSION_DENIED:
                NavBarLocation.consolelog("User denied the request for Geolocation.");
                errorMssg = GeoLocationUserDenied;
                break;
            case error.POSITION_UNAVAILABLE:
                NavBarLocation.consolelog("Location information is unavailable.");
                errorMssg = GeoLocationInfoUnavailable;
                break;
            case error.TIMEOUT:
                NavBarLocation.consolelog("The request to get user location timed out.");
                errorMssg = GeoLocationTimeOut;
                break;
            default:
                NavBarLocation.consolelog("An unknown error occurred.");
                errorMssg = GeoLocationUnknownError;
                break;
        }
        NavBarLocation.insertCustomFeedbackNode("modalBody-ul", errorMssg);

        NavBarLocation.removeLoader();

        // Test-code:
        // var position = { coords: { latitude: "52.379272", longitude: "4.900251" } }; //amsterdam cs 52.379272, 4.900251
        // NavBarLocation.getNearby(position);
    },

    changeText: function(elem, changeVal) {
        if (typeof elem.textContent !== "undefined") {
            elem.textContent = changeVal;
        } else {
            elem.innerText = changeVal;
        }
    },

    createLocationsList: function(listid, hasdistance, locations) {
        NavBarLocation.consolelog("Function createLocationsList for listid " + listid + ".");
        $("#genericModal #" + listid).empty();

        var ul = document.getElementById(listid);
        ul.className = "inDeBuurtUL";

        var index = 0;
        for (var locationIndex in locations) {
            if (locations.hasOwnProperty(locationIndex)) {
                var location = locations[locationIndex];

                var li = document.createElement("li");
                li.className = "location-icon-" + location.Type;
                li.id = listid + "_" + index;

                var subtypeValue = location.SubType;
                if (languageIsEnglish && location.EnglishSubType) {
                    subtypeValue = location.EnglishSubType;
                }
                var locationdistance = "";
                if (hasdistance) {
                    locationdistance = location.Distance;
                }

                var a = document.createElement("a");
                a.href = 'javascript:NavBarLocation.navigateToDeparturesPage(\'' + location.Name + '\',\'' + location.Displayname + '\',\'' + location.Region + '\',\'' + location.SubType + '\',\'' + location.EnglishSubType + '\',\'' + location.Type + '\',\'' + location.Url + '\')';
                a.title = subtypeValue + ' ' + location.Name + ' ' + location.Region + ' ' + locationdistance;
                var s1 = document.createElement("span");
                s1.setAttribute('aria-hidden', true);
                NavBarLocation.changeText(s1, location.Name);

                var s2 = document.createElement("span");
                s2.className = "text-muted";
                s2.setAttribute('aria-hidden', true);

                NavBarLocation.changeText(s2, subtypeValue);

                var s3 = document.createElement("span");
                s3.className = "text-muted";
                s3.setAttribute('aria-hidden', true);
                NavBarLocation.changeText(s3, location.Region);

                var s4 = null;
                if (hasdistance) {
                    s4 = document.createElement("span");
                    s4.className = "text-muted";
                    s4.setAttribute('aria-hidden', true);
                    NavBarLocation.changeText(s4, location.Distance);
                }

                a.appendChild(s1);
                a.appendChild(s2);
                a.appendChild(s3);
                if (hasdistance) {
                    a.appendChild(s4);
                }
                li.appendChild(a);
                ul.appendChild(li);

                index++;
            }
        }
    },

    storeLocation: function(location) {
        var usedLocations2;
        var freq = 0;
        var witness = -1;

        try {

            usedLocations2 = JSON.parse($.cookie("maxused")) || [];

            for (var k = 0; k < usedLocations2.length; k++) {
                if (usedLocations2[k].Name === location.Name) {
                    witness = k;
                    break;
                }
            }

            if (witness < 0) {
                freq = 1;

                usedLocations2.push({
                    Name: location.Name,
                    Displayname: location.Displayname,
                    Region: location.Region,
                    SubType: location.SubType,
                    EnglishSubType: location.EnglishSubType,
                    Type: location.Type,
                    Url: location.Url,
                    freq: freq
                });
            } else {
                freq = usedLocations2[witness].freq + 1;
                usedLocations2[witness].freq = freq;
            }

            $.cookie("maxused", JSON.stringify(usedLocations2), {
                expires: 1,
                path: '/'
            });
        } catch (err) {
            NavBarLocation.consolelog("error while saving location: " + err.message);
        }
    },

    navigateToDeparturesPage: function(name, displayname, region, subtype, englishsubtype, type, url) {
        var location = {
            Name: name,
            Displayname: displayname,
            Region: region,
            SubType: subtype,
            EnglishSubType: englishsubtype,
            Type: type,
            Url: url
        };
        var url = ((languageIsEnglish) ? '/en/' : '/') + location.Url;

        NavBarLocation.storeLocation(location);

        window.location.href = window.location.origin + url;
    },

    storeLocationAndNavigateToDeparturesPage: function(location) {
        var url = ((languageIsEnglish) ? '/en/' : '/') + location.Url;

        NavBarLocation.storeLocation(location);

        window.location.href = window.location.origin + url;
    },

    getNearby: function(pos) {
        NavBarLocation.consolelog('Function getNearby');

        var url = ((languageIsEnglish) ? '/en' : '') + "/suggest3" + "/" + pos.coords.latitude + '/' + pos.coords.longitude;

        NavBarLocation.consolelog('url=' + url);

        jQuery.ajax({
            type: "GET",
            url: url,
            dataType: "json",
            success: function(response) {
                NavBarLocation.consolelog('getNearby successful');
                NavBarLocation.createLocationsList("modalBody-ul", true, response['locations']);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                NavBarLocation.consolelog('Function getNearby has failed (' + thrownError + ').');
            },
            complete: function() {
                NavBarLocation.removeLoader();
            }
        });
    },

    insertCustomFeedbackNode: function(listid, customtext) {
        var txt = document.createElement("li");
        $(txt).addClass("alert alert-info");
        NavBarLocation.changeText(txt, customtext);

        $("#genericModal #" + listid).html(txt);
    },

    sortDescendingFreq: function(a, b) {
        if (a.freq >= b.freq) return -1;
        if (a.freq === b.freq) return 0;
        if (a.freq < b.freq) return 1;

        return 0;
    },

    getMostUsedStops: function() {
        NavBarLocation.consolelog('Function getMostUsedStops');

        if ($("#modalBody-mostUsed-ul").length == 0) {
            $("<ul id='modalBody-mostUsed-ul' class='inDeBuurtUL'></ul>").insertAfter('#modalBody-ul');
            $('<h2 class="h6 fat m-t-20 m-b-0">' + mostUsedTitle + '</h2>').insertBefore('#modalBody-mostUsed-ul');
        }

        var maxnumber = 3;
        var usedLocations2 = JSON.parse($.cookie("maxused"));
        if (usedLocations2 != null) {
            var sorted = usedLocations2.sort(NavBarLocation.sortDescendingFreq);
            for (var j = 0; j < sorted.length; j++) {
                if (j < maxnumber) {
                    NavBarLocation.consolelog("sorted: name=" + sorted[j].Name +
                        ", displayname=" + sorted[j].Displayname +
                        ", type=" + sorted[j].Type +
                        ", subtype=" + sorted[j].SubType +
                        ", freq=" + sorted[j].freq);
                }
            }
            NavBarLocation.createLocationsList("modalBody-mostUsed-ul", false, sorted.slice(0, maxnumber));
        } else {
            NavBarLocation.insertCustomFeedbackNode("modalBody-mostUsed-ul", noMostUsedTextTemplate);
        }
    }

};;
var MailForm = {
  grcSiteKey: "",
  mailSelector: '.toolbar-mail',

  init: function (sitekey) {
    grcSiteKey = sitekey;
  },

  initForm: function () {
    $('a.openMailForm').unbind('click.openMailForm').bind('click.openMailForm', function (event) {
      event.preventDefault();
      
      showLoaderIcon(MailForm.mailSelector);

      var $mailForm = $(this).parent().parent().parent().parent().next('div .journey-email');
      var url = $(this).data('route-url');
      var data = 'arrivalTime=' + $(this).data('arrival-time') +
        '&departureTime=' + $(this).data('departure-time') +
        '&mailContent=' + $('.tab-pane.active').data('mail-content');

      if ($mailForm.html().length < 2) {
        MailForm.loadForm($mailForm, url, data);
      }
    });
  },

  initReSendForm: function () {
    $('#reSendMail').unbind('click.reSendMail').bind('click.reSendMail', function (event) {
      event.preventDefault();
      var $mailForm = $(this).closest('div .journey-email');
      var url = $(this).data('route-url');
      var data = 'arrivalTime=' + $(this).data('arrival-time') +
        '&departureTime=' + $(this).data('departure-time') +
        '&mailContent=' + $('.tab-pane.active').data('mail-content');

      MailForm.loadForm($mailForm, url, data);
    }); 
  },

  initFormPartial: function () {
    $(function () {
      var btnSubmitSelector = '.toggle-send';
      
      $("#frmMail").submit(function (event) {

          event.preventDefault();
          showLoaderIcon(btnSubmitSelector, false);
          $(btnSubmitSelector).parent().prop('disabled', true);

          var $form = $(this);
          var frmValues = $form.serialize(),
              url = $form.attr('action');

          $.post(url, frmValues)
            .done(function (data) {
              if (data !== "reload") {
                $('#dataHolder').html(data);
                MailForm.renderReCaptcha();
                MailForm.initFormPartial();
              }
              else {
                closeGenericModal();
                location.reload();
              }
            })
            .fail(function (error) {
                //alert('test!');
                $('#frmMail').hide();
                $("#error").show();
            })
            .always(function () {
              removeLoaderIcon(btnSubmitSelector);
              $(btnSubmitSelector).parent().prop('disabled', false);
            });

      });

    });
  },

  loadForm: function ($mailForm, url, data) {
    // load e-mail form partial
    $.post(url, data, function(data) {
          $('#genericModal #dataHolder').html(data);
          MailForm.renderReCaptcha();
          MailForm.showForm($mailForm);

          var mailContent = $('.tab-pane.active').data('mail-content');
          $('#frmMail #mailJourneyContent').val(mailContent);

          MailForm.initFormPartial();
        })
      .fail(function() {
        var $openMailButton = $('.tab-pane.active .openMailForm');
        var error = $openMailButton.data('error');
        $openMailButton.each(function() {
          $(this).attr('title', error)
            .tooltip('dispose')
            .tooltip({
              placement: 'top',
              trigger: 'manual',
              template:
                '<div class="tooltip"><div class="tooltip-arrow orangearrow"></div><div class="tooltip-inner orangebg"></div></div>'
            })
            .tooltip('show');
        });
      })
      .always(function () {
        $(document).one('click',
          function() {
            var $openMailButton = $('.tab-pane.active .openMailForm');
            $openMailButton.each(function() {
              $(this).tooltip('dispose')
                .removeAttr('data-original-title')
                .attr('title', $(this).data('title'))
                .tooltip();
            });
          });
        $('#genericModal .curtain').hide();
        removeLoaderIcon(MailForm.mailSelector);
      });
  },

  showForm: function ($mailForm) {
    window.requestAnimationFrame(function () {
      loadGenericModal($mailForm);
    });

    $("#genericModal").on('shown.bs.modal', function () {
      $(this).find('#EmailReceiver').focus();
    });
  },

  renderReCaptcha: function () {
    var $reCaptchaWrapper = $('#recaptcha-frmMail');

    if ($reCaptchaWrapper.html() !== undefined && $reCaptchaWrapper.html().length <= 1) {
      $reCaptchaWrapper.empty();
      grecaptcha.render('recaptcha-frmMail', {
        'sitekey': grcSiteKey,
        'size': 'compact'
      });
    }
  },

  clearValidationErrors: function () {

  }
}
;
var UtilsJs = {

  contentClasses: '.step__item--toggleinfo, .journey-costs__detail-table',
  linkClasses: '.step__item--toggle, .link--toggle',

  hideJourneyDetailContent: function () {
    $(function () {
      $(UtilsJs.contentClasses).hide();
      $(UtilsJs.linkClasses).show();
    });
  },
  
  restoreCurrentJourneyDetailContent: function($slide) {
    $slide.find(UtilsJs.contentClasses).hide();
    $slide.find(UtilsJs.linkClasses).show();
  }
};

wait = function (ms, cb) {
  return setTimeout(cb, ms);
}

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function () {
    var context = this, args = arguments;
    var later = function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

function getLanguage() {
  return $('html').attr('lang') || 'nl';
}

function isLanguageDutch() {
  var lang = $('html').attr('lang') || 'nl';

  if (lang === 'nl') {
    return true;
  }
  return false;
}

function getIEVersion() {
  var ua = window.navigator.userAgent;

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }

  // other browser
  return 0;
}

function getSafariVersion() {
  if (isSafari) {
    var appVersion = navigator.appVersion;
    var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;
    var webkitVersion_positionEnd = webkitVersion_positionStart + 3;
    var webkitVersion = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);
    return webkeyVersion;
  }
  return 0;
}

function isIEBrowser() {
  var ua = window.navigator.userAgent;

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    return true;
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    return true;
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    return true;
  }

  // other browser
  return false;
}

function isSafari() {
  return (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1);
}

function isOpera() {
  return navigator.userAgent.indexOf("Opera");
}

var isMobile = {
  Android: function () {
    return navigator.userAgent.match(/Android/i);
  },
  BlackBerry: function () {
    return navigator.userAgent.match(/BlackBerry/i);
  },
  iOS: function () {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
  Opera: function () {
    return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function () {
    return navigator.userAgent.match(/IEMobile|Windows Phone|Lumia/i);
  },
  any: function () {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};



function setEqualHeight(columns) {
  var tallestcolumn = 0;
  columns.each(function () {
    currentHeight = $(this).height();
    if (currentHeight > tallestcolumn) {
      tallestcolumn = currentHeight;
    }
  });
  columns.height(tallestcolumn);
}

//this fixes the filter method problem for arrays basically for IE7 alone
if (!Array.prototype.filter) {
  Array.prototype.filter = function (fun) {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      return; //throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

$(document).ready(function () {
  setEqualHeight($(".equal"));
  //mailBtn.init();
  //mailtoTabs.init();
  //if($('iframe').css('visibility') == 'hidden') $('iframe').css({ 'display': 'none' });

  $('.calamities-bar__close-button').click(function () { $('.calamities-bar').hide().parent().removeClass('page--with-calamities'); });
});

var faq = {
  init: function () {
    if ($('.faq-list').length) {
      var doToggle = function ($toggleFaq) {
        var qs = $toggleFaq.parent().find('dt'),
            answers = $toggleFaq.parent().children('dd'),
            answer = $toggleFaq.next('dd');
        if ($toggleFaq.hasClass('expander')) {
          answers.addClass('hidden');
          qs.removeClass('collapser open').addClass('expander').attr('aria-expanded', 'false');
          $toggleFaq.removeClass('expander').addClass('collapser open');
          answer.removeClass('hidden');
          $toggleFaq.attr('aria-expanded', 'true');
        } else if ($toggleFaq.hasClass('collapser')) {
          answers.addClass('hidden');
          $toggleFaq.attr('aria-expanded', 'false');
          $toggleFaq.removeClass('open').toggleClass('collapser expander');
        }
      };

      // Collapse all questions on load
      $('.faq-list dt').attr('aria-expanded', 'false');
      $('.faq-list dd').addClass('hidden');

      $('.faq-list dt').addClass('expander').click(function () { doToggle($(this)); });
      $('.faq-list dt').addClass('expander').keypress(function (e) {
        if (e.keyCode == 13 || e.keyCode == 32) {
          // 13 = return, 32 = space
          // prevent default want anders zorgt de spatiebalk voor een page-down
          // daarom ook belangrijk dat we keypress afvangen en niet een andere key-event
          e.preventDefault();
          doToggle($(this));
        }
      });
    }
  }
};

var extWindows = {
  title: '',
  addTitles: function () {
    $('a[target="_blank"]').attr('title', extWindows.title);
  }
}

/*
accessibility alert
!*based upon work of Steve Faulkner @ http://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/ 
*/
var accessibleAlert = {
  init: function (container, text) {
    if (!$(container).find('p[role=alert]').length) {
      var $accAlert = $('<p class="vh inline abs" data-role="accessible-alert" />');
      $accAlert.attr('role', 'alert').text(text);
      container.prepend($accAlert);
      $accAlert.css({ 'visibility': 'hidden' });
      $accAlert.css({ 'visibility': 'visible', 'clip': 'auto' }).attr('tabindex', 3);
    } else {
      var $accAlert = $(container).find('p[data-role="accessible-alert"]');
      $accAlert.text(text).css({ 'visibility': 'hidden' });
      $accAlert.css({ 'visibility': 'visible', 'clip': 'auto' }).attr('tabindex', 3);
    }
  }
}

//hotkeys from http://www.gmarwaha.com/blog/2009/06/16/ctrl-key-combination-simple-jquery-plugin/
$.ctrl = function (key, callback, args) {
  $(document).keydown(function (e) {
    if (!args) args = []; // IE barks when args is null 
    if (e.keyCode == key.charCodeAt(0) && (e.ctrlKey || e.metaKey)) {
      callback.apply(this, args);
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
  });
};

jQuery.fn.customInput = function () {
  $(this).each(function (i) {
    var input = $(this);
    input.addClass('vh');

    // get the associated label using the input's id
    var label = $('label[for=' + input.attr('id') + ']');

    //get type, for classname suffix 
    var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';

    // find all inputs in this set using the shared name attribute
    var allInputs = $('input[name=' + input.attr('name') + ']');

    // necessary for browsers that don't support the :hover pseudo class on labels
    label.hover(function () {
      $(this).addClass('hover');
      if (inputType == 'checkbox' && input.is(':checked')) {
        $(this).addClass('hover');
      }
    }, function () {
      $(this).removeClass('hover');
    })
    .focus(function () {
      $(this).prev('input').trigger('updateState');
    });

    //bind custom event, trigger it, bind click,focus,blur events     
    input.on('updateState', function () {
      if (input.is(':checked')) {
        if (input.is(':radio')) {
          allInputs.each(function () {
            $('label[for=' + $(this).attr('id') + ']').removeClass('checked');
          });
        };
        label.addClass('checked');
      }
      else { label.removeClass('checked'); }

    })
     .trigger('updateState')
     .click(function () {
       $(this).trigger('updateState');
     })
     .focus(function () {
       label.addClass('hover');
       if (inputType == 'checkbox' && input.is(':checked')) {
         $(this).addClass('checked');
       }
     })
     .blur(function () {
       label.removeClass('hover');
     });
  });
};
;
var AdvertisementUtils = {
    allowBillboardRecall: true,


    // New function added for Info Plaza implementation on 01-12-2022


    isMobile: function () {
        return window.innerWidth <= 767;
    },
    isTablet: function () {
        return window.innerWidth > 767 && window.innerWidth <= 1024;
    },
    isDesktop: function () {
        return window.innerWidth >= 1025;
    },
    getScreenSize: function () {
        return isMobile() ? "XS" : isTablet() ? "MD" : isDesktop() ? "XL" : void 0;
    },


    // END OF NEW INFO PLAZA ads

    isElementInViewport: function (el) {
        if (typeof jQuery === "function" && el instanceof jQuery) {
            el = el[0];
        }

        if (el === undefined) {
            return false;
        }

        const rect = el.getBoundingClientRect();
        const html = document.documentElement;

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || html.clientHeight) &&
            rect.right <= (window.innerWidth || html.clientWidth)
        );
    },

    isBrowserWidthSmallerThan: function (width) {

        var browserWidthWithinRange;
        if (Modernizr.mq("(min-width: 0px)")) {
            // Browsers that support media queries
            browserWidthWithinRange = function (width_param) {
                return Modernizr.mq(`(max-width: ${width_param}px)`);
            };
        } else {
            // Fallback logic
            browserWidthWithinRange = function (width_param) {
                return $(window)
                    .width() <= width_param;
            };
        }

        return browserWidthWithinRange(width);
    },

    isBrowserWidthLargerThan: function (width) {
        var browserWidthWithinRange;
        if (Modernizr.mq("(min-width: 0px)")) {
            // Browsers that support media queries
            browserWidthWithinRange = function (width_param) {
                return Modernizr.mq(`(min-width: ${width_param}px)`);
            };
        } else {
            // Fallback logic
            browserWidthWithinRange = function (width_param) {
                return $(window)
                    .width() >= width_param;
            };
        }

        return browserWidthWithinRange(width);
    },

    lazyLoad: function (pageName, slotNumbers, screenClasses) {
        var already_refreshed = [];
        already_refreshed.length = slotNumbers.length;

        function onScrollChange(callback) {
            return function () {
                if (CookieWall.isConsentGiven() && slotNumbers !== undefined && slotNumbers.constructor === Array) {

                    for (var i = 0, max = slotNumbers.length; i < max; i++) {
                        // :visible is used to filter out hidden ads (e.g. sidebar ads on small screens)
                        $ad = $(`#div-gpt-ad-${pageName}-${screenClasses[i]}-${slotNumbers[i]}:visible`);

                        // if ads is visible on screen
                        const visible = AdvertisementUtils.isElementInViewport($ad);
                        if (visible && visible !== already_refreshed[i]) {
                            already_refreshed[i] = visible;
                            if (typeof callback === "function") {
                                callback(slotNumbers[i]);
                            }
                        }
                    }
                }
            };
        }

        var scrollHandler = onScrollChange(function (slotNr) {
            googletag.cmd.push(function () {
                googletag.pubads()
                    .refresh([gptadslots[slotNr]]);
            });
        });


        $(window)
            .on("DOMContentLoaded load resize scroll",
                debounce(function (e) {
                    scrollHandler();
                },
                    500
                ));
    },

    showAdAbovePlannerBlockIfNeeded: function () {
        setTimeout(function () {
            const heightImg = $(".homepage.ad_container img")
                .height() || 0;
            const heightVideo = $(".homepage.ad_container video")
                .height() || 0;
            const heightFrame = $(".homepage.ad_container iframe")
                .height() || 0;

            if ((heightImg + heightVideo + heightFrame) > 10) {
                $(".homepage.ad_container")
                    .show();

                // correct tooltip position by scrolling 1 pixel. It's dirty. I know, don't be MAD.
                if ($("div.tooltip-inner.orangebg")
                    .length) {
                    $(window)
                        .scrollTop($(window)
                            .scrollTop() + 1);
                }
            }
        },
            5000); // wait 5 secs
    },

    refreshAllNormalAdSlots: function (savingAdsAllowed) {
        CookieWall.isConsentGiven() &&
            (totalSlots = typeof gptadslots != "undefined" && $.isArray(gptadslots) ? gptadslots.length : 0,
                setTimeout(function () {
                    if (savingAdsAllowed) {
                        for (let i = 0; i < totalSlots; i++) {
                            googletag.pubads()
                                .refresh([gptadslots[i]]);
                        }
                    } else {
                        googletag.pubads()
                            .setPrivacySettings({
                                limitedAds: true
                            });

                        for (let i = 0; i < totalSlots; i++) {
                            googletag.pubads()
                                .refresh([gptadslots[i]]);
                        }
                    }
                },
                    500));
    },

    removeAllBanners: function () {

        if (!CookieWall.isConsentGiven()) {
            return;
        }

        for (let i = 0; i < eticketSlots.length; i++) {
            eticketSlots[i].clearTargeting();
            googletag.pubads()
                .clear([eticketSlots[i]]);
        }
    },

    addBannerSlotTargeting: function (keyValueItem) {

        for (let key in keyValueItem) {
            if (key === "SlotNumber")
                continue;

            const value = keyValueItem[key];
            eticketSlots[keyValueItem.SlotNumber].setTargeting(String(key), String(value));
        }
    },


    fetchAdviceBannersForSelectedJourney: function (savingAdsAllowed) {

        if (!CookieWall.isConsentGiven()) {
            return;
        }
        if (!savingAdsAllowed) {
            googletag.pubads()
                .setPrivacySettings({
                    limitedAds: true
                });
        }


        AdvertisementUtils.removeAllBanners();

        var targetKeyValueArray = $('#journeyTabs .tab-pane.active .eticket-slot')
            .map(function () { return eticketSlotTargets[this.id]; })
            .get();

        targetKeyValueArray.forEach(function (keyValueItem) {
                AdvertisementUtils.addBannerSlotTargeting(keyValueItem);
                googletag.pubads().refresh([eticketSlots[keyValueItem.SlotNumber]]);
        });

    }
};
;
// Images for markers
var START_ICON = "/static/images/journey/start-icon-big.png",
    DESTINATION_ICON = "/static/images/journey/destination-icon-big.png";


var mapList = [];

var GenerateWalkRouteMap = function(el, options, promise) {
    const $mapsContainer = $(`<div id="maps-container-${options.index}" class="maps-container"/>`).appendTo(el);
    const $directionsDiv = $('<div class="directions"/>').appendTo(el);

    // add disclaimer
    $directionsDiv.append(
        `<p class="alert alert-info m-t-10 m-b-20 p-10"><strong>${options.caution}</strong> ${options.disclaimer}</p>`);

    const map = CreateOsmWalkRouteMap($mapsContainer, options.index);

    mapList.push(map);

    const origin = { lat: options.startLat, lng: options.startLon };
    const destination = { lat: options.stopLat, lng: options.stopLon };

    AddOsmWalkMarkers(map, origin, destination, START_ICON, DESTINATION_ICON);
    SetWalkingRoute("/get-walking-route", origin, destination, map);

    // Load Google maps API 
    gml.init(options.mapsKey).done(function(mapsApi) {

        const directionsService = new mapsApi.DirectionsService();
        const request = {
            origin: origin.lat + "," + origin.lng,
            destination: destination.lat + "," + destination.lng,
            travelMode: mapsApi.TravelMode.WALKING
        };

        directionsService.route(request,
            function(result, status) {

                if (status !== mapsApi.DirectionsStatus.OK) {
                    return;
                }

                const leg = result.routes[0].legs[0];

                if (options.skipDirections === undefined || !options.skipDirections) {
                    showDirectionsDescription($directionsDiv, leg.steps, options);
                }
            });
    });


};

// Show the directions on the map 
var showDirectionsDescription = function($directionsDiv, steps, options) {
    const cleanup = function(s) {
        return s
            .replace(/<b>/g, "<strong>")
            .replace(/<\/b>/g, "</strong>")
            .replace(/style="[^"]*"/g, "");
    };

    const title = `<h3 class="h5">${options.title} ${options.description}</h3>`;
    const $ol = $('<ol class="directions__list"/>');

    for (var i = 0, l = steps.length; i < l; i++) {
        $ol.append(`<li class="directions__list-item">${cleanup(steps[i].instructions)}</li>`);
    }

    return $directionsDiv.append(title, $ol);
};

// OSM STUFF
function CreateOsmWalkRouteMap(elemId, mapId) {
    const osmUrl = "https://osmtile.9292.nl/pngut/{z}/{x}/{y}.png";

    const osmLayer = new L.TileLayer(osmUrl,
        {
            maxZoom: 20,
            maxNativeZoom: 17,
            minZoom: 9,
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        });

    const element = elemId[0].className + "-" + mapId;

    const map = new L.Map(element);

    map.addLayer(osmLayer);

    return map;
}

function AddOsmWalkMarkers(map, origin, destination, startIcon, destinationIcon) {
    const originLatlong = new L.LatLng(origin.lat, origin.lng);
    const destinationLatlong = new L.LatLng(destination.lat, destination.lng);

    const markers = [
        L.marker(
            originLatlong,
            {
                title: "START",
                icon: L.icon({
                    iconUrl: startIcon,
                    iconSize: [43, 73],
                    iconAnchor: [21.5, 73]
                })
            }),
        L.marker(
            destinationLatlong,
            {
                title: "END",
                icon: L.icon({
                    iconUrl: destinationIcon,
                    iconSize: [43, 73],
                    iconAnchor: [21.5, 73]
                })
            })
    ];

    var group = L.featureGroup(markers).addTo(map);

    //setTimeout(function() {
    //        map.fitBounds(group.getBounds());
    //    },
    //    100);
}

function SetWalkingRoute(url, origin, destination, map) {

    const request = {
        Legs: [
            {
                Id: "Leg_1",
                From: {
                    ClusterCode: "",
                    PhysicalStopId: "",
                    Latitude: origin.lat,
                    Longitude: origin.lng
                },
                To: {
                    ClusterCode: "",
                    PhysicalStopId: "",
                    Latitude: destination.lat,
                    Longitude: destination.lng
                },
                Modality: "Walking"
            }
        ],
        EncodeCoordinates: false
    };


    $.ajax({
        url: url,
        async: true,
        contentType: "application/json;charset=UTF-8",
        type: "POST",
        data: JSON.stringify(request),
        success: function(data) {
            const linestring = data.legs[0].coordinates.replace("LINESTRING (", "").replace(")", "").split(",");

            var coordinates = [];

            coordinates.push([origin.lng, origin.lat]);

            linestring.forEach(element => {
                var coordinate = element.trim().split(" ");
                coordinates.push([coordinate[0], coordinate[1]]);
            });

            coordinates.push([destination.lng, destination.lat]);

            const walkRoute = [
                {
                    "type": "LineString",
                    "coordinates": coordinates
                }
            ];

            const lineStyle = {
                "color": "#009ae0",
                "weight": 5,
                "opacity": 0.65
            };

            const line = L.geoJSON(walkRoute,
                {
                    style: lineStyle
                }).addTo(map);

            map.fitBounds(line.getBounds(), { padding: [10, 10] });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("Error");
        }
    });
};
var icons = {
    poi: {
        url: "/static/images/gmap-poi-icon-big.png",
        size: [30, 31],
        anchor: [15, 31]
    },
    station: {
        url: "/static/images/gmap-station-icon-big.png",
        size: [42, 40],
        anchor: [21, 40]
    },
    stop: {
        url: "/static/images/gmap-stop-icon-big.png",
        size: [35, 34],
        anchor: [17.5, 34]
    },
    destination: {
        url: "/static/images/journey/destination-icon-big.png",
        size: [43, 73],
        anchor: [21.5, 73]
    },
    start: {
        url: "/static/images/journey/start-icon-big.png",
        size: [43, 73],
        anchor: [21.5, 73]
    }
};


var osmUrl = "https://osmtile.9292.nl/pngut/{z}/{x}/{y}.png";

var osmLayer = new L.TileLayer(osmUrl, {
    maxZoom: 20,
    maxNativeZoom: 17,
    minZoom: 5,
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
});

var map;
var Locations = [];
var Markers = [];
var Latlongs = [];

function CreatePopup(location) {
    return L.popup()
        .setContent((location.url ? `<a href="${location.url}"` : "<div") +
            ' class="default">' +
            '<img src="' +
            icons[location.type].url +
            '" class="float-left m-r-10"/>' +
            '<div class="float-left w-max-70-p"><h6 class="fat m-b-5">' +
            location.title +
            "</h6>" +
            '<span class="text-muted m-t-0">' +
            location.subType +
            "</span>" +
            "</div>" +
            (location.url ? "</a>" : "</div>"));
}

function CreateOsmSurroundingsMap(elemId, centerLat, centerLng, zoom, locations) {
    map = new L.map(elemId);
    Locations = locations;

    locations.forEach(function (location) {
        Latlongs.push([location.lat, location.lng]);
    });

    const bounds = new L.LatLngBounds(Latlongs);

    map.setView(new L.LatLng(centerLat, centerLng), zoom);
    map.addLayer(osmLayer);

    map.fitBounds(bounds);

    $(".maps-container .curtain").addClass("hidden");

    AddOsmMarkers(locations);

    SetMarkerClickBinding();

    return map;
}

function SetMarkerClickBinding() {
    $(document).ready(function () {
        $(".marker-link").click(function () {
            var location = Locations[$(this).data("markerid")];
            const latlong = new L.LatLng(location.lat, location.lng);
            map.flyTo(latlong);

            Markers.forEach(function (marker) {
                const title = marker.options.title;
                if (title === location.url) {
                    marker.openPopup();
                }
            });
        });
    });
}


function AddOsmMarkers(locations) {
    locations.forEach(function (location) {
        const latlong = new L.LatLng(location.lat, location.lng);

        const marker = L.marker(
            latlong, {
            title: location.url,
            icon: L.icon({
                iconUrl: icons[location.type].url,
                popupAnchor: [15, 0],
                iconSize: icons[location.type].size,
                iconAnchor: icons[location.type].anchor
            })
        })
            .bindPopup(CreatePopup(location))
            .addTo(map);
        Markers.push(marker);
    });
}
;
var locationAutocomplete = {

    // Ajax call for getting json 
    getData: function (suggestUrl, userQuery, locationType) {
        return $.get(suggestUrl, { userInput: userQuery, locationType: locationType });
    },

    // Map data received from json to usable array in jquery ui 
    mapLocations: function (locations) {
        return $.map(locations, function (location) {
            return {
                value: location.Displayname,
                location: location,
                category: location.CategoryTitle
            };
        });
    },

    // Source function for jquery ui autocomplete 
    locationSuggestSource: function (request, response) {

        var locationType = this.element.data().locationType || "";
        var suggestUrl = this.element.data().suggestUrl;

        locationAutocomplete.getData(suggestUrl, request.term, locationType)
            .done(function (data) {
                // check if json object 
                if (data.hasOwnProperty('locations')) {
                    response(locationAutocomplete.mapLocations(data.locations));
                } else {
                    response(locationAutocomplete.mapLocations(JSON.parse(data).locations));
                }
            })
            .fail(function () {
                response([]);
            });
    },

    //  ===================== 
    //  = LocationSuggest component = 
    //  ===================== 
    getSuggestions: function (el, params) {
        var $el = $(el);
        var $input = $el.find('input[type=text]').addClass('location-suggest__input');
        var saveAndRedirect = $input.data("saveAndRedirect") || false;

        $input.data("suggest-url", params.suggestUrl || "/suggest");

        //  = Location suggest widget = 
        $input.locationSuggest({
            source: locationAutocomplete.locationSuggestSource,
            open: function (event, ui) {

                // Update width, otherwise autocomplete takes width of biggest child 
                $input.locationSuggest('widget').width($input.outerWidth());
            },
            select: function (event, ui) {

                // Let's not forget to set the location-url 
                var refUrlInputID = $(event.target).data('ref-url-input-id');
                if (refUrlInputID) {
                    $('#' + refUrlInputID).val(ui.item.location.Url);
                }

                saveAndRedirect = $(this).data("saveAndRedirect") || false;

                // If needed, store user selection in cookie AND redirect user to the selected location URL 
                if (saveAndRedirect && ui.item.location != undefined) {
                    NavBarLocation.storeLocationAndNavigateToDeparturesPage(ui.item.location);
                }
                else {
                    showResetButton($(this));
                    swapFieldButtons();
                }

            }
        });

        if (saveAndRedirect) {
            $input.unbind('keyup.vttInput').bind('keyup.vttInput', function (event) {

                // User has typed something and has hit the enter-button 
                if (event.keyCode == 13 && $input.val()) {

                    if ($input.locationSuggest('widget').is(':visible')) {

                        // match user-query with available suggestions 
                        var matchedLocation = [];
                        $input.locationSuggest('widget')
                            .find("li.location-suggest__item span.location-suggest__item-label")
                            .each(function () {
                                if ($(this).text().toUpperCase() === $.trim($input.val()).toUpperCase()) {
                                    matchedLocation.push($(this).data('location'));
                                }
                            });

                        // match found, redirect to the location's url 
                        if (matchedLocation.length == 1 && matchedLocation[0].Url) {
                            NavBarLocation.storeLocationAndNavigateToDeparturesPage(matchedLocation[0]);
                        }
                        // TODO: validation message 
                    }
                    else {
                        // simply show the autosuggestions again 
                        $input.locationSuggest('search');
                    }
                    event.preventDefault();
                }

            });
        }

        //  = Reset button = 
        $('.location-suggest input').unbind('keyup.allInputs click.allInputs').bind('keyup.allInputs click.allInputs', function () {
            if ($(this).val().length >= 1) {
                showResetButton($(this));
            } else {
                removeResetButton($(this));
            }
        });

    }
};

var UIInteractions = {
    init: function (suggestUrl) {
        $(document).ready(function () {
            locationAutocomplete.getSuggestions('.location-suggest', { suggestUrl: suggestUrl });
        });
    }
};

var lastScrollTop = 0;

// init homepage functions. This way the functions that are called when document is ready can be recalled when we ajax load the content blocks on the homepage. 
function initHomepageFunctions() {

    //Fietsopties tonen in het reisadvies 
    $('body').on('click', '.tab-pane.active .fietsopties .dropdown-toggle', function (e) {

        $('.tab-pane.active .fietsopties .dropdown-menu .loader-inline-template').show();
        $('.fietsitem').remove();
        $('.fietsopties .dropdown-toggle span .badge').remove();
        $('.tab-pane.active .fietsopties .dropdown-menu .card').remove();

        //get data 
        var stationList = $('.tab-pane.active .fietsopties')
            .data('bicyclelocationlist')
            .split(",")
            .filter(function (item) {
                return item !== null && item !== "";
            });

        if (stationList === undefined || stationList.length < 1) {

            $('.tab-pane.active .fietsopties .dropdown-menu .loader-inline-template').hide();

            var noResultsContent = '<div class="card p-10 lightgreybg m-b-5 small"><span class="small"><i class="fas fa-exclamation-triangle bluetxt"></i> ' + $(".tab-pane.active .fietsopties .dropdown-menu").data("ovfietsnoresultstext") + '</span></div>';
            $(".tab-pane.active .fietsopties.show .dropdown-menu").append(noResultsContent);

            return;
        }

        // TODO: Fiets request uitgeschakeld op 31-10-2018. Ooit verwijderen of hergebruiken als de tijd zover is 
        //var url = isLanguageDutch() ? '/BicycleStationListView?clusterCodes=' : '/en/BicycleStationListView?clusterCodes='; 
        //var clusters = stationList.join("&clusterCodes="); 
        //url = url + clusters; 

        var allItems;

        $.get(url)
            .done(function (data) {
                allItems = data;
                $('.tab-pane.active .fietsopties .dropdown-menu .loader-inline-template').hide();

                var explanationContent = '<div class="card p-10 lightgreybg m-b-5 small"><span class="small"><i class="fas fa-info-circle bluetxt"></i> ' + $(".tab-pane.active .fietsopties .dropdown-menu").data("ovfietsinfotext") + '</span></div>';
                $(".tab-pane.active .fietsopties .dropdown-menu").append(explanationContent);

                $(".tab-pane.active .fietsopties .dropdown-menu").append(allItems);

                var badgeContent = '<span class="badge badge-pill orangebg">' + (allItems !== undefined ? $(allItems).filter('a').length : 0) + '</span>';
                $('.fietsopties.show .dropdown-toggle span').append(badgeContent);

            })
            .fail(function (data) {
                //console.log('fail'); 
            });
    });

    $('.faqopen, .leg-item-toggle, #searchButt, #searchButtTile, .reset, .lock-from-button, .lock-to-button, .selectDate, .selectTime').keypress(function (e) {
        var key = e.which;
        if (key === 13)  // the enter key code 
        {
            $(this).click();
            return false;
        }
    });

    //Show and hide disturbance search reset button 
    //  = Reset button = 
    $('#searchDisturbance').unbind('keyup.allInputs click.allInputs').bind('keyup.allInputs click.allInputs', function () {
        if ($(this).val().length >= 1) {
            showResetButton($(this));
        } else {
            removeResetButton($(this));
        }
    });

    // reset form values when clicked 
    $("#planner .location-suggest__reset-button:not(#fromLock, #toLock), #vertrektijdenTile .location-suggest__reset-button, #vertrektijden .location-suggest__reset-button, #tussenPlanner .location-suggest__reset-button, #searchInDisturbance .location-suggest__reset-button, #widget-generator .location-suggest__reset-button").click(function () {
        $(this).parent().parent().find("input[type=text]").val("");
        $(this).parent().parent().find("input[type=hidden]").val("");
        $(this).parent().parent().find("input[type=text]").focus();
        removeResetButton($(this).parent().parent().find("input[type=text]"));
        swapFieldButtons();

        const lockButtonField = $(this).parent().parent().find(".input-group-append button");

        if (lockButtonField.attr("aria-pressed") === "false") {
            const txtInactive = lockButtonField.attr("data-txt-inactive");
            lockButtonField.attr("title", txtInactive);
            lockButtonField.attr("data-original-title", txtInactive);

            if (lockButtonField.hasClass("lock-from-button")) {
                $("#fromLock").val("false");
            } else {
                $("#toLock").val("false");
            }
        }
        else {
            const txtActive = lockButtonField.attr("data-txt-active");
            lockButtonField.attr("title", txtActive);
            lockButtonField.attr("data-original-title", txtActive);
            if (lockButtonField.hasClass("lock-to-button")) {
                $("#toLock").val("false");
            } else {
                $("#fromLock").val("false");
            }
        }

    });

    // make all tab navigations WCAG accessible 
    if (typeof AccessibleTab !== 'undefined' && !$('#journeyTabList').length)
        AccessibleTab.init();

    //check-uncheck checkboxes on plannerblock traveltypes 
    $('.vervoertypes .btn').click(function () {
        travelTypeCheckBoxCheck(this);
    });

}

//check-uncheck checkboxes on plannerblock traveltypes 
function travelTypeCheckBoxCheck(travelType) {
    if ($(travelType).hasClass('active')) {
        $(travelType).find('[type=checkbox]').attr('aria-checked', 'false');
    } else {
        $(travelType).find('[type=checkbox]').attr('aria-checked', 'true');
    }
}

function SwapFromAndToField() {
    var oldvan = $('#van').val();
    var oldnaar = $('#naar').val();
    var oldtourl = $('#to-url').val();
    var oldtooriginal = $('#to-original').val();
    var oldtourloriginal = $('#to-url-original').val();
    var oldfromurl = $('#from-url').val();
    var oldfromoriginal = $('#from-original').val();
    var oldfromurloriginal = $('#from-url-original').val();
    var oldFromLockHiddenValue = $('#fromLock').val();
    var oldToLockHiddenValue = $('#toLock').val();
    var oldFromLockButtonTitle = $('#fromLockButton').attr('title');
    var oldToLockButtonTitle = $('#toLockButton').attr('title');
    var oldFromLockButtonAriaPressed = $('#fromLockButton').attr('aria-pressed');
    var oldToLockButtonAriaPressed = $('#toLockButton').attr('aria-pressed');

    $('#naar').val(oldvan);
    $('#van').val(oldnaar);

    $('#from-url').val(oldtourl);
    $('#from-original').val(oldtooriginal);
    $('#from-url-original').val(oldtourloriginal);

    $('#to-url').val(oldfromurl);
    $('#to-original').val(oldfromoriginal);
    $('#to-url-original').val(oldfromurloriginal);

    $('#fromLock').val(oldToLockHiddenValue);
    $('#toLock').val(oldFromLockHiddenValue);

    $('#fromLockButton').attr('title', oldToLockButtonTitle);
    $('#toLockButton').attr('title', oldFromLockButtonTitle);
    $('#fromLockButton').attr('aria-pressed', oldToLockButtonAriaPressed);
    $('#toLockButton').attr('aria-pressed', oldFromLockButtonAriaPressed);
    $('#fromLockButton').attr('data-original-title', oldToLockButtonAriaPressed);
    $('#toLockButton').attr('data-original-title', oldFromLockButtonAriaPressed);
}


function copyUrlToClipboard(message) {
    var clipboard = new Clipboard('.btnCopyJourneyUrl');

    clipboard.on('success', function (e) {
        showUserMessage(message);

        e.clearSelection();
    });
}

// fullscreen plannerblok parent on IE (IE doesn't understand min-height:100vh/height:auto in a flexbox parent) 
function IEfullScreenPlannerBlockParent() {
    if (isIEBrowser()) {
        var topRowHeight = $('#toprow').outerHeight();
        var totalHeight = $(window).innerHeight();
        var mainsectionHeight = totalHeight - topRowHeight;
        if (mainsectionHeight > 673) {
            $('#mainhome').innerHeight(mainsectionHeight);
        }
    }
}

//growl messages 
function showUserMessage(message) {
    if (message || message.length > 0) {
        $.growl({
            title: message,
            duration: 5000,
            message: "",
            size: "large"
        });
    }
}

// navbar submenu positioning 
function positionMenu() {
    if ($(window).innerWidth() <= 750) {
        var subMenu = $('#highResMenu').detach();
        subMenu.appendTo('#smallResMenu');
        $('.inlineplanner').popover('dispose');
    } else {

        if ($('.menuWrapper #highResMenu').length) {
        } else {
            var subMenu = $('#highResMenu').detach();
            subMenu.prependTo('.menuWrapper #wrapperInMenu');
        }
    }
}

// show swapfields buttons when #van and #naar are both filled 
function swapFieldButtons() {
    if ($('#van').length > 0) {
        if ($('#van').val().length > 0 && $('#naar').val().length > 0) {
            $('.swapfieldsbut').addClass('swappable').attr('role', 'button').attr('tabindex', '0');
            $('.marker').addClass('hidden');
        } else {
            $('.swapfieldsbut').removeClass('swappable').removeAttr("role").removeAttr("tabindex");
            $('.marker').removeClass('hidden');
        }
    }
}

// show the X reset input field button 
function showResetButton($input) {
    if ($input.val().length > 0) {
        $input.parent().find('.input-group-append .location-suggest__reset-button').removeClass('hidden');
    }
}

// hide the X reset input field button 
function removeResetButton($input) {
    if ($input.val().length < 1) {
        $input.parent().find('.input-group-append .location-suggest__reset-button').addClass('hidden');
    };
}

// check value of inputfield, if empty it will clear the hiddenfield also. Used for the hidden form fields in the plannerbox 
function clearHiddenValueWhenInputFieldIsEmpty($input, $hidden) {
    $input.keyup(function () {
        var value = $input.val();
        if (value === "") {
            $hidden.val("");
        }
    }).keyup();
}

// Init the play and pause buttons for a carousel. The carousel name can be given to the function as parameter. 
function initCarouselAndControlButtons($CarouselName, $Interval) {
    $('#playButton').click(function () {
        $($CarouselName).carousel('cycle');
        $('#pauseButton, #playButton').toggleClass('hidden');
    });
    $('#pauseButton').click(function () {
        $($CarouselName).carousel('pause');
        $('#pauseButton, #playButton').toggleClass('hidden');
    });

    $($CarouselName).carousel({
        interval: $Interval
    });
}

// init of the custom tab actions. Tabbing shows and hides auto suggest in the planner box 
function initCustomTabBehaviorForPlanner() {
    $('#planner .location-suggest input').unbind('keydown.plannerInput').bind('keydown.plannerInput', function (event) {
        if (event.keyCode === 9) {
            if ($(this).locationSuggest('widget').is(':visible')) {
                $(this).locationSuggest('widget').hide();
                $(this).trigger(event);
            }
        }
    });
}

// make parent of adcontainer the height of neighbor 
function fitAdCont() {
    var hHeight = $(".journeyAdviceCol").innerHeight();
    $(".journeyAdviceAdCol").innerHeight(hHeight);
}

// stick to top of page on scroll 
function activateStickyAdSidebar() {
    //$("#adSideBar").stick_in_parent({ offset_top: 12 });  // not needed as yet. 
}

// sidebar function 
function toggleSideBar() {
    $('.sidebar_wrapper').show();

    setTimeout(function () {
        $('.sidebar_wrapper').toggleClass('active');
        $('.sidebar_button').toggleClass('active');
    }, 1);

    $('.tooltip').hide();

    if ($('.sidebar_wrapper').hasClass('active')) {
        setTimeout(function () {
            $('.sidebar_wrapper').hide();
        }, 1000);
    }
}

// shows the via input field 
function RemoveVia1ClassHidden() {
    if ($('.via1').hasClass('hidden')) {
        $('.via1').removeClass('hidden');
        $(".addvia").addClass('hidden');
    }
}

// hides the via input field 
function AddVia1ClassHidden() {
    $(".via1").addClass('hidden');
    $(".addvia").removeClass('hidden');
    $("#via-text").val("");
    $("#via-url").val("");
}

// shows the loader icon while waiting for mails to be send, journeys to be loaded, prints to be completed and locations modifications 
function showLoaderIcon(selector, findOnActiveTab) {
    if (typeof (findOnActiveTab) === 'undefined' || findOnActiveTab === true) {
        $('.tab-pane.active ' + selector).toggle();
    } else {
        $(selector).toggle();
    }
}

// hides the loader icon when mails are send, journey loaded, prints printed and locations modified.  
function removeLoaderIcon(selector) {
    // Poor man's progress bar.  
    // This is not good, but I'm checking it in due to time constraint. Don't be MAD 
    setTimeout(function () {
        $('.loader-inline-template')
            .filter(function () { return $(this).css("display") !== "none" })
            .parent().find(selector).toggle();
    }, 250);
}

// binds the correct function to accessibility feedback mail form 
function bindAccessibilityFeedbackEmail() {
    $(document).on("click", ".email-accessibility-feedback", function (event) {
        event.preventDefault();
        loadDynamicUrlModal($(this), accessibilityRemarkCallback);
    });
}

// Loading mail form and filling in the stop-name and destination fields for the  accesibility feedback 
function accessibilityRemarkCallback() {
    MailForm.renderReCaptcha();
    MailForm.initFormPartial();

    // set the stop-name & destination 
    $('#feedback-remark-stop-name').val($(this).data('stop-name'));
    $('#feedback-remark-destination').val($(this).data('stop-destination'));
}

/** 
 * @deprecated Currently not used 
 * 
 * Combines date and time to a datetime format. 
 */
function combineDateTime() {
    var startDate = $('#date').val();
    var startTime = $('#time').val();
    var newDateTime = new Date(startDate);
    var time = startTime.split(':');
    newDateTime.setHours($.trim(time[0]), $.trim(time[1]));
    newDateTime = moment(newDateTime).format("YYYY-MM-DDHH:mm");
    $('#dateTime').val(newDateTime);
}

// reverse the date and combine with time. 
function combineAndSwapDateTime() {
    var startDate = $('#date').val();
    startDate = startDate.split('-');
    startDate = startDate.reverse().join('-');
    var newDateTime = new Date(startDate);
    var startTime = $('#time').val();
    var time = startTime.split(':');
    newDateTime.setHours($.trim(time[0]), $.trim(time[1]));
    newDateTime = moment(newDateTime).format("YYYY-MM-DDHH:mm");
    $('#dateTime').val(newDateTime);
}

// function that overrides the default forms submit 
function overrideFormsSubmit() {
    var forms = ['#planner', '#tussenPlanner', '#register-form', '#forgot-pass-form', '#delete-account-form', '#edit-password-form', '#reset-password-form', '#login-form', '#genericModal #inlog-form', '#searchInDisturbance'];

    forms.forEach(function (item) {
        $(document).on('submit', item, function (event) {
            if ($(this).valid()) {
                //make sure the dateTime field is filled correctly 
                if (item == '#planner') {
                    combineAndSwapDateTime();
                }
                return disableSubmitButtonAndShowLoader();
            }
            return false;
        });
    });
}

// disables the submit button so it cant be pressed anymore and shows the loader icon. 
function disableSubmitButtonAndShowLoader() {
    var $button = $(event.target).find(':submit');
    if ($button.not('.widgetSubmit').length) {
        $button.attr("disabled", true);
        showLoaderIcon('.submitButton', false);
    }
    return true;
}

// validation for the login form that checks the input values 
function validateLoginForm() {
    var forms = ['#login-form', '#genericModal #login-form'];
    forms.forEach(function (item) {
        $(item).validate({
            ignore: "",
            errorClass: "topZindex",
            rules: {
                Email: { required: true },
                Password: { required: true }
            },
            tooltip_options: {
                Email: {
                    placement: 'top'
                },
                Password: {
                    placement: 'top'
                }
            },
            highlight: function (element, errorClass) {
                var tTip = $(element).attr('aria-describedby');
                $('#' + tTip).addClass(errorClass);
            },
            messages: {
                Email: {
                    required: isLanguageDutch() ? "E-mail is niet ingevuld" : "Email is not filled",
                    minlength: isLanguageDutch() ? jQuery.validator.format("Voer ten minste {0} karakters in") : jQuery.validator.format("Please enter at least {0} characters")
                },
                Password: isLanguageDutch() ? "Wachtwoord is niet ingevuld" : "Password is not filled"
            }

        });
    });
}

// validation for the edit password form that checks the requirments for the new password 
function validateEditPasswordForm() {
    $('#edit-password-form').validate({
        rules: {
            Password: { minlength: 8, required: true },
            NewPassword: { minlength: 8, required: true },
            VerifyNewPassword: { minlength: 8, required: true, equalTo: "#newpassword" }
        },
        tooltip_options: {
            Password: {
                placement: 'top'
            },
            NewPassword: {
                placement: 'top'
            },
            VerifyNewPassword: {
                placement: 'top'
            }
        },
        messages: {
            VerifyNewPassword: $('#verifynewpassword').data('modal-error'),
            NewPassword: {
                required: isLanguageDutch() ? "Nieuw wachtwoord is niet ingevuld" : "New Password is not filled",
                minlength: isLanguageDutch() ? jQuery.validator.format("Voer ten minste {0} karakters in") : jQuery.validator.format("Please enter at least {0} characters")
            },
            Password: isLanguageDutch() ? "Wachtwoord is niet ingevuld" : "Password is not filled"
        }
    });
}

// validation for the disturbances searchfield. Checks if something is filled in before searching. 
function validateSearchInDisturbance() {
    $('#searchInDisturbance').validate({
        rules: {
            search: { required: true }
        },
        tooltip_options: {
            search: {
                placement: 'top'
            }
        },
        search: {
            required: isLanguageDutch() ? "Zoeken is niet ingevuld" : "Search is not filled"
        },
    });
}

// shows the login modal if the mijn9292 icon is clicked 
function loadMy9292LoginModal($element) {
    loadGenericModal($element);
    var url = isLanguageDutch() ? '/inloggen-dialog' : '/en/login-dialog';

    $.get(url)
        .done(function (data) {
            $('#dataHolder').html(data);
        })
        .fail(function () {
            $('#dataHolder').html($element.data('modal-error'));
        })
        .always(function () {
            $("#genericModal .curtain").hide();
        });
}

// shows the amberalert modal if the amber alert icon is clicked 
function loadAmberAlert($element) {
    loadGenericModal($element);
    $('#dataHolder').html($("#amberAlertContent").html());
    $('#genericModal .curtain').hide();
}

// shows the popup for the disclaimer and privacy statement at the register screen 
function loadDisclaimerAndPrivacy($element) {
    loadGenericModal($element);

    var url = '/Document/GetCmsContentHtml/disclaimer-en-privacy';
    if (!isLanguageDutch()) {
        url = '/en' + url;
    }

    $.get(url)
        .done(function (data) {
            $('#dataHolder').html(data);
        })
        .fail(function () {
            $('#dataHolder').html($element.data('modal-error'));
        })
        .always(function () {
            $("#genericModal .curtain").hide();
        });
}

// changes the navigation button screenreader information based on the state 
function navigationBarAccessiblityInit(closedMenuText, openMenuText) {
    $('#mainNav')
        .on('hidden.bs.collapse', function () {
            $('.navbar-toggle').prev('.sr-only').html(closedMenuText);
            $('.navbar-toggle').attr('title', closedMenuText);
        })
        .on('shown.bs.collapse', function () {
            $('.navbar-toggle').prev('.sr-only').html(openMenuText);
            $('.navbar-toggle').attr('title', openMenuText);
            $('.tooltip').hide();
        });
}

// changes the mijn9292 button and contrast button screenreader information based on the state 
function dropDownAccessiblityInit(closedMenuText, openMenuText) {
    $('.dropdown')
        .on('hidden.bs.dropdown', function (event) {
            var fullTitle = $(this).find('.dropdown-toggle').attr('name') + ' - ' + closedMenuText;
            $(this).prev('.sr-only').html(fullTitle);
            $(this).find('.dropdown-toggle').attr('title', fullTitle);
        })
        .on('shown.bs.dropdown', function (event) {
            var fullTitle = $(this).find('.dropdown-toggle').attr('name') + ' - ' + openMenuText;
            $(this).prev('.sr-only').html(fullTitle);
            $(this).find('.dropdown-toggle').attr('title', fullTitle);
        });
}

// This function inits the contrast load and onclick function. Split from document ready so we can add translations for active and inactive. 
function activeContrastAccessiblityInit(activeName, inactiveName) {

    //contrast switch 
    // Check (onLoad) if the cookie is there and set the class if it is 
    if ($.cookie('highcontrast') == "yes") {
        $("body").addClass("highcontrast");
        $("#contrastButtons").addClass("addGreenCheck");
        $("#contrastButtons").attr('name', activeName);
        $("#contrastButtons").attr('title', activeName);
    }

    // When the element is clicked 
    $(".button-toggle-highcontrast").click(function () {
        $.cookie('highcontrast', 'yes', {
            expires: 7,
            path: '/'
        });
        $("body").addClass("highcontrast");
        $("#contrastButtons").addClass("addGreenCheck");
        $("#contrastButtons").attr('name', activeName);
        $("#contrastButtons").attr('data-original-title', activeName);
    });
    $(".button-toggle-remove").click(function () {
        $('body').removeClass('highcontrast');
        $("#contrastButtons").removeClass("addGreenCheck");
        $("#contrastButtons").attr('name', inactiveName);
        $("#contrastButtons").attr('data-original-title', inactiveName);
        if ($.cookie('highcontrast') == "yes") {
            $.cookie("highcontrast", null, {
                path: '/',
            });
        }
    });
}

// Generic Modal loader 
function loadGenericModal($element) {
    if ($element === 'undefined' || $element === '' || $element.length == 0)
        return;

    var title = $element.data('modal-title'),
        iconClass = $element.data('modal-icon'),
        dialogSize = $element.data('modal-size') || '',
        titleStyling = $element.data('modal-title-custom-class'),
        titleImageUrl = $element.data('modal-title-img-src'),
        titleImageAltText = $element.data('modal-title-img-alt'),
        headerStyling = $element.data('modal-header-custom-class'),
        showPrintButton = $element.data('modal-show-print-button'),
        bodyStyling = $element.data('modal-body-custom-class'),
        removeCloseButton = $element.data('modal-remove-dismiss-button'),
        isFixed = $element.data('modal-enable-fixed-dialog');

    setGenericModalProperties(title, dialogSize, removeCloseButton,
        isFixed, bodyStyling, titleStyling, headerStyling, showPrintButton, iconClass, titleImageUrl, titleImageAltText);

    $('#genericModal').modal('show');
}

function loadDynamicUrlModal($element, callbackFunction) {
    var url = $element.data('dynamic-url');
    var isConformationModal = $element.data('confirm-modal');

    loadGenericModal($element);

    if (isConformationModal) {
        var confirmMessage = '<div class="alert alert-info m-b-20 p-10">' + $element.data('confirm-modal-confirmtext') + '</div>';
        var closeButton = '<button type="button" class="btn btn-primary m-r-5 pull-left" data-dismiss="modal" aria-label="Sluit venster"><i class="fas fa-times whitetxt"></i> ' + $element.data('confirm-modal-cancelbuttontext') + '</button>';
        var confirmButton = '<form action="' +
            url +
            '" method="post" onsubmit="return disableSubmitButtonAndShowLoader()" > ' +
            closeButton +
            '<button type="submit" class="btn btn-darkgrey whitetxt"><span>' +
            $element.data('confirm-modal-confirmbuttontext') +
            '</span> <i class="fas fa-arrow-right submitButton"></i><i class="loader-inline-template submitButton fas fa-circle-notch fa-spin fa-fw" style="display: none"></i></button></form>';

        $('#dataHolder').html(confirmMessage + confirmButton);
        $("#genericModal .curtain").hide();
    }
    else {
        $.get(url)
            .done(function (data) {
                if (data === "reload") {
                    var url = isLanguageDutch() ? '/login' : '/en/login';
                    location.href = url + '?returnUrl=' + window.location.pathname;
                }
                else {
                    $('#dataHolder').html(data);
                    if (callbackFunction !== undefined) {
                        callbackFunction.call($element);
                    };
                }
            })
            .fail(function () {
                $('#dataHolder').html($element.data('modal-error'));
            })
            .always(function () {
                $("#genericModal .curtain").hide();
            });
    }
}

function setGenericModalProperties(title, dialogSize, removeCloseButton,
    isFixed, bodyStyling, titleStyling, headerStyling, showPrintButton, iconClass, titleImageUrl, titleImageAltText) {

    if (isFixed === true) {
        $('#genericModal').attr('data-backdrop', "static");
        $('#genericModal').attr('data-keyboard', "false");
    }

    dialogSize = dialogSize || '';
    $('#genericModal .modal-dialog').addClass(dialogSize);

    if (titleStyling) {
        $('#genericModal .modal-title').addClass(titleStyling);
    }

    if (bodyStyling) {
        $('#genericModal .modal-body').addClass(bodyStyling);
    }

    if (showPrintButton) {
        $('#genericModal .modal-footer').removeClass("hidden");
    }

    if (title) {
        if (iconClass) {
            $('#genericModal #modalTitle').html('<i class="' + iconClass + '"></i> ' + title);
        }
        else {
            $('#genericModal #modalTitle').html(title);
        }

        if (titleImageUrl) {
            $('#genericModal .modal-header-image img').attr('src', titleImageUrl);
            if (titleImageAltText) {
                $('#genericModal .modal-header-image img').attr('alt', titleImageAltText);
            }
        }
        else {
            $('#genericModal .modal-header-image').hide();
        }

        if (headerStyling) {
            $('#genericModal .modal-header').addClass(headerStyling);
        }

        if (removeCloseButton === true) {
            $('#genericModal #btnDismiss').hide();
        }

        $('#genericModal .modal-header').show();
    }
    else {
        $('#genericModal .modal-header').hide();
    }
}

function closeGenericModal() {
    $('#genericModal').modal('hide');
}

function resetGenericModal() {
    $('.tooltip').tooltip('dispose');
    $('#genericModal').removeAttr('data-backdrop');
    $('#genericModal').removeAttr('data-keyboard');
    $('#genericModal #modalDialog').attr('class', 'modal-dialog');
    $('#genericModal #modalTitle').attr('class', 'modal-title h5 absolutePos');
    $('#genericModal #modalTitle').empty();
    $('#genericModal #modalHeader').attr('class', 'modal-header darkgreybg');
    $('#genericModal #modalHeader').show();
    $('#genericModal .modal-header-image img').attr('src', '');
    $('#genericModal .modal-header-image img').attr('alt', '');
    $('#genericModal .modal-header-image').show();
    $('#genericModal #btnDismiss').show();
    $('#genericModal #btnAccord').remove();
    $('#genericModal .modal-footer').addClass("hidden");
    $('#genericModal #modalBody #dataHolder').empty();
    $('#genericModal #modalBody').attr('class', 'modal-body generic-modal-body');
    $('#genericModal #dataHolder').empty();
}

// scroll listener function 
function init() {
    window.addEventListener('scroll', function (e) {

        var shrinkNo = $('#mainnav').outerHeight();

        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            showTopBut = 80,
            shrinkOn = shrinkNo,
            navi = document.querySelector(".calamiteitenbalk");

        if (distanceY > showTopBut) {
            if ($(".btt").is(":hidden")) {
                $(".btt").fadeIn("slow");
            }
        } else {
            if ($(".btt").is(":visible")) {
                $(".btt").fadeOut("slow");
            }
        };
    });
}

// on load of the page init the scroll listeners 
$(window).onload = init();

// all functions that are called when the page is initially ready. 
$(document).ready(function () {

    IEfullScreenPlannerBlockParent();

    initHomepageFunctions();

    // Add autocomplete tags to mailchimp forms 
    $("#mce-EMAIL").attr("autocomplete", "email");
    $("#mce-FNAME").attr("autocomplete", "given-name");
    $("#mce-LNAME").attr("autocomplete", "family-name");
    $("#mce-MMERGE3").attr("autocomplete", "organization");

    //map control for my9292 google map 
    $('.collapseMap').on('click', function (e) {
        if ($("#map-container").hasClass("map-small")) {
            $("#map-container").removeClass("map-small").addClass("map-large");
            $('.collapseMap').addClass("active").attr("data-original-title", $(".collapseMap").data("txt-smaller"));
        }
        else {
            $("#map-container").removeClass("map-large").addClass("map-small");
            $('.collapseMap').removeClass("active").attr("data-original-title", $(".collapseMap").data("txt-larger"));
        }
    });

    // check if there is a cookie for a closed calamity bar and hide the calamitybar if so 
    if ($.cookie('calamiteitenbalk') == 'closed') {
        $('.calamiteitenbalk').hide();
    };

    // create a cookie when user closes the calamitybar 
    $('.closeCalamity').click(function (e) {
        $('.calamiteitenbalk').alert('close');
        e.preventDefault();
        $.cookie('calamiteitenbalk', 'closed', { path: '/' });
    });

    //reset loaders for Safari 
    $(window).bind("pageshow", function (event) {
        if (navigator.userAgent.indexOf('Safari')) {
            if (event.originalEvent.persisted) {
                $(":submit").attr("disabled", false);
                $(":submit .loader-inline-template").hide();
                $(":submit .fa-arrow-right").show();
            }
        }
    });

    // make sure only one tabnav can be active in the planner block 
    $('.disturbancetabs a').on('click', function (e) {
        $('.plannertabspanels .tab-pane').removeClass('show active');
        $('.plannertabs a').removeClass('active').attr('aria-selected', 'false');
        $('.disturbancetabspanels .tab-pane').addClass('show active');
    });
    $('.plannertabs a').on('click', function (e) {
        $('.disturbancetabspanels .tab-pane').removeClass('show active');
        $('.disturbancetabs a').removeClass('active').attr('aria-selected', 'false');
    })

    // load unplanned disturbances on click 
    $('.btnGetPlannedDisturbances').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
        var url = $('.btnGetPlannedDisturbances').attr('href');
        $.get(url)
            .done(function (data) {
                $('#disturbances').html(data);
            })
            .fail(function () {
                $('#disturbances').html($(this).data('modal-error'));
            })
            .always(function () {
                //do nothing 
            });
    });

    $('.tab-pane.active .dropdown .dropdown.keep-open').on({
        "shown.bs.dropdown": function () { this.closable = false; },
        "click": function () { this.closable = true; },
        "hide.bs.dropdown": function () { return this.closable; }
    });

    // hide all tooltips when opening the main menu 
    $('#btnHamburger').on('click', function () {
        $('.tooltip').hide();
    });

    // bootstrap dropdown with selectboxes 
    var options = [];

    $('body').on('click', '.tab-pane.active .dropdown.keep-open .dropdown-menu a', function (event) {

        var val = $(this).attr('data-value');
        var target = ".tab-pane.active .dropdown-menu a[data-value='" + val + "']";

        var $inp = $(target).find('input'),
            idx;

        if ((idx = options.indexOf(val)) > -1) {

            options.splice(idx, 1);
            setTimeout(function () { $inp.prop('checked', false) }, 0);

            if (val == 'timeline-content-stops') {
                if ($('.tab-pane.active .timeline-content-stops .leg-item-toggleInfo').css('display') == 'block') {
                    $('.tab-pane.active .timeline-content-stops .leg-item-toggleInfo').css('display', 'none');
                    $('.tab-pane.active .timeline-content-stops').removeClass('leg-item-open');
                }
            }

            if (val == 'timeline-content-route') {
                if ($('.tab-pane.active .timeline-content-route .leg-item-toggleInfo').css('display') == 'block') {
                    $('.tab-pane.active .timeline-content-route .leg-item-toggleInfo').css('display', 'none');
                    $('.tab-pane.active .timeline-content-route').removeClass('leg-item-open');
                }
            }

            var className = '.' + val;
            $(className).removeClass('printPart');

        } else {

            options.push(val);
            setTimeout(function () { $inp.prop('checked', true) }, 0);

            if (val == 'timeline-content-stops') {
                if ($('.tab-pane.active .timeline-content-stops .leg-item-toggleInfo').css('display') == 'none') {
                    $('.tab-pane.active .timeline-content-stops .leg-item-toggleInfo').css('display', 'block');
                    $('.tab-pane.active .timeline-content-stops').addClass('leg-item-open');
                }
            }

            if (val == 'timeline-content-route') {
                if ($('.tab-pane.active .timeline-content-route .leg-item-toggleInfo').css('display') == 'none') {
                    $('.tab-pane.active .leg-item-toggle.printmap').trigger("click.itemToggle");
                }
            }

            var className = '.' + val;
            $(className).addClass('printPart');

        }

        $(event.target).blur();

        return false;

    });

    // close all open dropdowns when opening a dropdown in the active journey toolbar 
    $('.tab-pane.active .journeyToolBar .btn-group .dropdown:not(.keep-open)').on('click', function () {
        $('.dropdown').removeClass('open');
    });

    //faq open/close 
    $(".faqopen").click(function (closedMenuText, openMenuText) {
        var container = $(this).parents(".faqtopic");
        var answer = container.find(".faqanswer");
        var trigger = container.find(".faq-t");
        var title = $(this).data('title');

        answer.slideToggle(200);

        if (trigger.hasClass("faq-o")) {
            trigger.removeClass("faq-o");
        }
        else {
            trigger.addClass("faq-o");
        }

        if (container.hasClass("expanded")) {
            container.removeClass("expanded");
        }
        else {
            container.addClass("expanded");
        }

        if ($(this).attr('aria-expanded') == 'true') {
            var arialabel = $(this).attr('data-txt-closed');
            $(this).attr('aria-label', arialabel);
            $(this).attr('aria-expanded', 'false');
            $(this).next('div').attr('aria-hidden', 'true');
        }
        else {
            var arialabel = $(this).attr('data-txt-open');
            $(this).attr('aria-label', arialabel);
            $(this).attr('aria-expanded', 'true');
            $(this).next('div').attr('aria-hidden', 'false');
        }

    });

    //accessibility features for the 'lock location' buttons in the planner 
    $(".lock-from-button, .lock-to-button").click(function () {
        if ($(this).attr('aria-pressed') == 'true') {
            var txtInactive = $(this).attr('data-txt-inactive');
            $(this).attr('title', txtInactive);
            $(this).attr('data-original-title', txtInactive);
            if ($(this).hasClass('lock-from-button')) {
                $('#fromLock').val('false');
            } else {
                $('#toLock').val('false');
            };
        }
        else {
            var txtActive = $(this).attr('data-txt-active');
            $(this).attr('title', txtActive);
            $(this).attr('data-original-title', txtActive);
            if ($(this).hasClass('lock-to-button')) {
                $('#toLock').val('true');
            } else {
                $('#fromLock').val('true');
            };
        }
    });

    $('body').on('keypress', '.leg-item-toggle, #clearButt, #searchButt, .reset, .lock-from-button, .lock-to-button, .swapfieldsbut, .locationtypes label.btn', function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code 
        {
            $(this).click();
            return false;
        }
    });

    $('.selectDate, .selectTime').keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code 
        {
            $(this).click();
            return false;
        }
    });

    var ranOnce = false;
    $('.selectDate, .selectTime').on('click tap touchstart', function () {
        if (ranOnce) return;
        ranOnce = true;
    });

    // onload position submenu 
    positionMenu();

    // onload add 'reset' crosses when planner inputs are filled use :not(#datetime) to exclude datetime field 
    $("#planner .input-group input[type=text]:not(#date,#time)").each(function () {
        if ($(this).val().length > 0) {
            $(this).parent().find('.input-group-append .reset').removeClass('hidden');
        } else {
            $(this).parent().find('.input-group-append .reset').addClass('hidden');
        }
    });

    swapFieldButtons();
    initCustomTabBehaviorForPlanner();

    clearHiddenValueWhenInputFieldIsEmpty($("#van"), $("#from-url"));
    clearHiddenValueWhenInputFieldIsEmpty($("#via-text"), $("#via-url"));
    clearHiddenValueWhenInputFieldIsEmpty($("#naar"), $("#to-url"));
    clearHiddenValueWhenInputFieldIsEmpty($("#newlocation"), $("#location-url"));

    // show via text field when field is filled 
    if ($("#via-text").length > 0 && $("#via-text").val().length > 0) {
        RemoveVia1ClassHidden();
    }

    if (isLanguageDutch()) {
        setNLValidationMessages();
    }
    else {
        resetValidationMessages();
    }


    // planner validation 
    $("#planner").validate({
        onfocusout: false,
        errorClass: 'plannerError',
        ignore: "",
        rules: {
            fromText: { required: true },
            toText: { required: true },
            date: { required: true },
            time: { required: true }
        },
        tooltip_options: {
            fromText: { placement: 'top' },
            toText: { placement: 'top' },
            date: { placement: 'top' },
            time: { placement: 'top' }
        },
        messages: {
            fromText: { required: isLanguageDutch() ? 'Van is niet ingevuld' : 'From is not filled' },
            toText: { required: isLanguageDutch() ? 'Naar is niet ingevuld' : 'To is not filled' },
            date: { required: isLanguageDutch() ? 'Datum is niet ingevuld' : 'Date is not filled', min: isLanguageDutch() ? 'Deze datum ligt te ver in het verleden' : 'This date is too far in the past', max: isLanguageDutch() ? 'Deze datum ligt te ver in de toekomst' : 'This date is too far in the future' },
            time: { required: isLanguageDutch() ? 'Tijd is niet ingevuld' : 'Time is not filled' }
        },
        highlight: function (element, errorClass) {
            var tTip = $(element).attr('aria-describedby');
            $('#' + tTip).addClass(errorClass);
        },
        success: function (element) {
            $(element).addClass("checked");
        },
        invalidHandler: function (event, validator) {
            // enforce validation on "Extra options" tab 
            if (!$("#planner #van").is(':visible')) {
                $('a[href$="#home"]').click();
                $("div#home").removeAttr("hidden");

                setTimeout(function () {
                    validator.defaultShowErrors();
                }, 250);
            };
        }
    });

    // swap '#van' and '#naar' values and hidden input values 
    $(".swapfieldsbut").click(function () {
        SwapFromAndToField();
    });

    $(".addvia").on("click", function () {
        RemoveVia1ClassHidden();
    }).on("keypress", function (event) {
        if (event.which === 13 || event.keyCode === 13) {
            RemoveVia1ClassHidden();
        };
    });

    // remove added via fields 
    $(".closevia").on("click", function () {
        AddVia1ClassHidden();
    }).on("keypress", function (event) {
        if (event.which === 13 || event.keyCode === 13) {
            AddVia1ClassHidden();
            $('a.addvia').focus();
        };
    });

    //fill the hidden combined date/time field of the planner when date or time changes 
    function blurChange(e) {
        clearTimeout(blurChange.timeout);
        blurChange.timeout = setTimeout(function () {
            combineAndSwapDateTime();
        }, 100);
    }
    $(".datum, .tijd").on('blur change focusout', blurChange);

    //fill the hidden combined date/time field of the widget planner when date or time changes (no html5 date/time detection here because detecting support on the parent from within an iframe doesn't work on all devices) 
    function widgetBlurChange(e) {
        clearTimeout(widgetBlurChange.timeout);
        widgetBlurChange.timeout = setTimeout(function () {
            combineAndSwapDateTime();
        }, 100);
    }
    $(".widgetDate, .widgetTime").on('blur change focusout', widgetBlurChange);

    // check location of the submenu on resize and move if resolution is too small 
    $(window).resize(function () {
        if ($("input").is(":focus") && isMobile.any()) {
            // do nothing 
        } else {
            positionMenu();
        }
        IEfullScreenPlannerBlockParent()
    });

    // scroll naar item 
    $('body').on('click', '.scroll', function (event) {
        event.preventDefault();
        var toLocation = $(this.hash).offset().top + 1;

        $(this.hash).focus();

        $('html,body').animate({ scrollTop: toLocation }, 500);
    });

    //remove tooltips on tab change 
    $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
        $('#planner input[type=text]').tooltip('dispose');
    });

    // Feedback modal opener 
    $('.feedbackBut').on('click', function () {
        $('#feedBackModal').modal('show');
    });

    // Mijn 9292 login on click action 
    $('body').on('click', '.bntLogInMy9292', function () {
        loadMy9292LoginModal($(this));
    });

    $('.agreeTOS').on('click', function () {
        loadDisclaimerAndPrivacy($(this));
    });

    overrideFormsSubmit();

    // register validation 
    $('#register-form').validate({
        rules: {
            Email: { required: true, email: true },
            Password: { required: true, minlength: 8, notEqualTo: "#inputEmail" },
            AgreeTOS: { required: true }
        },
        tooltip_options: {
            Email: {
                placement: 'top'
            },
            Password: {
                placement: 'top'
            },
            AgreeTOS: {
                placement: 'top'
            }
        },
        messages: {
            AgreeTOS: isLanguageDutch() ? "Je dient akkoord te gaan met de algemene voorwaarden" : "You need to agree to the terms of agreement",
            Email: {
                required: isLanguageDutch() ? "E-mail is niet ingevuld" : "Email is not filled"
            },
            Password: {
                required: isLanguageDutch() ? "Wachtwoord is niet ingevuld" : "Password is not filled",
                minlength: isLanguageDutch() ? jQuery.validator.format("Voer ten minste {0} karakters in") : jQuery.validator.format("Please enter at least {0} characters")
            }
        }
    });

    // forgot password form validation 
    $('#forgot-pass-form').validate({
        rules: {
            email: { required: true }
        },
        tooltip_options: {
            email: {
                placement: 'top'
            }
        },
        messages: {
            email: { required: isLanguageDutch() ? "E-mail is niet ingevuld" : "Email is not filled" }
        }
    });

    // reset passowrd form validation 
    $('#reset-password-form').validate({
        rules: {
            NewPassword: { minlength: 8, required: true },
            NewPasswordConfirm: { minlength: 8, required: true }
        },
        tooltip_options: {
            NewPassword: {
                placement: 'top'
            },
            NewPasswordConfirm: {
                placement: 'top'
            }
        },
        NewPassword: {
            required: isLanguageDutch() ? "Nieuw wachtwoord is niet ingevuld" : "New password is not filled",
            minlength: isLanguageDutch() ? jQuery.validator.format("Voer ten minste {0} karakters in") : jQuery.validator.format("Please enter at least {0} characters")
        },
        NewPasswordConfirm: {
            required: isLanguageDutch() ? "Bevestig nieuw wachtwoord is niet ingevuld" : "Confirm new password is not filled",
            minlength: isLanguageDutch() ? jQuery.validator.format("Voer ten minste {0} karakters in") : jQuery.validator.format("Please enter at least {0} characters")
        }
    });

    // edit password validation 
    validateEditPasswordForm();

    // search button is required 
    validateSearchInDisturbance();

    // Accessibility planner explanation modal opener 
    $('.modalbut').on('click', function () {
        loadGenericModal($(this));
        var modalContent = $(this).data('modal-content');
        $('#genericModal .modal-body #dataHolder').html(modalContent);
        $('#genericModal .modal-body .curtain').hide();
    });

    $('.accessibilityButton').on('click', function () {
        if ($(this).hasClass('active')) {
            $('#planWithAccessibility').val('false');
        } else {
            $('#planWithAccessibility').val('true');
        }
    });

    // Locations modal opener 
    $('body').on('click', '.nearbut', function () {
        loadGenericModal($(this));
        NavBarLocation.getNeighborhoodStops();
        NavBarLocation.getMostUsedStops();
    });

    // Are you sure modal opener 
    $('#mainnav .deleteloc').on('click', function () {
        $('#sureModal').modal('show');
    });

    // MyLocation functionality 
    function rowColor() {
        $('.list-group-flush .list-group-item input:checkbox').each(function () {
            if ($(this).is(':checked')) {
                $(this).closest('.list-group-item').addClass('lightbluebg');
            } else {
                $(this).closest('.list-group-item').removeClass('lightbluebg');
            }
        });
    };

    // check all checkboxes when the checkbox in the th is checked 
    $('#myLocationsForm .select_all').change(function () {
        var checkboxes = $(this).closest('form').find(':checkbox');
        if ($(this).is(':checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });

    //show delete button when at least one checkbox is checked 
    $('#myLocationsForm :checkbox').change(function () {
        var delBut = $(this).closest('form').find('.deleteloc');
        if ($(this).closest('form').find(".list-group-flush input:checkbox:checked").length > 0) {
            delBut.removeClass('hidden');
        } else {
            delBut.addClass('hidden');
        }
        rowColor();
    });

    $("#myLocationsForm .deleteloc").on("click", function (e) {

        var arr = [];
        var notificationtxt = $(this).data("notificationtxt");

        $('#myLocationsForm .list-group-flush .list-group-item input:checkbox').each(function () {
            if ($(this).is(':checked')) {
                if (!$(this).closest('.list-group-item').hasClass('hidden')) {
                    $(this).closest('.list-group-item').addClass('hidden');
                    arr.push($(this).data('location-id'));
                }
            }
        });

        $.post('/delete-location', $.param({ locationsids: arr }, true))
            .success(function () {
                showUserMessage(notificationtxt);
            })
            .always(function () {
                var aantal = $('#mySavedLocationsTable tbody tr').not(".hidden").length;
                if (aantal === 0) {
                    $('.noSavedLocation').removeClass('hidden');
                    $('#mySavedLocationsTable').addClass('hidden');
                    $('.deleteloc').addClass('hidden');
                }
            });
    });

    $('#mySavedJourneys .select_all').change(function () {
        var checkboxes = $(this).closest('form').find(':checkbox');
        if ($(this).is(':checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });

    $('#mySavedJourneys :checkbox').change(function () {
        var delBut = $(this).closest('form').find('.deletejrn');
        if ($(this).closest('form').find(".list-group-flush input:checkbox:checked").length > 0) {
            delBut.removeClass('hidden');
        } else {
            delBut.addClass('hidden');
        }
        rowColor();
    });

    $('#mySavedJourneysInPassed .select_all').change(function () {
        var checkboxes = $(this).closest('form').find(':checkbox');
        if ($(this).is(':checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });

    $('#mySavedJourneysInPassed :checkbox').change(function () {
        var delBut = $(this).closest('form').find('.deletejrnpss');
        if ($(this).closest('form').find(".list-group-flush input:checkbox:checked").length > 0) {
            delBut.removeClass('hidden');
        } else {
            delBut.addClass('hidden');
        }
        rowColor();
    });

    $("#mySavedJourneysInPassed .deletejrnpss").on("click", function (e) {
        e.stopPropagation();
        var arr = [];

        $('#mySavedJourneysInPassed .list-group-flush .list-group-item input:checkbox').each(function () {
            if ($(this).is(':checked')) {
                if (!$(this).closest('.list-group-item').hasClass('hidden')) {
                    $(this).closest('.list-group-item').addClass('hidden');
                    arr.push($(this).data('journey-id'));
                }
            }
        });

        $.post('/delete-journey', $.param({ hashs: arr }, true));
    });

    $("#mySavedJourneys .deletejrn").on("click", function (e) {
        e.stopPropagation();
        var arr = [];

        $('#mySavedJourneys .list-group-flush .list-group-item input:checkbox').each(function () {
            if ($(this).is(':checked')) {
                if (!$(this).closest('.list-group-item').hasClass('hidden')) {
                    $(this).closest('.list-group-item').addClass('hidden');
                    arr.push($(this).data('journey-id'));
                }
            }
        });

        $.post('/delete-journey', $.param({ hashs: arr }, true))
            .always(function () {
                var aantal = $('#mySavedJourneysTable tbody tr').not(".hidden").length;
                if (aantal === 0) {
                    $('#mySavedJourneys').addClass('hidden');
                }
            });

    });

    $('#myLocationsForm .list-group-flush .list-group-item .btn:not(.dropdown-toggle)').click(function (e) {
        e.stopPropagation();
    });

    $("[data-van-mijn9292]").on("click", function () {
        var van = $(this).data("van-mijn9292");
        $('#van').val(van);
        $('#from-url').val(van);

        if ($('#van').val().length > 0) {
            $('#van').addClass('flatright');
            $('#van').parent().parent().parent().parent().find('.input-group-addon').removeClass('hidden');
        } else {
            $('#van').removeClass('flatright');
            $('#van').parent().parent().parent().parent().find('.input-group-addon').addClass('hidden');
        };
        swapFieldButtons();

        if (!$(".sidebar_wrapper").hasClass("active")) {
            toggleSideBar();
        }
    });

    $("[data-naar-mijn9292]").on("click", function () {
        var naar = $(this).data("naar-mijn9292");
        OpenAndFillSideMenuNaar(naar);
    });

    $("[data-naar]").on("click", function () {
        var naar = $(this).data("naar");
        OpenAndFillSideMenuNaar(naar);
    });

    //$("myLocationsForm .sortable").sortable.update; 

    // Ensure proper reset of the generic modal 
    $('#genericModal').on('hidden.bs.modal', function () {
        resetGenericModal();
    });

    // Ensure that no tooltip from underlying page is shown on a new modal 
    $('#genericModal').on('show.bs.modal', function () {
        $('.tooltip').tooltip('hide');
    });

    //remove tooltip after click 
    $('[data-show="tooltip"]').on('click', function () {
        $(this).tooltip('hide')
    })

    // Amber alert load generic modal 
    $('.imgAmberAlert').on('click', function () {
        loadAmberAlert($(this));
    }).on("keypress", function (event) {
        if (event.which === 13 || event.keyCode === 13) {
            loadAmberAlert($(this));
        };
    });

    // SideBar 
    $(".sidebar_button").on("click", function () {
        toggleSideBar();
    });

    // onload activate tooltips 
    $('body').tooltip({ selector: '[data-show="tooltip"]' });

    bindAccessibilityFeedbackEmail();

    // show random icon on 404 page 
    var iconArray = ['far icon-train', 'far icon-tram', 'far icon-ferry', 'far icon-lightrail', 'far icon-subway'],
        selectIcon = iconArray[Math.floor(Math.random() * iconArray.length)];
    $('.fourOfour i').removeClass().addClass(selectIcon);
});

// Extending jquery ui autocomplete to be able to make 
// categories right now only for returned jsons, but in the future 
// my 9292. 
$.widget('custom.locationSuggest', $.ui.autocomplete, {
    _create: function () {

        this._super();
        this.widget().menu('option', 'items', '> :not(.location-suggest__category)');

        // Add class for custom styling 
        this.menu.element.addClass('easy-autocomplete-container');

        // Turn off events for touch devices 
        // due to the hover events tapping twice is required 
        // See bug report on: http://bugs.jqueryui.com/ticket/10544 
        if (Modernizr.touchevents || isMobile.any()) {
            this.widget().off('menufocus hover mouseover mouseenter');
        }

    },

    // Render menu with categories 
    _renderMenu: function (ul, items) {
        var that = this,
            currentCategory = '';

        $('#planner input[type=text]').tooltip('dispose'); // remove validation messages when visible 

        $.each(items, function (index, item) {
            var li;
            if (item.category !== currentCategory) {
                ul.append('<li class=\'location-suggest__category\'>' + item.category + '</li>');
                currentCategory = item.category;
            }
            li = that._renderItemData(ul, item);
            var subtypeValue = item.location.SubType;

            if (!isLanguageDutch() && item.location.EnglishSubType) {
                subtypeValue = item.location.EnglishSubType;
            }
            li.attr('aria-label', subtypeValue + ': ' + item.label);
        });
    },

    // Render list item in the following structure: 
    // li.location-suggest__item.location-icon-{type} 
    //  .location-suggest__item-label 
    //  .location-suggest__item-meta 
    _renderItem: function (ul, item) {

        var label = $('<span/>').addClass('location-suggest__item-label');
        var meta = $('<span/>').addClass('location-suggest__item-meta');

        label.text(item.location.Displayname);
        label.data('location', item.location); // this is bad. I know. Don't be MAD. 

        var subtypeValue = item.location.SubType;

        if (!isLanguageDutch() && item.location.EnglishSubType) {
            subtypeValue = item.location.EnglishSubType;
        }
        meta.text(subtypeValue + ' | ' + item.location.Region);

        return $('<li>')
            .addClass('location-suggest__item location-icon-' + item.location.Type)
            .append(label, meta)
            .appendTo(ul);
    }

});

$.validator.addMethod("notEqualTo", function (value, element, param) {
    return this.optional(element) || value.toLowerCase() != $(param).val().toLowerCase();
}, isLanguageDutch() ? "E-mail en wachtwoord mogen niet hetzelfde zijn" : "Your email cannot be your password");

$(window).scroll(function (event) {
    var st = $(this).scrollTop();
    if (st > lastScrollTop) {
        if ($("#toprow").hasClass("fixed")) {
            $("#toprow").removeClass("fixed");
            $(".fillerdiv").remove();
        }
    } else if (this.pageYOffset < 80) {
        if ($("#toprow").hasClass("fixed")) {
            $("#toprow").removeClass("fixed");
            $(".fillerdiv").remove();
        }
    } else {
        if (!$("#toprow").hasClass("fixed")) {
            var fillerdiv = '<div class="fillerdiv" style="width:100%; height:' + $("#toprow").height() + 'px"></div>';
            $("#toprow").addClass("fixed");
            $(fillerdiv).insertBefore("#mainhome");
        }
    }
    lastScrollTop = st;
});

function OpenAndFillSideMenuNaar(naar) {
    $('#naar').val(naar);
    $('#to-url').val(naar);

    if ($('#naar').val().length > 0) {
        $('#naar').addClass('flatright');
        $('#naar').parent().parent().parent().parent().find('.input-group-addon').removeClass('hidden');
    } else {
        $('#naar').removeClass('flatright');
        $('#naar').parent().parent().parent().parent().find('.input-group-addon').addClass('hidden');
    };
    swapFieldButtons();
    if (!$(".sidebar_wrapper").hasClass("active")) {
        toggleSideBar();
    }
}
;

var Journey = {
    maxNrOfTabs: 0,
    mapsKey: "",
    loaderText: '',
    downloadingData: false,

    init: function(maxNrOfTabs, mapsKey, loaderText) {
        Journey.maxNrOfTabs = maxNrOfTabs;
        Journey.mapsKey = mapsKey;
        Journey.loaderText = loaderText;

        Journey.initGoogleMaps(mapsKey);

        // onload function
        $(document).ready(function() {

            $('html,body').scrollTo($('#topAd'), 500);

            Journey.InsertNoSundayJourneyTab();

            Journey.centerJourneyTab();
            Journey.tabNumbering();
            fitAdCont();

            Journey.enableTouchEvents();
            Journey.bindCarouselLayoutSwitch();
            Journey.bindSliderEvents();
        });

        $(document).on('shown.bs.tab',
            'a[data-toggle="tab"]',
            function(e) {
                Journey.centerJourneyTab();
            });

        $(document).on('click',
            '.saveToCalendar',
            function(e) {
                var icsContent = $('.tab-pane.active').data('icscontent');
                $('.tab-pane.active .icsContent').val(icsContent);
            });

        // activate arrow keys to browse through journeys
        $(document).keydown(debounce(function(e) {
                // disengage while sidebar or modal is open and when user is in an input
                if (!$('.sidebar_wrapper.active').length &&
                    !$('#genericModal').is(':visible') &&
                    !$('.tab-pane.active input').is(':focus') &&
                    !$('.priceWizardBlock').is(':visible')) {
                    switch (e.which) {
                    case 37: // left
                        Journey.goToPrev();
                        break;
                    case 39: // right
                        Journey.goToNext();
                        break;
                    default:
                        return;
                    }
                    e.preventDefault();
                }
            },
            500));

        // keep selected journey tab visible on small resolution and position submenu
        // added a delay for 'laggy' response when resizing
        $(window).bind('resize',
            function(e) {
                window.resizeEvt;
                $(window)
                    .resize(function() {
                        clearTimeout(window.resizeEvt);
                        window.resizeEvt = setTimeout(function() {
                                Journey.centerJourneyTab();
                            },
                            250);
                    });

                if ($(window).width() <= 767) {
                    Journey.horizontalLayout();
                    $(".changeLayout").hide();
                } else {
                    $(".changeLayout").show();
                }

            });
    },

    initGoogleMaps: function(mapsKey) {
        var dfd = jQuery.Deferred();
        var loaded = false;
        var lang = getLanguage();

        var GoogleMapsLoader = {
            init: function(mapsKey) {
                if (!loaded) {
                    var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src = 'https://maps.googleapis.com/maps/api/js?v=3&key=' +
                        mapsKey +
                        '&callback=window.gml.googleMapsCallback&language=' +
                        lang;
                    document.body.appendChild(script);
                    loaded = true;
                }
                return dfd.promise();
            },
            googleMapsCallback: function() {
                dfd.resolve(google.maps);
            }
        };

        window.gml = GoogleMapsLoader;
    },

    enableTouchEvents: function() {
        // touch actions
        var myElement = document.getElementById('journeyTabs');

        if (myElement) {
            var mc = new Hammer(myElement);
            mc.on("swipeleft",
                debounce(function(ev) {
                        if (Modernizr.touchevents || isMobile.any()) {
                            Journey.goToNext();
                        }
                    },
                    500));
            mc.on("swiperight",
                debounce(function(ev) {
                        if (Modernizr.touchevents || isMobile.any()) {
                            Journey.goToPrev();
                        }
                    },
                    500));
            mc.on("press",
                function(ev) {

                    if (Modernizr.touchevents || isMobile.any()) {

                        if ($('#journeyTabs .tab-pane.active .curtain.is-cancelled').length) {
                            return false;
                        }

                        //journey advice longpress menu
                        var title = "Menu",
                            dialogSize = "modal-sm",
                            bodyStyling = "p-25",
                            content = $('#journeyTabs .tab-pane.active .btn-group-wrap').first().clone(),
                            more_content = $('.change-links li .btn').clone();

                        setGenericModalProperties(title, dialogSize, false, true, bodyStyling);

                        content = content.find('a, button');

                        //fill modal 
                        $('#genericModal #dataHolder').html('<div class="btn-group"></div>');
                        $('#genericModal #dataHolder div').html(content);

                        // don't show disabled button save to my 9292
                        $('#genericModal .modal-body .btnSaveJourney.disabled').remove();

                        $('#genericModal #dataHolder')
                            .find('.btn-group')
                            .removeClass('btn-group')
                            .addClass('btn-group-vertical w-100p')
                            .find('a, button')
                            .attr('data-show', '')
                            .find('span').removeClass('hidden-xs-down');

                        //add extra content
                        $('#genericModal .modal-body .btn-group-vertical').append(more_content);

                        //make all buttons the same color
                        $('#genericModal .modal-body .btn-group-vertical .btn')
                            .removeClass('btn-link')
                            .removeClass('btn-darkgrey')
                            .addClass('btn-primary whitetxt text-center');

                        //mark the savejourney, print, email buttons with an extra class            
                        $("#genericModal .modal-body .btn-group-vertical .btn.btnSaveJourney")
                            .removeClass("btnSaveJourney")
                            .addClass("modal-saveJourney");
                        $("#genericModal .modal-body .btn-group-vertical .btn.saveToCalendar")
                            .removeClass("saveToCalendar")
                            .addClass("modal-saveToCalendar");
                        $("#genericModal .modal-body .btn-group-vertical .btn.printjourney")
                            .removeClass("printjourney")
                            .addClass("modal-print");
                        $('#genericModal #dataHolder .btn.openMailForm')
                            .removeClass('openMailForm')
                            .addClass('modal-email');

                        //show the modal
                        $('#genericModal').modal('show');
                        $('#genericModal .curtain').hide();
                    }
                });
        }

        $(document).on('click',
                '.modal-saveJourney',
                function(e) {
                    e.preventDefault();
                    $('#genericModal').modal('hide');
                    $(".tab-pane.active .btnSaveJourney").first().click();
                })
            .on('click',
                '.modal-saveToCalendar',
                function(e) {
                    e.preventDefault();
                    $('#genericModal').modal('hide');
                    $(".tab-pane.active .saveToCalendar").first().click();
                })
            .on('click',
                '.modal-print',
                function(e) {
                    $('#genericModal').modal('hide');
                    $(".tab-pane.active .printjourney").first().click();
                })
            .on('click.modalEmail',
                '.modal-email',
                function(e) {
                    $('#genericModal').modal('hide').one('hidden.bs.modal',
                        function() {
                            setTimeout(function() {
                                    $(".tab-pane.active .openMailForm").first().click();
                                },
                                50);
                        });
                });
    },

    bindCarouselLayoutSwitch: function() {
        // change layout buttons
        $(".changeLayout-vert").on("click",
            function() {
                Journey.verticalLayout();
            });

        $(".changeLayout-hor").on("click",
            function() {
                Journey.horizontalLayout();
            });
    },

    bindStarLocationButtonEvents: function() {

        // Login to add star location to my9292
        $('.addToFavoritesLogin').off('click').on('click',
            function() {
                loadDynamicUrlModal($(this));
            });

        // Add star location to my9292
        $('.addToFavorites').off('click').on('click',
            function() {
                loadDynamicUrlModal($(this));
            });

        // Remove star location from my9292
        $('.deleteFavorites').off('click').on('click',
            function() {
                loadDynamicUrlModal($(this));
            });

    },

    bindPriceIndication: function() {

        // Prijsindicatie modal opener ('Wessel' pages)
        $('.prijsindicatie').off('click').on('click',
            function() {
                loadGenericModal($(this));
                $('#genericModal #dataHolder').html($(this).data('htmlText'));
                $('#genericModal .curtain').hide();

                $('.prijsindicatieModal table').addClass('table table-sm table-bordered table-striped');
                $('.prijsindicatieModal .1').addClass('table-responsive');

                $('.prijsindicatieModal caption').addClass('sr-only').hide();

                setupAllTabs();
                ChangeTab(1);

            });

    },

    bindPriceWizardEvent: function() {

        // Enter key press on a label (accessibility)
        $('.frmPriceAdvice .dynamic-switch-but-label').off('keypress').on('keypress',
            function(e) {
                if (event.which === 13 || event.keyCode === 13) {
                    $(this).find('input[name="frequencyPeriod"]').trigger('click');
                }
            });

        $('.frmPriceAdvice').each(function() {
            $(this).off('submit').on('submit',
                function(event) {
                    event.preventDefault();

                    var $form = $(this);

                    if (!$form.valid()) {
                        return false;
                    }

                    $form.find('.btn-pwSubmit').prop('disabled', true);

                    showLoaderIcon('.pwForm-get-advice');

                    var frmValues = $form.serialize(),
                        url = $form.attr('action');

                    $.post(url, frmValues)
                        .done(function(data) {
                            // add content to the page
                            $form.parent().parent().find('.response-content').html(data);
                            $('.tab-pane.active .pw-content-toggle').toggle();
                            $('[data-show="tooltip"]').tooltip({ trigger: 'hover' });
                        })
                        .always(function() {
                            $form.find('.btn-pwSubmit').prop('disabled', false);
                            removeLoaderIcon('.pwForm-get-advice');
                        });
                });
        });

        $(document).off('click.pwGoBack').on('click.pwGoBack',
            '.btnPWGoBackToForm',
            function(e) {
                $('.tab-pane.active .pw-content-toggle').toggle();
            });

        // Custom binding for highlighting needed labels
        $('input[name="frequencyPeriod"]').off('change.pwPeriod').on('change.pwPeriod',
            function() {
                $(this).parent().parent().find('label').toggleClass('rdChecked');
            });

        // PrijsWijzer Form validation
        $('.frmPriceAdvice').each(function() {
            $(this).validate({
                onfocusout: false,
                rules: {
                    "days": {
                        max: function() {
                            if ($('.tab-pane.active .frmPriceAdvice input[name=frequencyPeriod]:checked').val() ===
                                'maand') {
                                return 31;

                            } else {
                                return 7;

                            }
                        }
                    }
                },
                tooltip_options: {
                    freqPerWeek: {
                        placement: 'top'
                    },
                    freqPerMonth: {
                        placement: 'top'
                    }
                },
                messages: {
                    age: {
                        required: isLanguageDutch() ? "Het veld leeftijd is verplicht" : "Age is a required field"
                    },
                    days: {
                        required: isLanguageDutch() ? "Het veld aantal dagen is verplicht" : "Days is a required field"
                    }
                }
            });
        });
    },

    bindTabSelectionEvent: function() {
        $('#journeyTabList a.nav-link').unbind('click.selectJourney').bind('click.selectJourney', debounce(function(event) {
            AdvertisementUtils.fetchAdviceBannersForSelectedJourney(CookieWall.isSavingAdvertisementsAllowed(CookieWall.tcData));
        }, 500));
    },

    setBrowserUrl: function($journeyTab) {
        if ($journeyTab !== undefined && $journeyTab.length) {
            window.history.replaceState(null, $journeyTab.data('title-text'), $journeyTab.data('journey-url'));
        }
    },

    retrieveNextJourneysAsJson: function(url, direction) {

        Journey.downloadingData = true;

        setTimeout(function() {
                Journey.showLoader();
            },
            0); // add loading visualization

        $.ajax({
            url: url,
            async: true,
            dataType: "json",
            type: "GET",
            success: function(data) {
                Journey.processJourneyAdviceDataSet(data, direction);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                Journey.removeLoader();
                Journey.downloadingData = false;
            }
        });

    },

    processJourneyAdviceDataSet: function(dataSet, direction) {

        if ((dataSet === null) ||
            (undefined === dataSet) ||
            (undefined === dataSet.JourneySliderBlock) ||
            (dataSet.JourneySliderBlock.length === 0) ||
            (undefined === dataSet.JourneyDetailBlock) ||
            (dataSet.JourneyDetailBlock.length === 0)) {
            // there are no more items to retrieve
            dataSet = [];
            dataSet['hasSlides'] = false;
        } else {
            dataSet['hasSlides'] = true;
        }

        // Add retrieved journeys to carrousel
        setTimeout(function() {
                if (dataSet.hasSlides) {

                    Journey.carrouselCleanup(direction, dataSet.NrOfItemsInDataset);

                    Journey.appendDataToPage(dataSet, direction);

                    Journey.bindSliderEvents();
                    Journey.tabNumbering();
                    Journey.centerJourneyTab();

                    Journey.downloadingData = false;
                }

                Journey.removeLoader(direction);
            },
            1);
    },

    showLoader: function() {
        var $curtainWidth = $('.journeyAdviceCol').width();
        var $curtainHeight = $('.journeyAdviceCol').height();
        $(".journeyAdviceCol").prepend('<div class="advice-curtain" style="width:' +
            $curtainWidth +
            'px; height:' +
            $curtainHeight +
            'px"><i class="fas fa-circle-notch fa-spin fa-3x fa-fw"></i><br/><small>' +
            Journey.loaderText +
            '</small></div>');
    },

    removeLoader: function() {
        $(".journeyAdviceCol .advice-curtain").remove();
    },

    removeExisitingTooltips: function() {
        $('.tab-pane.active input[type=number]').tooltip('dispose');
        $('.tab-pane.active .btnSaveJourney').tooltip('dispose');
    },

    appendDataToPage: function(dataSet, direction) {
        var $journeySliderBlock = $('#journeyTabList');
        var $journeyDetailBlock = $('#journeyTabs');

        if (direction === 1) {
            $journeySliderBlock.append(dataSet.JourneySliderBlock);
            $journeyDetailBlock.append(dataSet.JourneyDetailBlock);
        } else {
            $journeySliderBlock.prepend(dataSet.JourneySliderBlock);
            $journeyDetailBlock.prepend(dataSet.JourneyDetailBlock);
        }
    },

    // Depending on the direction we either remove the slides from the beginning of the end of the carrousel
    carrouselCleanup: function(direction, numberOfSlidesToRemove) {

        if ($("#journeyTabList li").length < (4 * Journey.maxNrOfTabs))
            return false; // no need to remove existing slides

        if (direction === 1) {
            $("#journeyTabList li").slice(0, numberOfSlidesToRemove).remove();
            $("#journeyTabs .tab-pane").slice(0, numberOfSlidesToRemove).remove();
        } else {
            $("#journeyTabList li").slice(-numberOfSlidesToRemove).remove();
            $("#journeyTabs .tab-pane").slice(-numberOfSlidesToRemove).remove();
        }
        return true;
    },

    tabNumbering: function(event) {

        // make connection between tabnavs and tab
        $('#journeyTabList li .nav-link').attr('href',
            function(i) {
                return '#advice' + (i + 1);
            });
        $('#journeyTabs .tab-pane').attr('id',
            function(i) {
                return 'advice' + (i + 1);
            });

    },

    bindSliderEvents: function() {

        //// Toggle element for detailed information
        $(".leg-item-toggle").unbind('click.itemToggle').bind('click.itemToggle',
            '[data-toggle-selector]',
            function(event, promise) {
                event.preventDefault();

                var $toggleLink = $(this),
                    $toggleParent,
                    $toggleEl;

                // checking for a chevron icon and simulate open/close if there is one
                if ($(this).find('i.fa-chevron-down').length !== 0) {
                    $(this).find('i.fa-chevron-down').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                } else if ($(this).find('i.fa-chevron-up').length !== 0) {
                    $(this).find('i.fa-chevron-up').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                }

                // By supplying [data-toggle-parent], another parent will be used
                // to apply the class to and to find the element to open.
                if ($toggleLink.data('toggle-parent')) {
                    $toggleParent = $toggleLink.closest($toggleLink.data('toggle-parent'));
                } else {
                    $toggleParent = $toggleLink.parent();
                }

                $toggleEl = $toggleParent.find($toggleLink.data('toggle-selector'));


                // Open cookie popup
                var cookieAccepted = getCookie("walkingAccepted");

                if ($toggleLink.data('toggle-walking-maps')) {
                    if (!cookieAccepted) {
                        openWalkingModal().then(function() {
                            executeGoogle($toggleLink, $toggleEl, $toggleParent, true, promise);

                            walkingAccept();
                        });
                    } else {
                        executeGoogle($toggleLink, $toggleEl, $toggleParent, cookieAccepted, promise);
                    }
                } else {
                    window.requestAnimationFrame(function() {
                        $toggleEl.toggle();
                        $toggleParent.toggleClass($toggleLink.data('toggle-class'));
                    });
                }
            });

        Journey.bindPriceWizardEvent();
        Journey.bindPriceIndication();
        Journey.bindStarLocationButtonEvents();
        Journey.bindTabSelectionEvent();

        $('button.prevJourney').unbind('click.getNextJourneys').bind('click.getNextJourneys',
            debounce(function(event) {
                    Journey.goToPrev();
                },
                500));

        $('button.nextJourney').unbind('click.getPrevJourneys').bind('click.getPrevJourneys',
            debounce(function(event) {
                    Journey.goToNext();
                },
                500));
    },

// next tab function
    goToNext: function() {

        if (Journey.downloadingData)
            return false;

        // tab navigation
        var currentParent = $('#bar-row .nav-item .nav-link.active').parent();
        var currentItem = $(currentParent).find('.nav-link');
        var nextParent = $(currentParent).next();
        var nextItem = $(nextParent).find('.nav-link');

        Journey.removeExisitingTooltips();

        if ($(nextParent).length) {
            $(nextItem).click();
            $(currentItem).removeClass('active');
            $(nextItem).addClass('active');
            $(window).trigger('resize');
        }

        // check if we need to load more journeys or just move on to the next tab
        var tabTotal = $('#journeyTabList li').length;
        var tabIndex = $('#journeyTabList li a.active').parent().index();
        var nextTab = tabIndex + 1;
        var loadNewTabsTrigger = tabTotal - nextTab;

        if (loadNewTabsTrigger <= 1) {
            Journey.retrieveNextJourneysAsJson(
                $('#bar-row .nav-item .nav-link.active').parent().data('next-journey-url'),
                1);
        } else {
            Journey.centerJourneyTab();
        }

        AdvertisementUtils.fetchAdviceBannersForSelectedJourney(CookieWall.isSavingAdvertisementsAllowed(CookieWall.tcData));

        fitAdCont();
    },

// previous tab function
    goToPrev: function() {
        if (Journey.downloadingData)
            return false;

        var currentParent = $('#bar-row .nav-item .nav-link.active').parent();
        var currentItem = $(currentParent).find('.nav-link');
        var prevParent = $(currentParent).prev();
        var prevItem = $(prevParent).find('.nav-link');

        Journey.removeExisitingTooltips();

        if ($(prevParent).length) {
            $(prevItem).click();
            $(currentItem).removeClass('active');
            $(prevItem).addClass('active');
            $(window).trigger('resize');
        }

        // check if we need to load more journeys or just move on to the previous tab
        var tabIndex = $('#journeyTabList li a.active').parent().index();
        if (tabIndex <= 1) {
            Journey.retrieveNextJourneysAsJson(
                $('#bar-row .nav-item .nav-link.active').parent().data('previous-journey-url'),
                Journey.maxNrOfSlides,
                0);
        } else {
            Journey.centerJourneyTab();
        }

        AdvertisementUtils.fetchAdviceBannersForSelectedJourney(CookieWall.isSavingAdvertisementsAllowed(CookieWall.tcData));

        fitAdCont();
    },


    verticalLayout: function() {

        $("#journeyTabList").removeClass("flex").addClass("noFlex");
        $("#bar-row").addClass("Side");
        $(".prevJourney").removeClass("flex").addClass("Side");
        $(".prevJourney i").removeClass("fa-arrow-left").addClass("fa-arrow-up");
        $(".nextJourney").removeClass("flex").addClass("Side");
        $(".nextJourney i").removeClass("fa-arrow-right").addClass("fa-arrow-down");
        $(".tabNavRow").removeClass('row').addClass('float-left w-25p');
        $(".tabNavRow .col").addClass('p-0');
        $(".tabRow").removeClass('row').addClass('float-left w-75p');
        $("#tabNavContainer").removeClass("row").addClass("p-0");
        $("#tabContainer").removeClass("row").addClass("Side");

        setTimeout(function() {
                Journey.centerJourneyTab();
            },
            500);

    },

    horizontalLayout: function() {

        $("#journeyTabList").addClass("flex").removeClass("noFlex");
        $("#bar-row").removeClass("Side");
        $(".prevJourney").addClass("flex").removeClass("Side");
        $(".prevJourney i").addClass("fa-arrow-left").removeClass("fa-arrow-up");
        $(".nextJourney").addClass("flex").removeClass("Side");
        $(".nextJourney i").addClass("fa-arrow-right").removeClass("fa-arrow-down");
        $(".tabNavRow").addClass('row').removeClass('float-left w-25p');
        $(".tabNavRow .col").removeClass('p-0');
        $(".tabRow").addClass('row').removeClass('float-left w-75p');
        $("#tabNavContainer").addClass("row").removeClass("p-0");
        $("#tabContainer").addClass("row").removeClass("Side");

        setTimeout(function() {
                Journey.centerJourneyTab();
            },
            500);

    },


// scroll selected journey tab to center
    centerJourneyTab: function() {

        var scrollOffset;
        if (
            $("#bar-row")
                .hasClass("Side")) { // check layout and calculate horizontal or vertical selected tab position and scroll to it

            var halfTabBarHeight = $('#bar-row').height() / 2;
            var halfTabHeight = $('.nav-item .nav-link').outerHeight() / 2;
            scrollOffset = halfTabBarHeight - halfTabHeight;
            scrollOffset = scrollOffset *= -1;
            $('#bar-row').scrollTo($('.nav-item .nav-link.active'),
                500,
                {
                    offset: scrollOffset
                });

        } else {

            var halfTabBarWidth = $('#bar-row').width() / 2;
            var halfTabWidth = $('.nav-item .nav-link').outerWidth() / 2;
            scrollOffset = halfTabBarWidth - halfTabWidth;
            scrollOffset = scrollOffset *= -1;
            $('#bar-row').scrollTo($('.nav-item .nav-link.active'),
                500,
                {
                    offset: scrollOffset
                });
        }
    },

// init saveJourney
    initSaveJourney: function(savedTextTranslation, genericErrorTextTranslation) {
        $('a.btnSaveJourney').unbind('click.btnSaveJourney').bind('click.btnSaveJourney',
            function(event) {
                event.preventDefault();
                var $btnSaveJourney = $(this);
                var $bothBtnSaveJouney = $btnSaveJourney.parent().parent().parent().find('a.btnSaveJourney');
                var toolbarIconMy9292 = '.toolbar-savetomy9292';
                var url = $btnSaveJourney.attr('href');

                $bothBtnSaveJouney.each(function() { $(this).addClass('disabled') });

                showLoaderIcon(toolbarIconMy9292);

                $.post(url)
                    .done(function() {
                        var tooltipSavedMessage = $btnSaveJourney.data("saved-label");
                        $bothBtnSaveJouney.find('.saveJourneyText').each(function() {
                            $(this).text(savedTextTranslation);
                            $(this).wrap(
                                '<div class="float-right m-l-5" data-show="tooltip" data-placement="bottom" title="' +
                                tooltipSavedMessage +
                                '"></div>');
                            $(this).tooltip('hide');
                        });
                    })
                    .fail(function() {
                        $bothBtnSaveJouney.each(function() {
                            $(this).tooltip('dispose')
                                .attr('title', genericErrorTextTranslation)
                                .tooltip({
                                    placement: 'top',
                                    trigger: 'manual',
                                    template:
                                        '<div class="tooltip"><div class="tooltip-arrow orangearrow"></div><div class="tooltip-inner orangebg"></div></div>'
                                })
                                .tooltip('show')
                                .removeClass('disabled');
                        });
                    })
                    .always(function() {
                        removeLoaderIcon(toolbarIconMy9292);
                    });
            });
    },

    InsertNoSundayJourneyTab: function() {
        if ($('#NoSundayJourney').length) {
            var previousIndex = $('#NoSundayJourney').index();
            Journey.tabNumbering();
            $('#advice' + previousIndex)
                .after(
                    '<div class="dynamic-tab-pane-control tab-pane p-0 active show" role="tabpanel" aria-labelledby="tab-label"><div id="NoSundayContent" class="relativePos"></div></div>');
            $('#journeyTabList .nav-item:not(#NoSundayJourney) .nav-link').removeClass('active show');
            $('#journeyTabs .tab-pane:not(.active.show)').removeClass('active');

            Journey.loadNoSundayJourneyContent();
        }
    },

    loadNoSundayJourneyContent: function() {

        var url = '/GenerateNoJourneySundayView';
        if (!isLanguageDutch()) {
            url = '/en' + url;
        }

        url = url + '?sunday=' + $('#NoSundayJourney').attr('data-date');

        $.get(url)
            .done(function(data) {
                $('#NoSundayContent').html(data);
                Journey.filterSundayProvinces();
            })
            .fail(function() {
                //TODO: correct error handling??
            });
    },

    filterSundayProvinces: function() {
        var fromProvince = $('#NoSundayJourney').attr('data-from-province');
        var toProvince = $('#NoSundayJourney').attr('data-to-province');
        $('.province-item').hide();
        if (fromProvince !== toProvince) {
            $('#province-' + fromProvince).show();
        }
        $('#province-' + toProvince).show();
    }
};

function executeGoogle($toggleLink, $toggleEl, $toggleParent, cookieAccepted, promise) {
    if (cookieAccepted && $toggleLink.data('toggle-walking-maps')) {
        // Initialize map if not done already
        if ($toggleLink.data('toggle-walking-maps') === true && !$toggleLink.data('toggle-walking-maps-init')) {
            var opts = $toggleLink.data();

            opts['mapsKey'] = Journey.mapsKey;
            GenerateWalkRouteMap($toggleEl, opts, promise);
            $toggleLink.data('toggle-walking-maps-init', true);
        }

        window.requestAnimationFrame(function() {
            $toggleEl.toggle();
            $toggleParent.toggleClass($toggleLink.data('toggle-class'));
        });
    }
};

function openWalkingModal() {
    var result = new Promise(function(resolve, reject) {


        var title = $('.btn.kaart').attr('data-modal-title'),
            dialogSize = "modal-ms",
            bodyStyling = "p-25",
            content = $('#journeyTabs .tab-pane.active .btn-group-wrap').first().clone()

        setGenericModalProperties(title, dialogSize, false, true, bodyStyling);

        //fill modal 
        $('#genericModal #dataHolder').html('<div class="explanation">' +
            $('.btn.kaart').attr('data-modal-text') +
            '<br/><br/>' +
            '<a class="btn btn-tertiary noprint m-b-10 m-r-10" href="#" title="' +
            $('.btn.kaart').attr('data-modal-reject') +
            '" aria-label="" role="button" tabindex="0" data-dismiss="modal">' +
            $('.btn.kaart').attr('data-modal-reject') +
            '</a>' +
            '<a class="btn btn-primary whitetxt noprint m-b-10" title="' +
            $('.btn.kaart').attr('data-modal-accept') +
            '" aria-label="" id="acceptShowWalkRoute" role="button" tabindex="0">' +
            $('.btn.kaart').attr('data-modal-accept') +
            ' <i class="fas fa-arrow-right"></i></a></div>');

        $("#acceptShowWalkRoute").click(function() {
            resolve();
        });

        //show the modal
        $('#genericModal').modal('show');
        $('#genericModal .curtain').hide();
    });

    return result;
}

function walkingAccept() {
    setCookie("walkingAccepted", "true", 365);

    $("#btnDismiss").click();
}

// Cookies
function setCookie(cname, cvalue, exdays) {

    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));

    $.cookie(cname, cvalue, { path: '/', expires: d });
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
};
var PrintButtons = {
  printSelector: '.toolbar-print',

  init: function () {

    //bind ctrl+p event
    if (!isMobile.any()) {
      $.ctrl('P', function () {
        PrintButtons.openMaps();
      });
    }

    var $printButton = $("a.printjourney");

    $printButton.each(function (index, element) {
      $(element).on('click', function (event) {
        event.preventDefault();
        showLoaderIcon(PrintButtons.printSelector);
        PrintButtons.openMaps();
      });
    });

  },

  openMaps: function () {
    var maps = $(".tab-pane.active .printmap");
    var mapsState = {};
    var promises = [];
    // only open google map containers if the checkbox for route is checked
    if ($(".tab-pane.active a[data-value='timeline-content-route'] input[type='checkbox']").is(":checked")) {
      // Click the 'show maps' link on the selected journey page if maps are hidden
      $.each(maps, function (index, element) {
        var deferred = $.Deferred();
        mapsState[index] = $(element).closest('.leg-item.timeline-content').filter(".leg-item-open").length < 1; //open = false, closed = true
        if (mapsState[index]) {
          promises.push(deferred);
          // pass deferred and resolve it in GenerateWalkRouteMap when done
          $(element).trigger('click', deferred);
        }
      });
      $.when.apply($, promises).then(function (data) {
        setTimeout(function () {
          removeLoaderIcon(PrintButtons.printSelector);
          window.print();
          PrintButtons.restoreStates(maps, mapsState);
        }, 250);
      });
    } else {
      window.print();
    }
    
  },

  restoreStates: function (maps, previousMapState) {
    $.each(maps, function (index, element) {

      var isMapCurrentlyClosed = $(element).closest('.leg-item.timeline-content').filter(".leg-item-open").length < 1;
      if (isMapCurrentlyClosed !== previousMapState[index]) {
        $(element).click();
      }
    });
  }
};

;
var PriceWizard = {
  init: function (url) {

    // Add click-event to the "order-product" links on this page
    $('.order-product-link').off('click.productOrdering').on('click.productOrdering', function (event) {
      var data = { companyName: $(this).data('company-name'), productName: $(this).data('product-name') };

      $.ajax({
        method: 'GET',
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8"
      });
    });
  }
};
var LocationsInMap = {
    map: "",
    markers: [],
    isEnglishLanguage: false,
    locations: [],
    translatedUseAsTo: "",
    translatedUseAsFrom: "",
    translatedDepartureTimes: "",
    translatedCurrentLocation: "",
    translatedGeoLocationError: "",
    translatedGeoLocationIsNotSupported: "",
    i: "",

    addMarker: function(nearByLocation) {
        const marker = L.marker(
            new L.LatLng(
                nearByLocation.LatLong.Latitude,
                nearByLocation.LatLong.Longitude
            ),
            {
                icon: L.icon({
                    title: nearByLocation.Url,
                    iconUrl: `/static/images/gmap-icon-${nearByLocation.Type}.png`,
                    iconSize: [62, 50],
                    iconAnchor: [31, 50]
                }),
                bounceOnAd: true
            }
        );

        LocationsInMap.markers.push(marker);
        L.featureGroup(LocationsInMap.markers).addTo(LocationsInMap.map);


        var popupText =
            `<h6><i class="far icon-${nearByLocation.Type}"></i>${nearByLocation.Name}<br><small class="text-muted">${
                nearByLocation.SubType} &middot; ${nearByLocation.Region} &middot; ${nearByLocation.Distance
                }</small></h6><hr><button 
            }" onclick="processDataVan('${nearByLocation.Url}')" type="button" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-arrow-right"></i> ${LocationsInMap
                .translatedUseAsFrom
                }</button> <button  
            }" onclick="processDataNaar('${nearByLocation.Url}')" type="button" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-arrow-right"></i> ${LocationsInMap
                .translatedUseAsTo}</button>`;

        if (nearByLocation.SubType === "Bushalte" ||
            nearByLocation.SubType === "Station" ||
            nearByLocation.SubType === "Tramhalte") {
            popupText =
                popupText +
                ' <a href="/' +
                nearByLocation.Url +
                '" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-clock"></i> ' +
                LocationsInMap.translatedDepartureTimes +
                "</button>";
        }

        marker.bindPopup(popupText);
    },

    getNearBy: function() {

        const mylat = LocationsInMap.map.getCenter().lat;
        const mylng = LocationsInMap.map.getCenter().lng;
        var blnExists;
        const url = ((LocationsInMap.languageIsEnglish) ? "/en" : "") + "/locations" + "/" + mylat + "/" + mylng;
        var nearByLocations = [];

        jQuery.ajax({
            type: "GET",
            url: url,
            dataType: "json",
            success: function(response) {

                nearByLocations = response["locations"];

                //generate markers and popups for nearby locations
                for (i = 0; i < nearByLocations.length; i++) {
                    blnExists = false;
                    for (let j = 0; j < LocationsInMap.markers.length; j++) {
                        if (LocationsInMap.markers[j].Url === nearByLocations[i].Url) {
                            blnExists = true;
                            break;
                        }
                    };

                    if (!blnExists)
                        LocationsInMap.addMarker(nearByLocations[i]);
                };

            },
            error: function(xhr, ajaxOptions, thrownError) {
                //console.log('Function getNearby has failed (' + thrownError + ').');
            },
            complete: function() {
                //console.log('Function getNearby complete');
            }
        });

    },

    setCurrentPosition: function() {

        const getPosition = function() {
            if (navigator.geolocation) {
                return new Promise(function(resolve, reject) {
                    navigator.geolocation.getCurrentPosition(resolve, reject);
                });
            } else {
                return new Promise(function(resolve) { resolve({}) });
            }
        };

        getPosition()
            .then(function(position) {
                if (position.coords) {
                    handleLocationSuccess(position);
                } else {
                    handleLocationError(position);
                }

                LocationsInMap.getNearBy();
            })
            .catch(function(error) {
                handleUnsupportedError(error);

                LocationsInMap.getNearBy();
            });

        function handleLocationSuccess(position) {

            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            const marker = L.marker(
                new L.LatLng(
                    pos.lat,
                    pos.lng
                ),
                {
                    icon: L.icon({
                        iconUrl: `/static/images/gmap-currentLocation-icon-small.png`,
                        iconSize: [35, 35],
                        iconAnchor: [17.5, 17.5]
                    }),
                    bounceOnAd: true
                }
            );

            LocationsInMap.markers.push(marker);
            L.featureGroup(LocationsInMap.markers).addTo(LocationsInMap.map);

            // create radius
            const circle = new L.Circle([pos.lat, pos.lng],
                {
                    color: "#009ae0",
                    fillColor: "#009ae0",
                    fillOpacity: 0.1,
                    radius: 500
                }).addTo(LocationsInMap.map);

            const latLng = new L.LatLng(pos.lat, pos.lng);
            const bounds = latLng.toBounds(500);

            LocationsInMap.map.panTo(latLng).fitBounds(bounds);

            const centerOnCurrentLocationBut =
                `<button id="recenter" type="button" tabindex="0" class="btn btn-primary btn-sm p-5 p-lr-10" data-show="tooltip" data-placement="top" data-original-title="${
                    LocationsInMap.translatedCurrentLocation}"><i class="far fa-dot-circle"></i></button>`;
            $(".collapseMapContainer").append(centerOnCurrentLocationBut);

            $("#recenter").click(function() {
                LocationsInMap.map.setView([pos.lat, pos.lng]);
            });

        };

        function handleLocationError(pos) {
            console.log("HandlelocationError");
            console.log(pos);
        };

        function handleUnsupportedError(error) {
            console.log("UnsupportedError");
            console.log(error);
        };
    },

    initialize: function(locations,
        translatedUseAsTo,
        translatedUseAsFrom,
        translatedDepartureTimes,
        translatedCurrentLocation,
        translatedGeoLocationError,
        translatedGeoLocationIsNotSupported,
        isEnglishLanguage) {

        LocationsInMap.locations = locations;
        LocationsInMap.translatedUseAsTo = translatedUseAsTo;
        LocationsInMap.translatedUseAsFrom = translatedUseAsFrom;
        LocationsInMap.translatedDepartureTimes = translatedDepartureTimes;
        LocationsInMap.translatedCurrentLocation = translatedCurrentLocation;
        LocationsInMap.translatedGeoLocationError = translatedGeoLocationError;
        LocationsInMap.translatedGeoLocationIsNotSupported = translatedGeoLocationIsNotSupported;
        LocationsInMap.languageIsEnglish = isEnglishLanguage;
    },

    initializeMap: function() {

        //Osm URL
        const osmUrl = "https://osmtile.9292.nl/pngut/{z}/{x}/{y}.png";

        // set options for map
        const mapOptions = {
            maxZoom: 20,
            maxNativeZoom: 17,
            minZoom: 9,
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        };

        const osmLayer = new L.TileLayer(osmUrl, mapOptions);

        LocationsInMap.map = new L.Map(document.getElementById("map-container"),
            {
                zoomControl: false
            });

        LocationsInMap.map.addLayer(osmLayer);

        L.control.zoom({
            position: "bottomleft"
        }).addTo(LocationsInMap.map);

        const markers = LocationsInMap.markers;

        var locations = LocationsInMap.locations;

        // generate markers and popup for the saved locations
        for (let i = 0; i < locations.length; i++) {
            var marker = new L.marker(
                new L.LatLng(locations[i][1], locations[i][2]),
                {
                    icon: L.icon({
                        iconUrl: locations[i][3],
                        iconSize: [62, 50],
                        iconAnchor: [31, 50]
                    })
                }
            );
            markers.push(
                marker
            );

            var popupText =
                `<h6><i class="far icon-${locations[i][5]}"></i>${locations[i][0]}<br><small class="text-muted">${
                    locations[i][6]} &middot; ${locations[i][7]}</small></h6>`;
            popupText = popupText +
                '<hr><button data-van="' + 
                locations[i][4] +
                '" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-arrow-right"></i> ' +
                LocationsInMap.translatedUseAsFrom + 'type="button"' +
                '</button> <button type="button" data-naar="' +
                locations[i][4] +
                '" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-arrow-right"></i> ' +
                LocationsInMap.translatedUseAsTo +
                 "</button>";

            if (locations[i][6] === "Bushalte" || locations[i][6] === "Station" || locations[i][6] === "Tramhalte") {
                popupText = popupText +
                    '  <a href="/' +
                    locations[i][4] +
                    '" class="btn btn-primary btn-sm centered m-l-5 p-5"><i class="fas fa-clock"></i> ' +
                    LocationsInMap.translatedDepartureTimes +
                    "</button>";
            }

            marker.bindPopup(popupText);
        }

        if (LocationsInMap.map && LocationsInMap.map.length > 0) {
            var group = L.featureGroup(markers).addTo(LocationsInMap.map);
            LocationsInMap.markers = markers;
            LocationsInMap.map.fitBounds(group.getBounds());
        } else {
            var bounds = new L.LatLngBounds([[53.109257690399645, 4.777605698311008], [50.82162311783238, 5.959873416033991]]);
            LocationsInMap.map.fitBounds(bounds);
        }
        // use user's location to set the current position
        LocationsInMap.setCurrentPosition();

        // activate nearby function on map drag
        LocationsInMap.map.on("dragend",
            function() {
                LocationsInMap.getNearBy();
            });


        $(".collapseMap").on("click",
            function() {
                LocationsInMap.map.invalidateSize();
            });
    },
}

// Process data-van values.
function processDataVan(van) {
    $("#van").val(van);
    $("#from-url").val(van);

    if ($("#van").val().length > 0) {
        $("#van").parent().find(".input-group-append .reset").removeClass("hidden");
    } else {
        $("#van").parent().find(".input-group-append .reset").addClass("hidden");
    };
    swapFieldButtons();

    if (!$(".sidebar_wrapper").hasClass("active")) {
        toggleSideBar();
    }
};

// Process data-naar values. 
function processDataNaar(naar) {
    $("#naar").val(naar);
    $("#to-url").val(naar);

    if ($("#naar").val().length > 0) {
        $("#naar").parent().find(".input-group-append .reset").removeClass("hidden");
    } else {
        $("#naar").parent().find(".input-group-append .reset").addClass("hidden");
    };
    swapFieldButtons();

    if (!$(".sidebar_wrapper").hasClass("active")) {
        toggleSideBar();
    }
};;
function inner(aobj)
{
var innertext="";
try
{
  if (aobj)
  {
    try
    {
      l = aobj.innerText.length;
      return(aobj.innerText);
    }
    catch (e)
    {
      innerText = aobj.innerHTML.replace(/<\/?[^>]+>/gi,"");
    }
  }
}
catch (err)
{
  return("z");
}
return innerText;
}

function hasSupport() {

  if (typeof hasSupport.support != "undefined")
    return hasSupport.support;
  
  var ie55 = /msie 5\.[56789]/i.test( navigator.userAgent );
  
  hasSupport.support = ( typeof document.implementation != "undefined" &&
      document.implementation.hasFeature( "html", "1.0" ) || ie55 )
      
  // IE55 has a serious DOM1 bug... Patch it!
  if ( ie55 ) {
    document._getElementsByTagName = document.getElementsByTagName;
    document.getElementsByTagName = function ( sTagName ) {
      if ( sTagName == "*" )
        return document.all;
      else
        return document._getElementsByTagName( sTagName );
    };
  }

  return hasSupport.support;
}

///////////////////////////////////////////////////////////////////////////////////
// The constructor for tab panes
//
// el : HTMLElement    The html element used to represent the tab pane
// bUseCookie : Boolean  Optional. Default is true. Used to determine whether to us
//            persistance using cookies or not
//
function WebFXTabPane( el, bUseCookie ) {
  if ( !hasSupport() || el == null ) return;
  
  this.element = el;
  this.element.tabPane = this;
  this.pages = [];
  this.selectedIndex = null;
  this.useCookie = bUseCookie != null ? bUseCookie : true;
  
  // add class name tag to class name
  this.element.className = this.classNameTag + " " + this.element.className;
  
  // add tab row
  this.tabRow = document.createElement( "div" );
  this.tabRow.className = "tab-row";
  el.insertBefore( this.tabRow, el.firstChild );

  var tabIndex = 0;
  //if ( this.useCookie ) {
  //  tabIndex = Number( WebFXTabPane.getCookie( "webfxtab_" + this.element.id ) );
  //  if ( isNaN( tabIndex ) )
  //    tabIndex = 0;
  //}
  this.selectedIndex = tabIndex;
  
  // loop through child nodes and add them
  var cs = el.childNodes;
  var n;
  for (var i = 0; i < cs.length; i++) {
    if (cs[i].nodeType == 1 && cs[i].className == "tab-page") {
      this.addTabPage( cs[i] );
    }
  }
}

WebFXTabPane.prototype.classNameTag = "dynamic-tab-pane-control";

WebFXTabPane.prototype.setSelectedIndex = function ( n ) {
  if (this.selectedIndex != n) {
    if (this.selectedIndex != null && this.pages[ this.selectedIndex ] != null )
      this.pages[ this.selectedIndex ].hide();
    this.selectedIndex = n;
    this.pages[ this.selectedIndex ].show();
    
    if ( this.useCookie )
      WebFXTabPane.setCookie( "webfxtab_" + this.element.id, n );  // session cookie
  }
  var countername;
  switch(n) {
  case 0:
    countername = "Ritprijs";
    break;
  case 1:
    countername = "OV_chipkaart";
    break;
  case 2:
    countername = "Abonnementen";
    break;
  case 3:
    countername = "Regionaal";
    break;
  case 4:
    countername = "Meer";
    break;
  default:
    countername = "";
  }
  sitestat("http://nl.sitestat.com/ovr/ovr/s?tarief.uitgebreid." + countername);
};
  
WebFXTabPane.prototype.getSelectedIndex = function () {
  return this.selectedIndex;
};
  
WebFXTabPane.prototype.addTabPage = function ( oElement ) {
  if ( !hasSupport() ) return;
  
  if ( oElement.tabPage == this )  // already added
    return oElement.tabPage;

  var n = this.pages.length;
  var tp = this.pages[n] = new WebFXTabPage( oElement, this, n );
  tp.tabPane = this;
  
  // move the tab out of the box
  this.tabRow.appendChild( tp.tab );
      
  if ( n == this.selectedIndex )
    tp.show();
  else
    tp.hide();
    
  return tp;
};
  
WebFXTabPane.prototype.dispose = function () {
  this.element.tabPane = null;
  this.element = null;    
  this.tabRow = null;
  
  for (var i = 0; i < this.pages.length; i++) {
    this.pages[i].dispose();
    this.pages[i] = null;
  }
  this.pages = null;
};



// Cookie handling
WebFXTabPane.setCookie = function ( sName, sValue, nDays ) {
  var expires = "";
  if ( nDays ) {
    var d = new Date();
    d.setTime( d.getTime() + nDays * 24 * 60 * 60 * 1000 );
    expires = "; expires=" + d.toGMTString();
  }

  document.cookie = sName + "=" + sValue + expires + "; path=/";
};

WebFXTabPane.getCookie = function (sName) {
  var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" );
  var res = re.exec( document.cookie );
  return res != null ? res[3] : null;
};

WebFXTabPane.removeCookie = function ( name ) {
  setCookie( name, "", -1 );
};








///////////////////////////////////////////////////////////////////////////////////
// The constructor for tab pages. This one should not be used.
// Use WebFXTabPage.addTabPage instead
//
// el : HTMLElement      The html element used to represent the tab pane
// tabPane : WebFXTabPane  The parent tab pane
// nindex :  Number      The index of the page in the parent pane page array
//
function WebFXTabPage( el, tabPane, nIndex ) {
  if ( !hasSupport() || el == null ) return;
  
  this.element = el;
  this.element.tabPage = this;
  this.index = nIndex;
  
  var cs = el.childNodes;
  for (var i = 0; i < cs.length; i++) {
    if (cs[i].nodeType == 1 && cs[i].className == "tab") {
      this.tab = cs[i];
      break;
    }
  }
  
  // insert a tag around content to support keyboard navigation
  
  
  var a = document.createElement( "A" );
  this.aElement = a;
  a.href = "#";
  a.onclick = function () { return false; };
  while ( this.tab.hasChildNodes() )
    a.appendChild( this.tab.firstChild );
  this.tab.appendChild( a );

  
  // hook up events, using DOM0
  var oThis = this;
  this.tab.onclick = function () { oThis.select(); };
  this.tab.onmouseover = function () { WebFXTabPage.tabOver( oThis ); };
  this.tab.onmouseout = function () { WebFXTabPage.tabOut( oThis ); };
}

WebFXTabPage.prototype.show = function () {
  var el = this.tab;
  var s = el.className + " selected";
  s = s.replace(/ +/g, " ");
  el.className = s;
  this.element.style.display = "block";
  showcount(inner(el));
};

WebFXTabPage.prototype.hide = function () {
  var el = this.tab;
  var s = el.className;
  s = s.replace(/ selected/g, "");
  el.className = s;

  this.element.style.display = "none";
  hidecount(inner(el));
};
  
WebFXTabPage.prototype.select = function () {
  this.tabPane.setSelectedIndex( this.index );
};
  
WebFXTabPage.prototype.dispose = function () {
  this.aElement.onclick = null;
  this.aElement = null;
  this.element.tabPage = null;
  this.tab.onclick = null;
  this.tab.onmouseover = null;
  this.tab.onmouseout = null;
  this.tab = null;
  this.tabPane = null;
  this.element = null;
};

WebFXTabPage.tabOver = function ( tabpage ) {
  var el = tabpage.tab;
  var s = el.className + " hover";
  s = s.replace(/ +/g, " ");
  el.className = s;
};

WebFXTabPage.tabOut = function ( tabpage ) {
  var el = tabpage.tab;
  var s = el.className;
  s = s.replace(/ hover/g, "");
  el.className = s;
};

var mainpane;

// This function initializes all uninitialized tab panes and tab pages
function setupAllTabs() {
  if ( !hasSupport() ) return;
  var all = document.getElementsByTagName( "*" );
  var l = all.length;
  var tabPaneRe = /tab\-pane/;
  var tabPageRe = /tab\-page/;
  var cn, el;
  var parentTabPane;
  
  for ( var i = 0; i < l; i++ ) {
    el = all[i]
    cn = el.className;
    // no className
    if ( cn == "" ) continue;
    
    // uninitiated tab pane
    if ( tabPaneRe.test( cn ) && !el.tabPane )
    {
      mainpane = new WebFXTabPane( el );
      try
      {
        DefaultTab();
      }
      catch (err)
      {
      }
    }
  
    // unitiated tab page wit a valid tab pane parent
    else if ( tabPageRe.test( cn ) && !el.tabPage &&
          tabPaneRe.test( el.parentNode.className ) ) {
      el.parentNode.tabPane.addTabPage( el );      
    }
  }
}

function disposeAllTabs() {
  if ( !hasSupport() ) return;
  
  var all = document.getElementsByTagName( "*" );
  var l = all.length;
  var tabPaneRe = /tab\-pane/;
  var cn, el;
  var tabPanes = [];
  
  for ( var i = 0; i < l; i++ ) {
    el = all[i]
    cn = el.className;

    // no className
    if ( cn == "" ) continue;
    
    // tab pane
    if ( tabPaneRe.test( cn ) && el.tabPane )
      tabPanes[tabPanes.length] = el.tabPane;
  }
  
  for (var i = tabPanes.length - 1; i >= 0; i--) {
    tabPanes[i].dispose();
    tabPanes[i] = null;
  }
}


// initialization hook up

// DOM2
if ( typeof window.addEventListener != "undefined" )
  window.addEventListener( "load", setupAllTabs, false );

// IE 
else if ( typeof window.attachEvent != "undefined" ) {
  window.attachEvent( "onload", setupAllTabs );
  window.attachEvent( "onunload", disposeAllTabs );
}

else {
  if ( window.onload != null ) {
    var oldOnload = window.onload;
    window.onload = function ( e ) {
      oldOnload( e );
      setupAllTabs();
    };
  }
  else 
    window.onload = setupAllTabs;
}

function ChangeTab(index)
{
mainpane.setSelectedIndex(index);
}


function MyTip2(ElementName)
{
var Element;
Element = document.getElementById(ElementName);
if (Element)
{
  return Tip(Element.innerHTML , SHADOW, true, LEFT, true, FADEIN, 400, FADEOUT, 400);
}
}

function FareCalc(FareName,FareNr,FareArray)
{
var Element;
Element = document.getElementById(FareName);
if (Element)
{
  Element.innerHTML = '&euro;&nbsp;' + FareArray[FareNr] + '&nbsp;';
}
}

function DefaultTab()
{
mainpane.setSelectedIndex($deftab );
}

function showhide(name)
{
tobj = document.getElementById(name);
if (tobj)
{
   if (tobj.style.display == 'inline')
  {
    tobj.style.display = 'none'
  }
  else
  {
    tobj.style.display = 'inline'
  }
}
}

function show(name)
{
tobj = document.getElementById(name);
if (!tobj)
{
  tobj = document.getElementById(name.toLowerCase());
}
if (tobj)
{
  tobj.style.display = 'inline'
}
}

function showcount(name)
{
for (i=0; i<100; i++)
{
  nameplus = name + i;
  show(nameplus);
}
nameplus = name+"$snr";
show(nameplus);
}

function hide(name)
{
tobj = document.getElementById(name);
if (!tobj)
{
  tobj = document.getElementById(name.toLowerCase());
}
if (tobj)
{
  tobj.style.display = 'none'
}
}

function hidecount(name)
{
for (i=0; i<100; i++)
{
  nameplus = name + i;
  hide(nameplus);
}
nameplus = name+"$snr";
hide(nameplus);
}

function sitestat(ns_l){
ns_l+="&ns__t="+(new Date()).getTime();ns_pixelUrl=ns_l;
ns_0=document.referrer;
ns_0=(ns_0.lastIndexOf("/")==ns_0.length-1)?ns_0.substring(ns_0.lastIndexOf("/"),0):ns_0;
if(ns_0.length>0)ns_l+="&ns_referrer="+escape(ns_0);
if(document.images){ns_1=new Image();ns_1.src=ns_l;}else
document.write("<img src="+ns_l+" width='1' height='1'>");}
;
