/* ------------------------------------------------------------------------------
 *
 *  # Fancytree
 *
 *  Demo JS code for extra_trees.html page
 *
 * ---------------------------------------------------------------------------- */


// Setup module
// ------------------------------

var Fancytree = function() {


    //
    // Setup module components
    //

    // Uniform
    var _componentFancytree = function() {
        if (!$().fancytree) {
            console.warn('Warning - fancytree_all.min.js is not loaded.');
            return;
        }


        // Basic setup
        // ------------------------------

        // Basic example
        $('.tree-default').fancytree({
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });

        // Load JSON data
        $('.tree-ajax').fancytree({
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });

        // Embed JSON data
        $('.tree-json').fancytree({
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });

        // Child counter
        $('.tree-child-count').fancytree({
            extensions: ['childcounter'],
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            childcounter: {
                deep: true,
                hideZeros: true,
                hideExpanded: true
            },
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });

        // Drag and drop support
        $('.tree-drag').fancytree({
            extensions: ['dnd5'],
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            dnd5: {
                autoExpandMS: 400,
                focusOnClick: true,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                preventRecursion: true, // Prevent dropping nodes on own descendants
                dragStart: function(node, data) {
                    return true;
                },
                dragEnter: function(node, data) {
                    return true;
                },
                dragDrop: function(node, data) {

                    // This function MUST be defined to enable dropping of items on the tree.
                    data.otherNode.moveTo(node, data.hitMode);
                }
            },
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });

        // Editable nodes
        $('.tree-editable').fancytree({
            extensions: ['edit'],
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            edit: {
                adjustWidthOfs: 0,
                inputCss: {minWidth: '0'},
                triggerStart: ['f2', 'dblclick', 'shift+click', 'mac+enter'],
                save: function(event, data) {
                    alert('save ' + data.input.val()); // Save data.input.val() or return false to keep editor open
                }
            }
        });


        //
        // Selectable nodes
        //

        // Single selection
        $('.tree-radio').fancytree({
            checkbox: true,
            selectMode: 1,
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            }    
        });

        // Multiple selection
        $('.tree-checkbox').fancytree({
            checkbox: true,
            selectMode: 2,
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            }
        });

        // Disable selections
        $('.tree-checkbox-options').fancytree({
            checkbox: true,
            selectMode: 2
        });

        // Hierarchical select
        $('.tree-checkbox-hierarchical').fancytree({
            checkbox: true,
            selectMode: 3
        });


        //
        // Toggle checkbox state
        //

        // Initialize
        $('.tree-checkbox-toggle').fancytree({
            checkbox: true,
            selectMode: 2,
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            }    
        });

        // Define element
        var selectAllSwitch = document.querySelector('#select_all');

        // Change checkbox states
        selectAllSwitch.addEventListener('change', function() {
            if(selectAllSwitch.checked) {

                $.ui.fancytree.getTree('.tree-checkbox-toggle').visit(function(node){
                    node.setSelected(true);
                });
                return false;
            }
            else {
                $.ui.fancytree.getTree('.tree-checkbox-toggle').visit(function(node){
                    node.setSelected(false);
                });
                return false;
            }
        });



        // Advanced examples
        // ------------------------------

        //
        // Toggle state
        //

        // Define element
        var enableDisableSwitch = document.querySelector('#enable_disable');

        // Do something on state change
        enableDisableSwitch.addEventListener('change', function() {
            if(enableDisableSwitch.checked) {
                $('.tree-toggle').fancytree('disable');
            }
            else {
                $('.tree-toggle').fancytree('enable');
            }
        });

        // Initialize
        $('.tree-toggle').fancytree({
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            init: function(event, data) {
                $('.has-tooltip .fancytree-title').tooltip();
            }
        });


        //
        // Sorting
        //

        // Initialize
        $('.tree-sorting').fancytree();

        // Sort tree
        $('.sort-tree').on('click', function() {
            var node = $.ui.fancytree.getTree('.tree-sorting').getRootNode();
            node.sortChildren(null, true);
        });

        // Sort active nodes
        $('.sort-branch').on('click', function() {
            var node = $.ui.fancytree.getTree('.tree-sorting').getActiveNode();

            // Custom compare function (optional) that sorts case insensitive
            var cmp = function(a, b) {
                a = a.title.toLowerCase();
                b = b.title.toLowerCase();
                return a > b ? 1 : a < b ? -1 : 0;
            };
            node.sortChildren(cmp, false);
        });


        //
        // Tree persistence
        //

        // Initialize
        $('.tree-persistence').fancytree({
            extensions: ['persist'],
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            checkbox: true,
            persist: {
                overrideSource: false, // true: cookie takes precedence over `source` data attributes.
                store: 'auto' // 'cookie', 'local': use localStore, 'session': sessionStore
            },
            postProcess: function(event, data) {
                var prefix = data.node.getIndexHier() + '.';
                $.each(data.response, function(idx, childEntry) {
                    if( childEntry.key == null ) {
                        childEntry.key = prefix + (idx + 1);
                        childEntry.title += ' (' + childEntry.key + ')';
                    }
                })
            }
        });
        var tree5 = $.ui.fancytree.getTree('.tree-persistence');

        // Reset cookies on button click
        $('.reset-cookies').on('click', function() {
            tree5.clearPersistData();
        });


        //
        // Table tree
        //

        $('.tree-table').fancytree({
            extensions: ['table'],
            checkbox: true,
            table: {
                indentation: 20,      // indent 20px per node level
                nodeColumnIdx: 2,     // render the node title into the 2nd column
                checkboxColumnIdx: 0  // render the checkboxes into the 1st column
            },
            source: {
                url: '../../../assets/demo/data/fancytree/fancytree.json'
            },
            lazyLoad: function(event, data) {
                data.result = {url: 'ajax-sub2.json'}
            },
            renderColumns: function(event, data) {
                var node = data.node,
                $tdList = $(node.tr).find('>td');

                // (index #0 is rendered by fancytree by adding the checkbox)
                $tdList.eq(1).text(node.getIndexHier()).addClass('alignRight');

                // (index #2 is rendered by fancytree)
                $tdList.eq(3).text(node.key);
                $tdList.eq(4).addClass('text-center').html('<label class="form-check"><input type="checkbox" class="form-check-input" name="like" value="' + node.key + '"><span class="form-check-label p-0"></span></label>');
            }
        });

        // Handle custom checkbox clicks
        $('.tree-table').on('input[name=like]', 'click', function(e) {
            var node = $.ui.fancytree.getNode(e),
            $input = $(e.target);
            e.stopPropagation(); // prevent fancytree activate for this row
            if($input.is(':checked')){
                alert('like ' + $input.val());
            }
            else{
                alert('dislike ' + $input.val());
            }
        });
    };


    //
    // Return objects assigned to module
    //

    return {
        init: function() {
            _componentFancytree();
        }
    }
}();


// Initialize module
// ------------------------------

document.addEventListener('DOMContentLoaded', function() {
    Fancytree.init();
});
