jQuery(document).ready(function ($) {

    var menuItem = $('.irk-menu-item a');
    menuItem.click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var $toggle = $this.data('toggle');
        $('.irk-menu-item a').removeClass('irk-active');
        $this.addClass('irk-active');
        $('.irk-settings-area').removeClass('irk-active');
        $('.irk-settings-' + $toggle).addClass('irk-active');
    });

    $(".irk-confirm").click(function () {
        var $this = $(this);
        var $toggle = $this.data('toggle');
        if (this.checked) {
            $('#irk-' + $toggle).slideDown();
        } else {
            $('#irk-' + $toggle).slideUp();
        }
    });
    $(".irk-confirm").each(function () {
        var $this = $(this);
        if ($this.is(':checked')) {
            var $toggle = $this.data('toggle');
            $('#irk-' + $toggle).show();
        }
    });

    $("select.irk-confirm").change(function () {
        var $this = $(this);
        var $name = $this.attr('name');
        if ($this.val()) {
            $('#irk-' + $name).slideDown();
        } else {
            $('#irk-' + $name).slideUp();
        }
    });
    $("select.irk-confirm").each(function () {
        var $this = $(this);
        if ($this.val()) {
            var $name = $this.attr('name');
            $('#irk-' + $name).show();
        }
    });

    $('.irk-clipboard').click(function () {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(this).text()).select();
        document.execCommand("copy");
        $temp.remove();
    });

    $('.irk-upload-file').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var image = wp.media({
            multiple: false,
        }).open().on('select', function (e) {
            var uploadedImage = image.state().get('selection').first();
            var imageID = uploadedImage.toJSON().id;
            var imageURL = uploadedImage.toJSON().url;
            $this.val(imageURL);
            $this.prev('br').prev('input[type="hidden"]').val(imageID);
            $this.prev('br').prev('input[type="hidden"]').prev('img.irk-image').attr('src', imageURL);
        });
    });

    $('.irk-remove').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var $default = $this.data('default');
        var $image = $this.prev('button').prev('br').prev('input[type="hidden"]').prev('img.irk-image');
        $this.prev('button').prev('br').prev('input[type="hidden"]').val('');
        $image.attr('src', $default);
    });

    $('.irk--upload--file').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var image = wp.media({
            multiple: false,
        }).open().on('select', function (e) {
            var uploadedImage = image.state().get('selection').first();
            var imageID = uploadedImage.toJSON().id;
            var imageURL = uploadedImage.toJSON().url;
            $this.val(imageURL);
            $this.prev('input').val(imageID);
        });
    });

    $('.irk--remove').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.prev().val('');
        $this.prev().prev('input').val('');
    });

    var nonce = $('meta[name="irk-nonce"]').attr('content');

    $('#irk-settings-form').submit(function (e) {
        e.preventDefault();
        var $this = $(this);
        //tinyMCE.triggerSave();
        var button = $this.find('.irk-save');
        var loader = button.find('.loader');
        button.prop('disabled', true);
        loader.show();

        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            timeout: 20000,
            data: {
                action: 'irk_update_settings',
                nonce: nonce,
                formData: $this.serialize()
            },
            success: function (response) {
                if (response.result === true) {
                    UIkit.notification({
                        message: IRK_DATA.settings_saved,
                        status: 'success',
                        pos: 'bottom-center',
                        timeout: 5000
                    });
                }
            },
            error: function () {
                UIkit.notification({
                    message: IRK_DATA.error_occurred,
                    status: 'danger',
                    pos: 'bottom-center',
                    timeout: 5000
                });
            },
            complete: function (data) {
                button.prop('disabled', false);
                loader.hide();
            }
        });
    });

    $('.irk-new-custom-item').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.prev('div').after('<div class="uk-margin-small"><input type="text" class="uk-input" name="header-menu-custom-items[]" placeholder="' + IRK_DATA.title_url + '"></div>');
    });

    $('.irk-new-product-info').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.prev('div').after('<div class="uk-margin-small"><input type="text" class="uk-input" name="product-info[]" placeholder="' + IRK_DATA.icon_title + '"></div>');
    });

    $('.irk-new-attribute').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.prev('div').after('<div class="uk-margin-small"><input type="text" class="uk-input" name="product-attributes[]" placeholder="' + IRK_DATA.name_label + '"></div>');
    });

    $('.irk-new-faq').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.prev('div').after('<div class="uk-margin-small"><input type="text" class="uk-input" name="faqs[]" placeholder="' + IRK_DATA.title_content + '"></div>');
    });

    $('.irk-sortable').sortable();

    $(document).on('click', '.irk-actions .remove', function () {
        $(this).parentsUntil('.irk-sortable').remove();
    });

    $(document).on('click', '.irk-select-uploader', function (e) {
        e.preventDefault();
        var $this = $(this);
        var $target = $this.data('target');
        var targetType = $this.data('target-type');
        var image = wp.media({multiple: false,}).open().on('select', function (e) {
            var uploadedImage = image.state().get('selection').first();
            var imageID = uploadedImage.toJSON().id;
            var imageURL = uploadedImage.toJSON().url;
            switch (true) {
                case targetType === 'image' :
                    $('#' + $target).attr('src', imageURL);
                    $('#' + $target + '_input').val(imageID);
                    break;
                case targetType === 'widget' :
                    $('#' + $target).attr('src', imageURL);
                    $('#' + $target + '_input').val(imageID).trigger('change');
                    break;
            }
        });
    });

    $(document).on('click', '.irk-remove-uploader', function (e) {
        e.preventDefault();
        var $this = $(this);
        var target = $this.data('target');
        $('#' + target).attr('src', '');
        $('#' + target + '_input').attr('value', '').trigger('change');
    });

    $(document).on('click', '.irk-new-social-network', function (e) {
        e.preventDefault();
        var $this = $(this);
        var $key = Math.floor((Math.random() * 1000000000));

        var $html = '<div class="irk-social-network-item irk-item uk-margin-small">';
        $html += '<div class="irk-actions"><span class="move" uk-icon="move" uk-tooltip="title: ' + IRK_DATA.move + '"></span><span class="remove" uk-icon="close" uk-tooltip="title: ' + IRK_DATA.remove + '"></span></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="social-network[' + $key + '][icon]" value="" placeholder="' + IRK_DATA.icon + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="social-network[' + $key + '][url]" value="" placeholder="' + IRK_DATA.url + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="social-network[' + $key + '][title]" value="" placeholder="' + IRK_DATA.title + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="social-network[' + $key + '][xfn]" value="" placeholder="' + IRK_DATA.xfn + '"></div>';
        $html += '</div>';
        $this.before($html);
    });

    $(document).on('click', '.irk-new-bottom-nav', function (e) {
        e.preventDefault();
        var $this = $(this);
        var $key = Math.floor((Math.random() * 1000000000));

        var $html = '<div class="irk-bottom-nav-item irk-item uk-margin-small">';
        $html += '<div class="irk-actions"><span class="move" uk-icon="move" uk-tooltip="title: ' + IRK_DATA.move + '"></span><span class="remove" uk-icon="close" uk-tooltip="title: ' + IRK_DATA.remove + '"></span></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="bottom-navigation[' + $key + '][icon]" value="" placeholder="' + IRK_DATA.icon + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="bottom-navigation[' + $key + '][url]" value="" placeholder="' + IRK_DATA.url + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="bottom-navigation[' + $key + '][text]" value="" placeholder="' + IRK_DATA.text + '"></div>';
        $html += '</div>';
        $this.before($html);
    });

    $(document).on('change', '.widget-content .irk-post-type', function (e) {
        var $this = $(this);
        var postType = $this.val();
        $this.parentsUntil('.widget-inside').find('.taxonomy').addClass('irk-dnone');
        $this.parentsUntil('.widget-inside').find('.taxonomy.' + postType).removeClass('irk-dnone');
    });

    $(document).on('click', '.irk-new-price', function (e) {
        var $this = $(this);
        e.preventDefault();
        var $count = parseInt($this.data('count'));
        var $id = parseInt($this.data('id'));

        $this.data('count', ($count + 1));

        var $html = '<p class="form-field">';
        $html += '<label for="_irk_price_changes' + ($count + 1) + '">' + IRK_DATA.price + ' ' + ($count + 1) + '</label>';
        $html += '<input type="text" class="short" style="" name="_irk_price_changes' + $id + '[]" id="_irk_price_changes' + ($count + 1) + '" value="" placeholder="1399-01-11:1000" dir="ltr">';
        $html += '</p>';

        $this.parentsUntil('.options_group').before($html);
    });

    if ($('.color-field').length) {
        $('.color-field').wpColorPicker();
    }

    $(document).on('click', '.irk-new-order-status', function (e) {
        e.preventDefault();
        var $this = $(this);
        var $key = Math.floor((Math.random() * 1000000000));

        var $html = '<div class="irk-order-status-item irk-item uk-margin-small">';
        $html += '<div class="irk-actions"><span class="move" uk-icon="move" uk-tooltip="title: ' + IRK_DATA.move + '"></span><span class="remove" uk-icon="close" uk-tooltip="title: ' + IRK_DATA.remove + '"></span></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="order-status[' + $key + '][image]" placeholder="' + IRK_DATA.image + '"></div>';
        $html += '<div class="uk-margin-small"><input type="text" class="uk-input" name="order-status[' + $key + '][title]" placeholder="' + IRK_DATA.title + '"></div>';
        $html += '<div class="uk-margin-small"><textarea class="uk-textarea" name="order-status[' + $key + '][description]" placeholder="' + IRK_DATA.description + '" rows="4"></textarea></div>';
        $html += '</div>';
        $this.before($html);
    });

    $('#check-all-attr').change(function () {
        var checkboxes = $('.irk-settings-compare .attributes .uk-checkbox:not("#check-all-attr")');
        if (this.checked) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });

    /*$('#clear-warranty').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        $this.addClass('disabled');
        var productID = parseInt($this.data('id'));

        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            timeout: 20000,
            data: {
                action: 'irk_clear_warranty',
                nonce: nonce,
                productID: productID
            },
            success: function (response) {

            },
            error: function () {

            },
            complete: function (data) {
                $this.removeClass('disabled');
            }
        });
    });*/

    if ($('#_sale_price_dates_from').length) {
        $("#_sale_price_dates_from, #_sale_price_dates_to").autocomplete({disabled: true});
    }

    $(document).on('change', 'select.irk-product-cat[id^=widget-irk_products_slider]', function () {
        var $this = $(this);
        var optionsText = this.options[this.selectedIndex].text;
        $this.parentsUntil('form').find("p:first-child input[type=text][id^=widget-irk_products_slider]").val(optionsText.replace(/ *\([^)]*\) */g, "").trim())
    });

    function attribute_row_indexes() {
        $('.product_attributes .woocommerce_attribute').each(function (index, el) {
            $('.attribute_position', el).val(parseInt($(el).index('.product_attributes .woocommerce_attribute'), 10));
        });
    }

    $('#irk-load-attribute-group').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        var groupID = $('.irk-group-attribute-toolbar select option:selected').val();
        var loader = $('.irk-group-attribute-toolbar .irk-loader');
        if (!groupID) {
            return false;
        }
        loader.show();

        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            timeout: 20000,
            data: {
                action: 'irk_load_attribute_group',
                nonce: nonce,
                groupID: groupID
            },
            success: function (response) {
                if (response.result === true) {
                    var attributes = response.attributes;
                    var size = $('.product_attributes .woocommerce_attribute').length;
                    var $wrapper = $('#product_attributes');
                    var $attributes = $wrapper.find('.product_attributes');
                    var product_type = $('select#product-type').val();

                    $wrapper.block({
                        message: null,
                        overlayCSS: {
                            background: '#fff',
                            opacity: 0.6
                        }
                    });
                    $.each(attributes, function (i, index) {
                        var attribute = index;
                        var data = {
                            action: 'woocommerce_add_attribute',
                            taxonomy: attribute,
                            i: size,
                            security: woocommerce_admin_meta_boxes.add_attribute_nonce
                        };

                        $.post(woocommerce_admin_meta_boxes.ajax_url, data, function (response) {
                            $attributes.append(response);
                            if ('variable' !== product_type) {
                                $attributes.find('.enable_variation').hide();
                            }
                            $(document.body).trigger('wc-enhanced-select-init');
                            attribute_row_indexes();
                            $attributes.find('.woocommerce_attribute').last().find('h3').trigger('click');
                            $wrapper.unblock();
                            $(document.body).trigger('woocommerce_added_attribute');
                        });

                        if (attribute) {
                            $('select.attribute_taxonomy').find('option[value="' + attribute + '"]').attr('disabled', 'disabled');
                            $('select.attribute_taxonomy').val('');
                        }

                        size = size + 1;
                    });
                }

                loader.hide();
            },
            error: function () {
                loader.hide();
            },
            complete: function (data) {
                loader.hide();
            }
        });
    });

    if ($('body').hasClass('post-type-group_attribute')) {
        $('#adminmenu li.toplevel_page_irk-settings').addClass('wp-has-current-submenu wp-menu-open').removeClass('wp-not-current-submenu');
        $('#adminmenu li.toplevel_page_irk-settings li.wp-first-item.current').removeClass('current')
        $('#adminmenu li.toplevel_page_irk-settings li:nth-child(3)').addClass('current')
    }
    if ($('body').hasClass('post-type-notification')) {
        $('#adminmenu li.toplevel_page_irk-settings').addClass('wp-has-current-submenu wp-menu-open').removeClass('wp-not-current-submenu');
        $('#adminmenu li.toplevel_page_irk-settings li.wp-first-item.current').removeClass('current')
        $('#adminmenu li.toplevel_page_irk-settings li:nth-child(4)').addClass('current')
    }
    if ($('body').hasClass('post-type-header')) {
        $('#adminmenu li.toplevel_page_irk-settings').addClass('wp-has-current-submenu wp-menu-open').removeClass('wp-not-current-submenu');
        $('#adminmenu li.toplevel_page_irk-settings li.wp-first-item.current').removeClass('current')
        $('#adminmenu li.toplevel_page_irk-settings li:nth-child(5)').addClass('current')
    }
    if ($('body').hasClass('post-type-footer')) {
        $('#adminmenu li.toplevel_page_irk-settings').addClass('wp-has-current-submenu wp-menu-open').removeClass('wp-not-current-submenu');
        $('#adminmenu li.toplevel_page_irk-settings li.wp-first-item.current').removeClass('current')
        $('#adminmenu li.toplevel_page_irk-settings li:nth-child(6)').addClass('current')
    }

    $('.irk-hide-tuts-alert').click(function (e) {
        e.preventDefault();
        let $this = $(this);

        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            timeout: 20000,
            data: {
                action: 'irk_hide_tuts_alert',
                nonce: nonce,
            },
            success: function (response) {
                if (response.result === true) {
                    $this.parentsUntil('.uk-margin').slideUp(200);
                }
            },
        });
    });

    $(document).on('click', '.irk_is_amazing', function () {
        let $this = $(this);
        let pid = parseInt($this.data('id'));

        if ($this.prop("checked") === true) {
            $('.irk-amazing-alert-' + pid).slideDown();
            $('.sale_price_dates_fields').show().css({backgroundColor: '#ffacb4'});
            $('.sale_schedule').hide();
        } else {
            $('.irk-amazing-alert-' + pid).slideUp();
            $('.sale_price_dates_fields').css({backgroundColor: 'transparent'});
        }
    });
});