// spawntree
// overwriting date picker function

let spwnIncludedDays = [0,2,3,4,5,6];
let spawnDateInputValue = "";
let fp;

const inputSameDayDelivery = $("#shippingMethod67f8c7d3ecdb4ad7802bf8eb55c9b13b");
const inputShopPickup = $("#shippingMethod0f44c72f7560450caf061922daeb1602");
const inputDPD = $("#shippingMethod8c6d913e29c14c3cb3c6429724efaab8");
const inputVorkasse = $("#paymentMethod31bc923a38bc435a80d49d4d40368081");

$(document).ready(function() {
    // Add Class for Promotion Modal Box
    if ($(".swag-custom-notification-info-modal__content").length) {
        $(".swag-custom-notification-info-modal__content").parents(".modal").addClass("spwn-swag-custom-notification-info");
    }

    let dpInput = $(".confirm-delivery-date #dtgs-datepicker-inputfield");
    if (dpInput.length) {
        fp = document.querySelector("#dtgs-datepicker-inputfield")._flatpickr;
        dpInput.prop('disabled', true);
        dpInput.wrap('<div class="spwn-date-wrapper"></div>');
        $("<span id='spwn-remove-date' title='Zurücksetzen'></span>").insertAfter(dpInput);
        $("<input type='text' value='' id='spwn-dp-input' disabled='disabled' />").insertAfter(dpInput);
        let doNotShow = $(".do-not-show").length ? " class='do-not-show'" : "";
        $("<div id='spwn-delivery'" + doNotShow + "><p></p><div class='spwn-delivery--time'></div></div>").insertAfter(".confirm-delivery-date");
        fp.config.onChange.push(function() {
            manipulateDateInputValue();
        });

        // If Austria and same day delivery is checked change to DPD
        if ($(".confirm-address-shipping").data("iso") === "AT") {
            inputDPD.attr('checked', true).trigger("click");
            // No same day delivery
            inputSameDayDelivery.parents(".shipping-method").hide();
            // No shop
            inputShopPickup.parents(".shipping-method").hide();
        }

        // Call changeDelivery
        $("[name='shippingMethodId']").on('change', () => {
            changeDelivery(fp);
        });

        /* Set first selectable day selected */
        // remove hours
        if ($(".confirm-delivery-date #dtgs-datepicker-inputfield").val().indexOf(":") !== -1) {
            let inputTemp = $(".confirm-delivery-date #dtgs-datepicker-inputfield").val();
            spawnDateInputValue = inputTemp.substring(0, inputTemp.length - 6);
        } else {
            spawnDateInputValue = $(".confirm-delivery-date #dtgs-datepicker-inputfield").val();
        }
        if (spawnDateInputValue === '') {
            setDateSelected();
        }
        $("body").find("#spwn-dp-input").val(spawnDateInputValue);

        changeDelivery(fp);
    }

    var sticky = $(".thumbnail-container");
    if (sticky.length) {
        var parentContainer = sticky.parents(".aku-cms-factory-element"),
            stickyTop = sticky.offset().top;
        tagBar(sticky, parentContainer, stickyTop);
        $(window).on('resize scroll', function() {
            tagBar(sticky, parentContainer, stickyTop);
        });
    }

    $("body").on("click", "#spwn-remove-date", function() {
        $(".confirm-delivery-date #spwn-dp-input").val("");
        $(".confirm-delivery-date #dtgs-datepicker-inputfield").val("");
        spawnDateInputValue = "";
    });

    // Add smooth scrolling to all links
    $(".thumbnail-container a").on('click', function(event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();
            // Store hash
            var hash = this.hash;

            var sTop = parseInt($(hash).offset().top - $(".header-inner").outerHeight() - 12);
            scrollToPos(sTop, 800);
            window.location.hash = hash;
        } // End if
    });
});

// c = element or pixel position
// e = duration
// d = (optative) ease function. Default easeOutCuaic
function scrollToPos(c,e,d){d||(d=easeOutCuaic);var a=document.documentElement;if(0===a.scrollTop){var b=a.scrollTop;++a.scrollTop;a=b+1===a.scrollTop--?a:document.body}b=a.scrollTop;0>=e||("object"===typeof b&&(b=b.offsetTop),"object"===typeof c&&(c=c.offsetTop),function(a,b,c,f,d,e,h){function g(){0>f||1<f||0>=d?a.scrollTop=c:(a.scrollTop=b-(b-c)*h(f),f+=d*e,setTimeout(g,e))}g()}(a,b,c,0,1/e,20,d))};
function easeOutCuaic(t){
    t--;
    return t*t*t+1;
}

function manipulateDateInputValue() {
    console.log("manipulateDateInputValue");
    // remove hours
    if ($(".confirm-delivery-date #dtgs-datepicker-inputfield").val().indexOf(":") !== -1) {
        let inputTemp = $(".confirm-delivery-date #dtgs-datepicker-inputfield").val();
        spawnDateInputValue = inputTemp.substring(0, inputTemp.length - 6);
    } else {
        spawnDateInputValue = $(".confirm-delivery-date #dtgs-datepicker-inputfield").val();
    }
    if (inputSameDayDelivery.is(':checked')) {
        // If same day delivery is checked, select time
        // $("#spwn-delivery .spwn-delivery--time span.active").trigger("click");
        $(".confirm-delivery-date #spwn-dp-input").val(spawnDateInputValue + " " + $("#spwn-delivery .spwn-delivery--time span.active").text());
        $(".confirm-delivery-date #dtgs-datepicker-inputfield").val(spawnDateInputValue + " " + $("#spwn-delivery .spwn-delivery--time span.active").attr('data-time'));
        $(".flatpickr-hour").val($("#spwn-delivery .spwn-delivery--time span.active").attr('data-hour'));
    } else {
        $("#spwn-dp-input").val(spawnDateInputValue);
    }
}

function setDateSelected() {
    console.log("setDateSelected");
    let spwnFirstSelectableDay = $(".flatpickr-day:not(.flatpickr-disabled)").first().text();
    let spwnFPdate = new Date();
    let spwnDay = spwnFPdate.getDate();
    let spwnMonth = spwnFPdate.getMonth();
    // month +1 (january == 0)
    spwnMonth = spwnMonth + 1;
    if (spwnFirstSelectableDay < spwnDay) {
        // if selectable day in next month add +1 to month
        spwnMonth = spwnMonth + 1;
    }
    let spwnFrmattedDate = spwnFPdate.getFullYear() + '/' + spwnMonth + '/' + spwnFirstSelectableDay;
    fp.setDate(new Date(spwnFrmattedDate), true);
    spawnDateInputValue = spwnFirstSelectableDay + '.' + spwnMonth + '.' + spwnFPdate.getFullYear();
}

function changeDelivery(fp) {
    console.log("changeDelivery");
    $("body").on("click", "#spwn-delivery .spwn-delivery--time span", function() {
        $("#spwn-delivery .spwn-delivery--time span").removeClass("active");
        $(this).addClass("active");
        $(".confirm-delivery-date #spwn-dp-input").val(spawnDateInputValue + " " + $(this).text());
        let spawnDateTime = spawnDateInputValue + " " + $(this).attr('data-time');
        $(".confirm-delivery-date #dtgs-datepicker-inputfield").val(spawnDateTime);
        $(".flatpickr-hour").val($(this).attr('data-hour'));
        fp.setDate(spawnDateInputValue, true, "d.m.Y H:i");
    });

    let daysToAdd = 0;
    // if Vorkasse add 4 days
    if (inputVorkasse.is(':checked')) {
        daysToAdd = 4;
    }
    if ($(".confirm-address-shipping").data("iso") !== "AT") {
        if (inputShopPickup.is(':checked')) {
            // Abholung im Ladengeschäft
            console.log("Abholung");
            $(".confirm-delivery-date #spwn-dp-input").val('Abholung im Ladengeschäft');
            $(".confirm-delivery-date #dtgs-datepicker-inputfield").val('31.12.2050 04:00');
            $(".confirm-delivery-date").hide();
            $("#spwn-delivery p").text("Die bestellten Produkte stehen zur Abholung in unserem Ladengeschäft in Hamburg für Sie bereit.");
            $(".flatpickr-hour").val('04');
        } else if (inputSameDayDelivery.is(':checked')) {
            // Abendzustellung
            console.log("Abendzustellung");
            // ONLY TUE AND THU
            spwnIncludedDays = [2, 4];
            // spwnIncludedDays = [1, 2, 3, 4, 5];
            if (daysToAdd === 0) {
                daysToAdd = 0;
            }
            setIncludedDays("evening", fp, daysToAdd);
            $("#spwn-delivery p").text("Abendzustellung gewählt. Bitte wählen Sie nun eine Wunsch-Zeit:");
            $("#spwn-delivery .spwn-delivery--time").append("<span class='active' data-time='18:00' data-hour='18'>18 - 20 Uhr</span><span data-time='19:00' data-hour='19'>19 - 21 Uhr</span><span data-time='20:00' data-hour='20'>20 - 22 Uhr</span>");
            // If not date from DPD days
            if (!$(".flatpickr-day").hasClass("selected")) {
                setDateSelected();
            }
            if ($(".flatpickr-day").hasClass("selected")) {
                // || spawnDateInputValue.indexOf(":00") === -1
                if (spawnDateInputValue === "") {
                    manipulateDateInputValue();
                }
            } else {
                // If DPD date is not in Abendzustellung range
                setDateSelected();
            }
            $("#spwn-delivery .spwn-delivery--time span.active").trigger("click");
        } else {
            // DPD
            console.log("DPD");
            if ($(".confirm-address-shipping").data("iso") === "DE") {
                spwnIncludedDays = [2, 3, 4, 5, 6];
            } else {
                // All other countries without saturday
                spwnIncludedDays = [2, 3, 4, 5];
            }
            if (daysToAdd === 0) {
                daysToAdd = 1;
            }
            setIncludedDays("dpd", fp, daysToAdd);
            $("#spwn-delivery p").text("DPD gewählt. Die Zustellung erfolgt zwischen 7 und 13 Uhr.");
            if (!$(".flatpickr-day").hasClass("selected")) {
                // If Abendzustellung date is not in DPD range
                setDateSelected();
            }
            $(".flatpickr-hour").val('01');
        }
    } else {
        console.log("DPD AT");
        // only wednesday and thursday
        spwnIncludedDays = [3, 4];
        if (daysToAdd === 0) {
            daysToAdd = 2;
        }
        setIncludedDays("dpd", fp, daysToAdd);
        $("#spwn-delivery p").text("DPD gewählt. Die Zustellung erfolgt zwischen 7 und 18 Uhr.");
        if (!$(".flatpickr-day").hasClass("selected")) {
            // If Abendzustellung or DPD DE date is not in DPD AT range
            setDateSelected();
        }
        $(".flatpickr-hour").val('01');
    }
}

function setIncludedDays(delivery, fp, addDays) {
    // today
    let spwnDateTemp = new Date();
    spwnDateTemp.setDate(spwnDateTemp.getDate() + addDays);

    let spwnTime = parseInt((spwnDateTemp.getHours() < 10 ? '0' : '') + spwnDateTemp.getHours() + "" + (spwnDateTemp.getMinutes() < 10 ? '0' : '') + spwnDateTemp.getMinutes());
    // If "evening" after 11am add one extra day or if "dpd" after 2pm add one extra day
    if ((delivery === "evening" && spwnTime > 1100) || (delivery === "dpd" && spwnTime > 1400)) {
        spwnDateTemp.setDate(spwnDateTemp.getDate() + 1);
    }
    console.log(spwnDateTemp);
    let spwnDate = fp.formatDate(spwnDateTemp, "d.m.Y");
    fp.set("minDate", spwnDate);

    // fp.set("maxDate", new Date().fp_incr(21));

    fp.set("enable", [
        function(date) {
            let day = date.getDate();
            let month = date.getMonth();
            month = month + 1;
            if((String(day)).length===1)
                day='0'+day;
            if((String(month)).length===1)
                month='0'+month;
            let formattedDate = day + '.' + month + '.' + date.getFullYear();
            //Excluded Dates
            if($.inArray(formattedDate, dtgsDeliveryDateExcludedDates) > -1) {
                return false;
            }
            // Datum auf Bereich Montag = 1, Sonntag = 7 bringen
            return spwnIncludedDays.indexOf(((date.getDay() + 6) % 7) + 1) !== -1;
        }
    ]);
}

// For sticky bar in 6-Tage products
$.fn.isInViewport = function() {
    if ($(this).length) {
        var elementTop = $(this).offset().top + 50;
        var elementBottom = elementTop + $(this).outerHeight();

        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();

        return elementBottom > viewportTop && elementTop < viewportBottom;
    }
};

// 6-Tage products
function tagBar(sticky, parentContainer, stickyTop) {
    var headerHeight = $(".header-inner").outerHeight() + 13,
        windowTop = $(window).scrollTop() + headerHeight;
    if (stickyTop < windowTop && parentContainer.height() + parentContainer.offset().top - sticky.height() > windowTop) {
        sticky.css('position', 'fixed').css('top', headerHeight + 'px');
    } else {
        sticky.css('position', 'absolute').css('top', 0);
    }

    sticky.find("figure").removeClass("active");
    if ($("#day1").isInViewport() && !$("#day2").isInViewport() &&
        !$("#day3").isInViewport() && !$("#day4").isInViewport() &&
        !$("#day5").isInViewport() && !$("#day6").isInViewport()) {
        sticky.find(".day1Image").addClass("active");
    }
    if ($("#day2").isInViewport() &&
        !$("#day3").isInViewport() && !$("#day4").isInViewport() &&
        !$("#day5").isInViewport() && !$("#day6").isInViewport()) {
        sticky.find(".day2Image").addClass("active");
    }
    if ($("#day3").isInViewport() && !$("#day4").isInViewport() &&
        !$("#day5").isInViewport() && !$("#day6").isInViewport()) {
        sticky.find(".day3Image").addClass("active");
    }
    if ($("#day4").isInViewport() &&
        !$("#day5").isInViewport() && !$("#day6").isInViewport()) {
        sticky.find(".day4Image").addClass("active");
    }
    if ($("#day5").isInViewport() && !$("#day6").isInViewport()) {
        sticky.find(".day5Image").addClass("active");
    }
    if ($("#day6").isInViewport()) {
        sticky.find(".day6Image").addClass("active");
    }
}
