﻿// JScript File

Ext.namespace('FinnKodeWeb');

FinnKodeWeb.TreeDynamicXml = function(config) {
    Ext.apply(this, {
        listeners: {
            'click': {
                fn: function(node, e) {
                    MsgSvc.addMsg({
                        TrackEvent: true,
                        Category: 'TreeNavigator',
                        Action: 'Navigate',
                        Label: this.bookSection.Description + ' - ' + node.text + ' - ' + node.id
                    });
                    this.currentObjectId = node.id;
                    this.nextObjectId = node.id;
                    this.loadingObjectId = 0;
                    NavigateTo(this.bookSection.BookId, this.bookSection.BookSectionId, node.id);
                },
                scope: this
            },
            'activate': {
                fn: function() {
                    this.locateNode(this.nextObjectId);
                },
                scope: this
            }
        },
        animate: false
    });

    // call superclass constructor
    FinnKodeWeb.TreeDynamicXml.superclass.constructor.call(this, config);

    // set custom config option
    this.bookSection = config.bookSection;
    this.currentObjectId = 0;
    this.nextObjectId = -1;
    this.loadingObjectId = 0;

    var completeLoadingNodePath = function(node) {
        if (node != null) {
            completeLoadingNodePath(node.parentNode);
            node.loadComplete();
            node.renderChildren(true);
        }
    }

    this.locateNode = function(objectId) {
        // Find source
        // Find source tree
        // Activate source tree
        // Probe for node
        // If node present, activate and make node visible
        // If node not present, retrieve node-path from webservice
        objectId = typeof (objectId) == "number" ? objectId.toString() : objectId;
        if (this.currentObjectId != objectId) {
            if (this.isVisible()) {
                MsgSvc.addMsg({
                    ShowMaskInfo: true,
                    MaskElement: this.body,
                    Category: 'TreeNavigator',
                    Action: 'LocateNode',
                    Label: 'Finner node ' + objectId
                });
                var node = this.getNodeById(objectId)
                if (node) {
                    MsgSvc.addMsg({
                        MaskElement: this.body,
                        Category: 'TreeNavigator',
                        Action: 'LocateNode',
                        Label: 'Funnet node ' + objectId
                    });
                    this.currentObjectId = node.id;
                    if (node == this.getRootNode()) {
                        node.expand();
                    }
                    var selectFunction = function(node) {
                        var tree = node.getOwnerTree();
                        var fly = Ext.fly(node.getUI().getAnchor());
                        var offsets = fly.getOffsetsTo(tree.body);
                        var left = tree.body.dom.scrollLeft;
                        //                        if (tree.body.getBottom() < fly.getBottom()) {
                        //                            var top = tree.body.dom.scrollTop + offsets[1];
                        //                            tree.body.scrollTo('top', top, true);
                        //                        }
                        if (left > 0) {
                            tree.body.scrollTo('left', 0, true);
                        }
                    };
                    this.selectPath(node.getPath());
                    selectFunction.defer(400, this, [node]);
                }
                else {
                    var succeededCallback = function(result, userContext, methodName) {
                        MsgSvc.addMsg({
                            Category: 'TreeNavigator',
                            Action: 'AfterLoadNodePath',
                            Label: 'Lastet ' + userContext.loadingObjectId
                        });
                        loadNodePath.call(userContext, result, 0);
                    };
                    var failedCallback = function(result, userContext, methodName) {
                        MsgSvc.addMsg({
                            ShowAlertInfo: true,
                            Category: 'TreeNavigator',
                            Action: 'AfterLoadNodePath',
                            Label: 'Feilet ' + userContext.nextObjectId
                        });
                    };

                    MsgSvc.addMsg({
                        ShowMaskInfo: true,
                        MaskElement: this.body,
                        Category: 'TreeNavigator',
                        Action: 'BeforeLoadNodePath',
                        Label: 'Laster ' + objectId
                    });
                    var ws = new finnkode.kith.no.icontentservice();
                    ws.GetNodePath(this.bookSection.BookId, this.bookSection.BookSectionId, objectId, succeededCallback, failedCallback, this);
                }
            }
        }
    };

    this.navigate = function(hashManager) {
        if (!hashManager) return;
        if (hashManager.bookSectionId != this.bookSection.BookSectionId) return;
        if (hashManager.objectId && hashManager.objectId != this.currentObjectId) {
            this.nextObjectId = hashManager.objectId;
            this.locateNode(this.nextObjectId);
        }
    };

    this.scrollToNode = function(tree, node) {
        var offsets = Ext.fly(node.getUI().getAnchor()).getOffsetsTo(tree.body);
        var left = offsets[0] + tree.body.dom.scrollLeft;
        var top = offsets[1] + tree.body.dom.scrollTop;
        tree.body.scrollTo('left', 0, true);
        tree.body.scrollTo('top', top - 25, true);
    };

    // helper function for adding nodes to parentnode where nodes is structure retrieved from WebService
    var addChildNodes = function(parentNode, childNodes) {
        if (childNodes.length > 0) {
            var i = 0;
            for (i = 0; i < childNodes.length; i++) {
                var childNode = new Ext.tree.AsyncTreeNode({
                    id: childNodes[i].id,
                    text: childNodes[i].text,
                    leaf: childNodes[i].leaf,
                    qtipCfg: {
                        text: childNodes[i].text
                    },
                    listeners: {
                        beforeload: {
                            scope: this,
                            fn: handlerOnBeforeExpandNode
                        }
                    }
                });
                parentNode.appendChild(childNode);
            }
        }
        parentNode.loadComplete();
    }

    var loadNodePath = function(nodeIdArray, index) {
        var node = this.getNodeById(nodeIdArray[index])
        if (index + 1 >= nodeIdArray.length) {
            // Last node in path is reached
            if (node) {
                this.locateNode(node.id);
            }
        }
        else {
            index++;
            if (node.childNodes.length > 0) {
                // Child nodes are loaded, proceed with next node in path
                loadNodePath.call(this, nodeIdArray, index);
            }
            else {
                if (this.loadingObjectId != node.id) {
                    this.loadingObjectId = node.id;

                    var succeededCallback = function(result, userContext, methodName) {
                        MsgSvc.addMsg({
                            Category: 'TreeNavigator',
                            Action: 'AfterGetChildNodes',
                            Label: userContext.bookSection.Description + ' - ' + node.text
                        });
                        // add nodes to parent node
                        addChildNodes.call(userContext, node, result);
                        // proceed on loading node path
                        loadNodePath.call(userContext, nodeIdArray, index);
                    };
                    var failedCallback = function(response, userContext, methodName) {
                        MsgSvc.addMsg({
                            ShowAlertInfo: true,
                            Category: 'TreeNavigator',
                            Action: 'AfterGetChildNodes',
                            Label: 'Feilet i lasting av ' + userContext.loadingObjectId
                        });
                    };
                    MsgSvc.addMsg({
                        ShowMaskInfo: true,
                        MaskElement: this.body,
                        Category: 'TreeNavigator',
                        Action: 'BeforeGetChildNodes',
                        Label: 'Laster' + this.bookSection.Description + ' - ' + node.text
                    });
                    // load children of node
                    var cs = new finnkode.kith.no.icontentservice();
                    cs.GetChildNodes(this.bookSection.BookId, this.bookSection.BookSectionId, node.id, succeededCallback, failedCallback, this);
                }
            }
        }
    };

    var handlerOnBeforeExpandNode = function(node) {
        if (!node.isLeaf() && node.childNodes.length == 0) {
            if (this.loadingObjectId != node.id) {
                this.loadingObjectId = node.id;

                var succeededCallback = function(result, userContext, methodName) {
                    MsgSvc.addMsg({
                        MaskElement: userContext.body,
                        Category: 'TreeNavigator',
                        Action: 'AfterGetChildNodes',
                        Label: 'Lastet ' + node.id
                    });
                    addChildNodes.call(userContext, node, result);
                };
                var failedCallback = function(result, userContext, methodName) {
                    MsgSvc.addMsg({
                        ShowAlertInfo: true,
                        Category: 'TreeNavigator',
                        Action: 'AfterGetChildNodes',
                        Label: 'Feilet i lasting av ' + userContext.loadingObjectId
                    });
                };
                MsgSvc.addMsg({
                    MaskElement: this.body,
                    Category: 'TreeNavigator',
                    Action: 'BeforeGetChildNodes',
                    Label: 'Laster ' + node.id
                });
                var ws = new finnkode.kith.no.icontentservice();
                ws.GetChildNodes(this.bookSection.BookId, this.bookSection.BookSectionId, node.id, succeededCallback, failedCallback, this);
            }
        }
    };

    // set the root node
    var root = new Ext.tree.AsyncTreeNode({
        text: 'Systematisk del',
        id: '-1'
    });
    this.setRootNode(root);
    root.on({
        beforeload: {
            scope: this,
            fn: handlerOnBeforeExpandNode
        }
    });
}


Ext.extend(FinnKodeWeb.TreeDynamicXml, Ext.tree.TreePanel, {
    border: false,
    autoScroll: true,
    animate: true
    }
);

