/**
 * Function run when dashboard panel gets loaded
 * Contains all the native js events
 * @author Rihards Siliņš
 * @version 3 10/11/2016
 */
/*global $, window, cmsPreventDefault, displayVersionInformationBtn,
markReviewedBtn, pagePreviewBtn, viewVersionBtn, changeSiteTreeActive,
setUnsavedChanges, anchorClickLoadPage, fieldsetToggles, ldrSuccess, ldr
dashboardInitCustom, getSiteTree, ldrFailure, treatPage, content_manager,
getPage */
function dashboardInit(dom_scope) {
    'use strict';
    if (typeof dom_scope === 'undefined' || dom_scope === false || dom_scope === "" || dom_scope === 0) {
        dom_scope = '#workArea';
    }

    $(dom_scope).find('a.displayVersionInformationBtn').on("click", function (event) {
        cmsPreventDefault(event);
        displayVersionInformationBtn($(this));
        return false;
    });

    $(dom_scope).find('a.markReviewed').on("click", function (event) {
        cmsPreventDefault(event);
        markReviewedBtn($(this));
        return false;
    });

    $(dom_scope).find('a.preview').on("click", function (event) {
        cmsPreventDefault(event);
        pagePreviewBtn($(this).data("page-id"), $(this).data("page-url"));
        return false;
    });

    $(dom_scope).find('a.viewVersion').on("click", function (event) {
        cmsPreventDefault(event);
        viewVersionBtn($(this));
        return false;
    });

    var dash_old_order_array,
        dash_old_order_serialization;
    $("ul.dashboardSiteTree").nestedSortable({
        handle: '.move',
        items: 'li',
        toleranceElement: '> div',
        listType: 'ul',
        forcePlaceholderSize: true,
        placeholder: 'placeholder',
        startCollapsed: true,
        isTree: true,
        start: function () {
            dash_old_order_array = $("ul.dashboardSiteTree").nestedSortable('toArray');
            dash_old_order_serialization = $("ul.dashboardSiteTree").nestedSortable('serialize');
        },
        update: function (event, ui) {
            ldr("reordering pages...");
            var new_order = $("ul.dashboardSiteTree").nestedSortable('serialize');
            // AJAX call to sort pages
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/site-tree-sort.php',
                data: {
                    new_order: JSON.stringify(new_order)
                },
                success: function () {
                    getSiteTree();

                    var title,
                        text,
                        new_order_array = $("ul.dashboardSiteTree").nestedSortable('toArray'),
                        old_current_page_parent_id,
                        new_current_page_parent_id,
                        i,
                        moved_item_id_parts = ui.item.attr("id").split("_"),
                        moved_page_id = moved_item_id_parts[1];

                    for (i = dash_old_order_array.length - 1; i >= 0; i -= 1) {
                        if (typeof content_manager.page_live !== 'undefined' && parseInt(dash_old_order_array[i].id, 10) === parseInt(content_manager.page_live.id, 10)) {
                            if (dash_old_order_array[i].parent_id === null) {
                                old_current_page_parent_id = 0;
                            } else {
                                old_current_page_parent_id = parseInt(dash_old_order_array[i].parent_id, 10);
                            }
                        }
                    }

                    for (i = new_order_array.length - 1; i >= 0; i -= 1) {
                        if (typeof content_manager.page_live !== 'undefined' && parseInt(new_order_array[i].id, 10) === parseInt(content_manager.page_live.id, 10)) {
                            if (new_order_array[i].parent_id === null) {
                                new_current_page_parent_id = 0;
                            } else {
                                new_current_page_parent_id = parseInt(new_order_array[i].parent_id, 10);
                            }
                        }
                    }

                    $.ajax({
                        url: 'ajax/process_slugs_for_page_and_subs.php',
                        type: 'GET',
                        dataType: 'JSON',
                        data: {
                            page_id: moved_page_id,
                            recursive_limit: 1,
                            dry: 1
                        },
                        timeout: content_manager.timeout_limit
                    }).done(function (result) {

                        if (result.length === 0) {
                            if (new_current_page_parent_id !== old_current_page_parent_id) {
                                getPage(
                                    content_manager.page_live.id,
                                    function (page) {
                                        ldrSuccess();
                                        treatPage(page);
                                    },
                                    result.history_page_id
                                );
                            } else {
                                ldrSuccess();
                            }
                        } else {
                            title = "Page slug updated!";
                            text = "<p>The slug <strong>" + result[0].old_slug + "</strong> of the page you moved ";
                            text += "was updated to <strong>" + result[0].new_slug + "</strong> ";
                            text += "because it was already taken by another public page on that level</p>";

                            $('#dialog').html(text);
                            $('#dialog').dialog('option', 'title', title);
                            $('#dialog').dialog('option', 'width', "600px");
                            $('#dialog').dialog('option', 'buttons', {
                                Ok: function () {
                                    $('#dialog').dialog('close');
                                    ldr("finalizing...");
                                    $.ajax({
                                        url: 'ajax/process_slugs_for_page_and_subs.php',
                                        type: 'GET',
                                        dataType: 'JSON',
                                        data: {
                                            page_id: moved_page_id,
                                            recursive_limit: 1,
                                            dry: 0
                                        },
                                        timeout: content_manager.timeout_limit
                                    }).done(function () {
                                        if (new_current_page_parent_id !== old_current_page_parent_id) {
                                            getPage(
                                                content_manager.page_live.id,
                                                function (page) {
                                                    ldrSuccess();
                                                    treatPage(page);
                                                },
                                                result.history_page_id
                                            );
                                        } else {
                                            ldrSuccess();
                                        }
                                    }).fail(function () {
                                        ldrFailure();
                                    });
                                },
                                "Undo Move": function () {
                                    $('#dialog').dialog('close');
                                    ldr("undoing move...");
                                    $.ajax({
                                        type: 'post',
                                        cache: false,
                                        url: 'ajax/site-tree-sort.php',
                                        data: {
                                            new_order: JSON.stringify(dash_old_order_serialization)
                                        },
                                        success: function () {
                                            ldrSuccess();
                                            location.reload();
                                        }
                                    });
                                }
                            });
                            $('#dialog').dialog('open');
                        }
                        ldrSuccess();
                    }).fail(function () {
                        ldrFailure();
                    });
                }
            });
        }
    });

    $('.toggleOpen').on('click', function () {
        $(this).closest('li').toggleClass('mjs-nestedSortable-collapsed').toggleClass('mjs-nestedSortable-expanded');
    });

    $(dom_scope).find(".newPageBtn").on("click",function(event){
        let page_type = $(this).data('page-type');
        cmsPreventDefault(event);
        return newPage(page_type);
    });

    $(dom_scope).find('.paste-page-btn').on("click", function(event){
        cmsPreventDefault(event);
        pagePasteDialog();
        return false;
    });

    fieldsetToggles(dom_scope);

    $(dom_scope).find('a.anchorClickLoadPage').on("click", function (event) {
        cmsPreventDefault(event);
        anchorClickLoadPage($(this));
        return false;
    });
    changeSiteTreeActive();
    dashboardInitCustom(dom_scope);
    // reset unsaved changes
    setUnsavedChanges(false);
}
