var $ = jQuery.noConflict();

$(document).ready(function () {
  AOS.init({
    easing: "ease-in-out",
    duration: 700,
    once: true,
  });

  if (getCookie("dark-mode")) {
    $("body").toggleClass("dark-on");
  }
  $(".contrast-btn").on("click", function (e) {
    e.preventDefault();

    if ($(this).hasClass("active")) {
      setCookie("dark-mode", 0);
      $(this).removeClass("active");
      $("body").removeClass("dark-on");
    } else {
      setCookie("dark-mode", 1);
      $(this).addClass("active");
      $("body").addClass("dark-on");
    }
  });

  $(".cust-select").each(function () {
    NiceSelect.bind($(this)[0]);
  });

  $(".menu-wrap .btn").on("click", function () {
    $(this).parent().toggleClass("open");
  });

  $(".multiple-select, select.select2").each(function () {
    var id = $(this).attr("id");

    var $select2 = $(this).select2({
      minimumResultsForSearch: -1,
      dropdownParent: $(this).parent(),
      // allowClear: true,
      placeholder: {
        id: "-1", // the value of the option
        text: $(this).attr("data-placeholder"),
      },
    });
    $select2.val(null).trigger("change");

    $(this).on("change", function () {
      $(this).valid();

      if (id === "exam_lecturer" || id === "summary_lecturer") {
        var vals = $(this).val();

        if (vals.includes("other")) {
          $("#exam-other-lecturer, #summary-other-lecturer")
            .prop("disabled", false)
            .parent()
            .slideDown();
        } else {
          $("#exam-other-lecturer, #summary-other-lecturer")
            .prop("disabled", true)
            .parent()
            .slideUp();
        }
      }
    });
  });

  $(".acf-map").each(function () {
    var map = initMap($(this));
  });

    mobile_nav(); // Mobile navigation
    mobile_footer_nav_init(); // Turn mobile footer navigation into accordion
    fast_contact_form(); // Fast contact form init
    search_box_init(); // Toggle search box
    btn_scroll_to(); // Scroll-to button
    ajax_load_more(); // Ajax load more
    share_buttons(); // Share buttons
    ajax_form(); // Ajax forms handler
    init_events_calendar();
    init_rating_stars();
    init_custom_select();
    scroll_to_hash();

    inis_sticky_header();
    init_news_ticker();
    init_sub_menu();
    init_home_slider();
    init_events_slider();
    init_related_slider();
    init_articles_slider();
    init_float_contact();
    init_share_btn();
    init_img_slider();
    init_event_gallery_slider();
    init_mobile_calendar_slider();
    init_accordion();
    init_form_validator();
    ajax_comments_form();

    // upload exam
    ajax_upload_exam();
    init_file_upload_drag();
    init_upload_exam_form();
    /* Blocks */
    init_block_hero_slider(); // Block hero slider
    init_block_slider_with_thumbnails(); // Block slider with thumbnails
    init_block_slider_testimonials(); // Block slider testimonials
    init_block_slider_images(); // Block slider images
    init_block_slider_posts(); // Block slider posts
    init_block_tabs(); // Block tabs

    document.addEventListener("aos:in:float", ({ detail }) => {
        console.log("animated in", detail);
    });

    jQuery('.header-logged-link').click( function(e){
        jQuery(this).find('.log-submenu').toggleClass('active');
    });
});

$(window).load(function () {});

function init_form_validator() {
  $(".form,.wpcf7-form").validate({
    debug: true,
    ignore: ".select2-search__field",
    errorPlacement: function (error, element) {
      if (element.attr("id") !== "accept") {
        error.appendTo(element.parent());
      }
    },
  });
}

function inis_sticky_header() {
  $(window).scroll(function () {
    var windowTop = $(window).scrollTop();
    var offset = is_mobile(992) ? 0 : 45;
    if (windowTop > offset) {
      $(".site-header").addClass("sticky");
    } else {
      $(".site-header").removeClass("sticky");
    }
  });
}

function init_share_btn() {
  $(".copy-text").click(function (e) {
    e.preventDefault();
    var copyText = $(this).attr("href");

    document.addEventListener(
      "copy",
      function (e) {
        e.clipboardData.setData("text/plain", copyText);
        e.preventDefault();
      },
      true
    );

    document.execCommand("copy");
    alert("copied text: " + copyText);
  });
  $(".facebookShareBtn").click(function () {
    var href = $(this).data("href");
    window.open(
      "https://www.facebook.com/sharer/sharer.php?u=" + href,
      "",
      "resizable=yes,status=no,location=no,toolbar=no,menubar=no,fullscreen=no,scrollbars=no,dependent=no,width=900,left=200,height=300,top=100"
    );
  });
  $(".whatsappShareBtn").click(function () {
    var href = $(this).data("href");
    window.open(
      "https://api.whatsapp.com/send?text=" + href,
      "",
      "resizable=yes,status=no,location=no,toolbar=no,menubar=no,fullscreen=no,scrollbars=no,dependent=no,width=700,left=200,height=400,top=100"
    );
  });
}

function init_float_contact() {
  $(".contact-bubble").on("click", function (e) {
    e.preventDefault();
    $(this).parent().toggleClass("active");
  });

  $(".float-close").on("click", function (e) {
    e.preventDefault();
    $(this).parents(".float-contact").removeClass("active");
  });

  var container = $(".float-contact");

  $(document).scroll(function (e) {
    if (container.hasClass("active")) {
      container.removeClass("active");
    }
  });
  $(document).mouseup(function (e) {
    // if the target of the click isn't the container nor a descendant of the container
    if (
      !container.is(e.target) &&
      container.has(e.target).length === 0 &&
      container.hasClass("active")
    ) {
      container.removeClass("active");
    }
  });
}

function init_home_slider() {
    const swiper = new Swiper(".home-slider", {
        loop: true,
        autoplay: {
            delay: 4000,
            disableOnInteraction: false,
        },
        navigation: {
            nextEl: ".home-slider .swiper-button-next",
            prevEl: ".home-slider .swiper-button-prev",
        },
    });
}

function init_mobile_calendar_slider() {
  if (is_mobile(992)) {
    if (!$(".months-swiper").length) {
      return;
    }
    var activeItem;
    $(".months-swiper button").each(function (item, key) {
      if ($(this).hasClass("active")) {
        activeItem = item;
      }
    });

    const swiper = new Swiper(".months-swiper", {
      freeMode: true,
      slidesPerView: 5,
    });

    swiper.slideTo(activeItem);
  }
}

function init_img_slider() {
  const swiper = new Swiper(".img-swiper", {
    navigation: {
      nextEl: ".swiper-wrap .swiper-button-next",
      prevEl: ".swiper-wrap .swiper-button-prev",
    },
  });
}

function init_event_gallery_slider() {
  const swiper = new Swiper(".event-gallery-slider", {
    spaceBetween: 5,
    speed: 700,
    navigation: {
      nextEl: ".event-gallery-slider .swiper-button-next",
      prevEl: ".event-gallery-slider .swiper-button-prev",
    },
  });
}

function init_events_slider() {
  const swiper = new Swiper(".events-slider", {
    loop: true,
    spaceBetween: 150,
    navigation: {
      nextEl: ".home-events-section .swiper-button-next",
      prevEl: ".home-events-section .swiper-button-prev",
    },
  });
}

function init_related_slider() {
  const swiper = new Swiper(".related-slider", {
    loop: true,
    spaceBetween: 150,
    navigation: {
      nextEl: ".related-slider .swiper-button-next",
      prevEl: ".related-slider .swiper-button-prev",
    },
  });
}

function init_articles_slider() {
  const swiper = new Swiper(".articles-slider", {
    spaceBetween: 32,
    slidesPerView: 1,
    navigation: {
      nextEl: ".articles-slider .swiper-button-next",
      prevEl: ".articles-slider .swiper-button-prev",
    },
    breakpoints: {
      640: {
        slidesPerView: 2,
        spaceBetween: 20,
      },
      768: {
        slidesPerView: 3,
        spaceBetween: 32,
      },
      1024: {
        slidesPerView: 4,
        spaceBetween: 32,
      },
    },
  });
}

function init_news_ticker() {
  if ($(".news-ticker").length) {
    $(".news-ticker-list").AcmeTicker({
      type: "marquee",
      direction: "right",
      speed: 0.05,
      pauseOnFocus: false,
      pauseOnHover: true,

      controls: {
        toggle: $(".news-ticker-pause"),
      },
    });
  }

  $(".news-ticker-pause").on("click", function () {
    $(this).toggleClass("active");
  });
}

function init_upload_exam_form() {
  var autocompleteInput = $("input.autocomplete_input_cours_number");
  var formType = $("input.autocomplete_input_cours_number")
    .parents("form")
    .attr("data-type");
  autocompleteInput.on("focus", function () {
    var list = $(this).parent().find("ul");

    if (list.find("li").length) {
      list.show();
    }
  });

  autocompleteInput.autocomplete({
    appendTo: autocompleteInput.parent(),
    source: function (request, response) {
      var thisElement = autocompleteInput;

      thisElement.parents(".input-wrap").addClass("loading");

      $.ajax({
        type: "POST",
        dataType: "json",
        url: siteObject.ajaxurl,
        data: {
          action: "ajax_get_course_data_api",
          course_num: request.term,
        },

        success: function (results) {
			thisElement.parents(".input-wrap").removeClass("loading");
			$("#" + formType + "_lecturer").prop("disabled", true);

			var select_field = jQuery('.upload-form .lecturers select');
			if ( results.ok && results.data ) {
				select_field.show().next('.select2').show().siblings('.field-placeholder').remove();
				
				jQuery('.upload-form .disabled-class-placeholder').removeClass('disabled-class-placeholder').addClass('disabled');
				response(results.data);
			} else {
				var text = select_field.attr('data-placeholder');
				var name = select_field.attr('name');
				select_field.before('<input type="text" name="'+name+'" required placeholder="'+text+'" class="field-placeholder">');
				select_field.hide().next('.select2').hide();
				
				jQuery('.upload-form .disabled').addClass('disabled-class-placeholder').removeClass('disabled');
				response([]);
			}
        },
      });
    },
    select: function (event, ui) {
      $('[name="course_name"]').val(ui.item.label);
      $('[name="' + formType + '_faculty"]').val(ui.item.faculty);
      $('[name="' + formType + '_division"]').val(ui.item.depratment);

      $("#" + formType + "_lecturer").find("option").remove();
      if (ui.item.lecturers && typeof ui.item.lecturers.map === 'function') {
        ui.item.lecturers.map(function (item) {
          var newOption = new Option(item, item, false, false);
          $("#" + formType + "_lecturer").append(newOption);
        });

        var otherText = is_rtl() ? "אחר" : "Other";

        var otherOption = new Option(otherText, "other", false, false);
        $("#" + formType + "_lecturer").append(otherOption);
        $("#" + formType + "_lecturer").prop("disabled", false);
      }
    },
    minLength: 3,
  });

  var lastCoursNumber = "";

  autocompleteInput.on("keyup change", function (e) {
    e.preventDefault();

    var thisElement = jQuery(this);
    var coursNumber = thisElement.val();
    coursNumber = coursNumber.replace(/[\D\s\._\-]+/g, "");

    var chunk = [];
    chunk.push(coursNumber.substr(0, 3));
    chunk.push(coursNumber.substr(3, 1));
    chunk.push(coursNumber.substr(4, 4));

    //coursNumber = chunk.filter(Number).join("."); // not good cannot enter leading zero
    var filtered = chunk.filter(function (el) {
      return parseInt(el) == el;
    });
    coursNumber = filtered.join(".");
    thisElement.val(coursNumber);
    if (coursNumber.length >= 4 && lastCoursNumber !== coursNumber) {
      lastCoursNumber = coursNumber;
      coursNumber = coursNumber.replace(/\./g, "");
    }
  });
}

function init_sub_menu() {
  $(".toggle-menu-btn").on("click", function (e) {
    e.preventDefault();
    $(this).toggleClass("active");

    if ($(this).hasClass("active")) {
      $(this).attr("aria-expanded", "true");
    } else {
      $(this).attr("aria-expanded", "false");
    }

    // $(".main-navigation-wrap").toggleClass("active");
    $("body").toggleClass("menu-open");
  });

  $("#main-navigation .back-btn").on("click", function (e) {
    e.preventDefault();
    var parent = $(this).parent();
    parent.parent("ul").removeClass("item-active");

    parent.removeClass("active").siblings().removeClass("hidden");
  });

  $("body").on("click", '#main-navigation .toggle-sub-menu-arrow, #main-navigation .menu > li.menu-item-has-children > a', function (e) {
    e.preventDefault();

	var self = $(this);
	var parent = self.parent();
	self.closest('ul').nextAll('.sub-menu').remove();
	if( ! parent.hasClass('active') )
		self.siblings('.sub-menu').clone().addClass('hide-on-tablet').appendTo('.main-menu-container');

    parent.parent("ul").toggleClass("item-active");
    parent.find("li.active").removeClass("active");

    if ( ! is_mobile(992) ) {
      parent.find("ul").removeClass("item-active");
      parent.toggleClass("active").siblings().removeClass("active");
    } else {
      parent
        .toggleClass("active")
        .siblings()
        .toggleClass("hidden")
        .removeClass("active");
    }
  });
}

function is_home() {
  if ($("body").hasClass("home")) {
    return true;
  } else {
    return false;
  }
}

function is_rtl() {
  if ($("body").hasClass("rtl")) {
    return true;
  } else {
    return false;
  }
}

function is_mobile(width) {
  if (!width) {
    width = 992;
  }

  if ($(window).width() < width) {
    return true;
  } else {
    return false;
  }
}

function fade_in_init() {
  $(".fade-in").css("opacity", 1);
}

function mobile_nav() {
  mobileNav = {
    triggerClick: function () {
      $(".mn-trigger").click(function () {
        $("body").toggleClass("mn-active");
      });
    },

    menuItemClick: function () {
      $(".mn-menu ul > li.menu-item-has-children > a, .toggle-sub-menu").click(
        function (e) {
          e.preventDefault();
          $(this)
            .parent()
            .toggleClass("menu-item-open")
            .find("> ul.sub-menu")
            .slideToggle();
        }
      );

      $(".mn-menu li:not(.menu-item-has-children) a").click(function () {
        $("body").removeClass("mn-active");
      });
    },

    swipe: function () {
      $(".mn-menu").on("swiperight", function () {
        $("body").removeClass("mn-active");
      });
    },

    init: function () {
      mobileNav.triggerClick();
      mobileNav.menuItemClick();
      mobileNav.swipe();
    },
  };

  mobileNav.init();
}

function mobile_footer_nav_init() {
  if (!is_mobile(992)) {
    return;
  }
  $(".footer-col .footer-title").click(function (e) {
    e.preventDefault();

    $(".footer-col.active")
      .not($(this).closest(".footer-col"))
      .removeClass("active")
      .find(".footer-col-body")
      .slideUp(300);
    $(this)
      .closest(".footer-col")
      .toggleClass("active")
      .find(".footer-col-body")
      .slideToggle(300);
  });
}

function fast_contact_form() {
  $(".btn-hidden-form-toggle, .btn-close-hidden-form").click(function (e) {
    e.preventDefault();
    $(this).toggleClass("active");
    $(".bottom-strip-hidden-form, .header-hidden-form").toggleClass("active");
  });
}

function search_box_init() {
  $(".search-btn").on("click", function (e) {
    e.preventDefault();
    $(".header-search").addClass("active").find(".search-input").focus();
  });

  $(".close-search").on("click", function (e) {
    e.preventDefault();
    $(".header-search").removeClass("active");
  });

  // $(".search").submit(function (e) {
  //   if (!$(this).find(".search-input").val()) {
  //     e.preventDefault();
  //   }
  // });
}

function btn_scroll_to() {
  $("body").on("click", ".btn-scroll-to", function (e) {
    e.preventDefault();

    target = $($(this).data("scrollto"));
    $("html, body").animate({ scrollTop: target.offset().top }, 700);
    return false;
  });

  $(window).scroll(function () {
    if ($(window).scrollTop() > 0) {
      $(".btn-scroll-to-top").fadeIn(300);
    } else {
      $(".btn-scroll-to-top").fadeOut(300);
    }
  });
}

function ajax_load_more() {
  $("body").on("click", ".btn-load-more", function (e) {
    btn = $(this);
	btnClass = btn.attr('class');
    append = $(this).data("append");
    query = $(this).data("query");
    load = $(this).data("load");
    offset = $(this).data("offset");
    template = $(this).data("template");

    e.preventDefault();
	
	if( ! btn.parent().hasClass('loading') ) {
		btn.hide().after('<div class="js-loader '+btnClass+'"><img src="'+siteObject.themeurl+'/assets/img/loader.svg" alt="" style="max-height:30px;" /></div>');
		btn.parent().addClass("loading");
	}
    
    $.ajax({
      type: "POST",
      dataType: "json",
      url: siteObject.ajaxurl,
      data: {
        action: "ajax_load_more",
        args: query,
        offset: offset,
        load: load,
        template: template,
      },

		success: function (results) {
			btn.next('.js-loader').remove();
			btn.parent().removeClass("loading");

			$(append).append(results.html);
			if ( ! results.more ) {
				btn.parent().remove();
			} else {
				btn.show();
			}
      },
    });

    offset = $(this).data("offset") + load;
    btn.attr("data-offset", offset).data("offset", offset);
  });
}

function share_buttons() {
  $("a.btn-share").click(function (e) {
    e.preventDefault();
    var popup_window;

    var width = 555;
    var height = 500;
    var center_left = screen.width / 2 - width / 2;
    var center_top = screen.height / 2 - height / 2;
    var url = $(this).attr("href");

    popup_window = window.open(
      url,
      "Title",
      "scrollbars=1, width=" +
        width +
        ", height=" +
        height +
        ", left=" +
        center_left +
        ", top=" +
        center_top
    );
    popup_window.focus();
  });
}

function init_events_calendar() {
  $("body").on("click", ".month-select-btn", function (e) {
    e.preventDefault();

    if (!$(this).hasClass("active")) {
      $(this)
        .addClass("active")
        .parent()
        .siblings()
        .find("button")
        .removeClass("active");

      ajax_load_events();
    }
  });
  $("#event-select-category").on("change", function (e) {
    ajax_load_events();
  });

  var timer,
    delay = 300;

  $("#event-search-input").on("keydown blur change input", function (e) {
    clearTimeout(timer);
    timer = setTimeout(function () {
      ajax_load_events();
    }, delay);
  });
  $("#event-select-category").on("input", function (e) {
    ajax_load_events();
  });
}

function ajax_upload_exam() {
  /* Upload Exam */
  jQuery("form.upload-form").on("submit", function (e) {
    e.preventDefault();
    var form = jQuery(this);

    var formType = form.attr("data-type");
    if (!form.valid()) {
      return;
    }

    var data = new FormData(form[0]);

    if (formType === "exam") {
      data.append("action", "ajax_uploadExam");
      data.append("security", form.find('[name="wp_nonce_upload_exam"]').val());
    } else {
      data.append("action", "ajax_uploadSummary");
      data.append(
        "security",
        form.find('[name="wp_nonce_upload_summary"]').val()
      );
    }

    form.find(".input-wrap.submit").addClass("loading");
    jQuery.ajax({
      dataType: "json",
      url: siteObject.ajaxurl,
      data: data,
      cache: false,
      processData: false,
      contentType: false,
      type: "POST",
      success: function (result) {
        form.find(".input-wrap.submit").removeClass("loading");
        if (result.error) {
          form
            .find(".response-message")
            .html("ארעה שגיאה, אנא בדוק את שדות הטופס")
            .fadeIn(250);
        }

        if (result.msg) {
          form.find(".response-message").html(result.msg).fadeIn(250);
        }

        if (result.success) {
          // form.find(".formResult span").addClass("success");
          if (result.success.url) {
            location.assign(result.success.url);
            return;
          }
        }
      },
    });
  });
}

function ajax_comments_form() {
  $(".comments-form").on("submit", function (e) {
    e.preventDefault();
    var form = $(this);

    if (!form.valid()) {
      return;
    }

    $.post({
      dataType: "json",
      url: siteObject.ajaxurl,
      data: {
        action: "ajax_add_comment",
        data: $(this).serialize(),
      },

      success: function (response) {
        if (response.ok) {
          reset_comments_form();
          $(".entry-comments-list").html(response.html);
        }
      },
    });
  });
}
function ajax_load_events() {
  var selected_cat = $("#event-select-category").val();
  var free_search_text = $("#event-search-input").val();
  var month = $(".month-select-btn.active").attr("data-month");
  var year = $(".month-select-btn.active").attr("data-year");

  $(".calendar-body").addClass("loading");
  $.post({
    dataType: "json",
    url: siteObject.ajaxurl,
    data: {
      action: "ajax_load_events",
      selected_cat: selected_cat,
      free_search_text: free_search_text,
      month: month,
      year: year,
    },

    success: function (response) {
      $(".calendar-body").removeClass("loading");

      if (response.ok) {
        $(".calendar-body-wrap").html(response.html);
        init_mobile_calendar_slider();
      }
    },
  });
}

function ajax_form() {
  $(".form-login").on("submit", function (e) {
    e.preventDefault();

    var $form = $(this);

    if (!$form.valid()) {
      return;
    }

    $form.addClass("loading");
    $form.find(".message").html("");
    $.post({
      dataType: "json",
      url: siteObject.ajaxurl,
      data: {
        action: "ajax_login",
        data: $(this).serialize(),
      },

      success: function (response) {
        $form.removeClass("loading");

        $form.find(".message").html(response.message);

        if (response.ok) {
          var name = is_rtl()
            ? response.data.data[0].FIRSTNAME
            : response.data.data[0].FOREIGNFIRSTNAME;
          var box = $(".after-login-text");
          var text = box.find(".entry-text").html();

          $form.slideUp();
          box.find(".entry-text").html(text.replace("%name%", name));
          box.show();
        }
      },
    });
  });
}

function init_block_hero_slider() {
  $(".slider-hero").each(function () {
    var swiper = new Swiper($(this)[0], {
      effect: "fade",
      fadeEffect: {
        crossFade: true,
      },
      loop: true,
      autoplay: {
        delay: 5000,
      },
      keyboard: {
        enabled: true,
        onlyInViewport: true,
      },
      a11y: {
        prevSlideMessage: siteObject.strings.prev_slide,
        nextSlideMessage: siteObject.strings.next_slide,
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  });
}

function init_block_slider_with_thumbnails() {
  var galleryThumbs = new Swiper(".gallery-thumbs", {
    spaceBetween: 10,
    slidesPerView: 5,
    loop: true,
    centeredSlides: true,
    keyboard: {
      enabled: true,
      onlyInViewport: true,
    },
  });

  var galleryTop = new Swiper(".gallery-top", {
    loop: true,
    thumbs: {
      swiper: galleryThumbs,
    },
    keyboard: {
      enabled: true,
      onlyInViewport: true,
    },
  });
}

function init_block_slider_testimonials() {
  $(".slider-testimonials").each(function () {
    var swiper = new Swiper($(this)[0], {
      effect: "fade",
      fadeEffect: {
        crossFade: true,
      },
      loop: true,
      autoplay: {
        delay: 5000,
      },
      keyboard: {
        enabled: true,
        onlyInViewport: true,
      },
    });
  });
}

function init_block_slider_images() {
  $(".slider-images").each(function () {
    var swiper = new Swiper($(this)[0], {
      effect: "fade",
      loop: true,
      autoplay: {
        delay: 5000,
      },
      keyboard: {
        enabled: true,
        onlyInViewport: true,
      },
    });
  });
}

function init_block_slider_posts() {
  $(".slider-posts").each(function () {
    var swiper = new Swiper($(this)[0], {
      spaceBetween: 10,
      slidesPerView: 5,
      loop: true,
      a11y: {
        prevSlideMessage: siteObject.strings.next_slide,
        nextSlideMessage: siteObject.strings.next_slide,
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      keyboard: {
        enabled: true,
        onlyInViewport: true,
      },
    });
  });
}

function init_block_tabs() {
  $(".tab-link").click(function (e) {
    e.preventDefault();
    var tab = $(this).attr("href");
    console.log(tab);
    $(".tabs-header li").removeClass("active");
    $(this).parent().addClass("active");

    $(".tab-content").removeClass("active");
    $(tab).addClass("active");
    // history.pushState({}, null, tab);
  });
}

function init_accordion() {
  var accordion = {
    closeItems: function ($items) {
      $items
        .removeClass("active")
        .attr("aria-expanded", false)
        .find(".entry-body")
        .slideUp(400);
    },

    openItem: function ($item) {
      $item
        .addClass("active")
        .attr("aria-expanded", true)
        .find(".entry-body")
        .slideDown(400, function () {
          $([document.documentElement, document.body]).animate(
            {
              scrollTop: $item.offset().top - 150,
            },
            500
          );
        });
    },

    init: (function () {
      $("body").on(
        "click",
        ".qa-btn, .decision-btn, .job-header, .toggle-row-btn",
        function (e) {
			if( $(this).hasClass('job-header') && $('html').width() <= 767 ) {
				return false;
			}
			var $this = $(this).parents(".entry-item");
			var $siblings = $(this).parents(".entry-item").siblings();

			accordion.closeItems($siblings);

			if (!$this.hasClass("active")) {
				accordion.openItem($this);
			} else {
				accordion.closeItems($this);
			}
        }
      );
    })(),
  };
}

function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function init_rating_stars() {
  $("body").on("click", ".entry-rating li", function (e) {
    var _this = $(this);
    var thisKey = $(this).index();

    var ul = $(this).parent();
    var form = $(this).parents("form");
    ul.find("li").each(function (index) {
      if (!_this.hasClass("selected")) {
        if (index === +thisKey + 1) {
          return false;
        }

        $(this).addClass("selected");
      } else {
        if (index > +thisKey) {
          $(this).removeClass("selected");
        }
      }
    });

    form.find("#rating").val(+thisKey + 1);
  });
}

function reset_comments_form() {
  $(".entry-rating li").removeClass("selected");
  $("#rating").val("");
  $('textarea[name="comment"]').val("");
}

function init_custom_select($this = false) {
  var item = $this.length ? $this : $(".select-html");
  item.each(function () {
    $(this).addClass("hidden");

    var _this = $(this);
    var wrap = $('<div class="select-wrapper"></div>'),
      selected = $('<div class="selected" data-value=""></div>').text(
        $(this).attr("placeholder")
      ),
      header = $('<div class="entry-header"></div>'),
      listWrap = $('<div class="list-wrap"></div>'),
      list = $('<ul class="select-list"></ul>');

    if ($(this).attr("disabled")) {
      wrap.addClass("disabled");
    }
    if ($(this).hasClass("list")) {
      listWrap.addClass("list");
    }

    _this.find("option").each(function () {
      var val = $(this).val();
      var text = $(this).text();
      var item = $('<li data-value="' + val + '"></li>').text(text);

      if ($(this).attr("selected")) {
        item.attr("data-selected", true);
        _this.parent().addClass("has-value");
        selected.attr("data-value", item.attr("data-value")).text(item.text());
      }

      if ($(this).attr("data-hidden")) {
        item.addClass("hidden");
      }

      list.append(item);
    });

    header.append(selected);

    wrap.append(header, listWrap.append(list));
    _this.after(wrap);
  });

  $("body").on("click", ".select-wrapper .entry-header", function () {
    var toggleBox = $(this).parent().find(".list-wrap");
    var parent = $(this).parents(".select-wrap");

    if (!parent.hasClass("active")) {
      parent
        .addClass("active")
        .siblings()
        .removeClass("active")
        .find(".list-wrap")
        .fadeOut(300);

      toggleBox.fadeIn(300);
    }
  });

  $("body").on("click", ".select-list li", function () {
    var parent = $(this).parents(".select-wrap"),
      toggleBox = parent.find(".list-wrap"),
      value = $(this).attr("data-value");

    parent.find(".selected").attr("data-value", value).text($(this).text());
    $(this).attr("data-selected", true).siblings().attr("data-selected", false);

    parent.removeClass("active").addClass("has-value");
    toggleBox.fadeOut(300);

    parent.find("select").val(value).change();
  });

  $(document).mouseup(function (e) {
    var container = $(".select-wrap");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
      $(".select-wrap").removeClass("active").find(".list-wrap").slideUp(300);
    }
  });
}

function scroll_to_hash() {
  $('a[href^="#"]:not(.yBox)').click(function (event) {
    // The id of the section we want to go to.
    var id = $(this).attr("href");

    if (id === "#") {
      return;
    }
    // An offset to push the content down from the top.
    var offset = 150;

    // Our scroll target : the top position of the
    // section that has the id referenced by our href.
    var target = $(id).offset().top - offset;

    // The magic...smooth scrollin' goodness.
    $("html, body").animate({ scrollTop: target }, 800);

    //prevent the page from jumping down to our section.
    event.preventDefault();
  });
}

/**
 * initMap
 *
 * Renders a Google Map onto the selected jQuery element
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   jQuery $el The jQuery element.
 * @return  object The map instance.
 */
function initMap($el) {
  // Find marker elements within map.
  var $markers = $el.find(".marker");

  // Create gerenic map.
  var mapArgs = {
    zoom: 16,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    center: new google.maps.LatLng($el.data("lat"), $el.data("lng")),
    disableDefaultUI: true,
    scrollwheel: true,
    controls: {
      panControl: true,
      zoomControl: true,
      mapTypeControl: true,
      scaleControl: true,
      streetViewControl: true,
      overviewMapControl: true,
    },
  };

  var styledMapType = new google.maps.StyledMapType([
    {
      featureType: "administrative",
      elementType: "all",
      stylers: [{ visibility: "on" }],
    },
    {
      featureType: "administrative",
      elementType: "labels.text.fill",
      stylers: [{ color: "#444444" }],
    },
    {
      featureType: "administrative.locality",
      elementType: "geometry.fill",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "landscape",
      elementType: "all",
      stylers: [
        { visibility: "on" },
        { color: "#f8f8f8" },
        { lightness: "71" },
      ],
    },
    {
      featureType: "landscape.man_made",
      elementType: "all",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "landscape.natural",
      elementType: "labels.text.fill",
      stylers: [{ color: "#ff0000" }],
    },
    {
      featureType: "landscape.natural.landcover",
      elementType: "all",
      stylers: [{ visibility: "off" }, { color: "#b46c6c" }],
    },
    {
      featureType: "landscape.natural.landcover",
      elementType: "geometry.fill",
      stylers: [{ visibility: "on" }, { color: "#ff0000" }],
    },
    {
      featureType: "landscape.natural.terrain",
      elementType: "all",
      stylers: [{ visibility: "simplified" }, { color: "#be6262" }],
    },
    {
      featureType: "landscape.natural.terrain",
      elementType: "geometry.fill",
      stylers: [{ visibility: "on" }, { hue: "#ff0000" }],
    },
    {
      featureType: "poi",
      elementType: "all",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "poi",
      elementType: "labels.text.fill",
      stylers: [{ visibility: "on" }],
    },
    {
      featureType: "poi.attraction",
      elementType: "geometry.fill",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "poi.attraction",
      elementType: "labels.icon",
      stylers: [{ visibility: "off" }, { hue: "#ff0000" }],
    },
    {
      featureType: "poi.business",
      elementType: "labels.text.fill",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "poi.park",
      elementType: "all",
      stylers: [
        { visibility: "on" },
        { lightness: "22" },
        { color: "#ddf4dd" },
        { weight: "0.01" },
      ],
    },
    {
      featureType: "poi.park",
      elementType: "labels",
      stylers: [{ visibility: "on" }],
    },
    {
      featureType: "poi.park",
      elementType: "labels.text",
      stylers: [{ lightness: "100" }, { color: "#63929e" }],
    },
    {
      featureType: "road",
      elementType: "all",
      stylers: [
        { saturation: -100 },
        { lightness: 45 },
        { visibility: "simplified" },
        { color: "#f1edee" },
      ],
    },
    {
      featureType: "road",
      elementType: "labels.text",
      stylers: [{ color: "#306e80" }, { lightness: "10" }, { weight: "0.90" }],
    },
    {
      featureType: "road.highway",
      elementType: "all",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "road.arterial",
      elementType: "all",
      stylers: [{ visibility: "simplified" }],
    },
    {
      featureType: "road.arterial",
      elementType: "labels.icon",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "road.local",
      elementType: "all",
      stylers: [{ visibility: "simplified" }],
    },
    {
      featureType: "transit",
      elementType: "all",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "transit",
      elementType: "labels",
      stylers: [{ visibility: "on" }],
    },
    {
      featureType: "transit",
      elementType: "labels.text",
      stylers: [{ visibility: "on" }, { color: "#e31111" }],
    },
    {
      featureType: "transit",
      elementType: "labels.icon",
      stylers: [{ visibility: "simplified" }],
    },
    {
      featureType: "transit.station",
      elementType: "labels.text.fill",
      stylers: [{ visibility: "off" }],
    },
    {
      featureType: "transit.station",
      elementType: "labels.text.stroke",
      stylers: [{ color: "#306e80" }],
    },
    {
      featureType: "water",
      elementType: "all",
      stylers: [{ color: "#71c1e2" }, { visibility: "on" }],
    },
    {
      featureType: "water",
      elementType: "geometry",
      stylers: [{ color: "#d5e0f6" }],
    },
    {
      featureType: "water",
      elementType: "geometry.fill",
      stylers: [
        { visibility: "on" },
        { saturation: "23" },
        { color: "#337285" },
        { lightness: "79" },
      ],
    },
    {
      featureType: "water",
      elementType: "labels.text",
      stylers: [{ visibility: "on" }],
    },
  ]);
  var map = new google.maps.Map($el[0], mapArgs);

  // Append to reference for later use.
  map.mapTypes.set("styled_map", styledMapType);
  map.setMapTypeId("styled_map");
  // Add markers.
  map.markers = [];
  $markers.each(function () {
    initMarker($(this), map);
  });

  $('.map-filters [type="checkbox"]').on("change", function (e) {
    var type = $(this).attr("name");
    var show = false;
    if ($(this).is(":checked")) {
      show = true;
    }

    for (var marker in map.markers) {
      if (map.markers[marker].type === type) {
        map.markers[marker].setVisible(show);
      }
    }
  });
  // Return map instance.
  return map;
}

/**
 * initMarker
 *
 * Creates a marker for the given jQuery element and map.
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   jQuery $el The jQuery element.
 * @param   object The map instance.
 * @return  object The marker instance.
 */
function initMarker($marker, map) {
  // Get position from marker.
  var lat = $marker.data("lat");
  var lng = $marker.data("lng");
  var type = $marker.data("type");
  var latLng = {
    lat: parseFloat(lat),
    lng: parseFloat(lng),
  };

  // Create marker instance.
  var marker = new google.maps.Marker({
    position: latLng,
    map: map,
    icon: {
      url: siteObject.themeurl + "/assets/img/marker-" + type + ".svg",
      // size: new google.maps.Size(55, 55),
      // // The origin for this image is (0, 0).
      origin: new google.maps.Point(0, 0),
      // // The anchor for this image is the base of the flagpole at (0, 32).
      anchor: new google.maps.Point(40, 50),
    },
    clickable: false,
    type: type,
  });
  map.markers.push(marker);
}

/**
 * centerMap
 *
 * Centers the map showing all markers in view.
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   object The map instance.
 * @return  void
 */
function centerMap(map) {
  // Create map boundaries from all map markers.
  var bounds = new google.maps.LatLngBounds();
  map.markers.forEach(function (marker) {
    bounds.extend({
      lat: marker.position.lat(),
      lng: marker.position.lng(),
    });
  });

  // Case: Single marker.
  if (map.markers.length == 1) {
    map.setCenter(bounds.getCenter());

    // Case: Multiple markers.
  } else {
    map.fitBounds(bounds);
  }
}

function init_file_upload_drag() {
  if (!$(".drag-wrapper").length) {
    return;
  }
  const dargContainer = document.querySelector(".drag-wrapper"),
    dropArea = dargContainer.querySelector(".drag-area"),
    button = dargContainer.querySelector("button"),
    input = dargContainer.querySelector("input");
  let file; //this is a global variable and we'll use it inside multiple functions
  button.onclick = () => {
    input.click(); //if user click on the button then the input also clicked
  };
  input.addEventListener("change", function () {
    //getting user select file and [0] this means if user select multiple files then we'll select only the first one
    file = this.files[0];
    dropArea.classList.add("active");
    showFile(); //calling function
  });
  //If user Drag File Over DropArea
  dropArea.addEventListener("dragover", (event) => {
    event.preventDefault(); //preventing from default behaviour
    dropArea.classList.add("active");
    // dragText.textContent = "Release to Upload File";
  });
  //If user leave dragged File from DropArea
  dropArea.addEventListener("dragleave", () => {
    dropArea.classList.remove("active");
    // dragText.textContent = "Drag & Drop to Upload File";
  });
  //If user drop File on DropArea
  dropArea.addEventListener("drop", (event) => {
    event.preventDefault(); //preventing from default behaviour
    //getting user select file and [0] this means if user select multiple files then we'll select only the first one
    file = event.dataTransfer.files[0];
    showFile(); //calling function
  });
  function showFile() {
    let fileType = file.type; //getting selected file type
    let validExtensions = [
      "image/jpeg",
      "image/jpg",
      "image/png",
      "application/pdf",
      "application/msword",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "text/plain",
    ]; //adding some valid image extensions in array
    if (validExtensions.includes(fileType)) {
      //if user selected file is an image file
      let fileReader = new FileReader(); //creating new FileReader object
      fileReader.onload = () => {
        let fileURL = fileReader.result; //passing user file source in fileURL variable
        // UNCOMMENT THIS BELOW LINE. I GOT AN ERROR WHILE UPLOADING THIS POST SO I COMMENTED IT
        // let imgTag = `<img src="${fileURL}" alt="image">`; //creating an img tag and passing user selected file source inside src attribute
        // dropArea.innerHTML = imgTag; //adding that created img tag inside dropArea container

        dropArea.querySelector(".entry-text").textContent = file.name;
      };
      fileReader.readAsDataURL(file);
    } else {
      alert("This is not a valid File!");
      dropArea.classList.remove("active");
      // dragText.textContent = "Drag & Drop to Upload File";
    }
  }
}

var icsFile = null;

$(".add-to-apple-btn").on("click", function (e) {
  e.preventDefault();

  var eventDate = {
      start: $(this).attr("data-start"),
      end: $(this).attr("data-end"),
    },
    summary = $(this).attr("data-title"),
    description = $(this).attr("data-desc");

  var link = document.querySelector(".apple-download-btn");
  link.href = makeIcsFile(eventDate, summary, description);

  link.click();
  // window.location.href = link.href;
});

function convertDate(date) {
  var event = new Date(date).toISOString();
  event = event.split("T")[0];
  event = event.split("-");
  event = event.join("");
  return event;
}
function makeIcsFile(date, summary, description) {
  var test =
    "BEGIN:VCALENDAR\n" +
    "CALSCALE:GREGORIAN\n" +
    "METHOD:PUBLISH\n" +
    "PRODID:-//Test Cal//EN\n" +
    "VERSION:2.0\n" +
    "BEGIN:VEVENT\n" +
    "UID:test-1\n" +
    "DTSTART;VALUE=DATE:" +
    convertDate(date.start) +
    "\n" +
    "DTEND;VALUE=DATE:" +
    convertDate(date.end) +
    "\n" +
    "SUMMARY:" +
    summary +
    "\n" +
    "DESCRIPTION:" +
    description +
    "\n" +
    "END:VEVENT\n" +
    "END:VCALENDAR";

  var data = new File([test], { type: "text/plain" });

  // If we are replacing a previously generated file we need to
  // manually revoke the object URL to avoid memory leaks.
  if (icsFile !== null) {
    window.URL.revokeObjectURL(icsFile);
  }

  icsFile = window.URL.createObjectURL(data);

  return icsFile;
}

// Job Mobile - Open popup
$('body').on('click', '.open-job-content', function(){
	$(this).closest('.entry-job').addClass('active');
	$('body').addClass('open-job-popup-content');
})
// Job Mobile - Close popup
$('body').on('click', '.close-job-content', function(){
	$(this).closest('.entry-job').removeClass('active');
	$('body').removeClass('open-job-popup-content');
})
