// Vue delimiters as [% %] due to conflict with Twig template tags
Vue.config.delimiters = ['[%', '%]'];
Vue.config.unsafeDelimiters = ['[%%', '%%]'];

function custom_fields_ajax(item_id) {

    'use strict';

    var request_url = '/shop/admin/products/customfields.ajax.php';

    $.ajax({
        url: request_url,
        type: "get",
        data: {
            category_id: $("#category_1").val(),
            item_id: item_id
        },
        dataType: "html",
        success: function(response) {

            $("#customfields_html").html(response);

        }
    });
}

function tabs_on_overlay() {
    if ($('.mtcOverlay').length) {
        $('.mtcOverlay').mtcOverlay({
            onOpen: function () {
                $('.js_tabs').mtcTabs();
            }
        });
    }
}

function get_next_doctor_item(order_id, order_item_id) {
    $('.orderItemRow').removeClass('active');
    $.ajax({
        type: 'post',
        url: '/shop/admin/ajax.php',
        data: {
            action: 'get_doctor_item',
            order_id: order_id,
            order_item_id: order_item_id
        },
        success: function (response) {
            response = $.parseJSON(response);

            if (typeof response != 'undefined') {
                if (Array.isArray(response) && response.length) {
                    const temp_data = response.shift();
                    $('#orderItemDoctor').html(temp_data.html);
                    $('#orderItemRow-' + temp_data.order_item_id).addClass('active');
                }
            }

            $(window).trigger('resize.overlay');
        }
    });
}

$(document).ready(function() {

    'use strict';

    /*
     * Select box replacement
     */

    if ($('.styledForm select').length) {
        $('.styledForm select').chosen({
            disable_search_threshold: 8
        });
    }

    /*
     * Datepicker
     */

    if ($('.datePicker').length) {
        $(".datePicker").datepicker({
            showButtonPanel: true
        });
    }

    if ($('#dashboardStats').length) {
        //loadAdminStats(false, false);

        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(function(){

            loadAdminStats(false, false);

            $(document).on('submit', '#dashboard-dates', function (e) {
                e.preventDefault();
                loadAdminStats($('#start-date').val(), $('#end-date').val());
            });

        });
    }

    var sets = $("form fieldset > h1"),
        dialog = $('#dialog').dialog({
            resizable: false,
            modal: true,
            autoOpen: false
        }),
        jcrop_api,
        boundx,
        boundy,
        itemid = $('#item_id').val();

    $('div.items').mouseover(function(event) {
        $(this).find(".block").show();
    }).mouseout(function() {
        $(this).find(".block").hide();
    });

    $('.fancybox').fancybox();

    // recrop fancybox
    $('.recrop').fancybox({
        type: 'iframe',
        fitToView : false,
        autoSize : false,
        height : 550,
        width : 650,
        beforeClose: function () {
            var d = new Date(),
                imgObj = $(this.element).siblings('img'),
                imgSrc = imgObj.attr("src");
            imgObj.attr("src", imgSrc+"?"+d.getTime());
        }
    }); // end of recrop fancybox

    // image crop

    function updatePreview(c) {
        $('#jcropW').val(c.w);
        $('#jcropH').val(c.h);
        $('#jcropX').val(c.x);
        $('#jcropY').val(c.y);
    }

    $('#jCropTarget').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: $('#aspectratio').val(),
        minSize: [$('#minwidth').val(), $('#minheight').val()],
        boxWidth: 500,
        boxHeight: 500,
        setSelect: [0,0,$('#minwidth').val(), $('#minheight').val()]
    }, function() {
        // Use the API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        // Store the API for later use
        jcrop_api = this;
    });  // end of jCrop

    // nested sortable
    $('#menuSortable').nestedSortable({
        forcePlaceholderSize: true,
        handle: 'span',
        helper: 'clone',
        items: 'li',
        maxLevels: 2,
        opacity: 0.6,
        placeholder: 'menu-placeholder',
        revert: 250,
        tabSize: 15,
        tolerance: 'pointer',
        toleranceElement: '> span',
        update: function(event,ui) {
            var newOrder = $(this).nestedSortable('serialize');
            $('#menuInfo').val(newOrder);
        },
        create: function(event,ui) {
            var newOrder = $(this).nestedSortable('serialize');
            $('#menuInfo').val(newOrder);
        }
    });
    // end nested sortable

    /**
     * DropZone image uploader
     **/
    if ($("#dZUpload").length > 0) {
        Dropzone.autoDiscover = false;
        var myDropzone = new Dropzone("div#dZUpload", {
            acceptedFiles: '.jpg,.jpeg,.png,.gif',
            url: "/shop/admin/products/items.images.php",
            dictInvalidFileType: "You can't upload files of this type.",
            paramName: "userfile",
            params: {
                item_id: $("#item_id").val()
            },
            maxFiles: $("#max_images").val(),
            success: function (file, response) {
                if (!$('.tabular > tr:first').attr('id')) {
                    $('.tabular > tr:first').hide();
                }

                //add row to the beginning of the table
                $('.manage-items > tbody:last-child').prepend(response);
            }
        });
    }

    // end DropZone

    // fieldset hide and show
    sets.siblings().hide();

    // show selected or first one
    if($("form fieldset.show").length>0){
        $("form fieldset.show > h1").siblings().show();
    }

    sets.find("a.show").on("click", function(e) {
        e.preventDefault();
        var el = $(this);
        el.parent().siblings().stop(true, true).slideToggle(100, function() {
            var txt = el.find("i.fa-caret-down, i.fa-caret-right");
            if (el.parent().siblings().is(':visible')) {
                txt.attr("class", "fa fa-caret-down");

                // Method slideToggle() doesn't seem to reset overflow automatically.
                el.parent().siblings().css('overflow', 'visible');

            } else {
                txt.attr("class", "fa fa-caret-right");
            }
        });
    });

    $("body").on("click", "a.alert", function(e) {

        // prevent default
        e.preventDefault();

        // add title to dialog box
        var title = $(this).attr('title'),
            targetUrl = $(this).attr("href");

        if (title === '') {
            title = 'Are you sure?';
        }

        $('#dialog').html(title);

        // dialog box options
        $('#dialog').dialog('option', 'title', 'Confirmation');
        $('#dialog').dialog('option', 'buttons', {
            "Cancel": function () {
                $(this).dialog("close");
            },
            "Confirm": function () {
                window.location.href = targetUrl;
            }
        });

        // display dialog box
        dialog.dialog('open');

    });

    //focus on error element
    $(".error li a").on("click", function(e) {
        e.preventDefault();

        var el = $(this),
            target = el.attr("href"),
            offset = $(target).offset();

        //show fieldset
        $(target).closest("fieldset").show();

        $(target).focus();

        $('html,body').animate({
            scrollTop: offset.top
        }, 0);
    });

    //hide and show hints
    $('.hint').hover(function() {
        $(this).find(".text").delay(400).fadeIn(200);
    }, function(){
        $(this).find(".text").stop(true, true).delay(200).fadeOut(100);
    });

    $(".manage-items tbody.ui-sortable").sortable({
        opacity: 0.6,
        placeholder: 'ui-state-highlight',
        cursor: 'move',
        update: function (event, ui) {

            var order,
                order_script,
                page_num,
                rows_per_page,
                item_position,
                item_id,
                pagination_info;

            pagination_info = $('ul.paginationInfo').first();

            if (pagination_info.length) {

                page_num = parseInt($('li.pageNum', pagination_info).text(), 10);
                rows_per_page = parseInt($('li.rowsPerPage', pagination_info).text(), 10);
                item_position = parseInt(ui.item.index(), 10);
                item_id = parseInt($(ui.item).attr('id').replace(/^rorder-/, ''), 10);

                order_script = '/core/admin/includes/paginated_order.php';
                order = 'action=order&table=' + $('#orderbytable').val() + '&field=' + $('#orderbyfield').val() + '&page_num=' + page_num + '&rows_per_page=' + rows_per_page + '&item_position=' + item_position + '&item_id=' + item_id;
            } else {
                order_script = '/core/admin/includes/order.php';
                order = $(this).sortable("serialize") + '&action=order&table=' + $('#orderbytable').val() + '&field=' + $('#orderbyfield').val();
            }

            $.ajax({
                type: 'post',
                url: order_script,
                data: order
            });

            if(('#faqUpdateQuestions').length) {
                tinymce.remove();
                tinymce.init({selector:'.tinymce'});
            }
        }
    });

    $('#permissions .parent').on('change', function (e) {
        var id = $(this).attr('data-id'),
            checked = $(this).is(':checked');

        $('#permissions .child').each(function () {
            if ($(this).attr('data-parent') === id) {
                if (checked) {
                    $(this).prop('checked',true);
                } else {
                    $(this).prop('checked',false);
                }
            }
        });
    });

    /*
    Custom Fields
    */

    $("#category_1").on('change', function() {
        var $form = $(this).closest('form'),
            item_id = $form.find('input[name="id"]').val();
        custom_fields_ajax(item_id);
    });

    $('.loadDisableButton').on('click', function() {
        $(this).prop('disabled', true).val('Loading...').parents('form').submit();
    });

    $(".datepicker").datepicker({
        dateFormat: "dd/mm/yy"
    });

    $('.flyoutButton').on('click', function () {
        $('.flyoutButton, .sidebar').toggleClass('active');
        $('.flyoutButton i').toggleClass('fa-bars fa-times');
    });

    /*
     * Sticky Save Button in CORE Admin Settings
     */

    if ($('.js_settingsStickyRowWrap').length) {

        $('.js_settingsStickyRowWrap').waypoint(function (direction) {
            var sticky_row_wrap = $(this.element);

            if (direction === 'down') {
                sticky_row_wrap.addClass('fixed');
            } else {
                sticky_row_wrap.removeClass('fixed');
            }
        });
    }

    if ($('.mtcOverlay').length) {
        $('.mtcOverlay').mtcOverlay({
            onOpen: function () {
                $('.js_tabs').mtcTabs();
            }
        });
    }

    tabs_on_overlay();

    $('body').on('click', '.doctor-approval-button', function(e) {
        e.preventDefault();

        var url = $(this).attr('href');
        var id = $(this).data('order');

        $.get(url, function() {
            $('tr#' + id).remove();
            $('.overlayCloseButton').trigger('click');
        });
    });

    var question_type_select = $('#question_type_select');
    if (question_type_select.length) {
        question_type_select.on('change', function() {
            $('#variations_row, #bmi_row, #allow_multiple').hide();
            if (question_type_select.val() === 'variations') {
                $('#variations_row').show();
                $('#allow_multiple').show();
            }

            if (question_type_select.val() === 'bmi') {
                $('#bmi_row').show();
            }

            $('.question_subtypes').hide();
            $('#subtypes_' + question_type_select.val()).show();
        });
        question_type_select.trigger('change');
    }

    $("input.js_medications_tagit").each(function (key, input) {
        $(input).tagit({
            allowSpaces: true,
            availableTags: window.all_medications
        });
    });

    $("input.js_medical_conditions_tagit").each(function (key, input) {
        $(input).tagit({
            allowSpaces: true,
            availableTags: window.all_medical_conditions
        });
    });

    $("input.js_ingredients_tagit").each(function (key, input) {
        $(input).tagit({
            allowSpaces: true,
            availableTags: window.all_ingredients,
            singleFieldDelimiter: '#',
            beforeTagAdded: function(event, ui) {
                var tag_value = $('.tagit-label', ui.tag[0]).html();
                var found = false;
                $.each(window.all_ingredients, function(i, obj) {
                    if (obj === tag_value) {
                        found = true;
                        return true;
                    }
                });
                if (!found) {
                    return false;
                }
            }
        });
    });

    var showIfQuestion = $('.showIfQuestion');
    if (showIfQuestion.length) {
        showIfQuestion.on('change', function () {
            var request_url = '/shop/admin/assessment/manage.form.php';
            var question_id = $(this).val();
            var variations_question_id = $(this).data('question_id');
            $.ajax({
                url: request_url,
                type: "get",
                data: {
                    question_id: question_id,
                    action: 'get_variations'
                },
                dataType: "html",
                success: function(response) {

                    $('#show_if_variation-' + variations_question_id).html(response);

                }
            });
        })
    }

    // chosen
    if ($('.chosen').length) {
        $('.chosen').chosen({
            disable_search_threshold: 8
        });
    }

    if ($('#orderBulkActionForm').length) {
        $('#orderBulkActionForm').on("keypress", function(event) {
            return event.keyCode !== 13;
        }).on('submit', function (e) {
            if ($('[name=processing_action] option:selected').data('newWindow') === true) {
                $(this).attr('target', '_blank');
            } else {
                $(this).attr('target', '_self');
            }
        });
    }

    $('.doctorNoteColumn').on('dblclick', function (e) {
        var order_id = $(this).data('order_id');
        $('#doctorNoteText-' + order_id).addClass('hideme');
        $('#doctorNoteInput-' + order_id).removeClass('hideme').focus();
    });

    $('.doctorNoteInput').on('blur keyup', function(e) {
        if (e.type === 'keyup' && e.keyCode !== 13) {
            return;
        }
        var doctor_note = $(this).val(),
            order_id = $(this).data('order_id');
        $('#doctorNoteInput-' + order_id).addClass('hideme');
        $('#doctorNoteText-' + order_id).removeClass('hideme').html(doctor_note);
        $.post('/shop/admin/ajax.php', {
            action: 'update_doctor_note',
            order_id: order_id,
            note: doctor_note
        });
    });

    $('.pharmacistNoteColumn').on('dblclick', function (e) {
        var order_id = $(this).data('order_id');
        $('#pharmacistNoteText-' + order_id).addClass('hideme');
        $('#pharmacistNoteInput-' + order_id).removeClass('hideme').focus();
    });

    $('.pharmacistNoteInput').on('blur keyup', function(e) {
        if (e.type === 'keyup' && e.keyCode !== 13) {
            return;
        }
        var pharmacist_note = $(this).val(),
            order_id = $(this).data('order_id');
        $('#pharmacistNoteInput-' + order_id).addClass('hideme');
        $('#pharmacistNoteText-' + order_id).removeClass('hideme').html(pharmacist_note);
        $.post('/shop/admin/ajax.php', {
            action: 'update_pharmacist_note',
            order_id: order_id,
            note: pharmacist_note
        });
    });

    $('.itemVatRateColumn').on('dblclick', function (e) {
        var item_id = $(this).data('item_id');
        $('#itemVatRateText-' + item_id).addClass('hideme');
        $('#itemVatRateInput-' + item_id).removeClass('hideme').focus();
    });

    $('.itemVatRateInput').on('change', function(e) {
        var item_vat_rate = $(this).val(),
            item_id = $(this).data('item_id');

        $('#itemVatRateInput-' + item_id).addClass('hideme');
        $('#itemVatRateText-' + item_id).removeClass('hideme').html(item_vat_rate);
        $.post('/shop/admin/ajax.php', {
            action: 'update_item_vat_rate',
            item_id: item_id,
            vat_rate: item_vat_rate
        });
    });

    $('.itemProductTypeColumn').on('dblclick', function (e) {
        var item_id = $(this).data('item_id');
        $('#itemProductTypeText-' + item_id).addClass('hideme');
        $('#itemProductTypeInput-' + item_id).removeClass('hideme').focus();
    });

    $('.itemProductTypeInput').on('change', function(e) {
        var item_product_type = $(this).val(),
            item_id = $(this).data('item_id');

        $('#itemProductTypeInput-' + item_id).addClass('hideme');
        $('#itemProductTypeText-' + item_id).removeClass('hideme').html(item_product_type);
        $.post('/shop/admin/ajax.php', {
            action: 'update_item_product_type',
            item_id: item_id,
            product_type: item_product_type
        });
    });

    $('.itemAssessmentFormColumn').on('dblclick', function (e) {
        var item_id = $(this).data('item_id');
        $('#itemAssessmentFormText-' + item_id).addClass('hideme');
        $('#itemAssessmentFormInput-' + item_id).removeClass('hideme').focus();
    });

    $('.itemAssessmentFormInput').on('change', function(e) {
        var item_form_id = $(this).val(),
            item_id = $(this).data('item_id');

        var item_form_name = $('#itemAssessmentFormInput-' + item_id + ' option:selected').text();

        $('#itemAssessmentFormInput-' + item_id).addClass('hideme');
        $('#itemAssessmentFormText-' + item_id).removeClass('hideme').html(item_form_name);
        $.post('/shop/admin/ajax.php', {
            action: 'update_item_assessment_form',
            item_id: item_id,
            form_id: item_form_id
        });
    });

    $('.nhsNumberColumn').on('dblclick', function (e) {
        var member_id = $(this).data('member_id');
        $('#nhsNumberText-' + member_id).addClass('hideme');
        $('#nhsNumberInput-' + member_id).removeClass('hideme').focus();
    });

    $('.nhsNumberInput').on('blur keyup', function(e) {
        if (e.type === 'keyup' && e.keyCode !== 13) {
            return;
        }
        var nhs_number = $(this).val(),
            member_id = $(this).data('member_id');
        $('#nhsNumberInput-' + member_id).addClass('hideme');
        $('#nhsNumberText-' + member_id).removeClass('hideme').html(nhs_number);
        $.post('/plugins/NHS/admin/', {
            action: 'update_nhs_number',
            member_id: member_id,
            nhs_number: nhs_number
        });
    });

    var review_data = {};


    $(document).on('click', '.js_showNote', function () {
        var $parent = $(this).closest('.assessmentWrapper');

        if(!$(this).is(':checked')) {
            $parent.find('.js_reviewNoteForm').addClass('hideme');
        }else{
            $parent.find('.js_reviewNoteForm').removeClass('hideme');
        }

    });

    $(document).on('click', '.js_saveReviewNote', function () {
        const data = {};
        const $parent = $(this).closest('.assessmentWrapper');

        data.note = $parent.find('.js_reviewNote').val();
        data.order_item_id = $(this).attr('data-order-item-id');
        data.order_id = $(this).attr('data-order-id');
        data.action = $(this).closest('.js_reviewNoteForm').data('action');

        submitReview(data);
    });

    // When one of the action buttons is clicked
    $(document).on('click', '.approveRejectOrderItem', function () {

        var button_clicked = $(this),
            order_id = button_clicked.data('order_id');
        review_data.order_id = button_clicked.data('order_id');
        review_data.order_item_id = button_clicked.data('order_item_id');
        review_data.action = button_clicked.data('action');
        review_data.note = $(this).closest('.assessmentWrapper').find('.js_reviewNote').val();
        if (review_data.action === 'skip') {
            submitReview(review_data);
            return;
        }

        var $parent = $(this).closest('.assessmentWrapper');
        //js_showNote
        // If it's approve, we either show note field or approve straight away (depending on the checkbox)
        if (
            review_data.action === 'approve' ||
            review_data.action === 'clinic_check' ||
            review_data.action === 'reject'
        ) {
            submitReview(review_data);
            return;
        }
        if (review_data.action === 'contact') {
            $parent
                .find('.js_reviewNoteForm')
                .removeClass('hideme')
                .data('action', review_data.action)
        }
    });

    // Approve / Reject / Skip order item
    function submitReview(data) {
        if (data.action === 'skip') {
            $.get('/shop/admin/ajax.php', {
                action: 'get_next_item',
                order_id: data.order_id,
                order_item_id: data.order_item_id,
                note: data.note
            }).success(function (response) {
                response = $.parseJSON(response);
                if (response.success) {
                    if (response.next_order_item_id) {
                        get_next_doctor_item(data.order_id, response.next_order_item_id);
                    } else {
                        next_order(data.order_id);
                    }
                } else if (response.error !== '') {
                    alert('Error: ' + response.error);
                }
            });
            return;
        }
        $.get('/shop/admin/ajax.php', {
            action: 'approve_reject_item',
            order_id: data.order_id,
            order_item_id: data.order_item_id,
            approve: data.action === 'approve' ? '1' : '0',
            reject: data.action === 'reject' ? '1' : '0',
            clinic_check: data.action === 'clinic_check' ? '1' : '0',
            note: data.note
        }).success(function (response) {
            response = $.parseJSON(response);
            if (response.success) {
                var order_item_status = $('#orderItemStatus-' + data.order_item_id);
                order_item_status.removeClass('approved').removeClass('rejected');
                if (data.action === 'approve') {
                    order_item_status.addClass('approved');
                    order_item_status.html('Approved');
                } else if (data.action === 'reject') {
                    order_item_status.addClass('rejected');
                    order_item_status.html('Rejected');
                } else {
                    order_item_status.html('Awaiting');
                }
                if (response.next_order) {
                    next_order(data.order_id);
                } else if (response.next_order_item_id) {
                    get_next_doctor_item(data.order_id, response.next_order_item_id);
                }

            } else if (response.error !== '') {
                alert('Error: ' + response.error);
            }

        });
    }

    /**
     * Loads next order
     * @param order_id - Order Id of current order
     */
    function next_order(current_order_id) {
        $('#rorder-' + current_order_id).hide();
        var order_ids_field = $('#ordersToReview');
        let temp_order_ids = [];
        if (order_ids_field.val()) {
            temp_order_ids = order_ids_field.val().split(',');
        }

        var order_ids = [];
        temp_order_ids.forEach(function(temp_order_id) {
            if (temp_order_id != current_order_id) {
                order_ids.push(temp_order_id);
            }
        })

        var next_order_id = 0;
        var order_ids_new = [];
        for (var i = 0; i < order_ids.length; i++) {
            // If previous was the order that was reviewed, then we've found the next order
            if (current_order_id == order_ids[i - 1]) {
                next_order_id = order_ids[i];
                // If have not found and is last item, then the next is first item
            } else if (!next_order_id && i === order_ids.length - 1) {
                next_order_id = order_ids[0];
            }
            // Add all Ids except for the one that is already reviewed
            if (current_order_id != order_ids[i]) {
                order_ids_new.push(order_ids[i])
            }
        }
        order_ids_field.val(order_ids_new.join(','));
        // Create an invisible element and click on it to trigger the popup for the next order
        order_ids_field.after('<a href="/shop/admin/orders/manage.order.doctor.php?id=' + next_order_id + '" class="hideme mtcOverlay" id="nextOrder-' + next_order_id + '"></a>');
        $('.overlayBoxOuter').remove();
        tabs_on_overlay();

        if (next_order_id) {
            $('#nextOrder-' + next_order_id).trigger('click');
        }
    }

    // Function that allows one click filters in order table header
    $('.headerFilter').on('change', function() {
        var query = window.location.href.split('?')[1];
        var pairs = query.split('&');
        var found = false;
        for (var i = 0; i < pairs.length; i++) {
            var pair = pairs[i].split('=');
            var param_name = pair[0],
                param_value = pair[1];
            // If the param already exists in query,
            if (param_name === $(this).attr('name')) {
                param_value = $(this).val();
                found = true;
            }
            pairs[i] = param_name + '=' + param_value;
        }
        if (!found) {
            pairs.push($(this).attr('name') + '=' + $(this).val());
        }
        query = pairs.join('&');
        window.location.href = '?' + query;
    });

    if ($('.labelListOpen').length) {
        $('.labelListOpen').on('click', function () {
            $('#labelList-' + $(this).data('size_id')).removeClass('hideme');
        });
        $('.labelListClose').on('click', function () {
            $('#labelList-' + $(this).data('size_id')).addClass('hideme');
        });
    }


    $(document).on('click', '#js_updatePharmacyLabelText', function () {
        const $that = $(this);
        $.ajax({
            url: '/shop/admin/ajax.php',
            data: {
                action: 'update_pharmacy_label_text',
                order_item_id: $('#js_pharmacyLabelText').data('id'),
                pharmacy_label_text: $('#js_pharmacyLabelText').val(),
            },
            dataType: "json",
            beforeSend: function() {
                $that.prop('disabled', true).text('Saving...');
            },
            success: function(response) {
                if (response.success) {} else {}
            },
            complete: function() {
                setTimeout(function() {
                    $that.text('Save').prop('disabled', false);
                }, 800);
            },
        });
    });


}); // document ready

function loadAdminStats(start_date, end_date) {
    var spinner = '<i class="fa fa-circle-o-notch fa-spin fa-3x dashboardIcon"></i>';

    // Load all graph stats
    $.each($('.js_dashboardStat'), function (idx, stat_element) {
        $(stat_element).html(spinner);
        $.ajax({
            url: $(stat_element).data('url'),
            type: "get",
            data: {
                start_date: start_date,
                end_date: end_date
            },
            dataType: "json",
            context: stat_element,
            success: function(response) {
                var data = google.visualization.arrayToDataTable(response.data.data),
                    options = {
                        title: '',
                        vAxis: {
                            title: response.data.title,
                            titleTextStyle: {
                                color: 'black'
                            }
                        }
                    };
                var chart;
                if (response.data.type === 'line') {
                    chart = new google.visualization.LineChart(document.getElementById($(stat_element).attr('id')));

                } else {
                    chart = new google.visualization.ColumnChart(document.getElementById($(stat_element).attr('id')));
                }
                chart.draw(data, options);
            }
        });
    });

    // Load all numeric stats listings
    $.each($('.js_dashboardStatListing'), function (idx, stat_element) {
        $(stat_element).html(spinner);
        $.ajax({
            url: $(stat_element).data('url'),
            type: "get",
            data: {
                start_date: start_date,
                end_date: end_date
            },
            dataType: "json",
            context: stat_element,
            success: function(response) {
                $("#" + $(stat_element).attr('id')).html(response.data.html);
            }
        });
    });

}

$(function() {
    $('.js_clone_above').on('click', function(e) {
        e.preventDefault();

        let $element_above = $(this).prev("section");
        let $cloned_element = $element_above.clone();

        let temp_id = Math.random();

        $cloned_element.find("[name]").each(function() {
            $(this).prop("disabled", false);

            let current_name = $(this).attr("name");
            $(this).attr("name", current_name.replace("{temp_id}", temp_id));

            let current_id = $(this).attr("id");
            if (current_id) { $(this).attr("id", current_id.replace("{temp_id}", temp_id)); }
        });

        $cloned_element.find("textarea").addClass("tinymce");

        $cloned_element.insertBefore($(this).parent());
        $cloned_element.show();

        tinymce.remove();
        init_tinymce();
    });


    $(".js_movable").on("click", ".js_move_down", function(e) {
        e.preventDefault();

        let element = $(this).closest("section");
        tinymce.remove();
        element.next().insertBefore(element);
        init_tinymce();
    });

    $(".js_movable").on("click", ".js_move_up", function(e) {
        e.preventDefault();

        let element = $(this).closest("section");
        tinymce.remove();
        element.prev().insertAfter(element);
        init_tinymce();
    });

    $(".js_movable").on("click", ".js_delete_me", function(e) {
        e.preventDefault();

        let element = $(this).closest("section");
        element.remove();
    });

    setTimeout(function() {
        $('.mtcOverlay').mtcOverlay();
    }, 2000);
});

$(function() {
    const $btn = $('#btnUploadStockCSV');

    if(!$btn.length) return;

    new Dropzone($btn.get(0), {
        url: "/shop/admin/products/upload.stock.php",
        withCredentials: true,
        createImageThumbnails: false,
        disablePreviews: true,
        uploadMultiple: false,
        paramName: 'csv',
        previewsContainer: document.createElement('div'),
        acceptedFiles: 'text/csv',
        complete: function() {
            window.location.reload()
        }
    });
});

/**
 *
 * @param callback
 * @param value
 * @param meta
 */
function openFilePicker(callback, value, meta) {
    window.insertMediaToTinyMCE = function (url) {
        callback(url);
    };
    window.open('/admin/media-manager/tinymce', 'Media Manager', 'width=950,height=650');
}
