let coordinates = [];
let locationCookie;

if (getPolicyByName("c-functional")) {
    locationCookie = true;
}

$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
    },
});

/* SEND FORMS */
$("#post-contact-form").submit(function (event) {
    event.preventDefault();

    let form = $(this);
    if (!form.valid) return false;
    $.ajax({
        url: "/companies-contact",
        type: "POST",
        data: $("#post-contact-form").serialize(),
        // dataType: 'JSON',
        beforeSend: function () {
            $('#post-contact-form button[type="submit"]').prop(
                "disabled",
                true
            );
            // Add spinner to button
            $('#post-contact-form button[type="submit"] img').css(
                "display",
                "block"
            );
            $('#post-contact-form button[type="submit"] .btn-txt').css(
                "display",
                "none"
            );
        },
        success: function (data) {
            // Clear the contact form
            $(".contact-form-error").empty();
            $("#post-contact-form")[0].reset();

            // Reset toast
            $(".toasts").empty();
            // Display success flash message
            $(".toasts").html(data);
        },
        error: function (error) {
            // Reset all error messages
            $(".contact-form-error").empty();

            let errors = error.responseJSON.errors;

            for (let i in errors) {
                // Get the according input field
                $(`#post-contact-form .${i}-error`).text(errors[i][0]);
            }
        },
        complete: function () {
            $('#post-contact-form button[type="submit"]').prop(
                "disabled",
                false
            );
            $('#post-contact-form button[type="submit"] img').css(
                "display",
                "none"
            );
            $('#post-contact-form button[type="submit"] .btn-txt').css(
                "display",
                "block"
            );
        },
    });
});

$('#job-alert-modal').submit(function(event) {
    
    event.preventDefault()
    let form = $(this);

    let lang = $('html').attr('lang');

    if (!form.valid) return false;
    $.ajax({
        url: `/${lang}/job-alert`,
        type: 'POST',
        data: $('#job-alert-modal').serialize(),
        // dataType: 'JSON',
        beforeSend: function() {
            $('#job-alert-modal button[type="submit"]').prop('disabled', true)
            // Add spinner to button
            $('#job-alert-modal button[type="submit"] img').css('display', 'block')
            $('#job-alert-modal button[type="submit"] .btn-txt').css('display', 'none')
        },
        success: function(data) {
            // Clear the contact form
            $('.job-alert-form-error').empty()
            $('#job-alert-modal')[0].reset()

            // Close contact popup
            jobAlertClose()

            // Reset toast
            $('.toasts').empty()
            // Display success flash message
            $('.toasts').html(data)

        },
        error: function(error) {
            // Reset all error messages
            $('.job-alert-form-error').empty()

            let errors = error.responseJSON.errors

            for (let i in errors) {
                // Get the according input field
                $(`#job-alert-modal .${i}-error`).text(errors[i][0]);
            }
        },
        complete: function() {
            $('#job-alert-modal button[type="submit"]').prop('disabled', false)
            $('#job-alert-modal button[type="submit"] img').css('display', 'none')
            $('#job-alert-modal button[type="submit"] .btn-txt').css('display', 'block')
        }
    });
});

$('#post-preference-form').submit(function(event) {
    event.preventDefault()
    let form = $(this);

    let lang = $('html').attr('lang');

    if (!form.valid) return false;
    $.ajax({
        url: `/${lang}/mail-preferences`,
        type: 'POST',
        data: $('#post-preference-form').serialize(),
        // dataType: 'JSON',
        beforeSend: function() {
            $('#post-preference-form button[type="submit"]').prop('disabled', true)
            // Add spinner to button
            $('#post-preference-form button[type="submit"] img').css('display', 'block')
            $('#post-preference-form button[type="submit"] .btn-txt').css('display', 'none')
        },
        success: function(data) {
            // Clear the contact form
            $('.contact-form-error').empty()
            $('#post-preference-form')[0].reset()

            // Reset toast
            $('.toasts').empty()
            // Display success flash message
            $('.toasts').html(data)

        },
        error: function(error) {
            // Reset all error messages
            $('.contact-form-error').empty()

            let errors = error.responseJSON.errors

            for (let i in errors) {
                // Get the according input field
                $(`#post-preference-form .${i}-error`).text(errors[i][0]);
            }
        },
        complete: function() {
            $('#post-preference-form button[type="submit"]').prop('disabled', false)
            $('#post-preference-form button[type="submit"] img').css('display', 'none')
            $('#post-preference-form button[type="submit"] .btn-txt').css('display', 'block')
        }
    });
})

$('#post-mailing-preference-form').submit(function(event) {
    event.preventDefault()
    let form = $(this);

    let lang = $('html').attr('lang');

    if (!form.valid) return false;
    $.ajax({
        url: `/${lang}/mailing-preferences`,
        type: 'POST',
        data: $('#post-mailing-preference-form').serialize(),
        // dataType: 'JSON',
        beforeSend: function() {
            $('#post-mailing-preference-form button[type="submit"]').prop('disabled', true)
            // Add spinner to button
            $('#post-mailing-preference-form button[type="submit"] img').css('display', 'block')
            $('#post-mailing-preference-form button[type="submit"] .btn-txt').css('display', 'none')
        },
        success: function(data) {
            // Clear the contact form
            $('.contact-form-error').empty()
            $('#post-mailing-preference-form')[0].reset()

            // Reset toast
            $('.toasts').empty()
            // Display success flash message
            $('.toasts').html(data)

        },
        error: function(error) {
            // Reset all error messages
            $('.contact-form-error').empty()

            let errors = error.responseJSON.errors

            for (let i in errors) {
                // Get the according input field
                $(`#post-mailing-preference-form .${i}-error`).text(errors[i][0]);
            }
        },
        complete: function() {
            $('#post-mailing-preference-form button[type="submit"]').prop('disabled', false)
            $('#post-mailing-preference-form button[type="submit"] img').css('display', 'none')
            $('#post-mailing-preference-form button[type="submit"] .btn-txt').css('display', 'block')
        }
    });
})

/* COMMON JS */
// Hover event handler on navigation contact button
$(".contact-dropdown-dropbtn, .contact-dropdown-content").hover(
    function () {
        $(".contact-dropdown-content").css("display", "block");
        // $(".navigation").css("z-index", "-1");
    },
    function () {
        $(".contact-dropdown-content").css("display", "none");
        // $(".navigation").css("z-index", "0");
    }
);

/* SAVE COUNTRY PREFERENCES */
$(".save-country-preferences").on("click", function () {
    var country = $(this).data("country");
    setCookie("country-choose", country);

    if (country == "FR") {
        window.location.href = "https://fr.ago.jobs/fr/fr";
    } else {
        location.reload();
        // countryChooseClose();
    }
});

// Hover event handler on navigation contact button
$(".contact-dropdown-dropbtn, .contact-dropdown-content").hover(
    function () {
        $(".contact-dropdown-content").css("display", "block");
        $(".navigation").css("z-index", "-1");
    },
    function () {
        $(".contact-dropdown-content").css("display", "none");
        $(".navigation").css("z-index", "0");
    }
);

$(
    ".country-choosing-dropdown-dropbtn, .country-choosing-dropdown-content"
).hover(
    function () {
        $(".country-choosing-dropdown-content").css("display", "block");
        $(".navigation").css("z-index", "-1");
    },
    function () {
        $(".country-choosing-dropdown-content").css("display", "none");
        $(".navigation").css("z-index", "0");
    }
);

/* COOKIE PREFERENCES */
let privacyModal = $("#privacy-modal");
$(".save-cookie-preferences").on("click", function (e) {
    e.preventDefault();
    var disabled = privacyModal.find(":input:disabled").removeAttr("disabled");
    let data = $(".cookie-preferences").serialize();
    data = data + "&accept_cookie_policy=on";
    disabled.attr("disabled", "disabled");

    setCookie("cookie-policy", data);
    privacyModal.hide();
    location.reload();
    return false;
});

$(".accept-all-cookies").on("click", function (e) {
    e.preventDefault();
    let data =
        "c-functional=on&c-voorkeur=on&c-analytics=on&c-social=on&accept_cookie_policy=on";
    setCookie("cookie-policy", data);
    privacyModal.hide();
    $(".privacy-options-title").toggle();
    $(".privacy-options").toggle();
    location.reload();
    return false;
});

$("#privacy-modal .reveal-options").click(function () {
    $(".privacy-options-title").toggle();
    $(".privacy-options").toggle();
});

function setCookie(name, value) {
    var cookie = name + "=" + encodeURIComponent(value);
    cookie += "; path=/; expires=Thu, 1 Jan 2100 12:00:00 UTC;";
    document.cookie = cookie;
}

function getPolicyByName(name) {
    let data = getCookie("cookie-policy");
    dataArr = decodeURIComponent(data).split("&");

    if ($.inArray(name + "=on", dataArr) != -1) {
        // cookie allowed
        return true;
    } else {
        // cookie not allowed
        return false;
    }
}

function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
        return parts.pop().split(";").shift();
    }
}
/* END COOKIE PREFERENCES */

/* SLIDERS (VACANCIES / COMPANIES / BLOG / ... ) */
// VACANCY SLIDER
$("#vacancy-slider").slick({
    arrows: false,
    slidesToShow: $("#vacancy-slider").attr('data-amount'),
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 2000,
    infinite: true,
    responsive: [
        {
            breakpoint: 1369,
            settings: {
                slidesToShow: 3,
                slidesToScroll: 1
            }
        },
        {
            breakpoint: 1100,
            settings: {
                slidesToShow: 2,
                slidesToScroll: 1
            }
        },
        {
            breakpoint: 768,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
            },
        },
    ],
});

$(".vacancy-next").click(function () {
    $("#vacancy-slider").slick("slickNext");
});

$(".vacancy-prev").click(function () {
    $("#vacancy-slider").slick("slickPrev");
});

// COMPANY SLIDER
$(".company-slider").slick({
    arrows: false,
    slidesToShow: 6,
    slidesToScroll: 1,
    autoplaySpeed: 2000,
    infinite: true,
    autoplay: true,
    responsive: [
        {
            breakpoint: 1250,
            settings: {
                slidesToShow: 5,
                slidesToScroll: 1,
            },
        },
        {
            breakpoint: 1065,
            settings: {
                slidesToShow: 4,
                slidesToScroll: 1,
            },
        },
        {
            breakpoint: 768,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
            },
        },
    ],
});

$(".company-prev").click(function () {
    $(".company-slider").slick("slickNext");
});
$(".company-next").click(function () {
    $(".company-slider").slick("slickPrev");
});

// BLOG SLIDER
$("#blog-slider").slick({
    arrows: false,
    slidesToShow: 4,
    slidesToScroll: 1,
    autoplay: true,
    speed: 600,
    autoplaySpeed: 2000,
    infinite: true,
    responsive: [
        {
            breakpoint: 768,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
            },
        },
    ],
});

$(".blog-next").click(function () {
    $("#blog-slider").slick("slickNext");
});

$(".blog-prev").click(function () {
    $("#blog-slider").slick("slickPrev");
});

$("#division-slider").slick({
    arrows: false,
    slidesToShow: 5,
    slidesToScroll: 1,
    autoplay: true,
    speed: 600,
    autoplaySpeed: 6000,
    infinite: true,
    centerMode: true,
    centerPadding: "0",
    responsive: [
        {
            breakpoint: 768,
            settings: {
                slidesToShow: 1,
                slidesToScroll: 1,
            },
        },
    ],
});

$(".division-next").click(function () {
    $("#division-slider").slick("slickNext");
});

$(".division-prev").click(function () {
    $("#division-slider").slick("slickPrev");
});

/* END SLIDERS */

// SET LIKE COOKIE
$(document).on("click", ".fa-heart", function () {
    var self = $(this);
    var reference = self.data("reference");

    $.ajax({
        type: "GET",
        url: "/cookie/set/" + reference,
        contentType: "text/plain",
        dataType: "text",
        success: function (data) {
            if (self.hasClass("fas")) {
                self.removeClass("fas");
                self.addClass("far");
            } else {
                self.removeClass("far");
                self.addClass("fas");
            }

            if ("{{ Route::currentRouteName() }}" == "likes") {
                var job = self.closest(".job-offers-list-item").remove();
            }

            $.ajax({
                type: "GET",
                url: "/cookie/get/getamountlikes",
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    // $("#amount_likes").html(data.amount);
                    $(".amount_likes").html(data.amount);
                },
            });
        },
    });

    return false;
});

// JOBS OVERLAY
$(document).on(
    "click",
    ".toggle-filters-btn, .filters-overlay-show-btn",
    function (e) {
        e.preventDefault();
        $(".jobs-filter-overlay")
            .slideToggle(350)
            .promise()
            .done(overlayActive);
    }
);

function overlayActive() {
    if ($(".jobs-filter-overlay").css("display") == "none") {
        // Undo prevent scrolling on background
        $(document.body).css({ overflow: "initial" });

        // // Hide overlay action buttons
        $(".overlay-action-btn").hide();

        // Show back to top button
        $(".back-to-top").show();
    } else {
        // Prevent scrolling on background
        $(document.body).css({ overflow: "hidden" });

        // // Show overlay action buttons
        $(".overlay-action-btn").show();

        // Hide back to top button
        $(".back-to-top").hide();
    }
}

function useCurrentLocationHome() {
    event.preventDefault();
    if (locationCookie) {
        navigator.geolocation.getCurrentPosition((position) => {
            const {
                coords: { latitude, longitude },
            } = position;
            let lat = position["coords"]["latitude"];
            let lng = position["coords"]["longitude"];
            coordinates = [];
            coordinates.push(lat);
            coordinates.push(lng);

            $("input[name='autocomplete_lat']").val(lat);
            $("input[name='autocomplete_lng']").val(lng);

            $.ajax({
                url: "/reverse-geocode",
                type: "POST",
                data: { coordinates: coordinates },
                // dataType: 'JSON',
                success: function (data) {
                    if (data == false) {
                    } else {
                        $('input[type="text"][name="location"]')
                            .val(data)
                            .trigger("change");
                    }
                },
            });
        });
    }
}

$(document).on("click", "#mobile-nav-trigger", function () {
    if ($(this).hasClass("open")) {
        document.getElementById("mobile-nav-overlay").style.height = "0%";
        $(this).removeClass("open");

        // Enable scrolling again
        $("html, body").css({
            overflow: "initial",
            height: "initial",
        });
    } else {
        document.getElementById("mobile-nav-overlay").style.height =
            "calc(100% - 51px)";
        $(this).addClass("open");

        // Prevent scrolling if nav is open
        $("html, body").css({
            overflow: "hidden",
            height: "100%",
        });
    }
});

$(".get-directions").on("click", function (event) {
    event.preventDefault();
    let lat = $(this).data("lat");
    let lng = $(this).data("lng");

    if (
        navigator.platform.indexOf("iPhone") != -1 ||
        navigator.platform.indexOf("iPod") != -1 ||
        navigator.platform.indexOf("iPad") != -1
    )
        window.open(`http://maps.apple.com/?daddr=${lat},${lng}`);
    else
        window.open(
            `https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=${lat},${lng}`
        );
});
