// Configuration
var ajax_link = '/ajax/resmng/resmng_admin';
var ckeditorConfig = {
    toolbar: 'RTpanel',
    filebrowserBrowseUrl: '/assets/plugins/kcfinder/browse.php?type=files',
    filebrowserImageBrowseUrl: '/assets/plugins/kcfinder/browse.php?type=images',
    filebrowserFlashBrowseUrl: '/assets/plugins/kcfinder/browse.php?type=flash',
    filebrowserUploadUrl: '/assets/plugins/kcfinder/upload.php?type=files',
    filebrowserImageUploadUrl: '/assets/plugins/kcfinder/upload.php?type=images',
    filebrowserFlashUploadUrl: '/assets/plugins/kcfinder/upload.php?type=flash'
}


var item_id;
$(function () {
    treeMenuInit();
});
function treeMenuInit() {
    $('.resmng_tree_menu ul').sortable({
        opacity: 0.5,
        start: function (event, ui) {
            $('.resmng_tree_menu .empty-level ul').css('z-index', '2');
        },
        stop: function (event, ui) {
            var ul = $(ui.item).parent();
            var parent = ul.parent().attr('rel').replace('set_', '');
            var data = 'parent=' + parent + '&' + ul.sortable('serialize', {
                key: "item[]",
                attribute: 'rel'
            });
            $.post(ajax_link + '/move', data, function (rs) {
                var obj = jQuery.parseJSON(rs);
                if (obj.success !== 1) {
                    $('.resmng_tree_menu ul').sortable('cancel');
                } else {
                    ul.parent().removeClass('empty-level').addClass('sub-level');
                    $('.connectedSortable').each(function () {
                        var t = $(this).html().replace(/^\s+|\s+$/g, '');
                        if (t === '') {
                            $(this).parent().removeClass('sub-level').removeClass('empty-level').addClass('empty-level');
                        }
                    });
                }
            });
            $('.resmng_tree_menu .empty-level ul').css('z-index', '-2');
        },
        connectWith: ".connectedSortable"
    }).disableSelection();
    var tabTimer = 0;
    // Show-hide children
    $('.resmng_tree_menu li').click(function () {

        if (tabTimer) {
            clearTimeout(tabTimer);
        }
        var el = $(this);
        tabTimer = setTimeout(function () {
            if (el.hasClass('sub-level'))
                el.toggleClass('convolute');
            if (el.attr('rel') !== undefined) {
                $.post(ajax_link + '/convolute', {'id': el.attr('rel').replace('set_', '')});
            }
        }, 250);
        return false;
    });
    // Show resource content
    $('.resmng_tree_menu li').dblclick(function () {
        clearTimeout(tabTimer);
        openTab($(this));
        return false;
    });
    // Set-unset private status
    $('.resmng_tree_menu .icon-eye-open, .resmng_tree_menu .icon-eye-close').click(function () {
        var el = $(this);
        var cur_class = el.attr('class');
        var itemId = el.parents('li').attr('rel').replace('set_', '');
        var value = 0;
        if (cur_class === 'icon-eye-open') {
            value = 1;
        }
        $.post(ajax_link + '/set_private', {
            'id': itemId,
            'value': value
        }, function (rs) {
            var obj = jQuery.parseJSON(rs);
            if (obj.success === 1) {
                el.removeClass(cur_class);
                if (cur_class === 'icon-eye-open') {
                    el.addClass('icon-eye-close');
                } else {
                    el.addClass('icon-eye-open');
                }
            }
        });
        return false;
    });
    // Create context menu
    $('#resource a.tree_menu_item').mousedown(function (e) {
        if (e.button === 2) {
            item_id = $(this);
            // select item
            item_id.addClass('inAction');
            document.oncontextmenu = function () {
                return false;
            };
            var context_menu = $('#resmng_contextmenu_tree').show().position({
                my: "left top",
                at: "left bottom",
                of: this
            });
            $(document).one("click", function () {
                document.oncontextmenu = function () {
                    return true;
                };
                context_menu.hide();
                // Unselect item
                $('#resource a').removeClass('inAction');
            });
            return false;
        }
        return true;
    });
    $('#resmng_contextmenu_tree').menu();
    // Create context menu for cart
    $('#deleted a.tree_menu_item').mousedown(function (e) {
        if (e.button === 2) {
            item_id = $(this);
            // select item
            item_id.addClass('inAction');
            var parent = item_id.parent().parent().parent().attr('rel').replace('set_', '');
            // Hide recovery action if not parent
            if (parent != 0) {
                $('#resmng_contextmenu_tree_cart li:eq(0)').hide();
            } else {
                $('#resmng_contextmenu_tree_cart li:eq(0)').show();
            }

            document.oncontextmenu = function () {
                return false;
            };
            var context_menu = $('#resmng_contextmenu_tree_cart').show().position({
                my: "left top",
                at: "left bottom",
                of: this
            });
            $(document).one("click", function () {
                document.oncontextmenu = function () {
                    return true;
                };
                context_menu.hide();
                // Unselect item
                $('#deleted a').removeClass('inAction');
            });
            return false;
        }
        return true;
    });
    $('#resmng_contextmenu_tree_cart').menu();
}

function treeMenuRefresh(openById) {
    $.post(ajax_link + '/refrash_tree_menu', function (data) {
        var menu = jQuery.parseJSON(data);
        $('#resource div.resmng_tree_menu').html(menu.res);
        $('#deleted div.resmng_tree_menu').html(menu.cart);
        treeMenuInit();
        if (openById) {
            openTab($('li[rel=set_' + openById + ']'));
        }
    });
}

// Rename item
function treeMenuItemRename() {
// Hide contextmenu
    $('#resmng_contextmenu_tree').hide();
    // Hide prev edit input
    $('#item_rename').change();
    $(document).one("click", function () {
        $('#item_rename').change();
    });
    var elName = item_id.find('.item_name:eq(0)');
    var oldName = elName.html();
    elName.html('<input id="item_rename" value="' + oldName + '" />');
    // Set action
    $('#item_rename').click(function () {
        $(this).select();
        return false;
    }).change(function () {
        var elInput = $(this);
        var itemId = elInput.parents('li').attr('rel').replace('set_', '');
        var itemName = elInput.val();
        if (itemName !== oldName) {
            $.post(ajax_link + '/rename', {
                'id': itemId,
                'name': itemName
            }, function (rs) {
                var obj = jQuery.parseJSON(rs);
                if (obj.success !== 1) {
                    elInput.parent().html(oldName);
                } else {
                    elInput.parent().html(itemName);
                }
            });
        } else {
            elInput.parent().html(oldName);
        }
    }).select();
    return false;
}

// Clone item
function treeMenuItemClone(msg) {
    var dialog = $('#context_menu_dialog');
    var send_link = ajax_link;
    send_link += '/cloneitem'
    dialog.html(msg + ' ' + item_id.find('span.item_name').html() + '?');
    dialog.dialog({
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function () {
                var itemId = item_id.parent().attr('rel').replace('set_', '');
                $.post(send_link, {
                    'id': itemId
                }, function (rs) {
                    var obj = jQuery.parseJSON(rs);
                    if (obj.success === 1) {
                        treeMenuRefresh();
                    }
                });
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });
    return false;
}

function treeMenuItemCreate(type, msg) {
    var dialog = $('#context_menu_dialog');
    var dialog_html = msg + ': <input id="item_name" name="item_name" value="" />';
    dialog.html(dialog_html);
    dialog.dialog({
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function () {
                var name = $('#item_name').val();
                var itemId = item_id.parent().attr('rel').replace('set_', '');
                $.post(ajax_link + '/create', {
                    'name': name,
                    'id': itemId,
                    'type': type
                }, function (rs) {
                    var obj = jQuery.parseJSON(rs);
                    if (obj.success === 1) {
                        treeMenuRefresh(obj.resId);
                    }
                });
                $(this).dialog("close");
            }
        }
    });
}

function treeMenuTrashAction(action, msg) {
    var dialog = $('#context_menu_dialog');
    var send_link = ajax_link;
    if (action === 0) {
        send_link += '/delete'
        dialog.html(msg + ' ' + item_id.find('span.item_name').html() + '?');
    }

    if (action === 1) {
        send_link += '/recovery'
        dialog.html(msg + ' ' + item_id.find('span.item_name').html() + '?');
    }

    if (action === 2) {
        send_link += '/clear_trash'
        dialog.html(msg + ' ' + item_id.find('span.item_name').html() + '?');
    }

    dialog.dialog({
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function () {
                var itemId = item_id.parent().attr('rel').replace('set_', '');
                $.post(send_link, {
                    'id': itemId
                }, function (rs) {
                    var obj = jQuery.parseJSON(rs);
                    if (obj.success === 1) {
                        treeMenuRefresh();
                    }
                });
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });
}

function openTab(el) {
    var itemId = el.attr('rel').replace('set_', '');
    if ($('#tab-' + itemId).html() === undefined) {
        var itemName = el.find('span.item_name').html();
        $.post(ajax_link + '/get_content', {
            id: itemId
        }, function (data) {
            if (data !== '') {
                addTab(itemId, itemName, data);
            }
        });
    } else {
        $('#tabs_nav a[href=#tab-' + itemId + ']').tab('show');
    }
}

function addTab(itemId, itemName, data) {
    $('#tabs_nav').append('<li><a href="#tab-' + itemId + '" data-toggle="tab">' + itemName + '</a></li>');
    $('#tabs_content').append('<div class="tab-pane" id="tab-' + itemId + '">' + data + '</div>');
    $('#tabs_nav a:last').tab('show');
    var form = $('#tab-' + itemId + ' form');
    // Close click
    form.find('button.btnCancel').click(function () {
        closeTab(form.parent().attr('id'), form.closest('form').data('changed'));
    });
    // Close other
    form.find('button.btnCloseOther').click(function () {
        var currentId = 'tab-' + itemId;
        $('div.tab-pane:not(.noclose)').each(function () {
            var elId = $(this).attr('id');
            if (elId !== currentId) {
                closeTab(elId, $(this).find('form').closest('form').data('changed'));
            }
        });
    });
    // Save click
    form.find('button[type=submit]').click(function () {
        $.post(form.attr('action'), form.serialize(), function (rs) {
            var obj = jQuery.parseJSON(rs);
            var alertClass = 'alert-error';
            if (obj.success === 1) {
                alertClass = 'alert-success';
            }
            form.find('div.alert').remove();
            form.prepend('<div class="alert fade in ' + alertClass + '"><button class="close" data-dismiss="alert" type="button">×</button><p>' + obj.msg + '</p></div>');
            form.data('changed', false);
            $('#tabs_nav a[href=#tab-' + itemId + ']').css('font-weight', 'normal');
        });
        return false;
    });
    // Editor init
    if (form.find('input[name=editor]').is(':checked')) {
        form.find('textarea').ckeditor(ckeditorConfig);
    }
    form.find('input[name=editor]').click(function () {
        var subForm = $(this).parents('form');
        if ($(this).is(':checked')) {
// Create editor
            subForm.find('textarea').ckeditor(ckeditorConfig);
        } else {
// Destroy editor
            subForm.find('textarea').each(function () {
                var editor = this.id;
                if (CKEDITOR.instances[editor]) {
                    CKEDITOR.instances[editor].destroy();
                }
            });
        }
    });
    // If form was changed
    form.find('input, textarea').change(function () {
        form.closest('form').data('changed', true);
        $('#tabs_nav a[href=#tab-' + itemId + ']').css('font-weight', 'bold');
    });
}

function closeTab(tabId, checkForChanges) {
    if (checkForChanges) {
        $('#context_menu_dialog').html(msgCloseTab).dialog({
            resizable: false,
            modal: true,
            buttons: {
                Ok: function () {
                    closeTab(tabId, false);
                    $(this).dialog("close");
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    } else {
// Destroy editor
        $('#' + tabId).find('textarea').each(function () {
            var editor = this.id;
            if (CKEDITOR.instances[editor]) {
                CKEDITOR.instances[editor].destroy();
            }
        });
        // Destroy tab
        $('#' + tabId).remove();
        $('#tabs_nav li a[href=#' + tabId + ']').remove();
        $('#tabs_nav a:last').tab('show');
    }
}

//Search recource in tab by id
function search_resource() {
    $('.res_search button i').removeClass('fa-search').addClass('fa-spinner');
    var res_id = 0;
    $('.connectedSortable li').each(function () {
        var value = parseInt($(this).attr('rel').split('_')[1]);
        if ($('#search_1').val() == value) {
            res_id = value;
        }
    });
    if (res_id !== 0) {
        $('.connectedSortable li').removeClass('convolute');
        $('.connectedSortable').find('a').css('background-color', '');
        var parent = $('li[rel=set_' + res_id + ']');
        var el = parent.first();
        var tab = parent.parent().parent().parent();
        var container = $('.resmng_tree_menu .connectedSortable');
        container.animate({scrollTop: $(el).offset().top+container.scrollTop()-200}, 1000);
        console.log($(el).offset().top);
        console.log(container.scrollTop());
        parent.find('a:first').css('background-color','yellow');
        //openTab(parent);
        if (tab.attr('id') == 'deleted') {
            $('.nav li').toggleClass('active');
            $('#resource').removeClass('active');
            tab.addClass('active');
        }

    } else {
        alert('Id not found');
    }
    $('.res_search button i').removeClass('fa-spinner').addClass('fa-search');
}
