$(document).ready(function() {
    var date = new Date();
    var startDate = date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();

    $('[data-toggle="datepicker"]').datepicker({
        language: 'ru-RU',
        inline: true,
        startDate: startDate,
    }).on('pick.datepicker', function (e) {
        $('.checkout__form.active .form-input-date').val(e.date.toLocaleDateString());
        if ($('.checkout__form.active .form-input-date').hasClass('error')) {
            $('.checkout__form.active .form-input-date').removeClass('error')
        }

        var date = $('.checkout__form.active .form-input-date').val();
        var time = $('.checkout__form.active .form-input-time').val();

        if (date.length > 0 && time.length > 0) {
            checkConditions();
        }
    });

    $(document).on('click', '.checkout__hours-list label', function (e) {
        $(this).closest('.checkout__hours').removeClass('active');
        $(this).closest('.form__input-wrap').find('.form-input-time').val($(this).text());
        if ($(this).closest('.form__input-wrap').find('.form-input-time').hasClass('error')) {
            $(this).closest('.form__input-wrap').find('.form-input-time').removeClass('error');
        }
        var date = $('.checkout__form.active .form-input-date').val();
        var time = $('.checkout__form.active .form-input-time').val();

        if (date.length > 0 && time.length > 0) {
            checkConditions();
        }
    });
})

function checkConditions()
{
    zone = $('[name="deliveryzoneid"]').val();
    summ = summprod;

    var bIsPreorder = ($('.checkout__form.active').find('[name="checkouttime"]:checked').data('tab') == 'checkout-time-2') ? true : false;
    var bIsDeliveryZone = (zone !== false && zone !== '') ? true : false;
    var date = $('.checkout__form.active .form-input-date').val();
    var time = $('.checkout__form.active .form-input-time').val();

    $('[data-tab="checkout-1"]').find('.checkout__message-wrap').html('');
    $('.checkout__form.active').find('.fake-step-next').removeAttr('disabled');

    $.ajax({
        url: '/ajax/checkconditions.php',
        method: 'post',
        data: {
            'preorder' : bIsPreorder,
            'date': date,
            'time': time,
            'token': $('#ssf').attr('sstt'),
            'deliveryzone': bIsDeliveryZone,
            'sum': summ,
            'zone': zone
        },
        success: function (data) {
            data = JSON.parse(data);

            var htmlMessage = '';

            if (
                data !== null
                && typeof(data.worktime) !== 'undefined'
                && data.worktime.status === false
            ) {
                if (
                    typeof(data.worktime.notworkday) !== 'undefined'
                    && data.worktime.notworkday === true
                ) {
                    htmlMessage += '<div class="checkout__delivery-info _error">' +
                        '<span>Извините, мы не можем принять ваш заказ, т.к. в выбранный день не работаем.</span>' +
                        '</div>';
                } else if (
                    typeof(data.worktime.from) !== 'undefined'
                    && typeof(data.worktime.to) !== 'undefined'
                ) {
                    htmlMessage += '<div class="checkout__delivery-info _error">' +
                        '<span>Извините, но мы не можем принять ваш заказ, наш режим работы в выбранный день с <strong>' + data.worktime.from  + ' до ' + data.worktime.to + '</strong></span>' +
                        '</div>';
                } else if (typeof(data.worktime.pasttime) !== 'undefined' && data.worktime.pasttime === true) {
                    htmlMessage += '<div class="checkout__delivery-info _error">' +
                        '<span>Вы указали прошедшее время, исправьте время.</span>' +
                        '</div>';
                }

                $('.checkout__form.active').find('.fake-step-next').attr('disabled', 'disabled');
            }

            if (
                $('.checkout__form.active').data('tab') == 'checkout-1'
                && typeof(data.deliveryzone) !== 'undefined'
                && data.deliveryzone !== null
            ) {
                if (isNaN(data.deliveryzone.price)) {
                    price = data.deliveryzone.price;
                    htmlPrice = price;
                    $('form[data-tab="checkout-1"]').find('.checkout__total').text(summprod);
                } else {
                    price = Number(data.deliveryzone.price);
                    checkout = Number(summprod);
                    htmlPrice = price + ' ₽';
                    $('form[data-tab="checkout-1"]').find('.checkout__total').text(checkout + price);
                }
                if (isDeliveryEnabled) {
                    $('[name="deliverycost"]').val(price);
                }
                $('[name="deliveryavailable"]').val('yes');
                description = '';
                if (data.deliveryzone.description.length > 0) {
                    description = '<div>' + data.deliveryzone.description + '</div>'
                }

                var sErrorClass = '';

                if (data.deliveryzone.error == true) {
                    sErrorClass = '_error';
                }

                htmlMessage += '<div class="checkout__delivery-info ' + sErrorClass + '"> ';
                if (typeof (htmlPrice) !== 'undefined') {
                    $('[data-tab="checkout-1"]').find('.fake-step-next').removeAttr('disabled');
                    htmlMessage += '<span>Стоимость доставки: </span>' +
                        '<span class="bold">' + htmlPrice + '</span>';
                } else {
                    $('[data-tab="checkout-1"]').find('.fake-step-next').attr('disabled', 'disabled');
                }
                htmlMessage += description +
                    '</div>';
            }

            if (addingMessage.length > 0) {
                htmlMessage += '<div class="checkout__message">' +
                    '<span>' + addingMessage + '</span>' +
                    '</div>';
            }

            $('[data-tab="checkout-1"]').find('.checkout__message-wrap').html(htmlMessage);
            $('[data-tab="checkout-1"]').find('.checkout__message-wrap').slideDown();
        }
    })
}