import Dropzone from 'dropzone';
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);

        }
    });
}

$(document).ready(function() {

    'use strict';

    window.setInterval(function () {
        $.get('/admin/includes/auth.php?keep_alive=1');
    }, 900000); // every 15mins

    /*
     * 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);
        $(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();
    });

    $('.mtc_overlay').on('click', function(e) {

        e.preventDefault();
        target = $(this).attr('href');

        $.openMtcOverlay({
            target: target,
            iframe: true
        });
    });

    /*
     * Show's Crop Adjust on Overlay
     * On close updates image upload field
     */
    $('body').on('click', '.pagedata-crop-anchor', function (e) {
        e.preventDefault();
        var anchorEl = $(this),
            hiddenEl = anchorEl.siblings('.input_container').children('.real_file_value'),
            filename = hiddenEl.val(),
            plid_id = hiddenEl.attr('data-list-item-data-id'),
            target = 'crop_adjust.php?page_list_item_data_id=' + plid_id + '&filename=' + filename,
            crop_result_image_filename;

        $.openMtcOverlay({
            target: target,
            content_class: 'cropOverlay',
            // on open
            onOpen: function () {
                initCrop('#jCropTarget');
            },
            onClose: function() {
                crop_result_image_filename = $('.overlayContentInner #result-image').attr("data-filename");
                if (typeof crop_result_image_filename === "undefined") {
                    return false;
                }
                anchorEl.siblings('.input_container').children('.real_file_value').attr("value", crop_result_image_filename);
                anchorEl.siblings('.input_container').children('.image_container').find('img').attr("src", "/uploads/images/cms/small/" + crop_result_image_filename);
                setUnsavedChanges(true);
            }
        });
    });

    $('body').on('click', '#btn_cancel', function (e) {
        $('.overlayCloseButton').trigger('click');
    });

    /*
     * On Crop Adjust form submit change result image
     */
    $('body').on('submit', '#cropForm', function(e) {
        e.preventDefault();
        var form = $(this),
            formData = form.serialize() + '&submitBtn=true';

        $.ajax({
            type        : 'POST',
            url         : form.attr('action'),
            data        : formData,
            dataType    : 'html',
            success: function (html) {
                $('.cropOverlay .overlayAjax').html(html);
                initCrop('#jCropTarget');
            }
        });
    });

    /*
     * On Crop Adjust image size change result image
     */
    $('body').on('change', '#image_cms_images_size', function(e) {
        var form = $(this).closest('#cropForm'),
            formData = form.serialize();

        $.ajax({
            type        : 'POST',
            url         : form.attr('action'),
            data        : formData,
            dataType    : 'html',
            success: function (html) {
                $('.cropOverlay .overlayAjax').html(html);
                initCrop('#jCropTarget');
            }
        });
    });

    initCrop('#jCropTarget');

    // 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");
            }
            else {
                txt.attr("class", "fa fa-caret-right");
            }

            $(this).css('overflow', 'visible');
        });
    });

    $("body").on("click", "a.alert, a.js_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');

    });


    $('body').on('click', 'button.alert', function(e) {

        // prevent default
        e.preventDefault();

        // add title to dialog box
        var title = $(this).attr('title');
        var delete_id = $(this).data('delete_id');

        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 () {
                $('#' + delete_id).submit();
            }
        });

        // 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 = '/admin/api/paginated_order';
                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 = '/admin/api/order';
                order = $(this).sortable("serialize") + '&action=order&table=' + $('#orderbytable').val() + '&field=' + $('#orderbyfield').val();
            }

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

    $('#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');
            }
        });
    }

    // Add perfectScrollbar to the sidebar in admin area
    $('.sidebar').perfectScrollbar();


    $("input:file[name=csv]").hide();
    $("input:submit[name=import]").click(function(e) {
        if (!$("input:file[name=csv]").is(':visible')) {
            e.preventDefault();
            $("input:file[name=csv]").fadeIn(250);
        }
        else if ($("input:file[name=csv]").val() == '') {
            e.preventDefault();
            $("input:file[name=csv]").click();
        }
    });
}); // 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);
            }
        });
    });
}

// image crop

function updatePreview(c) {

    'use strict';

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

function initCrop (target, width, height) {

    'use strict';

    var width = width || 434,
        height = height || 390,
        target = $(target);
    target.Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: $('#aspectratio').val(),
        minSize: [$('#minwidth').val(), $('#minheight').val()],
        boxWidth: width,
        boxHeight: height,
        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
}
