(function() {
  const SearchUrl = "http://fvdspeeddial.com/fst/booking-search.php";
  //const SearchUrl = "http://localhost/fvdsd-tools/booking-search.php";

  var monthNames = [];
  for(let i = 0; i != 12; i++) {
    monthNames.push(window.__("month_" + i));
  }
  var daysOfWeek = [];
  var daysOfWeekShort = [];
  for(let i = 0; i != 7; i++) {
    daysOfWeek.push(window.__("dow_" + i));
    daysOfWeekShort.push(window.__("dow_short_" + i));
  }

  var userTouched = false;

  window.getExtraHeight = function() {
    var extraHeight = 0;
    var children = document.getElementById("children").value;
    if(children > 0) {
      extraHeight += 50;
    }
    if(children > 5) {
      extraHeight += 20;
    }
    return extraHeight;
  };

  window.arrowVerticalCorrect = function(value, viewportHeight) {
    var arrowAfter = document.querySelector(".booking-search-widget .arrow-after");
    var arrowBefore = document.querySelector(".booking-search-widget .arrow-before");
    var widgetHeight = document.querySelector(".booking-search-widget").clientHeight;
    var maxUpperMargin = Math.round(widgetHeight/2) - 10;
    var maxLowerMargin = Math.round(widgetHeight/2) - 30;
    value -= 10;
    if(value < -maxUpperMargin) {
      value = -maxUpperMargin;
    }
    else if(value > maxLowerMargin) {
      value = maxLowerMargin;
    }
    arrowAfter.style.marginTop = (value) + "px";
    arrowBefore.style.marginTop = (-1 + value) + "px";
  };

  window.setArrowPosition = function(position) {
    var widget = document.querySelector("body");
    widget.classList.remove("arrow-left");
    widget.classList.remove("arrow-right");
    widget.classList.add("arrow-" + position);
  };

  window.getArrowPosition = function() {
    var body = document.querySelector("body");
    if(body.classList.contains("arrow-left")) {
      return "left";
    }
    if(body.classList.contains("arrow-right")) {
      return "right";
    }
  };

  window.allowCloseOnMouseOut = function() {
    return !userTouched;
  };

  window.debounce = function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  };

  function setUserTouched() {
    if(window.ignoreUserTouch) {
      return;
    }
    userTouched = true;
  }

  function fireResizeEvent() {
    var e = new CustomEvent("widget-resize", {
      bubbles: true
    });
    document.querySelector(".booking-search-widget").dispatchEvent(e);
  }

  document.addEventListener("DOMContentLoaded", function() {
    var now = new Date();
    var maxDate = new Date(now.getTime() + 24 * 3600 * 365 * 1000);
    var suggestionsXHR;
    const cityInput = document.querySelector("#booking-search-widget-destination");
    const Suggestions = window.Suggestions;
    const widget = document.querySelector(".booking-search-widget");

    function onMouseOverAfterPickerClosed() {
      widget.removeEventListener("mouseover", onMouseOverAfterPickerClosed, false);
      window.externalInterface.emitEvent("onpickerhide");
    }

    function onPickerClose() {
      // if any picker is visible, ignore the event
      if(pickerCheckIn.isVisible() || pickerCheckOut.isVisible()) {
        return;
      }
      if(window.externalInterface) {
        console.log("set listener");
        // let user move cursor back to the widget main div and then emit event
        widget.addEventListener("mouseover", onMouseOverAfterPickerClosed, false);
      }
    }

    function onPickerOpen(type) {
      var picker = type == "checkin" ? pickerCheckIn : pickerCheckOut;
      if(window.externalInterface) {
        console.log("remove listener");
        widget.removeEventListener("mouseover", onMouseOverAfterPickerClosed, false);
        console.log("Send open")
        window.externalInterface.emitEvent("onpickershow");
      }
    }

    function buildPikaHead(pika, text) {
      if(!pika.el.querySelector(".pika-head")) {
        var head = document.createElement("div");
        var closeButton = document.createElement("div");
        closeButton.classList.add("pika-close");
        var closeButtonInner = document.createElement("div");
        closeButtonInner.textContent = "×";
        closeButton.appendChild(closeButtonInner);
        closeButton.addEventListener("click", function() {
          pika.hide();
        }, false);

        head.classList.add("pika-head");
        head.textContent = text;
        head.appendChild(closeButton);
        pika.el.insertBefore(head, pika.el.firstChild);
      }
      if(!pika.el.querySelector(".pika-foot") && getCheckoutParts() && getCheckinParts()) {
        var foot = document.createElement("div");
        foot.classList.add("pika-foot");
        var br = document.createElement("br");
        br.setAttribute("clear", "both");
        pika.el.appendChild(br);
        pika.el.appendChild(foot);
      }
    }

    function getCheckoutParts() {
      var checkout = document.getElementById('booking-datepicker-out').value;
      if(!checkout) {
        return null;
      }
      var checkoutDate = new Date(checkout);
      var checkoutYear = checkoutDate.getFullYear();
      var checkoutMonth = checkoutDate.getMonth();
      var checkoutDay = checkoutDate.getDate();
      return {
        year: checkoutYear,
        month: checkoutMonth,
        day: checkoutDay
      };
    }

    function getCheckinParts() {
      var checkout = document.getElementById('booking-datepicker-in').value;
      if(!checkout) {
        return null;
      }
      var checkoutDate = new Date(checkout);
      var checkoutYear = checkoutDate.getFullYear();
      var checkoutMonth = checkoutDate.getMonth();
      var checkoutDay = checkoutDate.getDate();
      return {
        year: checkoutYear,
        month: checkoutMonth,
        day: checkoutDay
      };
    }

    function getPickaParts(el) {
      return {
        year: parseInt(el.getAttribute("data-pika-year")),
        month: parseInt(el.getAttribute("data-pika-month")),
        day: parseInt(el.getAttribute("data-pika-day"))
      };
    }

    function twoDigits(d) {
      d = d.toString();
      if(d.length === 1) {
        d = "0" + d;
      }
      return d;
    }

    function compareParts(parts1, parts2) {
      var d1 = parts1.year + "-" + twoDigits(parts1.month) + "-" + twoDigits(parts1.day);
      var d2 = parts2.year + "-" + twoDigits(parts2.month) + "-" + twoDigits(parts2.day);
      if(d1 > d2) {
        return 1;
      }
      if(d1 < d2) {
        return -1;
      }
      return 0;
    }

    function partsToJsDate(parts) {
      return new Date(parts.year, parts.month, parts.day);
    }

    function getNextDayParts(parts) {
      var d = partsToJsDate(parts);
      var nd = new Date(d.getTime() + 24 * 3600 * 1000);
      return {
        year: nd.getFullYear(),
        month: nd.getMonth(),
        day: nd.getDate()
      };
    }

    function getPrevDayParts(parts) {
      var d = new Date(parts.year, parts.month, parts.day);
      var nd = new Date(d.getTime() - 24 * 3600 * 1000);
      return {
        year: nd.getFullYear(),
        month: nd.getMonth(),
        day: nd.getDate()
      };
    }

    function getPartsDaySelector(parts) {
      var selector = [
        '[data-pika-year=\"' + parts.year + '\"]',
        '[data-pika-month=\"' + parts.month + '\"]',
        '[data-pika-day=\"' + parts.day + '\"]',
      ];
      return selector.join("");
    }

    function addStayInfoInPicker(pika, checkin, checkout) {
      if(pika.el.querySelector(".pika-foot")) {
        var checkinStr = getHumanReadableDate(checkin, true);
        var checkoutStr = getHumanReadableDate(checkout, true);
        var footTextContainer = pika.el.querySelector(".pika-foot");
        var nights = countNights(checkin, checkout);
        var footText =
          _("from") + ' <strong>' + checkinStr + '</strong> ' + _("to") + ' <strong>' + checkoutStr + '</strong> ' +
          nights + _("night_stay");
        footTextContainer.innerHTML = footText;
      }
    }

    function checkinMouseOverListener(event) {
      var target = event.target;
      if(target.matches(".pika-button.pika-day")) {
        var checkout = getCheckoutParts();
        if(checkout) {
          // need to highlight period if hovered date is less than checkout date
          var parts = getPickaParts(target);
          if(compareParts(parts, checkout) < 0) {
            // remove other period startings if exist
            var periodStartings = pickerCheckIn.el.querySelectorAll(".pika-period-start");
            for(let periodStarting of periodStartings) {
              periodStarting.classList.remove("pika-period-start");
            }
            var periodMiddles = pickerCheckIn.el.querySelectorAll(".pika-period-middle");
            for(let periodMiddle of periodMiddles) {
              periodMiddle.classList.remove("pika-period-middle");
            }
            target.parentNode.classList.add("pika-period-start");
            var middleParts = parts;
            middleParts = getNextDayParts(middleParts);
            while(compareParts(middleParts, checkout) < 0) {
              var dayEl = pickerCheckIn.el.querySelector(getPartsDaySelector(middleParts));
              if(dayEl) {
                dayEl.parentNode.classList.add("pika-period-middle");
              }
              middleParts = getNextDayParts(middleParts);
            }
            addStayInfoInPicker(pickerCheckIn, parts, checkout);
          }
        }
      }
    }

    function checkinMouseOutListener() {
      // cleanup period first
      var periodStartings = pickerCheckIn.el.querySelectorAll(".pika-period-start");
      for(let periodStarting of periodStartings) {
        periodStarting.classList.remove("pika-period-start");
      }
      var periodMiddles = pickerCheckIn.el.querySelectorAll(".pika-period-middle");
      for(let periodMiddle of periodMiddles) {
        periodMiddle.classList.remove("pika-period-middle");
      }
      var checkin = getCheckinParts();
      var checkout = getCheckoutParts();
      if(checkin && checkout) {
        var pikaDay = pickerCheckIn.el.querySelector(getPartsDaySelector(checkin));
        if(pikaDay) {
          pikaDay.parentNode.classList.add("pika-period-start");
        }
        var middleParts = checkin;
        middleParts = getNextDayParts(middleParts);
        while(compareParts(middleParts, checkout) < 0) {
          var dayEl = pickerCheckIn.el.querySelector(getPartsDaySelector(middleParts));
          if(dayEl) {
            dayEl.parentNode.classList.add("pika-period-middle");
          }
          middleParts = getNextDayParts(middleParts);
        }
        addStayInfoInPicker(pickerCheckIn, checkin, checkout);
      }
    }

    function checkoutMouseOverListener(event) {
      var target = event.target;
      if(target.matches(".pika-button.pika-day")) {
        var checkin = getCheckinParts();
        if(checkin) {
          // need to highlight period if hovered date is greater than checkin date
          var parts = getPickaParts(target);
          if(compareParts(parts, checkin) > 0) {
            // remove other period endings if exist
            var periodEndings = pickerCheckOut.el.querySelectorAll(".pika-period-end");
            for(let periodEnding of periodEndings) {
              periodEnding.classList.remove("pika-period-end");
            }
            var periodMiddles = pickerCheckOut.el.querySelectorAll(".pika-period-middle");
            for(let periodMiddle of periodMiddles) {
              periodMiddle.classList.remove("pika-period-middle");
            }
            target.parentNode.classList.add("pika-period-end");
            var middleParts = checkin;
            middleParts = getNextDayParts(middleParts);
            while(compareParts(middleParts, parts) < 0) {
              var dayEl = pickerCheckOut.el.querySelector(getPartsDaySelector(middleParts));
              if(dayEl) {
                dayEl.parentNode.classList.add("pika-period-middle");
              }
              middleParts = getNextDayParts(middleParts);
            }
            addStayInfoInPicker(pickerCheckOut, checkin, parts);
          }
        }
      }
    }

    function checkoutMouseOutListener() {
      // cleanup period first
      var periodEndings = pickerCheckOut.el.querySelectorAll(".pika-period-end");
      for(let periodEnding of periodEndings) {
        periodEnding.classList.remove("pika-period-end");
      }
      var periodMiddles = pickerCheckOut.el.querySelectorAll(".pika-period-middle");
      for(let periodMiddle of periodMiddles) {
        periodMiddle.classList.remove("pika-period-middle");
      }
      var checkin = getCheckinParts();
      var checkout = getCheckoutParts();
      if(checkin && checkout) {
        var pikaDay = pickerCheckOut.el.querySelector(getPartsDaySelector(checkout));
        if(pikaDay) {
          pikaDay.parentNode.classList.add("pika-period-end");
        }
        var middleParts = checkin;
        middleParts = getNextDayParts(middleParts);
        while(compareParts(middleParts, checkout) < 0) {
          var dayEl = pickerCheckOut.el.querySelector(getPartsDaySelector(middleParts));
          if(dayEl) {
            dayEl.parentNode.classList.add("pika-period-middle");
          }
          middleParts = getNextDayParts(middleParts);
        }
        addStayInfoInPicker(pickerCheckOut, checkin, checkout);
      }
    }

    function jsDate(date) {
      if(!(date instanceof Date)) {
        date = partsToJsDate(date);
      }
      return date;
    }

    function countNights(checkinDate, checkoutDate) {
      checkinDate = jsDate(checkinDate);
      checkoutDate = jsDate(checkoutDate);
      return Math.floor((checkoutDate.getTime() - checkinDate.getTime())/(24 * 3600 * 1000));
    }

    function refreshDatesVisible() {
      var checkinFieldValue = document.getElementById("booking-datepicker-in").value;
      var checkoutFieldValue = document.getElementById("booking-datepicker-out").value;
      var checkinDate = pickerCheckIn.getDate();
      var checkoutDate = pickerCheckOut.getDate();
      var checkinSet = checkinDate && checkinFieldValue;
      var checkoutSet = checkoutDate && checkoutFieldValue;
      var checkoutTextContainer = document.querySelector(".booking-search-widget-check-out-container .input-text");
      var checkinTextContainer = document.querySelector(".booking-search-widget-check-in-container .input-text");
      if(checkinSet) {
        checkinTextContainer.textContent = getHumanReadableDate(checkinDate);
        checkinTextContainer.classList.add("active");
        document.querySelector(".booking-search-widget-check-in-container .calendar-small span").textContent
          = checkinDate.getDate();
      }
      else {
        checkinTextContainer.classList.remove("active");
        checkinTextContainer.textContent = _("checkin_date");
      }
      if(checkoutSet) {
        checkoutTextContainer.textContent = getHumanReadableDate(checkoutDate);
        checkoutTextContainer.classList.add("active");
        document.querySelector(".booking-search-widget-check-out-container .calendar-small span").textContent
          = checkoutDate.getDate();
      }
      else {
        checkoutTextContainer.classList.remove("active");
        checkoutTextContainer.textContent = _("checkout_date");
      }
      if(checkinSet && checkoutSet) {
        var stayDurationContainer = document.querySelector(".booking-search-widget .stay-duration");
        var stayDuration = countNights(checkinDate, checkoutDate);
        stayDurationContainer.classList.add("active");
        stayDurationContainer.querySelector("span.value").textContent = stayDuration;

        document.querySelector(".children-ages .title").textContent = _("children_ages_on") + " " +
          getHumanReadableDate(checkoutDate, true, "d M, Y");
      }
      else {
        document.querySelector(".children-ages .title").textContent = _("children_ages_at_checkout");
      }
    }

    function setArrowTopPosition() {
      var widgetHeight = widget.clientHeight;
      var arrowTop = Math.round(widgetHeight/2);
      var arrows = document.querySelectorAll(".arrow-before,.arrow-after");
      for(var i = 0; i != arrows.length; i++) {
        arrows[i].style.top = arrowTop + "px";
      }
    }

    function getYMDDate(date) {
      date = jsDate(date);
      return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate());
    }

    function getHumanReadableDate(date, short, format) {
      format = format || "w, M d, Y";
      date = jsDate(date);
      var dayOfWeek = daysOfWeek[date.getDay()];
      var month = monthNames[date.getMonth()];
      var year = date.getFullYear();
      var day = date.getDate();
      if(short) {
        month = month.substr(0, 3);
        dayOfWeek = dayOfWeek.substr(0, 3);
      }
      var replace = {
        w: dayOfWeek,
        M: month,
        d: day,
        Y: year
      };
      format = format.replace(/[wMdY]/g, function(k) {
        return replace[k];
      });
      return format;
    }

    function onWidgetResize() {
      if(window.externalInterface) {
        window.externalInterface.emitEvent("height-change");
      }
    }

    function onChildrenChange(event) {
      var countChildren = parseInt(event.target.value);
      var childrenAgesContainer = document.querySelector(".children-ages");
      var selectsContainer = document.querySelector(".children-ages .selects");
      var effectiveCount = selectsContainer.childNodes.length;
      var addCount = countChildren - effectiveCount;
      var removeCount = effectiveCount - countChildren;
      while(addCount > 0) {
        var select = document.createElement("select");
        var option = document.createElement("option");
        option.setAttribute("value", "");
        option.textContent = "";
        select.appendChild(option);
        for(var i = 0; i <= 17; i++) {
          option = document.createElement("option");
          option.setAttribute("value", i);
          option.textContent = i;
          select.appendChild(option);
        }
        addCount--;
        selectsContainer.appendChild(select);
      }
      while(removeCount > 0) {
        selectsContainer.removeChild(selectsContainer.lastChild);
        removeCount--;
      }
      if(countChildren > 0) {
        childrenAgesContainer.classList.add("active");
      }
      else {
        childrenAgesContainer.classList.remove("active");
      }
      fireResizeEvent();
    }

    function onFormSubmit() {
      event.preventDefault();
      var destInput = document.getElementById("booking-search-widget-destination");
      var ss = destInput.value;

      if(!ss) {
        document.querySelector("#destionation-field-container").classList.add("error");
        return;
      }
      if(countNights(pickerCheckIn.getDate(), pickerCheckOut.getDate()) > 30) {
        document.querySelector("#checkin-field-container").classList.add("error");
        return;
      }

      var destId = cityInput.getAttribute("data-id");
      var destType = cityInput.getAttribute("data-type");
      var ssRaw = destInput.getAttribute("data-raw");

      var checkin = getYMDDate(pickerCheckIn.getDate());
      var checkout = getYMDDate(pickerCheckOut.getDate());

      var rooms = document.getElementById("rooms").value;
      var adults = document.getElementById("adults").value;
      var children = document.getElementById("children").value;

      var purpose = "";
      if(document.querySelector("#travel-for-business").checked) {
        purpose = "business";
      }
      else if(document.querySelector("#travel-for-leisure").checked) {
        purpose = "leisure";
      }
      var childrenAges = [];
      if(children) {
        var childrenAgesSelects = document.querySelectorAll(".children-ages .selects select");
        for(var i = 0; i != childrenAgesSelects.length; i++) {
          var age = childrenAgesSelects[i].value;
          if(!age) {
            // default value is 12
            age = 12;
          }
          childrenAges.push(age);
        }
      }
      var params = {
        ss_raw: ssRaw,
        ss: ss,
        no_rooms: rooms,
        group_adults: adults,
        group_children: children,
        checkin: checkin,
        checkout: checkout,
        children_ages: childrenAges.join(",")
      };
      if(purpose) {
        params.sb_travel_purpose = purpose;
      }
      if(destId) {
        params.dest_id = destId;
      }
      if(destType) {
        params.dest_type = destType;
      }
      var query = [];
      for(let k in params) {
        query.push(k + "=" + encodeURIComponent(params[k]));
      }
      var url = SearchUrl + "?" + query.join("&");
      window.externalInterface.emitEvent("onformsubmit", {
        url: url
      });
    }

    // fill in selects content
    var roomsSelect = document.getElementById("rooms");
    for(var r = 1; r <= 30; r++) {
      var option = document.createElement("option");
      option.setAttribute("value", r);
      option.textContent = r;
      roomsSelect.appendChild(option);
    }
    var adultsSelect = document.getElementById("adults");
    for(var r = 1; r <= 30; r++) {
      var option = document.createElement("option");
      option.setAttribute("value", r);
      option.textContent = r;
      adultsSelect.appendChild(option);
    }
    var childrenSelect = document.getElementById("children");
    for(var r = 0; r <= 10; r++) {
      var option = document.createElement("option");
      option.setAttribute("value", r);
      option.textContent = r;
      childrenSelect.appendChild(option);
    }

    widget.addEventListener("change", function(event) {
      setUserTouched();
    }, false);

    document.addEventListener("keydown", function(event) {
      if(event.key === "Enter") {
        onFormSubmit();
      }
      if(event.key === "Escape") {
        if(window.externalInterface) {
          window.externalInterface.emitEvent("close-me");
        }
      }
    }, false);

    childrenSelect.addEventListener("change", onChildrenChange, false);

    document.addEventListener("click", function() {
      setUserTouched();
      document.querySelector("#checkin-field-container").classList.remove("error");
    }, false);

    cityInput.addEventListener("input", window.debounce(function(event) {
      setUserTouched();
      document.querySelector("#destionation-field-container").classList.remove("error");
      Suggestions.tryShow(cityInput.value, cityInput);
      cityInput.setAttribute("data-raw", cityInput.value);
      cityInput.removeAttribute("data-id");
      cityInput.removeAttribute("data-type");
    }, 100), false);
    cityInput.addEventListener("focus", function(event) {
      if(Suggestions.lastCities && Suggestions.lastCities.length) {
        Suggestions.show(cityInput);
      }
    }, false);

    Suggestions.onChose.addListener(function(data) {
      cityInput.value = data.value;
      cityInput.setAttribute("data-id", data.id);
      cityInput.setAttribute("data-type", data.type);
      var suggestionChosenEvent = new CustomEvent("suggestion-chosen", {bubbles: true});
      cityInput.dispatchEvent(suggestionChosenEvent);
      cityInput.blur();
    });

    document.querySelector(".close-link").addEventListener("click", function() {
      if(window.externalInterface) {
        window.externalInterface.emitEvent("close-me");
      }
    }, false);

    document.querySelector("#search-form").addEventListener("submit", onFormSubmit, false);

    widget.addEventListener("widget-resize", onWidgetResize, false)

    document.querySelector(".form-reset").addEventListener("click", function() {
      cityInput.value = "";
      cityInput.removeAttribute("data-id");
      cityInput.removeAttribute("data-raw");
      cityInput.removeAttribute("data-type");

      document.getElementById("travel-for-business").checked = false;
      document.getElementById("travel-for-leisure").checked = false;

      pickerCheckIn._d = null;
      pickerCheckOut._d = null;
      document.getElementById("booking-datepicker-in").value = "";
      document.getElementById("booking-datepicker-out").value = "";
      refreshDatesVisible();

      document.getElementById("dont-have-dates").checked = false;

      document.getElementById("rooms").value = 1;
      document.getElementById("adults").value = 1;
      document.getElementById("children").value = 0;

      // need to reset children's ages list
      var changeEvent = new Event("change", {});
      document.getElementById("children").dispatchEvent(changeEvent);

      window.Persister.clear();
    }, false);

    var pikai18n = {
      previousMonth : _("previous_month"),
      nextMonth     : _("next_month"),
      months        : monthNames,
      weekdays      : daysOfWeek,
      weekdaysShort : daysOfWeekShort
    };

    var pickerCheckIn = new window.Pikaday({
      field: document.getElementById('booking-datepicker-in'),
      numberOfMonths: 2,
      minDate: new Date(),
      theme: "booking",
      trigger: document.querySelector(".booking-search-widget-check-in-container"),
      maxDate: maxDate,
      i18n: pikai18n,
      onDraw: function(p) {
        var el = p.el;
        if(checkinMouseOverListener.el !== el) {
          el.addEventListener("mouseover", checkinMouseOverListener, false);
          el.addEventListener("mouseout", checkinMouseOutListener, false);
        }
        buildPikaHead(p, _("checkin"));
        var checkout = getCheckoutParts();
        if(checkout) {
          var pikaDay = el.querySelector(getPartsDaySelector(checkout));
          if(pikaDay) {
            pikaDay.parentNode.classList.add("pika-period-end");
          }
        }
        checkinMouseOutListener();
      },
      onSelect: function() {
        setUserTouched();

        pickerCheckIn.hide();
        var checkin = getCheckinParts();
        var checkout = getCheckoutParts();
        if(!checkout || compareParts(checkin, checkout) >= 0) {
          checkout = getNextDayParts(checkin);
          var checkoutDate = new Date(checkout.year, checkout.month, checkout.day);
          pickerCheckOut.setDate(checkoutDate);
        }
        refreshDatesVisible();
      },
      onOpen: onPickerOpen.bind(null, "checkout"),
      onClose: onPickerClose
    });
    var pickerCheckOut = new window.Pikaday({
      field: document.getElementById('booking-datepicker-out'),
      numberOfMonths: 2,
      minDate: new Date(now.getTime() + 24 * 3600 * 1000),
      theme: "booking",
      trigger: document.querySelector(".booking-search-widget-check-out-container"),
      maxDate: maxDate,
      i18n: pikai18n,
      onDraw: function(p) {
        var el = p.el;
        if(checkoutMouseOverListener.el !== el) {
          el.addEventListener("mouseover", checkoutMouseOverListener, false);
          el.addEventListener("mouseout", checkoutMouseOutListener, false);
        }
        buildPikaHead(p, _("checkout"));
        var checkin = getCheckinParts();
        if(checkin) {
          var pikaDay = el.querySelector(getPartsDaySelector(checkin));
          if(pikaDay) {
            pikaDay.parentNode.classList.add("pika-period-start");
          }
        }
        checkoutMouseOutListener();
      },
      onSelect: function() {
        setUserTouched();

        pickerCheckOut.hide();
        var checkin = getCheckinParts();
        var checkout = getCheckoutParts();
        if(!checkin || compareParts(checkin, checkout) >= 0) {
          checkin = getPrevDayParts(checkout);
          var checkinDate = new Date(checkin.year, checkin.month, checkin.day);
          pickerCheckIn.setDate(checkinDate);
        }
        refreshDatesVisible();
      },
      onOpen: onPickerOpen.bind(null, "checkin"),
      onClose: onPickerClose
    });

    window.pickerCheckIn = pickerCheckIn;
    window.pickerCheckOut = pickerCheckOut;

    refreshDatesVisible();
    setArrowTopPosition();

    window.Analytics.send({dl: "/booking-widget"});
  }, false);
})();