/*global $, window, cmsPreventDefault, displayVersionInformationBtn,
markReviewedBtn, pagePreviewBtn, viewVersionBtn, changeSiteTreeActive,
setUnsavedChanges, anchorClickLoadPage, fieldsetToggles, ldrSuccess, ldr
dashboardInitCustom, getSiteTree, initCustom, ldrFailure, content_manager,
getPage, treatPage, dialogueBuilderInit */
function init(dom_scope) {
    'use strict';
    if (typeof dom_scope === 'undefined' || dom_scope === false || dom_scope === "" || dom_scope === 0) {
        dom_scope = 'html';
    }

    // this is so that the submenu open/close btn doesn't trigger page load
    $(dom_scope).find("#site-tree li a i.submenu-button").click(function () {
        return false;
    });
    //$(dom_scope).find("#site-tree li a").click(function (event) {
    //    cmsPreventDefault(event);
    //    return anchorClickLoadPage($(this));
    //});

    $(dom_scope).find(".cms-buttom-page").click(function (event) {
        cmsPreventDefault(event);
        return anchorClickLoadPage($(this));
    });

    $(dom_scope).find('#site-tree .submenu-button').on("click", function (event) {
        cmsPreventDefault(event);
        var el = $(this).parent().parent().parent();
        if (el.hasClass('hide-submenu')) {
            el.removeClass('hide-submenu');
            $(this).removeClass('fa-chevron-circle-down');
            $(this).addClass('fa-chevron-circle-up');
        } else {
            el.addClass('hide-submenu');
            $(this).removeClass('fa-chevron-circle-up');
            $(this).addClass('fa-chevron-circle-down');
        }
        return false;
    });

    var old_order_array,
        old_order_serialization;
    $(dom_scope).find('#site-tree').nestedSortable({
        forcePlaceholderSize: true,
        opacity: 0.6,
        listType: 'ul',
        tabSize: 20,
        expandOnHover: 700,
        isTree: true,
        items: 'li',
        handle: ".menu-handle",
        start: function () {
            old_order_array = $('#site-tree').nestedSortable('toArray');
            old_order_serialization = $('#site-tree').nestedSortable('serialize');
        },
        update: function (event, ui) {
            ldr("reordering pages...");
            var new_order = $('#site-tree').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 = $('#site-tree').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 = old_order_array.length - 1; i >= 0; i -= 1) {
                        if (typeof content_manager.page_live !== 'undefined' && parseInt(old_order_array[i].id, 10) === parseInt(content_manager.page_live.id, 10)) {
                            if (old_order_array[i].parent_id === null) {
                                old_current_page_parent_id = 0;
                            } else {
                                old_current_page_parent_id = parseInt(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(old_order_serialization)
                                        },
                                        success: function () {
                                            ldrSuccess();
                                            getSiteTree();
                                        }
                                    });
                                }
                            });
                            $('#dialog').dialog('open');
                        }
                        ldrSuccess();
                    }).fail(function () {
                        ldrFailure();
                    });
                }
            });
        }
    });

    // This changes the view from mtcadmin to mtcclientadmin CMS manage page
    if ($('.layoutAdminToggle').length) {
        /* after an amount of time add a class to switch that adds the transition. Stops the transition
         * from showing on load of the checkbox is checked */
        setTimeout(function () {
            $(dom_scope).find('.layoutAdminToggle').addClass('transition');
        }, 250);

        // if the checkbox is checked(class js_checked is present) trigger the click
        if ($(dom_scope).find('.js_checked').length) {
            $(dom_scope).find('.js_checked').trigger('click');
        }

        // do the ajax request to reload the page
        $(dom_scope).on('change', '.layoutAdminToggle', function () {
            ldr("switching view...");
            $.ajax({
                type: 'post',
                cache: false,
                url: 'ajax/toggle_client_view.php'
            }).done(function () {
                ldr("reloading panels...");
                location.reload();
            }).fail(function () {
                ldrFailure();
            });

            return false;
        });
    }

    dialogueBuilderInit();

    initCustom(dom_scope);
}
