jQuery(function($) {
  'use strict';

  $(window).on('load', function() {
    $('.preloader').fadeOut();
    var $container;
    $container = $('.isotope-content');
    if ($('.isotope').length) {
      $container.isotope({ itemSelector: '.post__roll', masonry: { gutter: 0, columnWidth: '.grid-sizer' } });
    }
  });


  $(window).on('load', function() {
    $('.rooms-slider__item-wrap').matchHeight({
      byRow: true,
      property: 'height',
    });
  });


  var offset = $('.nav-bar').offset().top;

  $(window).on('scroll', function() {
    navBarSticky();
  });

  $(window).resize(function() {
    // resizes
  });

  function navBarSticky() {
    if ($(window).scrollTop() > offset) {
      $('body').addClass('sticky-menu-active');

      if (!$('.nav-bar-space').length) {
        $('.site-header').append('<div style="height: ' + $('.nav-bar').height() + 'px" class="nav-bar-space"></div>');
      } else {
        $('.nav-bar-space').show();
      }
    } else {
      $('body').removeClass('sticky-menu-active');
      $('.nav-bar-space').hide();
    }
  }

  $(document).ready(function() {
    $('.icon').matchHeight({
      byRow: true,
      property: 'height',
    });


    $('.testimonial').matchHeight({
      byRow: true,
      property: 'height',
    });

    $('.rooms-slider').each(function() {
      $(this).slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 3,
        dots: false,
        adaptiveHeight: true,
        appendArrows: $(this).next('.slick-nav'),
        prevArrow: '<button type="button" class="slick-nav__prev"><i class="fa fa-angle-left"></i></button>',
        nextArrow: '<button type="button" class="slick-nav__next"><i class="fa fa-angle-right"></i></button>',
        responsive: [{
            breakpoint: 767,
            settings: {
              slidesToShow: 2,
              slidesToScroll: 2,
            }
          },
          {
            breakpoint: 450,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1,
            }
          },
        ]
      });
    });

    /* Countdown */

    $('.counter').each(function() {
      var days = $(this).data('translation-days'),
        hours = $(this).data('translation-hours'),
        minutes = $(this).data('translation-minutes'),
        seconds = $(this).data('translation-seconds');

      var format = '<span class="counter__item"><span class="counter__time">%D</span><span class="counter__label">' + days + '</span></span>';
      format += '<span class="counter__item"><span class="counter__time">%H</span><span class="counter__label">' + hours + '</span></span>';
      format += '<span class="counter__item"><span class="counter__time">%M</span><span class="counter__label">' + minutes + '</span></span>';
      format += '<span class="counter__item"><span class="counter__time">%S</span><span class="counter__label">' + seconds + '</span></span>';

      $(this).countdown(new Date($(this).data('time')), function(event) {
        $(this).html(event.strftime(format));
      });
    });

    /* Featured rooms slider */

    $('.featured-rooms-slider').each(function() {
      var el = $(this);

      el.slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        dots: true,
      });

      $(this).find('.slick-nav__prev').on('click', function() {
        el.slick('slickPrev');
      });

      $(this).find('.slick-nav__next').on('click', function() {
        el.slick('slickNext');
      });
    });

    $('.hb-slider').slick({
      centerMode: true,
      centerPadding: '60px',
      slidesToShow: 1,
      prevArrow: '<button type="button" class="slick-nav__prev"><i class="fa fa-angle-left"></i></button>',
      nextArrow: '<button type="button" class="slick-nav__next"><i class="fa fa-angle-right"></i></button>'
    });

    /* Hero slider */
    var heroSliderItemSelector = $('.hero-slider__items'),
      heroSliderSelector = $('.hero-slider'),
      heroAutoPlay = heroSliderSelector.data('autoplay'),
      heroLoop = heroSliderSelector.data('loop'),
      heroSpeed = heroSliderSelector.data('speed');

    heroSliderItemSelector.slick({
      infinite: heroLoop,
      autoplay: heroAutoPlay,
      autoplaySpeed: heroSpeed,
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: true,
      prevArrow: '<button type="button" class="slick-prev slick-arrow"><i class="fa fa-angle-left"></i></button>',
      nextArrow: '<button type="button" class="slick-next slick-arrow"><i class="fa fa-angle-right"></i></button>',
    }).trigger('resize');


    $('.hero-tabs__button').on('click', function() {
      var index = $(this).parent().index();
      var item = $('.hero-tabs__item--active');
      var nextItem = $('.hero-tabs__item').eq(index);

      if (index !== item.index()) {
        $('.hero-tabs__list-item--active').removeClass('hero-tabs__list-item--active');
        $(this).parent().addClass('hero-tabs__list-item--active');

        $('.hero-tabs__items').height(item.height());

        item.removeClass('hero-tabs__item--active');
        nextItem.addClass('hero-tabs__item--active');

        if (index === 0) {
          $(this).parents('.hero-tabs').addClass('hero-tabs--first');
        } else {
          $(this).parents('.hero-tabs').removeClass('hero-tabs--first');
        }
      }
    });

    /* Datepicker */

    /* Amenities (same height) */

    $('.amenity').matchHeight({
      byRow: true,
      property: 'height',
    });

    /* Image gallery */

    $('.image-gallery__main').slick({
      infinite: true,
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: true,
      prevArrow: '<button type="button" class="slick-prev slick-arrow"><i class="fa fa-angle-left"></i></button>',
      nextArrow: '<button type="button" class="slick-next slick-arrow"><i class="fa fa-angle-right"></i></button>',
    });

    $('.image-gallery__button').on('click', function() {
      var index = $(this).parent().index();

      $('.image-gallery__main').slick('slickGoTo', index);
      $(this).blur();
    });

    /* Mobile menu */

    $('.btn--mobile-toggle').on('click', function() {
      $('body').toggleClass('mobile-menu-active');
    });

    $('.site-menu .menu-item-has-children').each(function() {
      $(this).append('<button class="sub-menu-toggle"><i class="fa fa-angle-down"></i></button>');
    });

    $('body').on('click', '.sub-menu-toggle', function(e) {
      e.preventDefault();

      $(this).parent().toggleClass('sub-menu-active');
    });

    /* Destination */

    $('.dest').each(function() {
      $(this).find('.dest__title').css('transform', 'translateY(' + $(this).find('.dest__desc').innerHeight() / 2 + 'px)');
    });

    $('.dest').on('mouseover', function() {
      $(this).find('.dest__title').css('transform', 'translateY(' + 0 + 'px)');
    });

    $('.dest').on('mouseout', function() {
      $(this).find('.dest__title').css('transform', 'translateY(' + $(this).find('.dest__desc').innerHeight() / 2 + 'px)');
    });

    navBarSticky();

    /* Widget search placeholder */

    $('.searchform input[type="text"]').attr('placeholder', 'Search Now');

    /* Price range */

    if ($.fn.ionRangeSlider !== undefined) {
      $(".price-slider__input").ionRangeSlider({
        type: "double",
        min: 1000,
        max: 2000,
        from: 1200,
        to: 1800,
        hide_min_max: true,
        hide_from_to: true,
        grid: false
      });
    }

    $('.search-filter__toggle').on('click', function(e) {
      e.preventDefault();

      $(this).parents('.search-filter').toggleClass('search-filter--active');
      $(this).parents('.search-filter').find('.search-filter__more').slideToggle();
    });
    $('input[type="checkbox"]').wrap("<div class='checkbox-select'></div>");
    $('input[type="checkbox"]').parents('.checkbox-select').append('<span class="cs-check"></span>');
    $("select").wrap("<div class='widget-select'></div>");


    $('.jumbotron').each(function() {
      var image_src = $(this).data('image'),
        body = $('body');
      $(this).parallax({ imageSrc: image_src });

      // fallback for boxed layout
      if (body.hasClass('boxed')) {
        $(this).css('background-image', 'url(' + image_src + ')');
      }
    });

    if ($('.player').length > 0) {
      $('.player').mb_YTPlayer();
    }

    $('.hb-video__anchor').each(function() {
      $(this).on('click', function(e) {
        console.log(this);
        var video = $(this).data('video');
        console.log(video);
        $('.hb-video__popup').addClass('active');
        $('.hb-video__popup').find('iframe').attr('src', video);
        e.preventDefault();
      });
    });

    $('.hb-video__close, .hb-video__caption').on('click', function(e) {
      $('.hb-video__popup').removeClass('active');
      $('.hb-video__popup').find('iframe').attr('src', 'about:blank');
      e.preventDefault();
    });



    if ($('.hb-google__map').length > 0) {

      var selector = ($('.hb-google__map'));

      selector.each(function() {
        var latitude = $(this).data('lat'),
          longitude = $(this).data('long'),
          marker = $(this).data('marker');

        var tbLatLan = {
          lat: latitude,
          lng: longitude
        };

        $(this).gmap3({
            zoom: 11,
            center: tbLatLan,
            scrollwheel: false,
            mapTypeId: "tbGreyMap",
            mapTypeControlOptions: {
              mapTypeIds: [google.maps.MapTypeId.ROADMAP, "tbGreyMap"]
            }
          })

          .styledmaptype(
            "tbGreyMap", [

              {
                "featureType": "administrative",
                "elementType": "geometry.stroke",
                "stylers": [{
                  "color": "#fefefe"
                }, {
                  "lightness": 17
                }, {
                  "weight": 1.2
                }]
              },
              {
                "featureType": "administrative",
                "elementType": "geometry.fill",
                "stylers": [{
                  "color": "#fefefe"
                }, {
                  "lightness": 20
                }]
              },
              {
                "featureType": "transit",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#f2f2f2"
                }, {
                  "lightness": 19
                }]
              },
              {
                "featureType": "all",
                "elementType": "labels.icon",
                "stylers": [{
                  "visibility": "off"
                }]
              },
              {
                "featureType": "all",
                "elementType": "labels.text.fill",
                "stylers": [{
                  "saturation": 36
                }, {
                  "color": "#333333"
                }, {
                  "lightness": 40
                }]
              },
              {
                "featureType": "all",
                "elementType": "labels.text.stroke",
                "stylers": [{
                  "visibility": "on"
                }, {
                  "color": "#ffffff"
                }, {
                  "lightness": 16
                }]
              },
              {
                "featureType": "poi",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#f5f5f5"
                }, {
                  "lightness": 21
                }]
              },
              {
                "featureType": "road.local",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#ffffff"
                }, {
                  "lightness": 16
                }]
              },
              {
                "featureType": "road.arterial",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#ffffff"
                }, {
                  "lightness": 18
                }]
              },
              {
                "featureType": "road.highway",
                "elementType": "geometry.stroke",
                "stylers": [{
                  "color": "#ffffff"
                }, {
                  "lightness": 29
                }, {
                  "weight": 0.2
                }]
              },
              {
                "featureType": "road.highway",
                "elementType": "geometry.fill",
                "stylers": [{
                  "color": "#ffffff"
                }, {
                  "lightness": 17
                }]
              },
              {
                "featureType": "landscape",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#f5f5f5"
                }, {
                  "lightness": 20
                }]
              },
              {
                "featureType": "water",
                "elementType": "geometry",
                "stylers": [{
                  "color": "#e9e9e9"
                }, {
                  "lightness": 17
                }]
              }
            ], {
              name: "HQ"
            }
          )

          .marker({
            position: tbLatLan,
            icon: marker
          })
      });

    } // end of if

    customDatePicker();
    customSelect();
    invalidQuantity();

  }); // endof document


  function isInteger(a) {
    return Number(a) || (a % 1 === 0);
  }

  function changeNumber() {
    var $max_child = $(' select[name="max_child"] option:selected').html();
    var $adults_capacity = $('select[name="adults_capacity"] option:selected').html();
    var $number_total = Math.round($adults_capacity);
    if ($number_total < 10) {
      $('#number').val('0' + $number_total);
    } else {
      $('#number').val($number_total);
    }
  }

  function customDatePicker() {

    var today = new Date();
    var tomorrow = new Date();

    var start_plus = $(document).triggerHandler('hotel_booking_min_check_in_date', [1, today, tomorrow]);
    start_plus = parseInt(start_plus);
    if (isInteger(start_plus)) {
      start_plus = 1;
    }
    tomorrow.setDate(today.getDate() + start_plus);

    $('.date-picker__alt input[id^="check_in_date"]').datepicker('option', {
      showOn: 'button',
      altField: $('.date-picker__alt input[id^="check_in_date"]').parent().find('.day'),
      altFormat: 'dd',
      beforeShow: function(input, inst) {
        $('.ui-datepicker').addClass('ui-datepicker__position');
      },
      onSelect: function() {
        var unique = $(this).attr('id');
        unique = unique.replace('check_in_date_', '');
        var date = $(this).datepicker('getDate');
        var month = hotel_booking_i18n.monthNamesShort[date.getMonth()];
        var datepicker_selector = $('.ui-datepicker');
        datepicker_selector.addClass('ui-custom__datepicker_position');
        $('.date-picker__alt input[id^="check_in_date"]').parent().find('.month').val(month);

        var checkout = $('.date-picker__alt #check_out_date_' + unique);

        date.setDate(date.getDate() + start_plus);

      },
      onClose: function() {

      },
    });

    $('.date-picker__alt input[id^="check_in_date"]').datepicker('refresh');


    $('.date-picker__alt input[id^="check_out_date"]').datepicker('option', {
      showOn: 'button',
      buttonText: '',
      altField: $('.date-picker__alt input[id^="check_out_date"]').parent().find('.day'),
      altFormat: 'dd',
      onSelect: function() {
        var unique = $(this).attr('id');
        unique = unique.replace('check_out_date_', '');
        var date = $(this).datepicker('getDate');
        var month = hotel_booking_i18n.monthNamesShort[date.getMonth()];
        $('.date-picker__alt input[id^="check_out_date"]').parent().find('.month').val(month);
      }
    });

    $('.date-picker__alt input[id^="check_out_date"]').datepicker('refresh');
  }

  function customSelect() {
    $('.hb__goup').on('click', function() {
      var index = $('.date-picker__alt select[name="adults_capacity"] option:selected').index();
      var count = $('.date-picker__alt select[name="adults_capacity"] option').length;

      if (index + 1 >= count) {
        return;
      }

      var selected = $($('.date-picker__alt select[name="adults_capacity"] option')[index + 1]).val();

      $('.date-picker__alt select[name="adults_capacity"]').val(selected);

      $('.date-picker__alt select[name="adults_capacity"]').trigger('change.select2'); // Notify only Select2 of changes

      changeNumber();

    });

    $('.hb__godown').on('click', function() {
      var index = $('.date-picker__alt select[name="adults_capacity"] option:selected').index();
      if (index <= 0) {
        return;
      }
      var selected = $($('.date-picker__alt select[name="adults_capacity"] option')[index - 1]).val();
      $('.date-picker__alt select[name="adults_capacity"]').val(selected);

      $('.date-picker__alt select[name="adults_capacity"]').trigger('change.select2'); // Notify only Select2 of changes

      changeNumber();
    });
  }

  function invalidQuantity() {
    $(document).on('submit', 'form.hb-search-room-results', function(event) {
      event.preventDefault();
      var _form = $(this),
        number_room_select = _form.find('.number_room_select option:selected').val(),
        select = _form.find('.number_room_select');

      //console.log(number_room_select);
      $('.number_room_select').removeClass('hotel_booking_invalid_quantity');
      $('.widget-select').removeClass('hotel_booking_invalid_quantity_widget');
      if (typeof number_room_select === 'undefined' || number_room_select === '') {
        select.parent().addClass('hotel_booking_invalid_quantity_widget');
        select.addClass('hotel_booking_invalid_quantity');
      }
    });
  }
});