function std_setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function std_getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
jQuery(document).ready(function ($) {
    "use strict";

    /**
     * Scrolls to the first error of the form
     *
     */
    function std_scroll_to_error(form) {
        form.find('.std-error-highlight').each(function () {
            var in_selector = $(this);
            $('html,body').animate({
                scrollTop: in_selector.closest('div').offset().top - 150
            },
                'slow');
            return false;

        });

    }

    $(document).on('focus', '.std-front-datepicker', function () {
        $(this).datepicker({
            todayHighlight: true,
            format: $(this).data('date-format'),
            autoclose: true
        })
    });

    /**
     * Form Submission
     * 
     * @since 1.0.0
     */
    $('body').on('submit', '.std-subscription-form', function (e) {
        e.preventDefault();
        var selector = $(this);
        var form_alias = $(this).data('form-alias');
        var form_data = $(this).serialize();
        $.ajax({
            type: 'post',
            url: std_frontend_obj.ajax_url,
            data: {
                form_data: form_data,
                _wpnonce: std_frontend_obj.ajax_nonce,
                action: 'std_form_process_action',
                form_alias: form_alias
            },
            beforeSend: function (xhr) {
                selector.find('.std-form-message').slideUp(500);
                selector.find('.std-form-loader-wraper').show();
                selector.find('*').removeClass('std-error-highlight');
            },
            success: function (res) {
                selector.find('.std-form-loader-wraper').hide();
                res = $.parseJSON(res);
                if (res.status == 200) {
                    selector[0].reset();
                    if (selector.find('#g-recaptcha-response').length > 0) {
                        std_reCaptcha_ready();
                    }
                    selector.find('.std-form-message').removeClass('std-error').addClass('std-success').html(res.message).slideDown(500, function () {
                        if (res.instant_download_button) {
                            setTimeout(function () {
                                selector.find('.std-form-message').after(res.instant_download_button);
                            }, 500);
                        } else {
                            if (res.redirection_url) {
                                setTimeout(function () {
                                    window.location = res.redirection_url;
                                    exit;
                                }, 500);
                            }
                        }
                    });

                } else {
                    if (selector.find('#g-recaptcha-response').length > 0) {
                        std_reCaptcha_ready();
                    }
                    selector.find('.std-form-message').removeClass('std-success').addClass('std-error').html(res.message).slideDown(500);
                    if (res.hasOwnProperty('data') && res.data.hasOwnProperty('error_keys')) {

                        var error_keys = res.data.error_keys;
                        for (var i = 0; i <= error_keys.length; i++) {
                            selector.find('*[data-field-key="' + error_keys[i] + '"]').addClass('std-error-highlight');
                            setTimeout(function () {
                                std_scroll_to_error(selector);
                            }, 1000);

                        }
                    }

                }
            }
        });
    });

    /**
     * Popup Trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-popup-trigger', function (e) {
        var temp_popup_html = $(this).next('.std-popup-innerwrap').clone();
        $('.std-temp-popup-wrapper').append(temp_popup_html);
        $('.std-temp-popup-wrapper .std-popup-innerwrap').fadeIn(500);
        e.stopPropagation();
    });
    /**
     * Popup Trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-popup-close, .std-overlay', function () {
        $('.std-popup-innerwrap').fadeOut(500, function () {
            $('.std-temp-popup-wrapper').html('');
        });

    });

    /**
     * Delay popup display trigger
     * 
     * @since 1.0.0
     */
    if ($('.std-delay-popup').length > 0) {
        var delay = $('.std-delay-popup').data('delay');
        if (delay == 0 || delay == '') {
            $('.std-delay-popup').fadeIn(500);
        } else {
            setTimeout(function () {
                $('.std-delay-popup').fadeIn(500);
            }, delay * 1000);
        }
    }
    /**
     * Prevents popup from being closed
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-form-wrap', function (e) {
        e.stopPropagation();
    });



    $('body').on('click', '.std-error-highlight', function () {
        $(this).removeClass('std-error-highlight');
    });

    $('body').on('click', '.std-disable-when-closed-trigger', function () {
        var alias = $(this).data('alias');
        var hide_days = $(this).data('hide-days');
        var hide_cookie_name = 'std_popup_hide_flag_' + alias;
        std_setCookie(hide_cookie_name, 1, hide_days);
    });


});