HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/zelfverkopen.komma.pro/wwwroot/js/site/app.js
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

var BrowserHandler = {
  userAgent: '',
  browserInfo: '',
  init: function init() {
    BrowserHandler.userAgent = window.navigator.userAgent;
    BrowserHandler.browserInfo = BrowserHandler.getBrowserInfo();
    BrowserHandler.handleIE();
    BrowserHandler.handleSafari();
  },
  handleIE: function handleIE() {
    // Detect versions below ie11
    var msie = BrowserHandler.userAgent.indexOf('MSIE ');
    var ielt11 = msie > 0; // Detect ie11

    var ie11 = !!navigator.userAgent.match(/Trident.*rv\:11\./); // If Internet Explorer

    if (ielt11 || ie11) {
      // Default version
      var version = '11'; // Way to detect version < 11

      if (ielt11) version = parseInt(BrowserHandler.userAgent.substring(msie + 5, BrowserHandler.userAgent.indexOf(".", msie))); // Append classes to HTML

      $('html').addClass('ie v' + version);
    }
  },
  // Fallback for older safari version
  handleSafari: function handleSafari() {
    if (BrowserHandler.browserInfo.name === 'Safari' && BrowserHandler.browserInfo.version <= 10) $('html').addClass('ie');
  },
  getBrowserInfo: function getBrowserInfo() {
    var ua = navigator.userAgent,
        tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(M[1])) {
      tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
      return {
        name: 'IE ',
        version: tem[1] || ''
      };
    }

    if (M[1] === 'Chrome') {
      tem = ua.match(/\bOPR\/(\d+)/);

      if (tem != null) {
        return {
          name: 'Opera',
          version: tem[1]
        };
      }
    }

    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];

    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
      M.splice(1, 1, tem[1]);
    }

    return {
      name: M[0],
      version: M[1]
    };
  }
};
BrowserHandler.init();
var BuyHouseFormHandler = {
  form: [],
  submitButton: '',
  // Initialize click event
  init: function init() {
    // Bind Start Sale Form to Handler
    BuyHouseFormHandler.form = document.getElementById('buyHouseFormEl');

    if (isset(BuyHouseFormHandler.form)) {
      // Bind click on submit p element
      BuyHouseFormHandler.submitButton = document.querySelector('#buyHouseFormEl .submit p');
      BuyHouseFormHandler.submitButton.addEventListener('click', function () {
        BuyHouseFormHandler.form.submit();
      });
    }
  }
};
BuyHouseFormHandler.init();
/* ==========================================================================
 | Prevent Bots handler
 |
 | We named this chocolate factory and belonging confusing js hooks
 | to prevent smart bots from blocking these variable or functions.
 |
 ========================================================================== */

var ChocolateFactory = {
  bannedVisitor: [],

  /** Get all the chocolate factory and start
   *  Looping through those start flashing tickets
   */
  enter: function enter() {
    var chocolateFactories = document.querySelectorAll('.js-chocolate-factory');

    if (isset(chocolateFactories)) {
      var amountOfChocolateFactories = chocolateFactories.length;

      for (var i = 0; i < amountOfChocolateFactories; i++) {
        var ChocolateBar = chocolateFactories[i];

        ChocolateFactory._flashTicket(ChocolateBar);
      }
    }
  },

  /**
   * If factory has a golden ticket
   * Then we can make them go on the tour if there has been click on the ticket
   *
   * @param chocolateBar
   * @private
   */
  _flashTicket: function _flashTicket(chocolateBar) {
    // Try get the ticket from the chocolateBar
    var goldenTicket = chocolateBar.querySelector('.js-golden-ticket'); // Only continue if chocolate bar has a golden ticket

    if (isset(goldenTicket)) {
      goldenTicket.addEventListener('click', function () {
        ChocolateFactory.enjoyTheTour(chocolateBar);
      });
    } else {
      console.log('To bad, no golden tickets has been found.');
    }
  },

  /**
   * Start the tour through the factory
   * And get the names and properties of the members of the group
   * If there are members in the group of course
   *
   * @param chocolateFactory
   */
  enjoyTheTour: function enjoyTheTour(chocolateFactory) {
    // Ask for the tour group
    var tourGroup = chocolateFactory.querySelectorAll('input, textarea, select');

    if (isset(tourGroup)) {
      // For each visitor we want a belonging Oompa Loompa
      var oompaLoompas = {};
      var amountOfOompaLoompas = 0;
      var tourGroupSize = tourGroup.length;

      for (var i = 0; i < tourGroupSize; i++) {
        // Get the visitor from the group
        var visitor = tourGroup[i]; // Ask for its name

        var visitorName = visitor.getAttribute('name'); // Check if the visitor is banned

        if (ChocolateFactory._isVisitorBanned(visitorName)) continue;
        oompaLoompas[visitorName] = ChocolateFactory._getArrangement(visitor);
        amountOfOompaLoompas++;
      } // Check for insurance that there are oompa loompas


      if (amountOfOompaLoompas === 0) return; // Send submit request

      ChocolateFactory._finishTour(oompaLoompas, chocolateFactory);
    } else {
      console.log('To bad, no members to visit this factory');
    }
  },

  /**
   * Check if the visitor name isn't allow
   *
   * @param visitorName
   * @returns {boolean}
   * @private
   */
  _isVisitorBanned: function _isVisitorBanned(visitorName) {
    if (ChocolateFactory.bannedVisitor.indexOf(visitorName) !== -1) {
      return true;
    }

    return false;
  },

  /**
   * Most get visitor have a normal arrangement
   * But sometimes there are special cases
   * Like a Selector or checkbox
   *
   * @param visitor
   * @returns {*}
   * @private
   */
  _getArrangement: function _getArrangement(visitor) {
    var visitorType = visitor.nodeName;

    switch (visitorType) {
      default:
        return visitor.value;
    }
  },

  /**
   * Finish the tour
   * If successful show thanks message
   * Or show defined error message or fallback
   *
   * @param group
   * @param chocolateFactory
   * @returns {*|void}
   * @private
   */
  _finishTour: function _finishTour(group, chocolateFactory) {
    // Add willie to the group
    group = ChocolateFactory._addWillieWonka(group); // Get the gate for finish the tour

    var gate = '/contact/process_new';

    try {
      Ajax.post(gate, group, function (HttpRequest) {
        var response = JSON.parse(HttpRequest.response);

        switch (HttpRequest.status) {
          case 200:
            return ChocolateFactory._thanksForVisiting(response.redirectUrl);

          case 422:
            return ChocolateFactory._giveFeedbackToMembers(response.errors, chocolateFactory);

          default:
            break;
        }

        return ChocolateFactory._unknownGapInFactory(chocolateFactory);
      });
    } catch (e) {
      console.log('Ajax post failed');
      return ChocolateFactory._unknownGapInFactory(chocolateFactory);
    }
  },

  /**
   * Add willie wonka to the group
   * Ps... it actually the secret code!
   *
   * @param group
   * @returns {*}
   * @private
   */
  _addWillieWonka: function _addWillieWonka(group) {
    group._willie = 'wonka';
    return group;
  },

  /**
   * Add the feedback to the desired area.
   * Most likely to the visitor directly, but sometime to the factory desired feedback area
   *
   * @param errors
   * @param chocolateFactory
   * @private
   */
  _giveFeedbackToMembers: function _giveFeedbackToMembers(errors, chocolateFactory) {
    // Grab the factory feedback area
    var feedbackArea = chocolateFactory.querySelector('.js-error-area'); // Clear the current html

    if (isset(feedbackArea)) {
      feedbackArea.innerHTML = '';
    } // Clear the previous marked jackets


    ChocolateFactory._clearPreviousMarkedJackets(chocolateFactory);

    Object.keys(errors).forEach(function (visitor) {
      var jacket = null;
      var visitorFeedbackArea = null; // Honey elements doesn't has a accessible element

      if (visitor !== '_honey' && visitor !== '_secretCode') {
        // Grab the visitor
        var visitorNode = chocolateFactory.querySelector('#' + visitor); // Find the jacket of a visitor

        jacket = ChocolateFactory._grabVisitorJacket(visitorNode); // If found get the desired area

        if (isset(jacket)) {
          visitorFeedbackArea = jacket.querySelector('.js-form-element-error');
        } // Clear the current html


        if (isset(visitorFeedbackArea)) {
          visitorFeedbackArea.innerHTML = '';
        }
      } // Get the feedback for this visitor


      var visitorFeedback = errors[visitor];
      var currentFeedbackArea; // Spit out each line

      var visitorFeedbackAmount = visitorFeedback.length;

      for (var i = 0; i < visitorFeedbackAmount; i++) {
        var visitorFeedbackLine = visitorFeedback[i]; // Honey elements doesn't has a accessible element area

        if (visitor !== '_honey' && visitor !== '_secretCode') {
          // Mark the jacket
          if (isset(jacket)) {
            jacket.classList.add('has-error');
          } // Append feedback to visitor feedback area if defined


          if (isset(visitorFeedbackArea)) {
            currentFeedbackArea = visitorFeedbackArea.innerHTML;
            currentFeedbackArea += '<span>' + visitorFeedbackLine + '</span>';
            visitorFeedbackArea.innerHTML = currentFeedbackArea;
          }
        } // Append feedback to factory feedback area if defined


        if (isset(feedbackArea)) {
          currentFeedbackArea = feedbackArea.innerHTML;
          currentFeedbackArea += '<li>' + visitorFeedbackLine + '</li>';
          feedbackArea.innerHTML = currentFeedbackArea;
        }
      }
    });
    ScrollToHandler.scrollToElement('contactForm', 180);
  },

  /**
   * Clear the previous marked jackets
   *
   * @param chocolateFactory
   * @private
   */
  _clearPreviousMarkedJackets: function _clearPreviousMarkedJackets(chocolateFactory) {
    var markedJackets = chocolateFactory.querySelectorAll('.has-error');
    var markedJacketsAmount = markedJackets.length;

    for (var i = 0; i < markedJacketsAmount; i++) {
      markedJackets[i].classList.remove('has-error');
    }
  },

  /**
   * Grab the jacket of the visitor
   *
   * @param visitor
   * @returns {null|*|(() => (Node | null))|ActiveX.IXMLDOMNode|(Node & ParentNode)}
   * @private
   */
  _grabVisitorJacket: function _grabVisitorJacket(visitor) {
    // Check if visitor is defined
    if (!isset(visitor)) return null; // Do loop settings

    var currentLayer = visitor;
    var safetyBreak = 0; // Grab the next layer till it is the jacket (or safetyBreak has been reached

    do {
      safetyBreak++;
      currentLayer = currentLayer.parentNode;
      if (currentLayer.classList.contains('js-form-element')) return currentLayer;
    } while (currentLayer.tagName !== 'BODY' && safetyBreak <= 10);

    return null;
  },

  /**
   * Redirect the visitor to the thanks page
   *
   * @param nextStop
   * @private
   */
  _thanksForVisiting: function _thanksForVisiting(nextStop) {
    window.location = nextStop;
  },

  /**
   * Unknown error occurred, log the error
   *
   * @param chocolateFactory
   * @private
   */
  _unknownGapInFactory: function _unknownGapInFactory(chocolateFactory) {
    console.log(chocolateFactory);
    console.log('ChocolateFactory: Unkown Error');
  }
};
ChocolateFactory.enter();
/* ==========================================================================
 Navigation handler
 ========================================================================== */

/**
 * Main navigation
 */

var Faq = {
  // Faq items settings
  items: [],
  amount: 0,
  // Faq Page extended settings
  faqPageWrapper: null,
  activeCategory: 0,
  categoryButtons: null,
  categoryButtonsLength: 0,
  categoryTitleElement: null,
  categoryQuestionContainers: null,
  // Initialize click event
  init: function init() {
    // Bind Navigation to Handler
    Faq.items = document.querySelectorAll('.faq-items .faq-item');
    Faq.amount = Faq.items.length;

    if (Faq.amount > 0) {
      for (var i = 0; i < Faq.amount; i++) {
        Faq.items[i].addEventListener('click', function () {
          Faq.toggle(this);
        });
      }
    } // Extended interaction for faq page


    Faq.faqPageWrapper = document.getElementById('faqQuestions');

    if (isset(Faq.faqPageWrapper)) {
      // Define the objects of the Faq Pages
      Faq.categoryButtons = Faq.faqPageWrapper.querySelectorAll('.question-categories ul li');
      Faq.categoryButtonsLength = Faq.categoryButtons.length;
      Faq.categoryQuestionContainers = Faq.faqPageWrapper.querySelectorAll('.questions-container-placeholder .questions-container');
      Faq.categoryTitleElement = Faq.faqPageWrapper.querySelector('.questions-container-placeholder .title');

      for (var i = 0; i < Faq.categoryButtonsLength; i++) {
        var categoryButton = Faq.categoryButtons[i];
        categoryButton.addEventListener('click', function () {
          Faq.changeFaqCategory(this);
        });
      }
    }
  },
  // Toggle faq
  toggle: function toggle(question) {
    // Determine if currently open or closed
    var _boolean = true;
    var answer = question.querySelector('.answer');
    var answerContent = question.querySelector('.answer .inner-content');

    if (question.getAttribute('data-open') === 'true') {
      _boolean = false;
      answer.style.maxHeight = 0;
    } else {
      answer.style.maxHeight = answerContent.offsetHeight + 'px';
    }

    question.setAttribute('data-open', _boolean);
  },
  // Change Faq Question Category
  changeFaqCategory: function changeFaqCategory(categoryButton) {
    Faq.activeCategory = categoryButton.getAttribute('data-category');
    var categoryString = categoryButton.getAttribute('data-name'); // CategoryButtons and CategoryContainers have the same length and order so we only need one loop

    for (var i = 0; i < Faq.categoryButtonsLength; i++) {
      var categoryButton = Faq.categoryButtons[i];
      var categoryQuestionContainer = Faq.categoryQuestionContainers[i];

      if (categoryButton.getAttribute('data-category') === Faq.activeCategory && categoryQuestionContainer.getAttribute('data-category') === Faq.activeCategory) {
        categoryButton.classList.add('active');
        categoryQuestionContainer.classList.add('active');
        Faq.categoryTitleElement.innerHTML = categoryString;
      } else {
        categoryButton.classList.remove('active');
        categoryQuestionContainer.classList.remove('active');
      }
    }
  }
};
Faq.init();
/**
 * Created by Pascal on 23/11/17.
 */

/**
 *
 * @param {string} id - html id of form
 * @param {array} required - list of required field
 * @constructor
 */

function FormHandler(id, required) {
  // Define form object
  this.formObject = document.getElementById(id); // Set required fields

  this.requiredFields = required; // Set default valid to true

  this.valid = true; // Validate form function

  this.validate = function () {
    // Reset valid to true
    this.valid = true; // Define this to self

    var self = this;
    var fieldToValidate = self.requiredFields.slice(); // Get all form elements

    var formElements = this.formObject.querySelectorAll('input, textarea'); // Loop through the form elements

    var formElementsLength = formElements.length;

    for (var i = 0; i < formElementsLength; i++) {
      var el = formElements[i]; // Remove alert

      el.classList.remove('alert');
      var indexOfValidator = fieldToValidate.indexOf(el.getAttribute('name')); // Check if it's in the required fields

      if (indexOfValidator !== -1) {
        // Temporary store the value (for future checks or so ex. check if mail)
        var value = el.value; // Check if value is filled

        if (value === null || value === '') {
          // Else set alert and set form valid to false
          el.classList.add('alert');
          self.valid = false;
        } // Remove from fields to validate array


        fieldToValidate.splice(indexOfValidator, 1);
      }
    } // Check if all required fields are filled


    if (fieldToValidate.length !== 0) {
      // Else also set form valid to false
      // And log because it should only happen in development
      self.valid = false;
      console.log('Not all required field are filled:');
      console.log(fieldToValidate);
    }
  }; // Send form


  this.send = function () {
    this.formObject.submit();
  };
}
/*
 * Simple isset method for this does not exist in javascript
 */


var isset = function isset(obj) {
  return typeof obj !== 'undefined' && obj !== null;
}; //get url params by name


$.urlParam = function (name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
};
/* update url string */


function updateQueryString(key, value, urlString) {
  if (!urlString) urlString = window.location.href;

  if (urlString.indexOf(key + '=') > -1) {
    $current = $.urlParam(key);

    if ($current == 0) {
      $split = urlString.split(key + '=');
      $url = $split[0] + key + "=" + value + $split[1];
    } else {
      $url = urlString.replace(key + "=" + $current, key + "=" + value);
    }
  } else {
    if (urlString.indexOf('?') == -1) {
      $split = urlString.split('?');
      $url = $split[0] + '?' + key + '=' + value;
    } else {
      $url = urlString + '&' + key + '=' + value;
    }
  }

  return $url;
}

var Ajax = {
  get: function get(url, callback) {
    var xhr = new XMLHttpRequest();
    var token = document.querySelector('meta[name="csrf-token"]').content;
    xhr.open('get', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('X-CSRF-TOKEN', token);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        callback(xhr);
      }
    };

    xhr.send();
  },
  post: function post(url, data, callback) {
    var xhr = new XMLHttpRequest();
    var token = document.querySelector('meta[name="csrf-token"]').content;
    xhr.open('post', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('X-CSRF-TOKEN', token);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        callback(xhr);
      }
    };

    xhr.send(JSON.stringify(data));
  }
};
/* ==========================================================================
 Image related javascript
 ========================================================================== */

/**
 * Preload images
 */

var ImagePreloader = {
  // Init preloader
  init: function init() {
    $('img.preload').one('load', function () {
      // Once loaded remove the preload class
      // Our CSS will take care of the fade in
      $(this).removeClass('preload');
    }).each(function () {
      if (this.complete) $(this).load();
    });
  }
};
/* ==========================================================================
    Google Maps handler

    -- https://developers.google.com/maps/documentation/javascript/adding-a-google-map
 ========================================================================== */

var MapsHandler = {
  map: '',
  key: '',
  location: {
    lat: 51.2618222,
    lng: 5.5965538
  },
  styling: '',
  init: function init() {
    // Get map by id
    MapsHandler.map = document.getElementById('map'); // Check if a map is defined

    if (isset(MapsHandler.map)) {
      MapsHandler.key = MapsHandler.map.getAttribute('data-api-key');
      MapsHandler.location.lat = parseFloat(MapsHandler.map.getAttribute('data-google-lat'));
      MapsHandler.location.lng = parseFloat(MapsHandler.map.getAttribute('data-google-lng'));
      MapsHandler.setCustomStyling(); // See if google variable exists

      if (typeof google == 'undefined' || typeof google.maps == 'undefined') {
        // Load external script
        $.getScript('https://maps.googleapis.com/maps/api/js?key=' + MapsHandler.key).done(function (script, textStatus) {
          MapsHandler.drawMap();
        });
      } else {
        MapsHandler.drawMap();
      }
    }
  },
  drawMap: function drawMap() {
    // Create a map
    var map = new google.maps.Map(MapsHandler.map, {
      zoom: 12,
      center: MapsHandler.location,
      disableDefaultUI: true,
      styles: MapsHandler.styling
    }); // Add a marker

    var marker = new google.maps.Marker({
      position: MapsHandler.location,
      map: map
    });
  },
  setCustomStyling: function setCustomStyling() {
    MapsHandler.styling = [{
      "featureType": "landscape",
      "stylers": [{
        "saturation": -100
      }, {
        "lightness": 60
      }]
    }, {
      "featureType": "road.local",
      "stylers": [{
        "saturation": -100
      }, {
        "lightness": 40
      }, {
        "visibility": "on"
      }]
    }, {
      "featureType": "transit",
      "stylers": [{
        "saturation": -100
      }, {
        "visibility": "simplified"
      }]
    }, {
      "featureType": "administrative.province",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "water",
      "stylers": [{
        "visibility": "on"
      }, {
        "lightness": 30
      }]
    }, {
      "featureType": "road.highway",
      "elementType": "geometry.fill",
      "stylers": [{
        "color": "#ef8c25"
      }, {
        "lightness": 40
      }]
    }, {
      "featureType": "road.highway",
      "elementType": "geometry.stroke",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "geometry.fill",
      "stylers": [{
        "color": "#b6c54c"
      }, {
        "lightness": 40
      }, {
        "saturation": -40
      }]
    }];
  }
};
MapsHandler.init();
/* ==========================================================================
   NavigationHandler handler
 ========================================================================== */

/**
 * Navigation Handler
 * Primary usage for mobile NavigationHandler
 * Secondary if site used a pop-up/slide-in menu
 */

var NavigationHandler = {
  navElement: '',
  scrolled: 0,
  isActive: false,
  // Initialize click event
  init: function init() {
    // Bind Navigation to Handler
    NavigationHandler.navElement = document.getElementById('mobile-navigation'); // Bind clicks to menu button

    var menuButton = document.getElementById('menu-trigger');

    if (isset(menuButton)) {
      menuButton.addEventListener('click', function () {
        NavigationHandler.open();
      });
    } // Bind clicks to sticky menu button


    var stickyMenuButton = document.getElementById('sticky-menu-trigger');

    if (isset(stickyMenuButton)) {
      stickyMenuButton.addEventListener('click', function () {
        NavigationHandler.open();
      });
    } // Bind clicks to menu button


    var mobileMenuButton = document.getElementById('mobile-menu-trigger');

    if (isset(mobileMenuButton)) {
      mobileMenuButton.addEventListener('click', function () {
        NavigationHandler.open();
      });
    } // Bind clicks to sticky menu button


    var stickyMenuButton = document.getElementById('sticky-menu-trigger');

    if (isset(stickyMenuButton)) {
      stickyMenuButton.addEventListener('click', function () {
        NavigationHandler.open();
      });
    }

    var mobileShade = document.getElementById('mobile-shader');

    if (isset(mobileShade)) {
      mobileShade.addEventListener('click', function () {
        NavigationHandler.close();
      });
    }

    var mobileClose = document.getElementById('mobile-close');

    if (isset(mobileClose)) {
      mobileClose.addEventListener('click', function () {
        NavigationHandler.close();
      });
    }

    var mobileClose = document.getElementById('mobile-close');

    if (isset(mobileClose)) {
      mobileClose.addEventListener('click', function () {
        NavigationHandler.close();
      });
    }

    if (isset(NavigationHandler.navElement)) {
      setTimeout(function () {
        NavigationHandler.navElement.classList.add('allow-animation');
      }, 500);
    }
  },
  // Open Navigation
  open: function open() {
    NavigationHandler.scrolled = window.pageYOffset;
    NavigationHandler.navElement.classList.add('active');
    NavigationHandler.navElement.classList.add('shader-active');
    NavigationHandler.isActive = true;
    setTimeout(function () {
      document.body.classList.add('preventScroll');
    }, 400);
  },
  // Close Navigation
  close: function close() {
    NavigationHandler.navElement.classList.remove('active');
    NavigationHandler.navElement.classList.remove('shader-active');
    NavigationHandler.isActive = false;
    document.body.classList.remove('preventScroll');
    window.scrollTo(0, NavigationHandler.scrolled);
  }
};
NavigationHandler.init();
/*! nouislider - 11.1.0 - 2018-04-02 11:18:13 */

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
    // Node/CommonJS
    module.exports = factory();
  } else {
    // Browser globals
    window.noUiSlider = factory();
  }
})(function () {
  'use strict';

  var VERSION = '11.1.0';

  function isValidFormatter(entry) {
    return _typeof(entry) === 'object' && typeof entry.to === 'function' && typeof entry.from === 'function';
  }

  function removeElement(el) {
    el.parentElement.removeChild(el);
  }

  function isSet(value) {
    return value !== null && value !== undefined;
  } // Bindable version


  function preventDefault(e) {
    e.preventDefault();
  } // Removes duplicates from an array.


  function unique(array) {
    return array.filter(function (a) {
      return !this[a] ? this[a] = true : false;
    }, {});
  } // Round a value to the closest 'to'.


  function closest(value, to) {
    return Math.round(value / to) * to;
  } // Current position of an element relative to the document.


  function offset(elem, orientation) {
    var rect = elem.getBoundingClientRect();
    var doc = elem.ownerDocument;
    var docElem = doc.documentElement;
    var pageOffset = getPageOffset(doc); // getBoundingClientRect contains left scroll in Chrome on Android.
    // I haven't found a feature detection that proves this. Worst case
    // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.

    if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) {
      pageOffset.x = 0;
    }

    return orientation ? rect.top + pageOffset.y - docElem.clientTop : rect.left + pageOffset.x - docElem.clientLeft;
  } // Checks whether a value is numerical.


  function isNumeric(a) {
    return typeof a === 'number' && !isNaN(a) && isFinite(a);
  } // Sets a class and removes it after [duration] ms.


  function addClassFor(element, className, duration) {
    if (duration > 0) {
      addClass(element, className);
      setTimeout(function () {
        removeClass(element, className);
      }, duration);
    }
  } // Limits a value to 0 - 100


  function limit(a) {
    return Math.max(Math.min(a, 100), 0);
  } // Wraps a variable as an array, if it isn't one yet.
  // Note that an input array is returned by reference!


  function asArray(a) {
    return Array.isArray(a) ? a : [a];
  } // Counts decimals


  function countDecimals(numStr) {
    numStr = String(numStr);
    var pieces = numStr.split(".");
    return pieces.length > 1 ? pieces[1].length : 0;
  } // http://youmightnotneedjquery.com/#add_class


  function addClass(el, className) {
    if (el.classList) {
      el.classList.add(className);
    } else {
      el.className += ' ' + className;
    }
  } // http://youmightnotneedjquery.com/#remove_class


  function removeClass(el, className) {
    if (el.classList) {
      el.classList.remove(className);
    } else {
      el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
  } // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/


  function hasClass(el, className) {
    return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
  } // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes


  function getPageOffset(doc) {
    var supportPageOffset = window.pageXOffset !== undefined;
    var isCSS1Compat = (doc.compatMode || "") === "CSS1Compat";
    var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? doc.documentElement.scrollLeft : doc.body.scrollLeft;
    var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? doc.documentElement.scrollTop : doc.body.scrollTop;
    return {
      x: x,
      y: y
    };
  } // we provide a function to compute constants instead
  // of accessing window.* as soon as the module needs it
  // so that we do not compute anything if not needed


  function getActions() {
    // Determine the events to bind. IE11 implements pointerEvents without
    // a prefix, which breaks compatibility with the IE10 implementation.
    return window.navigator.pointerEnabled ? {
      start: 'pointerdown',
      move: 'pointermove',
      end: 'pointerup'
    } : window.navigator.msPointerEnabled ? {
      start: 'MSPointerDown',
      move: 'MSPointerMove',
      end: 'MSPointerUp'
    } : {
      start: 'mousedown touchstart',
      move: 'mousemove touchmove',
      end: 'mouseup touchend'
    };
  } // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  // Issue #785


  function getSupportsPassive() {
    var supportsPassive = false;

    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function get() {
          supportsPassive = true;
        }
      });
      window.addEventListener('test', null, opts);
    } catch (e) {}

    return supportsPassive;
  }

  function getSupportsTouchActionNone() {
    return window.CSS && CSS.supports && CSS.supports('touch-action', 'none');
  } // Value calculation
  // Determine the size of a sub-range in relation to a full range.


  function subRangeRatio(pa, pb) {
    return 100 / (pb - pa);
  } // (percentage) How many percent is this value of this range?


  function fromPercentage(range, value) {
    return value * 100 / (range[1] - range[0]);
  } // (percentage) Where is this value on this range?


  function toPercentage(range, value) {
    return fromPercentage(range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0]);
  } // (value) How much is this percentage on this range?


  function isPercentage(range, value) {
    return value * (range[1] - range[0]) / 100 + range[0];
  } // Range conversion


  function getJ(value, arr) {
    var j = 1;

    while (value >= arr[j]) {
      j += 1;
    }

    return j;
  } // (percentage) Input a value, find where, on a scale of 0-100, it applies.


  function toStepping(xVal, xPct, value) {
    if (value >= xVal.slice(-1)[0]) {
      return 100;
    }

    var j = getJ(value, xVal);
    var va = xVal[j - 1];
    var vb = xVal[j];
    var pa = xPct[j - 1];
    var pb = xPct[j];
    return pa + toPercentage([va, vb], value) / subRangeRatio(pa, pb);
  } // (value) Input a percentage, find where it is on the specified range.


  function fromStepping(xVal, xPct, value) {
    // There is no range group that fits 100
    if (value >= 100) {
      return xVal.slice(-1)[0];
    }

    var j = getJ(value, xPct);
    var va = xVal[j - 1];
    var vb = xVal[j];
    var pa = xPct[j - 1];
    var pb = xPct[j];
    return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb));
  } // (percentage) Get the step that applies at a certain value.


  function getStep(xPct, xSteps, snap, value) {
    if (value === 100) {
      return value;
    }

    var j = getJ(value, xPct);
    var a = xPct[j - 1];
    var b = xPct[j]; // If 'snap' is set, steps are used as fixed points on the slider.

    if (snap) {
      // Find the closest position, a or b.
      if (value - a > (b - a) / 2) {
        return b;
      }

      return a;
    }

    if (!xSteps[j - 1]) {
      return value;
    }

    return xPct[j - 1] + closest(value - xPct[j - 1], xSteps[j - 1]);
  } // Entry parsing


  function handleEntryPoint(index, value, that) {
    var percentage; // Wrap numerical input in an array.

    if (typeof value === "number") {
      value = [value];
    } // Reject any invalid input, by testing whether value is an array.


    if (!Array.isArray(value)) {
      throw new Error("noUiSlider (" + VERSION + "): 'range' contains invalid value.");
    } // Covert min/max syntax to 0 and 100.


    if (index === 'min') {
      percentage = 0;
    } else if (index === 'max') {
      percentage = 100;
    } else {
      percentage = parseFloat(index);
    } // Check for correct input.


    if (!isNumeric(percentage) || !isNumeric(value[0])) {
      throw new Error("noUiSlider (" + VERSION + "): 'range' value isn't numeric.");
    } // Store values.


    that.xPct.push(percentage);
    that.xVal.push(value[0]); // NaN will evaluate to false too, but to keep
    // logging clear, set step explicitly. Make sure
    // not to override the 'step' setting with false.

    if (!percentage) {
      if (!isNaN(value[1])) {
        that.xSteps[0] = value[1];
      }
    } else {
      that.xSteps.push(isNaN(value[1]) ? false : value[1]);
    }

    that.xHighestCompleteStep.push(0);
  }

  function handleStepPoint(i, n, that) {
    // Ignore 'false' stepping.
    if (!n) {
      return true;
    } // Factor to range ratio


    that.xSteps[i] = fromPercentage([that.xVal[i], that.xVal[i + 1]], n) / subRangeRatio(that.xPct[i], that.xPct[i + 1]);
    var totalSteps = (that.xVal[i + 1] - that.xVal[i]) / that.xNumSteps[i];
    var highestStep = Math.ceil(Number(totalSteps.toFixed(3)) - 1);
    var step = that.xVal[i] + that.xNumSteps[i] * highestStep;
    that.xHighestCompleteStep[i] = step;
  } // Interface


  function Spectrum(entry, snap, singleStep) {
    this.xPct = [];
    this.xVal = [];
    this.xSteps = [singleStep || false];
    this.xNumSteps = [false];
    this.xHighestCompleteStep = [];
    this.snap = snap;
    var index;
    var ordered = []; // [0, 'min'], [1, '50%'], [2, 'max']
    // Map the object keys to an array.

    for (index in entry) {
      if (entry.hasOwnProperty(index)) {
        ordered.push([entry[index], index]);
      }
    } // Sort all entries by value (numeric sort).


    if (ordered.length && _typeof(ordered[0][0]) === "object") {
      ordered.sort(function (a, b) {
        return a[0][0] - b[0][0];
      });
    } else {
      ordered.sort(function (a, b) {
        return a[0] - b[0];
      });
    } // Convert all entries to subranges.


    for (index = 0; index < ordered.length; index++) {
      handleEntryPoint(ordered[index][1], ordered[index][0], this);
    } // Store the actual step values.
    // xSteps is sorted in the same order as xPct and xVal.


    this.xNumSteps = this.xSteps.slice(0); // Convert all numeric steps to the percentage of the subrange they represent.

    for (index = 0; index < this.xNumSteps.length; index++) {
      handleStepPoint(index, this.xNumSteps[index], this);
    }
  }

  Spectrum.prototype.getMargin = function (value) {
    var step = this.xNumSteps[0];

    if (step && value / step % 1 !== 0) {
      throw new Error("noUiSlider (" + VERSION + "): 'limit', 'margin' and 'padding' must be divisible by step.");
    }

    return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false;
  };

  Spectrum.prototype.toStepping = function (value) {
    value = toStepping(this.xVal, this.xPct, value);
    return value;
  };

  Spectrum.prototype.fromStepping = function (value) {
    return fromStepping(this.xVal, this.xPct, value);
  };

  Spectrum.prototype.getStep = function (value) {
    value = getStep(this.xPct, this.xSteps, this.snap, value);
    return value;
  };

  Spectrum.prototype.getNearbySteps = function (value) {
    var j = getJ(value, this.xPct);
    return {
      stepBefore: {
        startValue: this.xVal[j - 2],
        step: this.xNumSteps[j - 2],
        highestStep: this.xHighestCompleteStep[j - 2]
      },
      thisStep: {
        startValue: this.xVal[j - 1],
        step: this.xNumSteps[j - 1],
        highestStep: this.xHighestCompleteStep[j - 1]
      },
      stepAfter: {
        startValue: this.xVal[j - 0],
        step: this.xNumSteps[j - 0],
        highestStep: this.xHighestCompleteStep[j - 0]
      }
    };
  };

  Spectrum.prototype.countStepDecimals = function () {
    var stepDecimals = this.xNumSteps.map(countDecimals);
    return Math.max.apply(null, stepDecimals);
  }; // Outside testing


  Spectrum.prototype.convert = function (value) {
    return this.getStep(this.toStepping(value));
  };
  /*	Every input option is tested and parsed. This'll prevent
  	endless validation in internal methods. These tests are
  	structured with an item for every option available. An
  	option can be marked as required by setting the 'r' flag.
  	The testing function is provided with three arguments:
  		- The provided value for the option;
  		- A reference to the options object;
  		- The name for the option;
  
  	The testing function returns false when an error is detected,
  	or true when everything is OK. It can also modify the option
  	object, to make sure all values can be correctly looped elsewhere. */


  var defaultFormatter = {
    'to': function to(value) {
      return value !== undefined && value.toFixed(2);
    },
    'from': Number
  };

  function validateFormat(entry) {
    // Any object with a to and from method is supported.
    if (isValidFormatter(entry)) {
      return true;
    }

    throw new Error("noUiSlider (" + VERSION + "): 'format' requires 'to' and 'from' methods.");
  }

  function testStep(parsed, entry) {
    if (!isNumeric(entry)) {
      throw new Error("noUiSlider (" + VERSION + "): 'step' is not numeric.");
    } // The step option can still be used to set stepping
    // for linear sliders. Overwritten if set in 'range'.


    parsed.singleStep = entry;
  }

  function testRange(parsed, entry) {
    // Filter incorrect input.
    if (_typeof(entry) !== 'object' || Array.isArray(entry)) {
      throw new Error("noUiSlider (" + VERSION + "): 'range' is not an object.");
    } // Catch missing start or end.


    if (entry.min === undefined || entry.max === undefined) {
      throw new Error("noUiSlider (" + VERSION + "): Missing 'min' or 'max' in 'range'.");
    } // Catch equal start or end.


    if (entry.min === entry.max) {
      throw new Error("noUiSlider (" + VERSION + "): 'range' 'min' and 'max' cannot be equal.");
    }

    parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.singleStep);
  }

  function testStart(parsed, entry) {
    entry = asArray(entry); // Validate input. Values aren't tested, as the public .val method
    // will always provide a valid location.

    if (!Array.isArray(entry) || !entry.length) {
      throw new Error("noUiSlider (" + VERSION + "): 'start' option is incorrect.");
    } // Store the number of handles.


    parsed.handles = entry.length; // When the slider is initialized, the .val method will
    // be called with the start options.

    parsed.start = entry;
  }

  function testSnap(parsed, entry) {
    // Enforce 100% stepping within subranges.
    parsed.snap = entry;

    if (typeof entry !== 'boolean') {
      throw new Error("noUiSlider (" + VERSION + "): 'snap' option must be a boolean.");
    }
  }

  function testAnimate(parsed, entry) {
    // Enforce 100% stepping within subranges.
    parsed.animate = entry;

    if (typeof entry !== 'boolean') {
      throw new Error("noUiSlider (" + VERSION + "): 'animate' option must be a boolean.");
    }
  }

  function testAnimationDuration(parsed, entry) {
    parsed.animationDuration = entry;

    if (typeof entry !== 'number') {
      throw new Error("noUiSlider (" + VERSION + "): 'animationDuration' option must be a number.");
    }
  }

  function testConnect(parsed, entry) {
    var connect = [false];
    var i; // Map legacy options

    if (entry === 'lower') {
      entry = [true, false];
    } else if (entry === 'upper') {
      entry = [false, true];
    } // Handle boolean options


    if (entry === true || entry === false) {
      for (i = 1; i < parsed.handles; i++) {
        connect.push(entry);
      }

      connect.push(false);
    } // Reject invalid input
    else if (!Array.isArray(entry) || !entry.length || entry.length !== parsed.handles + 1) {
        throw new Error("noUiSlider (" + VERSION + "): 'connect' option doesn't match handle count.");
      } else {
        connect = entry;
      }

    parsed.connect = connect;
  }

  function testOrientation(parsed, entry) {
    // Set orientation to an a numerical value for easy
    // array selection.
    switch (entry) {
      case 'horizontal':
        parsed.ort = 0;
        break;

      case 'vertical':
        parsed.ort = 1;
        break;

      default:
        throw new Error("noUiSlider (" + VERSION + "): 'orientation' option is invalid.");
    }
  }

  function testMargin(parsed, entry) {
    if (!isNumeric(entry)) {
      throw new Error("noUiSlider (" + VERSION + "): 'margin' option must be numeric.");
    } // Issue #582


    if (entry === 0) {
      return;
    }

    parsed.margin = parsed.spectrum.getMargin(entry);

    if (!parsed.margin) {
      throw new Error("noUiSlider (" + VERSION + "): 'margin' option is only supported on linear sliders.");
    }
  }

  function testLimit(parsed, entry) {
    if (!isNumeric(entry)) {
      throw new Error("noUiSlider (" + VERSION + "): 'limit' option must be numeric.");
    }

    parsed.limit = parsed.spectrum.getMargin(entry);

    if (!parsed.limit || parsed.handles < 2) {
      throw new Error("noUiSlider (" + VERSION + "): 'limit' option is only supported on linear sliders with 2 or more handles.");
    }
  }

  function testPadding(parsed, entry) {
    if (!isNumeric(entry) && !Array.isArray(entry)) {
      throw new Error("noUiSlider (" + VERSION + "): 'padding' option must be numeric or array of exactly 2 numbers.");
    }

    if (Array.isArray(entry) && !(entry.length === 2 || isNumeric(entry[0]) || isNumeric(entry[1]))) {
      throw new Error("noUiSlider (" + VERSION + "): 'padding' option must be numeric or array of exactly 2 numbers.");
    }

    if (entry === 0) {
      return;
    }

    if (!Array.isArray(entry)) {
      entry = [entry, entry];
    } // 'getMargin' returns false for invalid values.


    parsed.padding = [parsed.spectrum.getMargin(entry[0]), parsed.spectrum.getMargin(entry[1])];

    if (parsed.padding[0] === false || parsed.padding[1] === false) {
      throw new Error("noUiSlider (" + VERSION + "): 'padding' option is only supported on linear sliders.");
    }

    if (parsed.padding[0] < 0 || parsed.padding[1] < 0) {
      throw new Error("noUiSlider (" + VERSION + "): 'padding' option must be a positive number(s).");
    }

    if (parsed.padding[0] + parsed.padding[1] >= 100) {
      throw new Error("noUiSlider (" + VERSION + "): 'padding' option must not exceed 100% of the range.");
    }
  }

  function testDirection(parsed, entry) {
    // Set direction as a numerical value for easy parsing.
    // Invert connection for RTL sliders, so that the proper
    // handles get the connect/background classes.
    switch (entry) {
      case 'ltr':
        parsed.dir = 0;
        break;

      case 'rtl':
        parsed.dir = 1;
        break;

      default:
        throw new Error("noUiSlider (" + VERSION + "): 'direction' option was not recognized.");
    }
  }

  function testBehaviour(parsed, entry) {
    // Make sure the input is a string.
    if (typeof entry !== 'string') {
      throw new Error("noUiSlider (" + VERSION + "): 'behaviour' must be a string containing options.");
    } // Check if the string contains any keywords.
    // None are required.


    var tap = entry.indexOf('tap') >= 0;
    var drag = entry.indexOf('drag') >= 0;
    var fixed = entry.indexOf('fixed') >= 0;
    var snap = entry.indexOf('snap') >= 0;
    var hover = entry.indexOf('hover') >= 0;

    if (fixed) {
      if (parsed.handles !== 2) {
        throw new Error("noUiSlider (" + VERSION + "): 'fixed' behaviour must be used with 2 handles");
      } // Use margin to enforce fixed state


      testMargin(parsed, parsed.start[1] - parsed.start[0]);
    }

    parsed.events = {
      tap: tap || snap,
      drag: drag,
      fixed: fixed,
      snap: snap,
      hover: hover
    };
  }

  function testTooltips(parsed, entry) {
    if (entry === false) {
      return;
    } else if (entry === true) {
      parsed.tooltips = [];

      for (var i = 0; i < parsed.handles; i++) {
        parsed.tooltips.push(true);
      }
    } else {
      parsed.tooltips = asArray(entry);

      if (parsed.tooltips.length !== parsed.handles) {
        throw new Error("noUiSlider (" + VERSION + "): must pass a formatter for all handles.");
      }

      parsed.tooltips.forEach(function (formatter) {
        if (typeof formatter !== 'boolean' && (_typeof(formatter) !== 'object' || typeof formatter.to !== 'function')) {
          throw new Error("noUiSlider (" + VERSION + "): 'tooltips' must be passed a formatter or 'false'.");
        }
      });
    }
  }

  function testAriaFormat(parsed, entry) {
    parsed.ariaFormat = entry;
    validateFormat(entry);
  }

  function testFormat(parsed, entry) {
    parsed.format = entry;
    validateFormat(entry);
  }

  function testCssPrefix(parsed, entry) {
    if (typeof entry !== 'string' && entry !== false) {
      throw new Error("noUiSlider (" + VERSION + "): 'cssPrefix' must be a string or `false`.");
    }

    parsed.cssPrefix = entry;
  }

  function testCssClasses(parsed, entry) {
    if (_typeof(entry) !== 'object') {
      throw new Error("noUiSlider (" + VERSION + "): 'cssClasses' must be an object.");
    }

    if (typeof parsed.cssPrefix === 'string') {
      parsed.cssClasses = {};

      for (var key in entry) {
        if (!entry.hasOwnProperty(key)) {
          continue;
        }

        parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
      }
    } else {
      parsed.cssClasses = entry;
    }
  } // Test all developer settings and parse to assumption-safe values.


  function testOptions(options) {
    // To prove a fix for #537, freeze options here.
    // If the object is modified, an error will be thrown.
    // Object.freeze(options);
    var parsed = {
      margin: 0,
      limit: 0,
      padding: 0,
      animate: true,
      animationDuration: 300,
      ariaFormat: defaultFormatter,
      format: defaultFormatter
    }; // Tests are executed in the order they are presented here.

    var tests = {
      'step': {
        r: false,
        t: testStep
      },
      'start': {
        r: true,
        t: testStart
      },
      'connect': {
        r: true,
        t: testConnect
      },
      'direction': {
        r: true,
        t: testDirection
      },
      'snap': {
        r: false,
        t: testSnap
      },
      'animate': {
        r: false,
        t: testAnimate
      },
      'animationDuration': {
        r: false,
        t: testAnimationDuration
      },
      'range': {
        r: true,
        t: testRange
      },
      'orientation': {
        r: false,
        t: testOrientation
      },
      'margin': {
        r: false,
        t: testMargin
      },
      'limit': {
        r: false,
        t: testLimit
      },
      'padding': {
        r: false,
        t: testPadding
      },
      'behaviour': {
        r: true,
        t: testBehaviour
      },
      'ariaFormat': {
        r: false,
        t: testAriaFormat
      },
      'format': {
        r: false,
        t: testFormat
      },
      'tooltips': {
        r: false,
        t: testTooltips
      },
      'cssPrefix': {
        r: true,
        t: testCssPrefix
      },
      'cssClasses': {
        r: true,
        t: testCssClasses
      }
    };
    var defaults = {
      'connect': false,
      'direction': 'ltr',
      'behaviour': 'tap',
      'orientation': 'horizontal',
      'cssPrefix': 'noUi-',
      'cssClasses': {
        target: 'target',
        base: 'base',
        origin: 'origin',
        handle: 'handle',
        handleLower: 'handle-lower',
        handleUpper: 'handle-upper',
        horizontal: 'horizontal',
        vertical: 'vertical',
        background: 'background',
        connect: 'connect',
        connects: 'connects',
        ltr: 'ltr',
        rtl: 'rtl',
        draggable: 'draggable',
        drag: 'state-drag',
        tap: 'state-tap',
        active: 'active',
        tooltip: 'tooltip',
        pips: 'pips',
        pipsHorizontal: 'pips-horizontal',
        pipsVertical: 'pips-vertical',
        marker: 'marker',
        markerHorizontal: 'marker-horizontal',
        markerVertical: 'marker-vertical',
        markerNormal: 'marker-normal',
        markerLarge: 'marker-large',
        markerSub: 'marker-sub',
        value: 'value',
        valueHorizontal: 'value-horizontal',
        valueVertical: 'value-vertical',
        valueNormal: 'value-normal',
        valueLarge: 'value-large',
        valueSub: 'value-sub'
      }
    }; // AriaFormat defaults to regular format, if any.

    if (options.format && !options.ariaFormat) {
      options.ariaFormat = options.format;
    } // Run all options through a testing mechanism to ensure correct
    // input. It should be noted that options might get modified to
    // be handled properly. E.g. wrapping integers in arrays.


    Object.keys(tests).forEach(function (name) {
      // If the option isn't set, but it is required, throw an error.
      if (!isSet(options[name]) && defaults[name] === undefined) {
        if (tests[name].r) {
          throw new Error("noUiSlider (" + VERSION + "): '" + name + "' is required.");
        }

        return true;
      }

      tests[name].t(parsed, !isSet(options[name]) ? defaults[name] : options[name]);
    }); // Forward pips options

    parsed.pips = options.pips; // All recent browsers accept unprefixed transform.
    // We need -ms- for IE9 and -webkit- for older Android;
    // Assume use of -webkit- if unprefixed and -ms- are not supported.
    // https://caniuse.com/#feat=transforms2d

    var d = document.createElement("div");
    var msPrefix = d.style.msTransform !== undefined;
    var noPrefix = d.style.transform !== undefined;
    parsed.transformRule = noPrefix ? 'transform' : msPrefix ? 'msTransform' : 'webkitTransform'; // Pips don't move, so we can place them using left/top.

    var styles = [['left', 'top'], ['right', 'bottom']];
    parsed.style = styles[parsed.dir][parsed.ort];
    return parsed;
  }

  function scope(target, options, originalOptions) {
    var actions = getActions();
    var supportsTouchActionNone = getSupportsTouchActionNone();
    var supportsPassive = supportsTouchActionNone && getSupportsPassive(); // All variables local to 'scope' are prefixed with 'scope_'

    var scope_Target = target;
    var scope_Locations = [];
    var scope_Base;
    var scope_Handles;
    var scope_HandleNumbers = [];
    var scope_ActiveHandlesCount = 0;
    var scope_Connects;
    var scope_Spectrum = options.spectrum;
    var scope_Values = [];
    var scope_Events = {};
    var scope_Self;
    var scope_Pips;
    var scope_Document = target.ownerDocument;
    var scope_DocumentElement = scope_Document.documentElement;
    var scope_Body = scope_Document.body; // For horizontal sliders in standard ltr documents,
    // make .noUi-origin overflow to the left so the document doesn't scroll.

    var scope_DirOffset = scope_Document.dir === 'rtl' || options.ort === 1 ? 0 : 100;
    /*! In this file: Construction of DOM elements; */
    // Creates a node, adds it to target, returns the new node.

    function addNodeTo(addTarget, className) {
      var div = scope_Document.createElement('div');

      if (className) {
        addClass(div, className);
      }

      addTarget.appendChild(div);
      return div;
    } // Append a origin to the base


    function addOrigin(base, handleNumber) {
      var origin = addNodeTo(base, options.cssClasses.origin);
      var handle = addNodeTo(origin, options.cssClasses.handle);
      handle.setAttribute('data-handle', handleNumber); // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
      // 0 = focusable and reachable

      handle.setAttribute('tabindex', '0');
      handle.setAttribute('role', 'slider');
      handle.setAttribute('aria-orientation', options.ort ? 'vertical' : 'horizontal');

      if (handleNumber === 0) {
        addClass(handle, options.cssClasses.handleLower);
      } else if (handleNumber === options.handles - 1) {
        addClass(handle, options.cssClasses.handleUpper);
      }

      return origin;
    } // Insert nodes for connect elements


    function addConnect(base, add) {
      if (!add) {
        return false;
      }

      return addNodeTo(base, options.cssClasses.connect);
    } // Add handles to the slider base.


    function addElements(connectOptions, base) {
      var connectBase = addNodeTo(base, options.cssClasses.connects);
      scope_Handles = [];
      scope_Connects = [];
      scope_Connects.push(addConnect(connectBase, connectOptions[0])); // [::::O====O====O====]
      // connectOptions = [0, 1, 1, 1]

      for (var i = 0; i < options.handles; i++) {
        // Keep a list of all added handles.
        scope_Handles.push(addOrigin(base, i));
        scope_HandleNumbers[i] = i;
        scope_Connects.push(addConnect(connectBase, connectOptions[i + 1]));
      }
    } // Initialize a single slider.


    function addSlider(addTarget) {
      // Apply classes and data to the target.
      addClass(addTarget, options.cssClasses.target);

      if (options.dir === 0) {
        addClass(addTarget, options.cssClasses.ltr);
      } else {
        addClass(addTarget, options.cssClasses.rtl);
      }

      if (options.ort === 0) {
        addClass(addTarget, options.cssClasses.horizontal);
      } else {
        addClass(addTarget, options.cssClasses.vertical);
      }

      scope_Base = addNodeTo(addTarget, options.cssClasses.base);
    }

    function addTooltip(handle, handleNumber) {
      if (!options.tooltips[handleNumber]) {
        return false;
      }

      return addNodeTo(handle.firstChild, options.cssClasses.tooltip);
    } // The tooltips option is a shorthand for using the 'update' event.


    function tooltips() {
      // Tooltips are added with options.tooltips in original order.
      var tips = scope_Handles.map(addTooltip);
      bindEvent('update', function (values, handleNumber, unencoded) {
        if (!tips[handleNumber]) {
          return;
        }

        var formattedValue = values[handleNumber];

        if (options.tooltips[handleNumber] !== true) {
          formattedValue = options.tooltips[handleNumber].to(unencoded[handleNumber]);
        }

        tips[handleNumber].innerHTML = formattedValue;
      });
    }

    function aria() {
      bindEvent('update', function (values, handleNumber, unencoded, tap, positions) {
        // Update Aria Values for all handles, as a change in one changes min and max values for the next.
        scope_HandleNumbers.forEach(function (index) {
          var handle = scope_Handles[index];
          var min = checkHandlePosition(scope_Locations, index, 0, true, true, true);
          var max = checkHandlePosition(scope_Locations, index, 100, true, true, true);
          var now = positions[index];
          var text = options.ariaFormat.to(unencoded[index]);
          handle.children[0].setAttribute('aria-valuemin', min.toFixed(1));
          handle.children[0].setAttribute('aria-valuemax', max.toFixed(1));
          handle.children[0].setAttribute('aria-valuenow', now.toFixed(1));
          handle.children[0].setAttribute('aria-valuetext', text);
        });
      });
    }

    function getGroup(mode, values, stepped) {
      // Use the range.
      if (mode === 'range' || mode === 'steps') {
        return scope_Spectrum.xVal;
      }

      if (mode === 'count') {
        if (values < 2) {
          throw new Error("noUiSlider (" + VERSION + "): 'values' (>= 2) required for mode 'count'.");
        } // Divide 0 - 100 in 'count' parts.


        var interval = values - 1;
        var spread = 100 / interval;
        values = []; // List these parts and have them handled as 'positions'.

        while (interval--) {
          values[interval] = interval * spread;
        }

        values.push(100);
        mode = 'positions';
      }

      if (mode === 'positions') {
        // Map all percentages to on-range values.
        return values.map(function (value) {
          return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value) : value);
        });
      }

      if (mode === 'values') {
        // If the value must be stepped, it needs to be converted to a percentage first.
        if (stepped) {
          return values.map(function (value) {
            // Convert to percentage, apply step, return to value.
            return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));
          });
        } // Otherwise, we can simply use the values.


        return values;
      }
    }

    function generateSpread(density, mode, group) {
      function safeIncrement(value, increment) {
        // Avoid floating point variance by dropping the smallest decimal places.
        return (value + increment).toFixed(7) / 1;
      }

      var indexes = {};
      var firstInRange = scope_Spectrum.xVal[0];
      var lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length - 1];
      var ignoreFirst = false;
      var ignoreLast = false;
      var prevPct = 0; // Create a copy of the group, sort it and filter away all duplicates.

      group = unique(group.slice().sort(function (a, b) {
        return a - b;
      })); // Make sure the range starts with the first element.

      if (group[0] !== firstInRange) {
        group.unshift(firstInRange);
        ignoreFirst = true;
      } // Likewise for the last one.


      if (group[group.length - 1] !== lastInRange) {
        group.push(lastInRange);
        ignoreLast = true;
      }

      group.forEach(function (current, index) {
        // Get the current step and the lower + upper positions.
        var step;
        var i;
        var q;
        var low = current;
        var high = group[index + 1];
        var newPct;
        var pctDifference;
        var pctPos;
        var type;
        var steps;
        var realSteps;
        var stepsize; // When using 'steps' mode, use the provided steps.
        // Otherwise, we'll step on to the next subrange.

        if (mode === 'steps') {
          step = scope_Spectrum.xNumSteps[index];
        } // Default to a 'full' step.


        if (!step) {
          step = high - low;
        } // Low can be 0, so test for false. If high is undefined,
        // we are at the last subrange. Index 0 is already handled.


        if (low === false || high === undefined) {
          return;
        } // Make sure step isn't 0, which would cause an infinite loop (#654)


        step = Math.max(step, 0.0000001); // Find all steps in the subrange.

        for (i = low; i <= high; i = safeIncrement(i, step)) {
          // Get the percentage value for the current step,
          // calculate the size for the subrange.
          newPct = scope_Spectrum.toStepping(i);
          pctDifference = newPct - prevPct;
          steps = pctDifference / density;
          realSteps = Math.round(steps); // This ratio represents the amount of percentage-space a point indicates.
          // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided.
          // Round the percentage offset to an even number, then divide by two
          // to spread the offset on both sides of the range.

          stepsize = pctDifference / realSteps; // Divide all points evenly, adding the correct number to this subrange.
          // Run up to <= so that 100% gets a point, event if ignoreLast is set.

          for (q = 1; q <= realSteps; q += 1) {
            // The ratio between the rounded value and the actual size might be ~1% off.
            // Correct the percentage offset by the number of points
            // per subrange. density = 1 will result in 100 points on the
            // full range, 2 for 50, 4 for 25, etc.
            pctPos = prevPct + q * stepsize;
            indexes[pctPos.toFixed(5)] = ['x', 0];
          } // Determine the point type.


          type = group.indexOf(i) > -1 ? 1 : mode === 'steps' ? 2 : 0; // Enforce the 'ignoreFirst' option by overwriting the type for 0.

          if (!index && ignoreFirst) {
            type = 0;
          }

          if (!(i === high && ignoreLast)) {
            // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
            indexes[newPct.toFixed(5)] = [i, type];
          } // Update the percentage count.


          prevPct = newPct;
        }
      });
      return indexes;
    }

    function addMarking(spread, filterFunc, formatter) {
      var element = scope_Document.createElement('div');
      var valueSizeClasses = [options.cssClasses.valueNormal, options.cssClasses.valueLarge, options.cssClasses.valueSub];
      var markerSizeClasses = [options.cssClasses.markerNormal, options.cssClasses.markerLarge, options.cssClasses.markerSub];
      var valueOrientationClasses = [options.cssClasses.valueHorizontal, options.cssClasses.valueVertical];
      var markerOrientationClasses = [options.cssClasses.markerHorizontal, options.cssClasses.markerVertical];
      addClass(element, options.cssClasses.pips);
      addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);

      function getClasses(type, source) {
        var a = source === options.cssClasses.value;
        var orientationClasses = a ? valueOrientationClasses : markerOrientationClasses;
        var sizeClasses = a ? valueSizeClasses : markerSizeClasses;
        return source + ' ' + orientationClasses[options.ort] + ' ' + sizeClasses[type];
      }

      function addSpread(offset, values) {
        // Apply the filter function, if it is set.
        values[1] = values[1] && filterFunc ? filterFunc(values[0], values[1]) : values[1]; // Add a marker for every point

        var node = addNodeTo(element, false);
        node.className = getClasses(values[1], options.cssClasses.marker);
        node.style[options.style] = offset + '%'; // Values are only appended for points marked '1' or '2'.

        if (values[1]) {
          node = addNodeTo(element, false);
          node.className = getClasses(values[1], options.cssClasses.value);
          node.setAttribute('data-value', values[0]);
          node.style[options.style] = offset + '%';
          node.innerText = formatter.to(values[0]);
        }
      } // Append all points.


      Object.keys(spread).forEach(function (a) {
        addSpread(a, spread[a]);
      });
      return element;
    }

    function removePips() {
      if (scope_Pips) {
        removeElement(scope_Pips);
        scope_Pips = null;
      }
    }

    function pips(grid) {
      // Fix #669
      removePips();
      var mode = grid.mode;
      var density = grid.density || 1;
      var filter = grid.filter || false;
      var values = grid.values || false;
      var stepped = grid.stepped || false;
      var group = getGroup(mode, values, stepped);
      var spread = generateSpread(density, mode, group);
      var format = grid.format || {
        to: Math.round
      };
      scope_Pips = scope_Target.appendChild(addMarking(spread, filter, format));
      return scope_Pips;
    }
    /*! In this file: Browser events (not slider events like slide, change); */
    // Shorthand for base dimensions.


    function baseSize() {
      var rect = scope_Base.getBoundingClientRect();
      var alt = 'offset' + ['Width', 'Height'][options.ort];
      return options.ort === 0 ? rect.width || scope_Base[alt] : rect.height || scope_Base[alt];
    } // Handler for attaching events trough a proxy.


    function attachEvent(events, element, callback, data) {
      // This function can be used to 'filter' events to the slider.
      // element is a node, not a nodeList
      var method = function method(e) {
        e = fixEvent(e, data.pageOffset, data.target || element); // fixEvent returns false if this event has a different target
        // when handling (multi-) touch events;

        if (!e) {
          return false;
        } // doNotReject is passed by all end events to make sure released touches
        // are not rejected, leaving the slider "stuck" to the cursor;


        if (scope_Target.hasAttribute('disabled') && !data.doNotReject) {
          return false;
        } // Stop if an active 'tap' transition is taking place.


        if (hasClass(scope_Target, options.cssClasses.tap) && !data.doNotReject) {
          return false;
        } // Ignore right or middle clicks on start #454


        if (events === actions.start && e.buttons !== undefined && e.buttons > 1) {
          return false;
        } // Ignore right or middle clicks on start #454


        if (data.hover && e.buttons) {
          return false;
        } // 'supportsPassive' is only true if a browser also supports touch-action: none in CSS.
        // iOS safari does not, so it doesn't get to benefit from passive scrolling. iOS does support
        // touch-action: manipulation, but that allows panning, which breaks
        // sliders after zooming/on non-responsive pages.
        // See: https://bugs.webkit.org/show_bug.cgi?id=133112


        if (!supportsPassive) {
          e.preventDefault();
        }

        e.calcPoint = e.points[options.ort]; // Call the event handler with the event [ and additional data ].

        callback(e, data);
      };

      var methods = []; // Bind a closure on the target for every event type.

      events.split(' ').forEach(function (eventName) {
        element.addEventListener(eventName, method, supportsPassive ? {
          passive: true
        } : false);
        methods.push([eventName, method]);
      });
      return methods;
    } // Provide a clean event with standardized offset values.


    function fixEvent(e, pageOffset, eventTarget) {
      // Filter the event to register the type, which can be
      // touch, mouse or pointer. Offset changes need to be
      // made on an event specific basis.
      var touch = e.type.indexOf('touch') === 0;
      var mouse = e.type.indexOf('mouse') === 0;
      var pointer = e.type.indexOf('pointer') === 0;
      var x;
      var y; // IE10 implemented pointer events with a prefix;

      if (e.type.indexOf('MSPointer') === 0) {
        pointer = true;
      } // In the event that multitouch is activated, the only thing one handle should be concerned
      // about is the touches that originated on top of it.


      if (touch) {
        // Returns true if a touch originated on the target.
        var isTouchOnTarget = function isTouchOnTarget(checkTouch) {
          return checkTouch.target === eventTarget || eventTarget.contains(checkTouch.target);
        }; // In the case of touchstart events, we need to make sure there is still no more than one
        // touch on the target so we look amongst all touches.


        if (e.type === 'touchstart') {
          var targetTouches = Array.prototype.filter.call(e.touches, isTouchOnTarget); // Do not support more than one touch per handle.

          if (targetTouches.length > 1) {
            return false;
          }

          x = targetTouches[0].pageX;
          y = targetTouches[0].pageY;
        } else {
          // In the other cases, find on changedTouches is enough.
          var targetTouch = Array.prototype.find.call(e.changedTouches, isTouchOnTarget); // Cancel if the target touch has not moved.

          if (!targetTouch) {
            return false;
          }

          x = targetTouch.pageX;
          y = targetTouch.pageY;
        }
      }

      pageOffset = pageOffset || getPageOffset(scope_Document);

      if (mouse || pointer) {
        x = e.clientX + pageOffset.x;
        y = e.clientY + pageOffset.y;
      }

      e.pageOffset = pageOffset;
      e.points = [x, y];
      e.cursor = mouse || pointer; // Fix #435

      return e;
    } // Translate a coordinate in the document to a percentage on the slider


    function calcPointToPercentage(calcPoint) {
      var location = calcPoint - offset(scope_Base, options.ort);
      var proposal = location * 100 / baseSize(); // Clamp proposal between 0% and 100%
      // Out-of-bound coordinates may occur when .noUi-base pseudo-elements
      // are used (e.g. contained handles feature)

      proposal = limit(proposal);
      return options.dir ? 100 - proposal : proposal;
    } // Find handle closest to a certain percentage on the slider


    function getClosestHandle(proposal) {
      var closest = 100;
      var handleNumber = false;
      scope_Handles.forEach(function (handle, index) {
        // Disabled handles are ignored
        if (handle.hasAttribute('disabled')) {
          return;
        }

        var pos = Math.abs(scope_Locations[index] - proposal);

        if (pos < closest || pos === 100 && closest === 100) {
          handleNumber = index;
          closest = pos;
        }
      });
      return handleNumber;
    } // Fire 'end' when a mouse or pen leaves the document.


    function documentLeave(event, data) {
      if (event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null) {
        eventEnd(event, data);
      }
    } // Handle movement on document for handle and range drag.


    function eventMove(event, data) {
      // Fix #498
      // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
      // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
      // IE9 has .buttons and .which zero on mousemove.
      // Firefox breaks the spec MDN defines.
      if (navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0) {
        return eventEnd(event, data);
      } // Check if we are moving up or down


      var movement = (options.dir ? -1 : 1) * (event.calcPoint - data.startCalcPoint); // Convert the movement into a percentage of the slider width/height

      var proposal = movement * 100 / data.baseSize;
      moveHandles(movement > 0, proposal, data.locations, data.handleNumbers);
    } // Unbind move events on document, call callbacks.


    function eventEnd(event, data) {
      // The handle is no longer active, so remove the class.
      if (data.handle) {
        removeClass(data.handle, options.cssClasses.active);
        scope_ActiveHandlesCount -= 1;
      } // Unbind the move and end events, which are added on 'start'.


      data.listeners.forEach(function (c) {
        scope_DocumentElement.removeEventListener(c[0], c[1]);
      });

      if (scope_ActiveHandlesCount === 0) {
        // Remove dragging class.
        removeClass(scope_Target, options.cssClasses.drag);
        setZindex(); // Remove cursor styles and text-selection events bound to the body.

        if (event.cursor) {
          scope_Body.style.cursor = '';
          scope_Body.removeEventListener('selectstart', preventDefault);
        }
      }

      data.handleNumbers.forEach(function (handleNumber) {
        fireEvent('change', handleNumber);
        fireEvent('set', handleNumber);
        fireEvent('end', handleNumber);
      });
    } // Bind move events on document.


    function eventStart(event, data) {
      var handle;

      if (data.handleNumbers.length === 1) {
        var handleOrigin = scope_Handles[data.handleNumbers[0]]; // Ignore 'disabled' handles

        if (handleOrigin.hasAttribute('disabled')) {
          return false;
        }

        handle = handleOrigin.children[0];
        scope_ActiveHandlesCount += 1; // Mark the handle as 'active' so it can be styled.

        addClass(handle, options.cssClasses.active);
      } // A drag should never propagate up to the 'tap' event.


      event.stopPropagation(); // Record the event listeners.

      var listeners = []; // Attach the move and end events.

      var moveEvent = attachEvent(actions.move, scope_DocumentElement, eventMove, {
        // The event target has changed so we need to propagate the original one so that we keep
        // relying on it to extract target touches.
        target: event.target,
        handle: handle,
        listeners: listeners,
        startCalcPoint: event.calcPoint,
        baseSize: baseSize(),
        pageOffset: event.pageOffset,
        handleNumbers: data.handleNumbers,
        buttonsProperty: event.buttons,
        locations: scope_Locations.slice()
      });
      var endEvent = attachEvent(actions.end, scope_DocumentElement, eventEnd, {
        target: event.target,
        handle: handle,
        listeners: listeners,
        doNotReject: true,
        handleNumbers: data.handleNumbers
      });
      var outEvent = attachEvent("mouseout", scope_DocumentElement, documentLeave, {
        target: event.target,
        handle: handle,
        listeners: listeners,
        doNotReject: true,
        handleNumbers: data.handleNumbers
      }); // We want to make sure we pushed the listeners in the listener list rather than creating
      // a new one as it has already been passed to the event handlers.

      listeners.push.apply(listeners, moveEvent.concat(endEvent, outEvent)); // Text selection isn't an issue on touch devices,
      // so adding cursor styles can be skipped.

      if (event.cursor) {
        // Prevent the 'I' cursor and extend the range-drag cursor.
        scope_Body.style.cursor = getComputedStyle(event.target).cursor; // Mark the target with a dragging state.

        if (scope_Handles.length > 1) {
          addClass(scope_Target, options.cssClasses.drag);
        } // Prevent text selection when dragging the handles.
        // In noUiSlider <= 9.2.0, this was handled by calling preventDefault on mouse/touch start/move,
        // which is scroll blocking. The selectstart event is supported by FireFox starting from version 52,
        // meaning the only holdout is iOS Safari. This doesn't matter: text selection isn't triggered there.
        // The 'cursor' flag is false.
        // See: http://caniuse.com/#search=selectstart


        scope_Body.addEventListener('selectstart', preventDefault, false);
      }

      data.handleNumbers.forEach(function (handleNumber) {
        fireEvent('start', handleNumber);
      });
    } // Move closest handle to tapped location.


    function eventTap(event) {
      // The tap event shouldn't propagate up
      event.stopPropagation();
      var proposal = calcPointToPercentage(event.calcPoint);
      var handleNumber = getClosestHandle(proposal); // Tackle the case that all handles are 'disabled'.

      if (handleNumber === false) {
        return false;
      } // Flag the slider as it is now in a transitional state.
      // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.


      if (!options.events.snap) {
        addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
      }

      setHandle(handleNumber, proposal, true, true);
      setZindex();
      fireEvent('slide', handleNumber, true);
      fireEvent('update', handleNumber, true);
      fireEvent('change', handleNumber, true);
      fireEvent('set', handleNumber, true);

      if (options.events.snap) {
        eventStart(event, {
          handleNumbers: [handleNumber]
        });
      }
    } // Fires a 'hover' event for a hovered mouse/pen position.


    function eventHover(event) {
      var proposal = calcPointToPercentage(event.calcPoint);
      var to = scope_Spectrum.getStep(proposal);
      var value = scope_Spectrum.fromStepping(to);
      Object.keys(scope_Events).forEach(function (targetEvent) {
        if ('hover' === targetEvent.split('.')[0]) {
          scope_Events[targetEvent].forEach(function (callback) {
            callback.call(scope_Self, value);
          });
        }
      });
    } // Attach events to several slider parts.


    function bindSliderEvents(behaviour) {
      // Attach the standard drag event to the handles.
      if (!behaviour.fixed) {
        scope_Handles.forEach(function (handle, index) {
          // These events are only bound to the visual handle
          // element, not the 'real' origin element.
          attachEvent(actions.start, handle.children[0], eventStart, {
            handleNumbers: [index]
          });
        });
      } // Attach the tap event to the slider base.


      if (behaviour.tap) {
        attachEvent(actions.start, scope_Base, eventTap, {});
      } // Fire hover events


      if (behaviour.hover) {
        attachEvent(actions.move, scope_Base, eventHover, {
          hover: true
        });
      } // Make the range draggable.


      if (behaviour.drag) {
        scope_Connects.forEach(function (connect, index) {
          if (connect === false || index === 0 || index === scope_Connects.length - 1) {
            return;
          }

          var handleBefore = scope_Handles[index - 1];
          var handleAfter = scope_Handles[index];
          var eventHolders = [connect];
          addClass(connect, options.cssClasses.draggable); // When the range is fixed, the entire range can
          // be dragged by the handles. The handle in the first
          // origin will propagate the start event upward,
          // but it needs to be bound manually on the other.

          if (behaviour.fixed) {
            eventHolders.push(handleBefore.children[0]);
            eventHolders.push(handleAfter.children[0]);
          }

          eventHolders.forEach(function (eventHolder) {
            attachEvent(actions.start, eventHolder, eventStart, {
              handles: [handleBefore, handleAfter],
              handleNumbers: [index - 1, index]
            });
          });
        });
      }
    }
    /*! In this file: Slider events (not browser events); */
    // Attach an event to this slider, possibly including a namespace


    function bindEvent(namespacedEvent, callback) {
      scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
      scope_Events[namespacedEvent].push(callback); // If the event bound is 'update,' fire it immediately for all handles.

      if (namespacedEvent.split('.')[0] === 'update') {
        scope_Handles.forEach(function (a, index) {
          fireEvent('update', index);
        });
      }
    } // Undo attachment of event


    function removeEvent(namespacedEvent) {
      var event = namespacedEvent && namespacedEvent.split('.')[0];
      var namespace = event && namespacedEvent.substring(event.length);
      Object.keys(scope_Events).forEach(function (bind) {
        var tEvent = bind.split('.')[0];
        var tNamespace = bind.substring(tEvent.length);

        if ((!event || event === tEvent) && (!namespace || namespace === tNamespace)) {
          delete scope_Events[bind];
        }
      });
    } // External event handling


    function fireEvent(eventName, handleNumber, tap) {
      Object.keys(scope_Events).forEach(function (targetEvent) {
        var eventType = targetEvent.split('.')[0];

        if (eventName === eventType) {
          scope_Events[targetEvent].forEach(function (callback) {
            callback.call( // Use the slider public API as the scope ('this')
            scope_Self, // Return values as array, so arg_1[arg_2] is always valid.
            scope_Values.map(options.format.to), // Handle index, 0 or 1
            handleNumber, // Unformatted slider values
            scope_Values.slice(), // Event is fired by tap, true or false
            tap || false, // Left offset of the handle, in relation to the slider
            scope_Locations.slice());
          });
        }
      });
    }
    /*! In this file: Mechanics for slider operation */


    function toPct(pct) {
      return pct + '%';
    } // Split out the handle positioning logic so the Move event can use it, too


    function checkHandlePosition(reference, handleNumber, to, lookBackward, lookForward, getValue) {
      // For sliders with multiple handles, limit movement to the other handle.
      // Apply the margin option by adding it to the handle positions.
      if (scope_Handles.length > 1) {
        if (lookBackward && handleNumber > 0) {
          to = Math.max(to, reference[handleNumber - 1] + options.margin);
        }

        if (lookForward && handleNumber < scope_Handles.length - 1) {
          to = Math.min(to, reference[handleNumber + 1] - options.margin);
        }
      } // The limit option has the opposite effect, limiting handles to a
      // maximum distance from another. Limit must be > 0, as otherwise
      // handles would be unmoveable.


      if (scope_Handles.length > 1 && options.limit) {
        if (lookBackward && handleNumber > 0) {
          to = Math.min(to, reference[handleNumber - 1] + options.limit);
        }

        if (lookForward && handleNumber < scope_Handles.length - 1) {
          to = Math.max(to, reference[handleNumber + 1] - options.limit);
        }
      } // The padding option keeps the handles a certain distance from the
      // edges of the slider. Padding must be > 0.


      if (options.padding) {
        if (handleNumber === 0) {
          to = Math.max(to, options.padding[0]);
        }

        if (handleNumber === scope_Handles.length - 1) {
          to = Math.min(to, 100 - options.padding[1]);
        }
      }

      to = scope_Spectrum.getStep(to); // Limit percentage to the 0 - 100 range

      to = limit(to); // Return false if handle can't move

      if (to === reference[handleNumber] && !getValue) {
        return false;
      }

      return to;
    } // Uses slider orientation to create CSS rules. a = base value;


    function inRuleOrder(v, a) {
      var o = options.ort;
      return (o ? a : v) + ', ' + (o ? v : a);
    } // Moves handle(s) by a percentage
    // (bool, % to move, [% where handle started, ...], [index in scope_Handles, ...])


    function moveHandles(upward, proposal, locations, handleNumbers) {
      var proposals = locations.slice();
      var b = [!upward, upward];
      var f = [upward, !upward]; // Copy handleNumbers so we don't change the dataset

      handleNumbers = handleNumbers.slice(); // Check to see which handle is 'leading'.
      // If that one can't move the second can't either.

      if (upward) {
        handleNumbers.reverse();
      } // Step 1: get the maximum percentage that any of the handles can move


      if (handleNumbers.length > 1) {
        handleNumbers.forEach(function (handleNumber, o) {
          var to = checkHandlePosition(proposals, handleNumber, proposals[handleNumber] + proposal, b[o], f[o], false); // Stop if one of the handles can't move.

          if (to === false) {
            proposal = 0;
          } else {
            proposal = to - proposals[handleNumber];
            proposals[handleNumber] = to;
          }
        });
      } // If using one handle, check backward AND forward
      else {
          b = f = [true];
        }

      var state = false; // Step 2: Try to set the handles with the found percentage

      handleNumbers.forEach(function (handleNumber, o) {
        state = setHandle(handleNumber, locations[handleNumber] + proposal, b[o], f[o]) || state;
      }); // Step 3: If a handle moved, fire events

      if (state) {
        handleNumbers.forEach(function (handleNumber) {
          fireEvent('update', handleNumber);
          fireEvent('slide', handleNumber);
        });
      }
    } // Takes a base value and an offset. This offset is used for the connect bar size.
    // In the initial design for this feature, the origin element was 1% wide.
    // Unfortunately, a rounding bug in Chrome makes it impossible to implement this feature
    // in this manner: https://bugs.chromium.org/p/chromium/issues/detail?id=798223


    function transformDirection(a, b) {
      return options.dir ? 100 - a - b : a;
    } // Updates scope_Locations and scope_Values, updates visual state


    function updateHandlePosition(handleNumber, to) {
      // Update locations.
      scope_Locations[handleNumber] = to; // Convert the value to the slider stepping/range.

      scope_Values[handleNumber] = scope_Spectrum.fromStepping(to);
      var rule = 'translate(' + inRuleOrder(toPct(transformDirection(to, 0) - scope_DirOffset), '0') + ')';
      scope_Handles[handleNumber].style[options.transformRule] = rule;
      updateConnect(handleNumber);
      updateConnect(handleNumber + 1);
    } // Handles before the slider middle are stacked later = higher,
    // Handles after the middle later is lower
    // [[7] [8] .......... | .......... [5] [4]


    function setZindex() {
      scope_HandleNumbers.forEach(function (handleNumber) {
        var dir = scope_Locations[handleNumber] > 50 ? -1 : 1;
        var zIndex = 3 + (scope_Handles.length + dir * handleNumber);
        scope_Handles[handleNumber].style.zIndex = zIndex;
      });
    } // Test suggested values and apply margin, step.


    function setHandle(handleNumber, to, lookBackward, lookForward) {
      to = checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward, false);

      if (to === false) {
        return false;
      }

      updateHandlePosition(handleNumber, to);
      return true;
    } // Updates style attribute for connect nodes


    function updateConnect(index) {
      // Skip connects set to false
      if (!scope_Connects[index]) {
        return;
      }

      var l = 0;
      var h = 100;

      if (index !== 0) {
        l = scope_Locations[index - 1];
      }

      if (index !== scope_Connects.length - 1) {
        h = scope_Locations[index];
      } // We use two rules:
      // 'translate' to change the left/top offset;
      // 'scale' to change the width of the element;
      // As the element has a width of 100%, a translation of 100% is equal to 100% of the parent (.noUi-base)


      var connectWidth = h - l;
      var translateRule = 'translate(' + inRuleOrder(toPct(transformDirection(l, connectWidth)), '0') + ')';
      var scaleRule = 'scale(' + inRuleOrder(connectWidth / 100, '1') + ')';
      scope_Connects[index].style[options.transformRule] = translateRule + ' ' + scaleRule;
    }
    /*! In this file: All methods eventually exposed in slider.noUiSlider... */
    // Parses value passed to .set method. Returns current value if not parse-able.


    function resolveToValue(to, handleNumber) {
      // Setting with null indicates an 'ignore'.
      // Inputting 'false' is invalid.
      if (to === null || to === false || to === undefined) {
        return scope_Locations[handleNumber];
      } // If a formatted number was passed, attempt to decode it.


      if (typeof to === 'number') {
        to = String(to);
      }

      to = options.format.from(to);
      to = scope_Spectrum.toStepping(to); // If parsing the number failed, use the current value.

      if (to === false || isNaN(to)) {
        return scope_Locations[handleNumber];
      }

      return to;
    } // Set the slider value.


    function valueSet(input, fireSetEvent) {
      var values = asArray(input);
      var isInit = scope_Locations[0] === undefined; // Event fires by default

      fireSetEvent = fireSetEvent === undefined ? true : !!fireSetEvent; // Animation is optional.
      // Make sure the initial values were set before using animated placement.

      if (options.animate && !isInit) {
        addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
      } // First pass, without lookAhead but with lookBackward. Values are set from left to right.


      scope_HandleNumbers.forEach(function (handleNumber) {
        setHandle(handleNumber, resolveToValue(values[handleNumber], handleNumber), true, false);
      }); // Second pass. Now that all base values are set, apply constraints

      scope_HandleNumbers.forEach(function (handleNumber) {
        setHandle(handleNumber, scope_Locations[handleNumber], true, true);
      });
      setZindex();
      scope_HandleNumbers.forEach(function (handleNumber) {
        fireEvent('update', handleNumber); // Fire the event only for handles that received a new value, as per #579

        if (values[handleNumber] !== null && fireSetEvent) {
          fireEvent('set', handleNumber);
        }
      });
    } // Reset slider to initial values


    function valueReset(fireSetEvent) {
      valueSet(options.start, fireSetEvent);
    } // Get the slider value.


    function valueGet() {
      var values = scope_Values.map(options.format.to); // If only one handle is used, return a single value.

      if (values.length === 1) {
        return values[0];
      }

      return values;
    } // Removes classes from the root and empties it.


    function destroy() {
      for (var key in options.cssClasses) {
        if (!options.cssClasses.hasOwnProperty(key)) {
          continue;
        }

        removeClass(scope_Target, options.cssClasses[key]);
      }

      while (scope_Target.firstChild) {
        scope_Target.removeChild(scope_Target.firstChild);
      }

      delete scope_Target.noUiSlider;
    } // Get the current step size for the slider.


    function getCurrentStep() {
      // Check all locations, map them to their stepping point.
      // Get the step point, then find it in the input list.
      return scope_Locations.map(function (location, index) {
        var nearbySteps = scope_Spectrum.getNearbySteps(location);
        var value = scope_Values[index];
        var increment = nearbySteps.thisStep.step;
        var decrement = null; // If the next value in this step moves into the next step,
        // the increment is the start of the next step - the current value

        if (increment !== false) {
          if (value + increment > nearbySteps.stepAfter.startValue) {
            increment = nearbySteps.stepAfter.startValue - value;
          }
        } // If the value is beyond the starting point


        if (value > nearbySteps.thisStep.startValue) {
          decrement = nearbySteps.thisStep.step;
        } else if (nearbySteps.stepBefore.step === false) {
          decrement = false;
        } // If a handle is at the start of a step, it always steps back into the previous step first
        else {
            decrement = value - nearbySteps.stepBefore.highestStep;
          } // Now, if at the slider edges, there is not in/decrement


        if (location === 100) {
          increment = null;
        } else if (location === 0) {
          decrement = null;
        } // As per #391, the comparison for the decrement step can have some rounding issues.


        var stepDecimals = scope_Spectrum.countStepDecimals(); // Round per #391

        if (increment !== null && increment !== false) {
          increment = Number(increment.toFixed(stepDecimals));
        }

        if (decrement !== null && decrement !== false) {
          decrement = Number(decrement.toFixed(stepDecimals));
        }

        return [decrement, increment];
      });
    } // Updateable: margin, limit, padding, step, range, animate, snap


    function updateOptions(optionsToUpdate, fireSetEvent) {
      // Spectrum is created using the range, snap, direction and step options.
      // 'snap' and 'step' can be updated.
      // If 'snap' and 'step' are not passed, they should remain unchanged.
      var v = valueGet();
      var updateAble = ['margin', 'limit', 'padding', 'range', 'animate', 'snap', 'step', 'format']; // Only change options that we're actually passed to update.

      updateAble.forEach(function (name) {
        if (optionsToUpdate[name] !== undefined) {
          originalOptions[name] = optionsToUpdate[name];
        }
      });
      var newOptions = testOptions(originalOptions); // Load new options into the slider state

      updateAble.forEach(function (name) {
        if (optionsToUpdate[name] !== undefined) {
          options[name] = newOptions[name];
        }
      });
      scope_Spectrum = newOptions.spectrum; // Limit, margin and padding depend on the spectrum but are stored outside of it. (#677)

      options.margin = newOptions.margin;
      options.limit = newOptions.limit;
      options.padding = newOptions.padding; // Update pips, removes existing.

      if (options.pips) {
        pips(options.pips);
      } // Invalidate the current positioning so valueSet forces an update.


      scope_Locations = [];
      valueSet(optionsToUpdate.start || v, fireSetEvent);
    }
    /*! In this file: Calls to functions. All other scope_ files define functions only; */
    // Create the base element, initialize HTML and set classes.
    // Add handles and connect elements.


    addSlider(scope_Target);
    addElements(options.connect, scope_Base); // Attach user events.

    bindSliderEvents(options.events); // Use the public value method to set the start values.

    valueSet(options.start);
    scope_Self = {
      destroy: destroy,
      steps: getCurrentStep,
      on: bindEvent,
      off: removeEvent,
      get: valueGet,
      set: valueSet,
      reset: valueReset,
      // Exposed for unit testing, don't use this in your application.
      __moveHandles: function __moveHandles(a, b, c) {
        moveHandles(a, b, scope_Locations, c);
      },
      options: originalOptions,
      // Issue #600, #678
      updateOptions: updateOptions,
      target: scope_Target,
      // Issue #597
      removePips: removePips,
      pips: pips // Issue #594

    };

    if (options.pips) {
      pips(options.pips);
    }

    if (options.tooltips) {
      tooltips();
    }

    aria();
    return scope_Self;
  } // Run the standard initializer


  function initialize(target, originalOptions) {
    if (!target || !target.nodeName) {
      throw new Error("noUiSlider (" + VERSION + "): create requires a single element, got: " + target);
    } // Throw an error if the slider was already initialized.


    if (target.noUiSlider) {
      throw new Error("noUiSlider (" + VERSION + "): Slider was already initialized.");
    } // Test the options and create the slider environment;


    var options = testOptions(originalOptions, target);
    var api = scope(target, options, originalOptions);
    target.noUiSlider = api;
    return api;
  } // Use an object instead of a function for future expandability;


  return {
    version: VERSION,
    create: initialize
  };
});

var ProfitCalculator = {
  // Slider settings
  sliderObject: '',
  slider: '',
  fillOut: '',
  marker: '',
  valuePlaceholder: '',
  inputField: '',
  value: 350000,
  valuePercentage: 0.35,
  minValue: 100000,
  maxValue: 1000000,
  // Pricing settings
  pricingObject: '',
  priceEstateAgentPercentage: 0.0165,
  btwPercentage: 1.21,
  zelfverkopenPrice: 1098,
  priceEstateAgent: 5690,
  init: function init() {
    ProfitCalculator.sliderObject = document.getElementById("calculatorSlider");
    ProfitCalculator.pricingObject = document.getElementById("profitPricing");

    if (isset(ProfitCalculator.sliderObject)) {
      ProfitCalculator.slider = ProfitCalculator.sliderObject.querySelector('.slider');
      ProfitCalculator.fillOut = ProfitCalculator.sliderObject.querySelector(".fill-out span");
      ProfitCalculator.marker = ProfitCalculator.sliderObject.querySelector(".marker");
      ProfitCalculator.inputField = ProfitCalculator.sliderObject.querySelector("#house-price");
      ProfitCalculator.valuePlaceholder = ProfitCalculator.sliderObject.querySelector(".tooltip .estimated-value .value-placeholder");
      ProfitCalculator.value = parseInt(ProfitCalculator.slider.value);
      ProfitCalculator.minValue = parseInt(ProfitCalculator.slider.min);
      ProfitCalculator.maxValue = parseInt(ProfitCalculator.slider.max);
      ProfitCalculator.updateValue();

      if (document.querySelector('html').classList.contains('ie')) {
        var stepSlider = document.getElementById('slider-step');
        noUiSlider.create(stepSlider, {
          start: [ProfitCalculator.value],
          step: 5000,
          range: {
            'min': [ProfitCalculator.minValue],
            'max': [ProfitCalculator.maxValue]
          }
        });
        stepSlider.noUiSlider.on('update', function (values, handle) {
          ProfitCalculator.updateValueIe(parseInt(values[handle]));
        });
      }

      ProfitCalculator.slider.oninput = function () {
        ProfitCalculator.updateValue();
      };

      var submitButton = ProfitCalculator.sliderObject.querySelector('.calculate-button');
      submitButton.addEventListener('click', function () {
        ProfitCalculator.sliderObject.querySelector('form').submit();
      });
    }
  },
  updateValue: function updateValue() {
    // Update values based upon the value
    ProfitCalculator.value = ProfitCalculator.slider.value;
    ProfitCalculator.valuePercentage = (ProfitCalculator.value - ProfitCalculator.minValue) / (ProfitCalculator.maxValue - ProfitCalculator.minValue); // Update hidden input field

    ProfitCalculator.inputField.value = ProfitCalculator.value; // Convert value to percentage and update styling

    ProfitCalculator.fillOut.style.width = ProfitCalculator.valuePercentage * 100 + '%';
    ProfitCalculator.marker.style.left = ProfitCalculator.valuePercentage * 100 + '%'; // Convert value to visual pricing

    var showNumber = ProfitCalculator.numberWithSeperator(ProfitCalculator.value, '.');
    ProfitCalculator.valuePlaceholder.setAttribute('data-value', showNumber + ',-'); //Calculated Estate agent pricing

    ProfitCalculator.priceEstateAgent = ProfitCalculator.value * (ProfitCalculator.priceEstateAgentPercentage * ProfitCalculator.btwPercentage);
    ProfitCalculator.updatePricing();
  },
  updateValueIe: function updateValueIe(sliderValue) {
    ProfitCalculator.value = sliderValue;
    ProfitCalculator.inputField.value = sliderValue; // Convert value to visual pricing

    var showNumber = ProfitCalculator.numberWithSeperator(ProfitCalculator.value, '.');
    ProfitCalculator.valuePlaceholder.setAttribute('data-value', showNumber + ',-'); //Calculated Estate agent pricing

    ProfitCalculator.priceEstateAgent = ProfitCalculator.value * (ProfitCalculator.priceEstateAgentPercentage * ProfitCalculator.btwPercentage);
    ProfitCalculator.updatePricing();
  },
  updatePricing: function updatePricing() {
    // Check if pricing object is defined
    if (isset(ProfitCalculator.pricingObject)) {
      var estateAgentPricingObject = ProfitCalculator.pricingObject.querySelector('#estateAgentPrice');
      var yourProfitObject = ProfitCalculator.pricingObject.querySelector('#profitPrice'); // Also check if the to be changed object are defined

      if (isset(estateAgentPricingObject) && isset(yourProfitObject)) {
        var priceEstateAgent = ProfitCalculator.priceEstateAgent.toFixed(2).toString().replace('.', ',');
        var profitValue = (ProfitCalculator.priceEstateAgent - ProfitCalculator.zelfverkopenPrice).toFixed(2);
        profitValue = profitValue.toString().replace('.', ',');
        if (priceEstateAgent.substr(priceEstateAgent.length - 3) === ',00') priceEstateAgent = priceEstateAgent.replace(',00', ',-');
        if (profitValue.substr(profitValue.length - 3) === ',00') profitValue = profitValue.replace(',00', ',-');
        estateAgentPricingObject.setAttribute('data-value', ProfitCalculator.numberWithSeperator(priceEstateAgent, '.'));
        yourProfitObject.setAttribute('data-value', ProfitCalculator.numberWithSeperator(profitValue, '.'));
      }
    }
  },
  numberWithSeperator: function numberWithSeperator(x, seperator) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, seperator);
  }
};
ProfitCalculator.init();
var PropertyFiltersHandler = {
  form: '',
  filters: [],

  /*
   * Initialize Property Filter Handling
   * If view has Property Filters Form add the event event listeners and add the filters
   */
  init: function init() {
    PropertyFiltersHandler.form = document.getElementById('propertiesFilters');

    if (isset(PropertyFiltersHandler.form)) {
      PropertyFiltersHandler.form.querySelector('.submit .button').addEventListener('click', function () {
        // Handle filters so the name is translated and empty values dont get send
        PropertyFiltersHandler.handleFilters(); // Send form as usual

        PropertyFiltersHandler.form.submit();
      });
      PropertyFiltersHandler.form.addEventListener('submit', function (e) {
        e.preventDefault();
        PropertyFiltersHandler.handleFilters();
        PropertyFiltersHandler.form.submit();
      }); // Define filters

      var location = PropertyFiltersHandler.form.querySelector('#location');
      var minimumPrice = PropertyFiltersHandler.form.querySelector('#minimum-price');
      var maximumPrice = PropertyFiltersHandler.form.querySelector('#maximum-price');
      if (isset(location)) PropertyFiltersHandler.filters.push(location);
      if (isset(minimumPrice)) PropertyFiltersHandler.filters.push(minimumPrice);
      if (isset(maximumPrice)) PropertyFiltersHandler.filters.push(maximumPrice);
    }
  },
  handleFilters: function handleFilters() {
    var filterLength = PropertyFiltersHandler.filters.length;

    for (var f = 0; f < filterLength; f++) {
      var filter = PropertyFiltersHandler.filters[f];
      var filterTranslation = filter.getAttribute('data-translation');

      if (filter.value === '') {
        // console.log('Remove ' + filterTranslation);
        filter.setAttribute('name', '');
      } else {
        filter.setAttribute('name', filterTranslation);
      }
    }
  }
};
PropertyFiltersHandler.init();
var PropertyImageHandler = {
  photoSlider: document.getElementById('photoslider'),
  propertyImagesWrapper: document.getElementById('property-image-wrapper'),
  propertySliderOpenLinks: null,
  images: null,
  gallery: null,
  options: {
    index: 0,
    // start at first slide
    history: false,
    focus: false,
    shareEl: false,
    tapToClose: true,
    closeOnScroll: false,
    showHideOpacity: true,
    bgOpacity: 0.85,
    showAnimationDuration: 0,
    hideAnimationDuration: 0
  },
  init: function init() {
    if (isset(PropertyImageHandler.photoSlider) && isset(PropertyImageHandler.propertyImagesWrapper)) {
      // Prepare the images
      var images = [];
      var imageCollection = PropertyImageHandler.propertyImagesWrapper.querySelectorAll('#images-for-slider span');

      if (isset(imageCollection)) {
        var imageAmount = imageCollection.length;

        if (imageAmount !== 0) {
          for (var i = 0; i < imageAmount; i++) {
            var image = imageCollection[i];
            images.push({
              src: image.getAttribute('data-src'),
              w: image.getAttribute('data-width'),
              h: image.getAttribute('data-height')
            });
          }
        }

        PropertyImageHandler.images = images;
      } // Bind click events to the open slider links


      PropertyImageHandler.propertySliderOpenLinks = PropertyImageHandler.propertyImagesWrapper.querySelectorAll('.open-photo-slider'); // Only continue if there are even images and links to the slider

      if (isset(PropertyImageHandler.images) && isset(PropertyImageHandler.propertySliderOpenLinks)) {
        // Add the event listeners to the links
        var amountOfLinks = PropertyImageHandler.propertySliderOpenLinks.length;

        for (var i = 0; i < amountOfLinks; i++) {
          var link = PropertyImageHandler.propertySliderOpenLinks[i];
          link.addEventListener('click', function () {
            PropertyImageHandler.openSliderOnIndex(this.getAttribute('data-index'));
          });
        }
      }
    }
  },
  openSliderOnIndex: function openSliderOnIndex(index) {
    PropertyImageHandler.options.index = parseInt(index); // console.log(index);
    // Initializes and opens PhotoSwipe

    PropertyImageHandler.gallery = new PhotoSwipe(PropertyImageHandler.photoSlider, PhotoSwipeUI_Default, PropertyImageHandler.images, PropertyImageHandler.options);
    PropertyImageHandler.gallery.init();
  }
};
PropertyImageHandler.init();
var PropertyTabsHandler = {
  propertyTabs: '',
  tabsListItems: '',
  tabsItems: '',

  /*
   * Initialize Property Filter Handling
   * If view has Property Filters Form add the event event listeners and add the filters
   */
  init: function init() {
    PropertyTabsHandler.propertyTabs = document.getElementById('property-tabs');

    if (isset(PropertyTabsHandler.propertyTabs)) {
      PropertyTabsHandler.tabsListItems = PropertyTabsHandler.propertyTabs.querySelectorAll('.tabs-nav li');
      PropertyTabsHandler.tabsItems = PropertyTabsHandler.propertyTabs.querySelectorAll('.tab-placeholder .tab');
      var tabsListItemsLength = PropertyTabsHandler.tabsListItems.length;

      for (var i = 0; i < tabsListItemsLength; i++) {
        PropertyTabsHandler.tabsListItems[i].addEventListener('click', function () {
          PropertyTabsHandler.setTab(this.getAttribute('data-tab'));
        });
      }

      document.querySelector('#main-property-text .read-more').addEventListener('click', function () {
        document.getElementById('main-property-text').classList.add('open');
      });
    }
  },
  setTab: function setTab(tabName) {
    // Set Tab List item
    var tabsListItemsLength = PropertyTabsHandler.tabsListItems.length;

    for (var i = 0; i < tabsListItemsLength; i++) {
      var loopTabListItem = PropertyTabsHandler.tabsListItems[i];

      if (loopTabListItem.getAttribute('data-tab') === tabName) {
        loopTabListItem.classList.add('active');
      } else {
        loopTabListItem.classList.remove('active');
      }
    } // Set Tab item


    var tabsItemsLength = PropertyTabsHandler.tabsItems.length;

    for (var j = 0; j < tabsItemsLength; j++) {
      var loopTabItem = PropertyTabsHandler.tabsItems[j];

      if (loopTabItem.getAttribute('data-tab') === tabName) {
        loopTabItem.classList.add('active');
      } else {
        loopTabItem.classList.remove('active');
      }
    }
  }
};
PropertyTabsHandler.init();
/* ==========================================================================
   Resize handler
 ========================================================================== */

/**
 * Handler the objects which are or need to be recalculated on resize
 */

var ResizeHandler = {
  time: Date.now(),
  timeout: null,
  waitThrottle: 1000,
  waitDebounce: 500,
  //Initialisation
  init: function init() {
    // Trigger start up resizes
    ResizeHandler.triggerOnInit(); // Throttle Resize

    window.addEventListener('resize', function () {
      if (ResizeHandler.time + ResizeHandler.waitThrottle - Date.now() < 0) {
        ResizeHandler.triggerThrottle();
        ResizeHandler.time = Date.now();
      }
    }); // Smooth Resize

    window.addEventListener('resize', function () {
      ResizeHandler.triggerSmooth();
    }); // Debounce Resize

    window.addEventListener('resize', function () {
      if (isset(ResizeHandler.timeout)) clearTimeout(ResizeHandler.timeout);
      ResizeHandler.timeout = setTimeout(ResizeHandler.triggerDebounce, ResizeHandler.waitDebounce);
    });
  },
  // Trigger on start up
  // All function should be in here
  triggerOnInit: function triggerOnInit() {
    ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
  },
  // Trigger resize functions with throttle (preferred)
  triggerThrottle: function triggerThrottle() {// console.log('Throttled Resize');
  },
  // Trigger resize on debounce
  triggerDebounce: function triggerDebounce() {
    // console.log('Debounce Resize');
    ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
  },
  // Trigger resize on the flight
  triggerSmooth: function triggerSmooth() {// console.log('Smooth Resize');
  },
  resizeWhatDoesItCostAdvantageFigure: function resizeWhatDoesItCostAdvantageFigure() {
    var el = document.querySelector('.advantages-own-guiding-row figure');

    if (isset(el)) {
      el.style.maxHeight = 'none';
      el.style.maxHeight = el.offsetHeight + 'px';
    }
  }
};
ResizeHandler.init();
/* ==========================================================================
   Scroll handler
 ========================================================================== */

/**
 * Handler the objects which are bind on scroll events or visible in viewport
 */

var ScrollHandler = {
  // Variables for debounce and throttle effects
  time: Date.now(),
  timeout: null,
  waitThrottle: 1000,
  waitDebounce: 300,
  // Variables for scroll direction
  lastScrollTopPosition: 0,
  scrollDirectionDown: true,
  scrollDirectionUp: false,
  //Initialisation
  init: function init() {
    // Trigger start on start up
    ScrollHandler.triggerOnInit(); // Throttle scroll

    window.addEventListener('scroll', function () {
      if (ScrollHandler.time + ScrollHandler.waitThrottle - Date.now() < 0) {
        ScrollHandler.triggerThrottle();
        ScrollHandler.time = Date.now();
      }
    }); // Smooth scroll

    window.addEventListener('scroll', function () {
      ScrollHandler.triggerSmooth();
    }); // Debounce scroll

    window.addEventListener('scroll', function () {
      if (isset(ScrollHandler.timeout)) clearTimeout(ScrollHandler.timeout);
      ScrollHandler.timeout = setTimeout(ScrollHandler.triggerDebounce, ScrollHandler.waitDebounce);
    });
  },
  // Trigger on start up
  triggerOnInit: function triggerOnInit() {
    ScrollHandler.triggerElementInViewportAnimation();
  },
  // Trigger scroll functions with throttle (preferred)
  triggerThrottle: function triggerThrottle() {
    // console.log('Throttled scroll');
    ScrollHandler.triggerElementInViewportAnimation();
  },
  // Trigger scroll on debounce
  triggerDebounce: function triggerDebounce() {// console.log('Debounce scroll');
  },
  // Trigger scroll on the flight
  triggerSmooth: function triggerSmooth() {
    // console.log('Smooth scroll');
    ScrollHandler.detectScrollDirection();
    ScrollHandler.toggleStickyNavigation();
  },
  // Detect if part of a given element is visible in the viewport
  // El must be a node element
  detectIfElementIsPartlyInViewport: function detectIfElementIsPartlyInViewport(el) {
    if (isset(el)) {
      var rect = el.getBoundingClientRect(); // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }

      var windowHeight = window.innerHeight || document.documentElement.clientHeight;
      var windowWidth = window.innerWidth || document.documentElement.clientWidth;
      var vertInView = rect.top <= windowHeight && rect.top + rect.height >= 0;
      var horInView = rect.left <= windowWidth && rect.left + rect.width >= 0;
      return vertInView && horInView;
    }
  },
  // Detect if a given element is fully visible in the viewport
  // El must be a node element
  detectIfElementIsFullyInViewport: function detectIfElementIsFullyInViewport(el) {
    if (isset(el)) {
      var rect = el.getBoundingClientRect();
      return rect.top >= 0 && rect.bottom <= window.innerHeight;
    }
  },
  detectScrollDirection: function detectScrollDirection() {
    var scrollTopPosition = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"

    if (scrollTopPosition >= ScrollHandler.lastScrollTopPosition) {
      ScrollHandler.scrollDirectionDown = true;
      ScrollHandler.scrollDirectionUp = false;
    } else {
      ScrollHandler.scrollDirectionDown = false;
      ScrollHandler.scrollDirectionUp = true;
    }

    ScrollHandler.lastScrollTopPosition = scrollTopPosition;
  },
  // Trigger animation on elements that have 'element-in-viewport' and that are in the viewport
  // These animation can only be triggered once, if you want more then that you should write an specific function for this
  triggerElementInViewportAnimation: function triggerElementInViewportAnimation() {
    var elements = document.querySelectorAll('.element-in-viewport');
    var elementsLength = elements.length;

    for (var e = 0; e < elementsLength; e++) {
      var element = elements[e];

      if (ScrollHandler.detectIfElementIsPartlyInViewport(element)) {
        element.classList.remove('element-in-viewport');
      }
    }
  },
  // ------------------------------ CUSTOM SCROLL HANDLERS ------------------------------------
  // Hide or show sticky navigation when header isn't visible
  toggleStickyNavigation: function toggleStickyNavigation() {
    var mainNavigation = document.querySelector('body >header');
    var stickyNavigation = document.getElementById('sticky-navigation');

    if (isset(stickyNavigation) && isset(mainNavigation)) {
      // Show sticky navigation
      if (!ScrollHandler.detectIfElementIsFullyInViewport(mainNavigation) && ScrollHandler.scrollDirectionUp) {
        stickyNavigation.classList.add('active');
      } // Hide sticky navigation


      if (ScrollHandler.scrollDirectionDown || ScrollHandler.detectIfElementIsPartlyInViewport(mainNavigation)) {
        stickyNavigation.classList.remove('active');
      }
    }
  }
};
ScrollHandler.init();
/* ==========================================================================
    Scroll To Click handler
 ========================================================================== */

var ScrollToHandler = {
  init: function init() {
    $('.scroll-to-target').bind('click', function () {
      ScrollToHandler.scrollToTarget($(this));
      return false;
    });
  },

  /**
   * Handles click on the mouse with the arrow
   *
   * @param el
   */
  scrollToTarget: function scrollToTarget(el) {
    var scrollTo = el.prop('href');
    scrollTo = scrollTo.substr(scrollTo.indexOf('#') + 1);
    ScrollToHandler.scrollToElement(scrollTo);
  },
  scrollToElement: function scrollToElement(id, offset, time) {
    offset = isset(offset) ? offset : 60;
    time = isset(time) ? time : 800;
    var body = $('html,body');
    body.animate({
      scrollTop: $('#' + id).offset().top - offset
    }, time);
    body.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function () {
      body.stop();
    });
  }
};
ScrollToHandler.init();
/* ==========================================================================
 Navigation handler
 ========================================================================== */

/**
 * Main navigation
 */

var Services = {
  items: [],
  amount: 0,
  // Initialize click event
  init: function init() {
    // Bind Navigation to Handler
    Services.items = document.querySelectorAll('.what-does-it-cost-services .group-overview article');
    Services.amount = Services.items.length;

    if (Services.amount > 0) {
      for (var i = 0; i < Services.amount; i++) {
        Services.items[i].addEventListener('click', function () {
          Services.toggle(this);
        });
      }
    }
  },
  // Toggle faq
  toggle: function toggle(service) {
    // Determine if currently open or closed
    var _boolean2 = true;
    var description = service.querySelector('.description');
    var descriptionContent = service.querySelector('.description .inner-content');

    if (service.getAttribute('data-open') === 'true') {
      _boolean2 = false;
      description.style.maxHeight = 0;
    } else {
      description.style.maxHeight = descriptionContent.offsetHeight + 'px';
    }

    service.setAttribute('data-open', _boolean2);
  }
};
Services.init();
/**
 * Created by Pascal on 06/12/17.
 */

/*

HTML Example
<script src="/js/slider.js"></script>
<script>

    var imageSliderSetting = new SliderSetting({
        sliderId: 'image-slider',
        slideQuery: '#image-slider .placeholder figure',
        slideContentQuery: 'span',
        definedPreviousNext: true,
        navigationButtons: '#image-slider .placeholder .controllers .nav-item',
        dots: '#image-slider .placeholder .controllers .dots',
        autoSlider: true,
        sliderInterval: 4000
    });
    imageSliderSetting = imageSliderSetting.prepareParameters();

    var imageSlider = new Slider(imageSliderSetting);

</script>

 */

function SliderSetting(settingsObject) {
  var self = this;
  this.sliderId = '';
  this.definedPreviousNext = true;
  this.autoSlider = false;
  this.sliderInterval = 4000;
  this.navigationButtons = '';
  this.dots = '';
  this.slideQuery = '';
  this.slideContentQuery = '';

  this.setSliderId = function ($string) {
    this.sliderId = $string;
    return this;
  };

  this.setDefinedPreviousNext = function ($boolean) {
    this.definedPreviousNext = $boolean;
    return this;
  };

  this.setAutoSlider = function ($boolean) {
    this.autoSlider = $boolean;
    return this;
  };

  this.setSliderInterval = function ($integer) {
    this.sliderInterval = $integer;
    return this;
  };

  this.setSlideQuery = function ($string) {
    this.slideQuery = $string;
    return this;
  };

  this.setNavigationButtons = function ($string) {
    this.navigationButtons = $string;
    return this;
  };

  this.setDots = function ($string) {
    this.dots = $string;
    return this;
  };

  this.getSliderId = function () {
    return this.sliderId;
  };

  this.getDefinedPreviousNext = function () {
    return this.definedPreviousNext;
  };

  this.getAutoSlider = function () {
    return this.autoSlider;
  };

  this.getSliderInterval = function () {
    return this.sliderInterval;
  };

  this.getSlideQuery = function () {
    return this.slideQuery;
  };

  this.getNavigationButtons = function () {
    return this.navigationButtons;
  };

  this.getDots = function () {
    return this.dots;
  }; // Invert setters to getters


  this.prepareParameters = function () {
    return {
      sliderId: self.getSliderId(),
      definedPreviousNext: self.getDefinedPreviousNext(),
      autoSlider: self.getAutoSlider(),
      sliderInterval: self.getSliderInterval(),
      navigationButtons: self.getNavigationButtons(),
      dots: self.getDots(),
      slideQuery: self.getSlideQuery()
    };
  }; // Mass assign settings


  this.fill = function () {
    // Object.keys(settingsObject).forEach(function (key) {
    //     self[key] = settingsObject[key];
    // });
    var settingsObjectKeys = Object.keys(settingsObject);
    var settingsObjectLength = settingsObjectKeys.length;

    for (var i = 0; i < settingsObjectLength; i++) {
      var key = settingsObjectKeys[i];
      self[key] = settingsObject[key];
    }
  };

  this.fill();
  return {
    sliderId: self.setSliderId,
    definedPreviousNext: self.setDefinedPreviousNext,
    autoSlider: self.setAutoSlider,
    sliderInterval: self.setSliderInterval,
    navigationButtons: self.setNavigationButtons,
    dots: self.setDots,
    slideQuery: self.setSlideQuery,
    prepareParameters: self.prepareParameters
  };
}

function Slider(settings) {
  //Define Slider object
  var self = this;
  this.sliderObject = ''; //SlideParameters

  this.activeSlideId = 0;
  this.previousSlideId = 0;
  this.nextSlideId = 0;
  this.availableSlides = 1;
  this.slides = [];
  this.autoSliderInterval = null;
  this.settings = {};

  this.init = function () {
    //Append settings to self
    this.settings = settings; //Assign needed elements and calculations

    this.sliderObject = document.getElementById(this.settings.sliderId);
    this.slides = document.querySelectorAll(this.settings.slideQuery);
    this.availableSlides = this.slides.length;
    this.activeSlideId = 0; //Define previous and next if we want to use those

    if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide(); // Set active slide (and possible previous and next classes)

    this.setSlide(); // Swipe interaction

    $(this.sliderObject).swipe({
      swipeLeft: function swipeLeft() {
        self.resetAutoSlider();
        self.nextSlide();
        self.setSlide();
      },
      swipeRight: function swipeRight() {
        self.resetAutoSlider();
        self.previousSlide();
        self.setSlide();
      }
    });

    if (this.settings.navigationButtons != '') {
      // Click interaction
      var navigationButtons = document.querySelectorAll(this.settings.navigationButtons);
      var navigationButtonsLength = navigationButtons.length;

      for (var i = 0; i < navigationButtonsLength; i++) {
        var navigationButton = navigationButtons[i];
        navigationButton.addEventListener('click', function () {
          self.clickNavigationButton(this);
        });
      }
    }

    if (this.settings.dots != '') {
      // Click interaction
      var dots = document.querySelectorAll(this.settings.dots);
      var dotsLength = dots.length;

      for (var i = 0; i < dotsLength; i++) {
        var dot = dots[i];
        dot.addEventListener('click', function () {
          self.clickDot(this);
        });
      }
    } // Define resize


    $(window).resize($.throttle(20, self.resizeSlider));
    self.resizeSlider();
    self.autoSlider();
    setTimeout(self.resizeSlider(), 500);
  };

  this.autoSlider = function () {
    if (this.autoSliderInterval !== null) clearInterval(this.autoSliderInterval);

    if (this.settings.autoSlider && Number.isInteger(this.settings.sliderInterval)) {
      this.autoSliderInterval = setInterval(function () {
        self.nextSlide();
        self.setSlide();
      }, this.settings.sliderInterval);
    }
  };

  this.resetAutoSlider = self.autoSlider;

  this.nextSlide = function () {
    this.activeSlideId++;
    if (this.activeSlideId >= this.availableSlides) this.activeSlideId = 0;
    if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
  };

  this.previousSlide = function () {
    this.activeSlideId--;
    if (this.activeSlideId < 0) this.activeSlideId = this.availableSlides - 1;
    if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
  };

  this.setPreviousAndNextSlide = function () {
    this.nextSlideId = this.activeSlideId + 1;
    if (this.nextSlideId >= this.availableSlides) this.nextSlideId = 0;
    this.previousSlideId = this.activeSlideId - 1;
    if (this.previousSlideId < 0) this.previousSlideId = this.availableSlides - 1;
  };

  this.setSlide = function () {
    // Loop through the form elements
    var slidesLength = self.slides.length;

    for (var i = 0; i < slidesLength; i++) {
      var slide = self.slides[i]; // Convert dataset attribute to desired type

      var slideOrder = parseInt(slide.dataset.order); // Remove and set active for all slides

      if (slideOrder !== self.activeSlideId) slide.classList.remove('active');else slide.classList.add('active'); // If we use the previous and next, also set those classes

      if (self.settings.definedPreviousNext) {
        if (slideOrder !== self.previousSlideId) slide.classList.remove('previous');else slide.classList.add('previous');
        if (slideOrder !== self.nextSlideId) slide.classList.remove('next');else slide.classList.add('next');
      }
    }

    if (self.settings.dots != '') {
      self.setActiveDot();
    }
  };

  this.clickNavigationButton = function (navButton) {
    self.activeSlideId = parseInt(navButton.dataset.order);
    if (self.settings.definedPreviousNext) self.setPreviousAndNextSlide();
    self.setSlide();
    var next = document.querySelector(self.settings.navigationButtons + '.next');
    var previous = document.querySelector(self.settings.navigationButtons + '.previous');
    next.dataset.order = self.nextSlideId;
    previous.dataset.order = self.previousSlideId;
    self.resetAutoSlider(); // next.querySelector('p').innerHTML = self.slides[self.nextSlideId].dataset.name;
    // previous.querySelector('p').innerHTML = self.slides[self.previousSlideId].dataset.name;
  };

  this.clickDot = function (clickedDot) {
    self.activeSlideId = parseInt(clickedDot.dataset.order);
    self.setSlide();
    self.resetAutoSlider();
  };

  this.setActiveDot = function () {
    var dots = document.querySelectorAll(this.settings.dots);
    var dotsLength = dots.length;

    for (var i = 0; i < dotsLength; i++) {
      var dot = dots[i];
      dotOrder = parseInt(dot.dataset.order);
      if (dotOrder !== self.activeSlideId) dot.classList.remove('active');else dot.classList.add('active');
    }
  };

  this.resizeSlider = function () {// console.log('hier');
  }; // this.init();

}

var SpecialCharacterHandler = {
  init: function init() {
    var titles = document.querySelectorAll('h1, h2, h3, h4, h5');
    var titlesLength = titles.length;

    for (var i = 0; i < titlesLength; i++) {
      var title = titles[i];
      titleContent = title.innerHTML;
      titleContent = titleContent.replace(/€/g, '<span class="euro-sign">€</span>');
      title.innerHTML = titleContent;
    }
  }
};
SpecialCharacterHandler.init();
/* ==========================================================================
 Navigation handler
 ========================================================================== */

/**
 * Main navigation
 */

var StartSaleFormHandler = {
  form: [],
  sellerOtherAddressToSell: '',
  sellerOtherAddressToSellArea: '',
  submitButton: '',
  // Initialize click event
  init: function init() {
    // Bind Start Sale Form to Handler
    StartSaleFormHandler.form = document.getElementById('startSaleForm');

    if (isset(StartSaleFormHandler.form)) {
      // Get bind element for other selling address to the handler
      StartSaleFormHandler.sellerOtherAddressToSell = document.getElementById('sellerOtherAddressToSell');
      StartSaleFormHandler.sellerOtherAddressToSellArea = document.querySelector('#startSaleForm .other-selling-address'); // Bind change event of the other address for selling checkbox

      StartSaleFormHandler.sellerOtherAddressToSell.addEventListener('change', function () {
        StartSaleFormHandler.toggleOtherSellingAddressArea();
      }); // Bind click on submit p element

      StartSaleFormHandler.submitButton = document.querySelector('#startSaleForm .submit p');
      StartSaleFormHandler.submitButton.addEventListener('click', function () {
        StartSaleFormHandler.form.submit();
      });
    }
  },
  // Toggle faq
  toggleOtherSellingAddressArea: function toggleOtherSellingAddressArea() {
    // Determine if currently open or closed
    var _boolean3 = true;

    if (StartSaleFormHandler.sellerOtherAddressToSellArea.getAttribute('data-open') === 'true') {
      _boolean3 = false;
    }

    StartSaleFormHandler.sellerOtherAddressToSellArea.setAttribute('data-open', _boolean3);
  }
};
StartSaleFormHandler.init();
var TipsHandler = {
  tipDescriptionRow: '',
  tipGroupDescriptions: '',
  tipSelectors: '',
  tipListRow: '',
  tipLists: '',
  tipActiveSlug: '',

  /*
   * Initialize Property Filter Handling
   * If view has Property Filters Form add the event event listeners and add the filters
   */
  init: function init() {
    TipsHandler.tipDescriptionRow = document.getElementById('tips-description-row');
    TipsHandler.tipListRow = document.getElementById('tip-lists-row');

    if (isset(TipsHandler.tipDescriptionRow) && isset(TipsHandler.tipListRow)) {
      TipsHandler.tipSelectors = TipsHandler.tipDescriptionRow.querySelectorAll('.tip-group-selector ul li');
      TipsHandler.tipGroupDescriptions = TipsHandler.tipDescriptionRow.querySelectorAll('.tip-group-descriptions .tip-group-description');
      TipsHandler.tipLists = TipsHandler.tipListRow.querySelectorAll('.tip-list');
      var tipSelectorsLength = TipsHandler.tipSelectors.length;

      for (var i = 0; i < tipSelectorsLength; i++) {
        TipsHandler.tipSelectors[i].addEventListener('click', function () {
          TipsHandler.tipActiveSlug = this.getAttribute('data-slug');
          TipsHandler.setTipGroup(this.getAttribute('data-tips-group'));
        });
      }
    }
  },
  setTipGroup: function setTipGroup(tipGroup) {
    var tipSelectorsLength = TipsHandler.tipSelectors.length;

    for (var t = 0; t < tipSelectorsLength; t++) {
      var loopTipSelector = TipsHandler.tipSelectors[t];
      if (loopTipSelector.getAttribute('data-tips-group') === tipGroup) loopTipSelector.classList.add('active');else loopTipSelector.classList.remove('active');
    } // Set tip group description


    var tipGroupDescriptionsLength = TipsHandler.tipGroupDescriptions.length;

    for (var i = 0; i < tipGroupDescriptionsLength; i++) {
      var loopTipGroup = TipsHandler.tipGroupDescriptions[i];
      if (loopTipGroup.getAttribute('data-tips-group') === tipGroup) loopTipGroup.classList.add('active');else loopTipGroup.classList.remove('active');
    } // Set tip list


    var tipListsLength = TipsHandler.tipLists.length;

    for (var j = 0; j < tipListsLength; j++) {
      var loopTipList = TipsHandler.tipLists[j];
      if (loopTipList.getAttribute('data-tips-group') === tipGroup) loopTipList.classList.add('active');else loopTipList.classList.remove('active');
    }

    var newUrl = updateQueryString('tip', TipsHandler.tipActiveSlug, null); // window.location.href = newUrl;

    window.history.pushState("", "", newUrl); // console.log(newUrl);
  }
};
TipsHandler.init();
/* ==========================================================================
    Youtube handler
 ========================================================================== */

var YoutubeHandler = {
  elementId: '',
  youtubeId: '',

  /**
   * 
   */
  init: function init() {
    YoutubeHandler.elementId = 'ytplayer'; // YoutubeHandler.youtubeId = 'L1SzPfYkeF4'; //Komma sfeerimpressie video

    YoutubeHandler.youtubeId = 'X-dMOvEOQiM'; //Blue motion video

    YoutubeHandler.playVideo();
  },

  /**
   * Check if external script is loaded
   * 
   */
  playVideo: function playVideo() {
    // See if YT variable exists
    if (typeof YT == 'undefined' || typeof YT.Player == 'undefined') {
      // Setup API ready function
      window.onYouTubePlayerAPIReady = function () {
        YoutubeHandler.loadPlayer();
      }; // Load external script


      $.getScript('https://www.youtube.com/iframe_api'); // If YT already exists load player
    } else {
      YoutubeHandler.loadPlayer();
    }
  },

  /**
   * Load Youtube player with parameters
   *
   */
  loadPlayer: function loadPlayer() {
    // Load player
    window.player = new YT.Player(YoutubeHandler.elementId, {
      height: 200,
      width: 200,
      videoId: YoutubeHandler.youtubeId,
      playerVars: {
        modestbranding: 0,
        showinfo: 0,
        rel: 0,
        controls: 0,
        disablekb: 1
      },
      events: {
        'onReady': YoutubeHandler.onReady,
        'onStateChange': YoutubeHandler.onStateChange
      }
    });
  },

  /**
   * When player is ready to play
   */
  onReady: function onReady() {
    // Show video
    setTimeout(function () {
      $('#' + YoutubeHandler.elementId).stop().animate({
        opacity: 1
      }, 1000);
    }, 800); // If not on tablet or mobile, play on high quality

    window.player.mute();
    window.player.playVideo();
    window.player.setPlaybackQuality('hd1080');
  },

  /**
   * Listener for Youtube state change
   *
   * @param state
   */
  onStateChange: function onStateChange(state) {
    // Loop video
    if (state.data === YT.PlayerState.ENDED) {
      window.player.playVideo();
    }
  }
};