﻿
function LoadSheet(SheetID, ParentID) {



    return $.ajax({
        url: '/api/bulknode',
        cache: false,
        type: 'post',
        data: 'ItemKey=' + SheetID + "&ParentID=" + ParentID,
        success: function (data) {
            //now add the topic html to the topic
//            if (data.MaxDate > LastStreamTime)
//            {
//            LastStreamTime = data.MaxDate;
//            }
            AddSheetUI(SheetID, ParentID, data, 1, true);

            setTimeout(function () {

                FetchUpdateStream();

            }, gCurrentPoll);
            //            if (typeof _gaq =="undefined") {

            //                setTimeout("gaSSDSLoad('UA-21197590-1')",1000);
            //            }

        },
        error: ProcessAddedNodeError
    });


}
var gCurrentPoll = 20000;
var gNodeList = new Array();
var gPositionList = new Array();

var gUserList = new Array();

var gUserSheetList = new Array();
var LastStreamTime = -1;
//var WaitingForClean = new Array();



function AddSheetUI(ItemKey, ParentID, data, ExpandLevel, bFreshSet) {

                if (data.MaxDate > LastStreamTime)
                {
                LastStreamTime = data.MaxDate;
                }
    $.each(data.Users, function (idx, value) {
        if (FindUser(value.UserID, gUserList) >= 0) {

        }
        else {
            gUserList.push(value);
        }

    });

    $.each(data.UserSheets, function (idx, value) {
        if (FindUserSheet(value.UserID, gUserSheetList) >= 0) {

        }
        else {
            gUserSheetList.push(value);
        }

    });



    $.each(data.Nodes, function (idx, value) {

        if (gNodeList[value.NodeID] == null) {
            gNodeList[value.NodeID] = new Object;
            gNodeList[value.NodeID].Positions = new Array();


        }
        if (gNodeList[value.NodeID].Positions[value.Position.PositionID] == null) {

            gNodeList[value.NodeID].Positions[value.Position.PositionID] = value;
        }
        else {
            //todo:  do we need to sync here to make sure we cover dupes?
            var currentNode = gNodeList[value.NodeID].Positions[value.Position.PositionID];
            if (gNodeList[value.NodeID].Notifications != null) {


                gNodeList[value.NodeID].Notifications = new Array();
            }
            if (currentNode.Dirty == null || !currentNode.Dirty) {
                currentNode.ItemKey = value.Position.ItemKey;
                currentNode.Position.ParentID = value.Position.ParentID;
                currentNode.Position.AfterID = value.Position.AfterID;
                currentNode.Position.bComplete = value.Position.bComplete;
                currentNode.Position.bExpanded = value.Position.bExpanded;
                currentNode.CanUpdate = true;

                currentNode.NodeText = value.NodeText;
                currentNode.NodeNote = value.NodeNote;
                currentNode.bComplete = value.bComplete;
                currentNode.DateUpdated = value.DateUpdated;
                currentNode.ViewSecurityType = value.ViewSecurityType;
                currentNode.EditSecurityType = value.EditSecurityType;
            }
            else {
                //this node is dirty so we need to wait for a clean copy to update

            }
        }
    });

    $.each(data.Stream, function (idx, value) {

        
            if (gNodeList[value.StreamKey].Notifications == null) {
                gNodeList[value.StreamKey].Notifications = new Array();
            }
            
                gNodeList[value.StreamKey].Notifications.push(value);
            
       
    });

    //loop through again out of process to find the  last item
    setTimeout(function () {
        $.each(data.Stream, function (idx, value) {

            if (value.DateCreated > LastStreamTime) {
                LastStreamTime = value.DateCreated;
            }

        });
    }, 15000);
    $.each(data.Apps, function (idx, value) {
        var ThisNode = gNodeList[value.NodeID].Positions[value.PositionID];
        if (ThisNode != null) {
            if (ThisNode.Apps == null) {
                ThisNode.Apps = new Array();
            }
            if (ThisNode.Apps[value.AppName] == null) {
                ThisNode.Apps[value.AppName] = value;
            }
        }

    });

    for (var ThisNodeCount = 0; ThisNodeCount < data.Nodes.length; ThisNodeCount = ThisNodeCount + 25) {
        var LastNodeCount = 0;

        setTimeout(function () {
            var foundNodeList = new Array();

            var NodesToProc = new Array();
            $.each(data.Nodes, function (idx, value) {
                if (idx >= LastNodeCount && idx < LastNodeCount + 25) {

                    NodesToProc.push(value);

                }
            });
            LastNodeCount = LastNodeCount + 25;

            //add each item as we come to it.


            var NodesToPosition = new Array();
            //add each item as we come to it.
            var LeftArea = $('.SplitPaneLeft').first();
            var Processed = new Array();
            if (bFreshSet) {
                $.each(NodesToProc, function (zidx, zvalue) {
                    var ExistingNodes = $('.node' + zvalue.Position.PositionID);
                    if (ExistingNodes.length == 0) {
                        NodesToPosition.push(zvalue);
                        CreateNode(LeftArea, zvalue.NodeID, zvalue.Position.PositionID, zvalue.NodeText);
                        Processed.push(zvalue.Position.PositionID);
                        if (isExpanded(zvalue)==false ) {
                            if (foundNodeList[zvalue.Position.ItemKey] == null) {
                                foundNodeList[zvalue.Position.ItemKey] = new Array();
                            }

                            foundNodeList[zvalue.Position.ItemKey].push(zvalue.NodeID);
                        }
                    }
                    else {
                        NodesToPosition.push(zvalue);
                        //we need to replace then nodes
                        //but what if they have moved?
                        //we only do this replace shinanagans if the item hasn't been processed yet.

                    }

                });
            }
            else {

                $.each(NodesToProc, function (zidx, zvalue) {

                    if (zvalue.Position.ItemKey == ItemKey) {

                        var ExistingNodes = $('.node' + zvalue.Position.PositionID);
                        if (ExistingNodes.length == 0) {
                            NodesToPosition.push(zvalue);
                            CreateNode(LeftArea, zvalue.NodeID, zvalue.Position.PositionID, zvalue.NodeText);
                            Processed.push(zvalue.Position.PositionID);
                            if (isExpanded(zvalue)==false) {
                                if (foundNodeList[zvalue.Position.ItemKey] == null) {
                                    foundNodeList[zvalue.Position.ItemKey] = new Array();
                                }

                                foundNodeList[zvalue.Position.ItemKey].push(zvalue.NodeID);
                            }
                        }
                        else {
                            //we need to replace then nodes
                            //but what if they have moved?
                            //update the position



                            //                               
                            //we only do this replace shinanagans if the item hasn't been processed yet.

                            var Multiple = false;
                            $.each(ExistingNodes, function (tidx, tvalue) {

                                //move it to split pane left and add it to the position que...if it already exists in psplit pane left,remove it


                                var etValue = $(tvalue);
                                var PositionID = etValue.attr('PositionID');
                                var NodeID = etValue.attr('NodeID');

                                var oCurrent = gNodeList[NodeID].Positions[PositionID];



                                //                           

                                var ThisParent = GetParentNode(etValue);
                                var ThisParentID = ThisParent == null ? CurrentParentID : ThisParent.attr('NodeID');
                                var ThisAfter = GetAfterNode(etValue);
                                var ThisAfterID = ThisAfter == null ? EmptyGUID : ThisAfter.attr('NodeID');



                                if (gNodeList[NodeID].Notifications != null && gNodeList[NodeID].Notifications.length > 0) {
                                    var Note = etValue.children('.bullet').children(".notification");
                                    if (Note.first().text().toString() != gNodeList[NodeID].Notifications.length.toString()) {

                                        bFlash = true;
                                        Note.text(gNodeList[NodeID].Notifications.length);
                                    }

                                }

                                //update the position




                                if (oCurrent.Dirty == null || !oCurrent.Dirty) {

                                    if (oCurrent.Position.ParentID != ThisParentID || oCurrent.Position.AfterID != ThisAfterID) {

                                        var efound = $('.SplitPaneLeft').children('.node' + PositionID);

                                        if (efound.length == 0) {
                                            
                                            NodesToPosition.push(oCurrent);
                                            bFlash = true;
                                        }
                                        else {
                                            //
                                            //we should remvoe this unless what we found was ourself.
                                            if (ThisParent == null) {
                                                //this is probably us
                                            }
                                            else {
                                                efound.remove()
                                                $('.SplitPaneLeft').append(etValue);
                                            }
                                        }

                                        bFlash = true;

                                    }
                                    //update the text
                                    var txtBox = etValue.children('textarea.nodeContent');
                                    var bFlash = false;
                                    if (txtBox.first().text().toString() != oCurrent.NodeText.toString()) {

                                        bFlash = true;
                                        txtBox.text(oCurrent.NodeText);

                                    }


                                    //update the notification



                                    //                                }

                                    if (bFlash) {
                                        txtBox.css('background-color', '#87C9ED');

                                        //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                                        txtBox.stop().animate(
                                        { backgroundColor: 'White' }, 6000);
                                    }
                                }

                            });


                        }

                    }

                    //if it has been processed then the if part of the above block will handle it.
                });
            }

            //once we've added all items we can loop through and use selectors to find children
            //if we find children then we can add them to sub nodes
            var NodeRePlace = new Array();
            $.each(NodesToPosition, function (ridx, rvalue) {
                var oNode = gNodeList[rvalue.NodeID].Positions[rvalue.Position.PositionID];

                if (oNode.Position.ParentID == EmptyGUID) {
                    //move behind its after
                    var eNode = $('.SplitPaneLeft').children('.node' + oNode.Position.PositionID).first();
                    NodeRePlace.push(eNode);
                    if (oNode.Position.AfterID != EmptyGUID) {
                        var ExistingChildren = $('.SplitPaneLeft').children('.node');
                        var FoundAfter = null;
                        //find any item that it goes after
                        for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                            var oThisChild = $(ExistingChildren[ThisChild]);
                            var nodeID = oThisChild.attr('NodeID');
                            var positionID = oThisChild.attr('PositionID');
                            if (oNode.Position.AfterID == nodeID) {
                                FoundAfter = $('.SplitPaneLeft').children('.node' + gNodeList[nodeID].Positions[positionID].Position.PositionID);
                                break;
                            }
                        }

                        if (FoundAfter != null) {
                            FoundAfter.after(eNode);
                            eNode.children('textarea.nodeContent').elastic();
                        }
                        else {
                            //NodeRePlace.push(eNode);
                        }

                    }
                    else {
                        eNode.children('textarea.nodeContent').elastic();
                    }


                }
                else {
                    //only pull things that haven't been filed yet
                    var eNode = $('.SplitPaneLeft').children('.node' + oNode.Position.PositionID).first();
                    
                    if (eNode.length != 0) {
                        if (rvalue.Position.ParentID != EmptyGUID && gNodeList[rvalue.Position.ParentID] != null) {
                            var oParentPos = gNodeList[rvalue.Position.ParentID].Positions;
                            var ParentPos = "";

                            //these are the parents that should recieve a copy of this node
                            var AddedParents = new Array();
                            //var MovedEnode = null;
                            for (var key in oParentPos) {
                                ParentPos = key;



                                //this is one parent
                                var oParent = gNodeList[rvalue.Position.ParentID].Positions[ParentPos];


                                //this might be an issue when we get duplicate ids
                                var ParentNode = $('.node' + oParent.Position.PositionID);

                                if (ParentNode.children('.SubNodes').children('.node' + oNode.Position.PositionID).length > 0)
                                { break; }



                                ThisENode = eNode.clone(true, true);
                                NodeRePlace.push(ThisENode);

                                //                        if ($.inArray(oParent.Position.PositionID, AddedParents) >= 0) {
                                //                            TheENode.remove();
                                //                            break;
                                //                            //we have already added to this parent and don't want dups 
                                //                        }

                                //AddedParents.push(oParent.Position.PositionID);



                                if (ParentNode.length == 0) {
                                    //This item doesn't have a loded parent
                                }
                                else {

                                    if (oNode.Position.AfterID == EmptyGUID) {
                                        ParentNode.children('.SubNodes').prepend(ThisENode);
                                        ThisENode.children('textarea.nodeContent').elastic();
                                    }
                                    else {
                                        var ExistingChildren = ParentNode.children('.SubNodes').children('.node');
                                        var FoundAfter = null;
                                        //find any item that it goes after
                                        for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                                            var oThisChild = $(ExistingChildren[ThisChild]);
                                            var nodeID = oThisChild.attr('NodeID');
                                            var positionID = oThisChild.attr('PositionID');
                                            if (oNode.Position.AfterID == nodeID) {
                                                FoundAfter = ParentNode.children('.SubNodes').children('.node' + gNodeList[nodeID].Positions[positionID].Position.PositionID);
                                                break;
                                            }
                                        }

                                        if (FoundAfter != null) {
                                            FoundAfter.after(ThisENode);
                                            ThisENode.children('textarea.nodeContent').elastic();
                                        }
                                        else {
                                            //find any tiem that goes after this
                                            var FoundBefore = null;
                                            for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                                                var oThisChild = $(ExistingChildren[ThisChild]);
                                                var nodeID = oThisChild.attr('NodeID');
                                                var positionID = oThisChild.attr('PositionID');
                                                if (oNode.Position.NodeID == gNodeList[nodeID].Positions[positionID].Position.AfterID) {
                                                    FoundBefore = ParentNode.children('.SubNodes').children('.node' + gNodeList[nodeID].Positions[positionID].Position.PositionID);
                                                    break;
                                                }
                                            }
                                            if (FoundBefore != null) {
                                                FoundBefore.before(ThisENode);
                                                ThisENode.children('textarea.nodeContent').elastic();
                                            }
                                            else {
                                                //just stick it at the end
                                                ParentNode.children('.SubNodes').append(ThisENode);
                                                ThisENode.children('textarea.nodeContent').elastic();
                                                //NodeRePlace.push(ThisENode);
                                            }

                                        }
                                    }

                                    //find any tiem that goes after this
                                    //ParentNode.first().children('.SubNodes').first().append(eNode);
                                    SetUpBull(ParentPos);
                                    SetUpLinks(ThisENode)
                                }


                            }
                            eNode.remove();
                        }
                        else {
                            var AddArea = $('.SplitPaneLeft');

                            if (oNode.Position.AfterID == EmptyGUID) {
                                AddArea.prepend(eNode);
                                eNode.children('textarea.nodeContent').elastic();
                            }
                            else {
                                var ExistingChildren = AddArea.children('.node');
                                var FoundAfter = null;
                                //find any item that it goes after
                                for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                                    var oThisChild = $(ExistingChildren[ThisChild]);
                                    var nodeID = oThisChild.attr('NodeID');
                                    var positionID = oThisChild.attr('PositionID');
                                    if (oNode.Position.AfterID == gNodeList[nodeID].Positions[positionID].NodeID) {
                                        FoundAfter = $('.node' + gNodeList[nodeID].Positions[positionID].Position.PositionID);
                                        break;
                                    }
                                }

                                if (FoundAfter != null) {
                                    FoundAfter.after(eNode);
                                    eNode.children('textarea.nodeContent').elastic();
                                }
                                else {
                                    //find any tiem that goes after this
                                    var FoundBefore = null;
                                    for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                                        var oThisChild = $(ExistingChildren[ThisChild]);
                                        var nodeID = oThisChild.attr('NodeID');
                                        var positionID = oThisChild.attr('PositionID');
                                        if (oNode.Position.NodeID == gNodeList[nodeID].Positions[positionID].Position.AfterID) {
                                            FoundBefore = $('.node' + gNodeList[nodeID].Positions[positionID].Position.PositionID);
                                            break;
                                        }
                                    }
                                    if (FoundBefore != null) {
                                        FoundBefore.before(eNode);
                                        eNode.children('textarea.nodeContent').elastic();
                                    }
                                    else {
                                        //just stick it at the end
                                        AddArea.append(eNode);
                                        eNode.children('textarea.nodeContent').elastic();
                                    }

                                }
                            }
                        }


                        if (eNode.parent().parent().attr('NodeID') == null || isExpanded(gNodeList[eNode.parent().parent().attr('NodeID')].Positions[eNode.parent().parent().attr('PositionID')])) {
                            //activate the apps
                            if (oNode.Apps != null) {
                                for (var key in oNode.Apps) {
                                    if (_MW.apps[key].ActivationNodes[oNode.Position.PositionID] == null) {
                                        _MW.apps[key].ActivationNodes[oNode.Position.PositionID] = new Object;
                                    }
                                    _MW.apps[key].ActivationNodes[oNode.Position.PositionID].AccessToken = oNode.Apps[key].PublicToken;
                                    _MW.apps[key].ActivationNodes[oNode.Position.PositionID].AccessTokenOwner = false;
                                    _MW.apps[key].onActivate(oNode);
                                }
                            }
                        }
                    }


                }
            });


            //try moving again
            $.each(NodeRePlace, function (idx, val) {
                //val = $(val);
                var Parent = GetParentNode(val);
                if (Parent == null) {
                    Parent = $('.SplitPaneLeft').first();
                }
                var oNode = gNodeList[val.attr('NodeID')].Positions[val.attr('PositionID')];
                var ExistingChildren = Parent.children('.SubNodes').children('.node');
                var FoundAfter = null;
                //find any item that it goes after
                for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                    var oThisChild = $(ExistingChildren[ThisChild]);
                    var nodeID = oThisChild.attr('NodeID');
                    var positionID = oThisChild.attr('PositionID');
                    if (oNode.Position.AfterID == gNodeList[nodeID].Positions[positionID].NodeID) {
                        FoundAfter = $(ExistingChildren[ThisChild]);
                        break;
                    }
                }

                if (FoundAfter != null) {
                    FoundAfter.after(val);
                    //val.children('textarea.nodeContent').elastic();
                }
                else {
                    //find any tiem that goes after this
                    var FoundBefore = null;
                    for (var ThisChild = 0; ThisChild < ExistingChildren.length; ThisChild++) {
                        var oThisChild = $(ExistingChildren[ThisChild]);
                        var nodeID = oThisChild.attr('NodeID');
                        var positionID = oThisChild.attr('PositionID');
                        if (oNode.Position.NodeID == gNodeList[nodeID].Positions[positionID].Position.AfterID) {
                            FoundBefore = $(ExistingChildren[ThisChild]);
                            break;
                        }
                    }
                    if (FoundBefore != null) {
                        FoundBefore.before(val);
                        //eNode.children('textarea.nodeContent').elastic();
                    }
                    else {
                        //just leave it an move on.
                    }

                }

            });



            //and now we can cheat a the next level down
            if (ExpandLevel == 1) {

                for (var key in foundNodeList) {
                    if (foundNodeList[key].length > 0) {
                        $.ajax({
                            url: '/api/bulknode',
                            cache: false,
                            type: 'post',
                            data: 'ItemKey=' + key + "&ParentID=" + foundNodeList[key],
                            success: function (data) {
                                //now add the topic html to the topic
                                AddSheetUI(ItemKey, foundNodeList[key], data, 0, true);
                            },
                            error: ProcessAddedNodeError
                        });
                    }
                }
            }



        }, 1);


        
    }

}


function FetchUpdateStream() {

    var Nodes = new Array();
    for (var key in gNodeList) {
        Nodes.push(key);
    }
    var AllNodes =Nodes.join(",");
    return $.ajax({
        url: '/api/nodeUpdates',
        cache: false,
        type: 'post',
        data: 'Nodes=' + AllNodes + "&LastUpdate=" + LastStreamTime,
        success: function (data) {
            //now add the topic html to the topic
            ProcessUpdates(data);
            if (data.MaxDate > 0) {
                if (data.MaxDate > LastStreamTime) {
                    LastStreamTime = data.MaxDate;
                }
            }
            setTimeout(function () {

                FetchUpdateStream();

            }, gCurrentPoll);
            //            if (typeof _gaq =="undefined") {

            //                setTimeout("gaSSDSLoad('UA-21197590-1')",1000);
            //            }

        },
        error: ProcessAddedNodeError
    });
}

function ProcessUpdates(data) {
    $.each(data.Users, function (idx, value) {
        if (FindUser(value.UserID, gUserList) >= 0) {

        }
        else {
            gUserList.push(value);
        }

    });

    $.each(data.UserSheets, function (idx, value) {
        if (FindUserSheet(value.UserID, gUserSheetList) >= 0) {

        }
        else {
            gUserSheetList.push(value);
        }

    });

    var foundNodeList = new Array();

    $.each(data.Nodes, function (idx, value) {
        //find the nodes affected

//        for (var key in gNodeList[value].Positions) {
//            var ParentID = gNodeList[value].Positions[key].Position.ParentID;
//            var ItemKey = gNodeList[value].Positions[key].Position.ItemKey;
//            if (foundNodeList[ItemKey] == null) {
//                foundNodeList[ItemKey] = new Array();
//            }
//            if (gNodeList[value].Positions[key].Position.ParentID != EmptyGUID) {
//                foundNodeList[ItemKey].push(gNodeList[value].Positions[key].Position.ParentID);
//            }
//        }

        for (var key in gNodeList[value].Positions) {
            var ParentID = gNodeList[value].Positions[key].Position.ParentID;
            var ItemKey = gNodeList[value].Positions[key].Position.ItemKey;
            if (foundNodeList[ItemKey] == null) {
                foundNodeList[ItemKey] = new Array();
            }
            if (gNodeList[value].Positions[key].NodeID != EmptyGUID) {
                foundNodeList[ItemKey].push(gNodeList[value].Positions[key].NodeID);
            }
        }


        //get the new data from the server




    });

    for (var rkey in foundNodeList) {
        if (foundNodeList[rkey].length > 0) {
            var NodeID = foundNodeList[rkey].join(",");
            var ThisKey = rkey;
            $.ajax({
                url: '/api/bulknode',
                cache: false,
                type: 'post',
                data: 'ItemKey=' + ThisKey + "&NodeID=" + NodeID,
                success: function (data) {
                    //now add the topic html to the topic
                    AddSheetUI(data.RequestingItemKey, NodeID, data, 0, false);
                },
                error: ProcessAddedNodeError
            });
        }
    }

}

function FindTopMost(oNodes, LastNode) {
    for (var ThisNode = 0; ThisNode < oNodes.length; ThisNode++) {
        var nodeID = oNodes[ThisNode].attr('NodeID');
        var positionID = oNodes[ThisNode].attr('PositionID');

        if (gNodeList[nodeID].Positions[positionID].Position.AfterID == EmptyGUID) {
            return ThisNode;
        }
        else if (LastNode != null && gNodeList[nodeID].Positions[positionID].Position.AfterID == LastNode.attr('NodeID')) {
            return ThisNode;
        }
    }

    return 0;
}

function HideBar() {
    $('.ActionBar').hide();
}

function CreateNode(AddArea, NodeID, PositionID, NodeText) {
    var oNode = gNodeList[NodeID].Positions[PositionID];

    if ($('.node' + PositionID).length > 0) {
        //oops.  Doubled up.
        //alert('doubledup');
    }

    var Node = $("<div class='node node" + PositionID + "'><div class=bullet><div class='bull'><a href='/?ItemKey=" + oNode.Position.ItemKey + "&ParentID=" + NodeID + "'>&bull;</a></div></div><textarea rows=1 class='nodeContent'>" + NodeText + "</textarea><br style='clear:both'/><div class='ActionBar'><br style='clear:both;height:0px;'/></div><div class='SubNodes' " + (oNode.Position.bExpanded != null && oNode.Position.bExpanded ? "" : "style='display:none'") + "></div></div>");
    AddArea.first().append(Node);
   

    if (oNode.Position.NodeTypeID == 3) {
        //add the image
        var ThisUser = gUserList[FindUser(oNode.AddedByUserID, gUserList)];
        if (ThisUser != null) {
            Node.children('.bullet').children('.bull').find('a').text('').append("<img title='" + ThisUser.DisplayName + "' class='NodeType3Image' src='https://graph.facebook.com/" + ThisUser.FBID + "/picture'/>");
            Node.children('.bullet').children('.bull').addClass("bullbold");
        }

    }
   
    if (oNode.bComplete != null && oNode.bComplete == true) {
        Node.children('.nodeContent').css('text-decoration', 'line-through');
    }
    if (oNode.AddedByUserID == CurrentUserID) {
        // Node.children('textarea.nodeContent').show();
    }
    else {

        Node.children('textarea.nodeContent').attr('readonly', true);
    }

    var ThisBull = Node.children('.bullet').first();
    Node.hover(BullIn, BullOut);

    //add notification and clear
    var Notifications = gNodeList[NodeID].Notifications;

    var ActionBar = Node.children('.ActionBar').first();

    if (Notifications != null) {
        Node.children('.bullet').append('<div class="notification">' + gNodeList[NodeID].Notifications.length + '</div>');
    }



    if (oNode.EditSecurityType == "locked") {
        Node.children('textarea.nodeContent').addClass('LinkNode');
    }

    if (oNode.AddedByUserID != CurrentUserID) {

        if (getEditSecurity(oNode) == "locked") {
            ThisBull.children('.bull').addClass('LinkNode');
           
        }
        else {
            ThisBull.children('.bull').addClass('ContributeNode');
        }
    }
    else {
        if (getViewSecurity(oNode) == "view") {
            ThisBull.children('.bull').addClass('ViewNode');
        }
    }

    if (oNode.NodeTypeID == 2) {

        ThisBull.children('.bull').addClass('AppNode');
    }

//    if (CurrentUserID == oNode.AddedByUserID) {
//        var MoveBadge = $('<div />', { "class": "nodeMove ActionIcon",
//            onclick: function () {
//                Meld(Node);
//            }
//        });
//        MoveBadge.append('move');

//        ActionBar.prepend(MoveBadge);

//    }

    



    //Node.children('.nodeContent').elastic();
    //MoveNode(Node, ParentID, ParentPositionID, AfterID, AfterPositionID);





    Node.attr("NodeID", NodeID);
    Node.attr("PositionID", PositionID);
    var Editor = Node.children('.nodeContent').first();
    Editor.attr("NodeID", NodeID);
    Editor.attr("PositionID", PositionID);

    Editor.focus(StartEditorTracking);


    //if the Parent ID is not empty then we need to see if the children stuff has been set up


    //we will have to set up the bull somewhere else
    //    if (ParentID != CurrentParentID) {
    //        SetUpBull(ParentPositionID);

    //    }

    //MoveNode(Node, ParentID, ParentPositionID, AfterID, AfterPositionID, Manipulate);

    //SetUpLinks(Node.first());

    return Node;
}

function BuildActionBar(Node) {
    var ActionBar = Node.children('.ActionBar').first();
    var NodeID = Node.attr('NodeID')
    var PositionID = Node.attr('PositionID');
    var oNode = gNodeList[NodeID].Positions[PositionID];

    var Notifications = gNodeList[NodeID].Notifications;

    if (ActionBar.text().length>0)
    { }
    else {
        ActionBar.append("<div class='ActionBarHider' onClick='HideBar()'>Hide</div>");
        ActionBar.Built = true;
        if (Notifications != null) {

            var NotiClearBadge = $('<div />', { "class": "nodeNotiClear ActionIcon" }).click(
                function () {
                $.ajax({
                    url: '/api/notificationClear',
                    data: { itemKey: oNode.Position.ItemKey,
                        nodeID: oNode.NodeID,
                        positionID: oNode.Position.PositionID
                    },
                    cache: false,
                    type: 'post',
                    success: function (data) {
                        $.each(data.NewCounts, function (idx, value) {
                            var positions = gNodeList[value.NodeID]
                            if (positions != null) {
                                for (var key in gNodeList[value.NodeID].Positions) {
                                    if (value.Count > 0) {
                                        $('.node' + key).children('.bullet').children('.notification').text(value.Count);
                                    }
                                    else {
                                        $('.node' + key).children('.bullet').children('.notification').remove();
                                        $('.node' + key).children('.ActionBar').children('.nodeNotiClear').remove();
                                    }
                                }
                            }

                        });
                    },
                    error: ProcessAddedNodeError

                    });

            });
            //end badge
            NotiClearBadge.append('Clear Alerts');

            ActionBar.prepend(NotiClearBadge);
            }



            if (isAuthenticated && CurrentUserID == oNode.AddedByUserID) {
                //add security controls
                var CurrentViewBadge;


                if (getViewSecurity(oNode) == 'locked') {
                    CurrentViewBadge = PrivateBadge.clone();
                }
                else if (getViewSecurity(oNode) == 'view') {
                    CurrentViewBadge = PublicBadge.clone();
                    //                if (oNode.AddedByUserID == CurrentUserID) {
                    //                    //ThisBull.children('.bull').addClass('ViewNode');
                    //                }
                }

                var SecurityWidget = $("<div class='NodeSecurity ActionIcon'></div>");
                SecurityWidget.click(function () { SwitchSecurity(NodeID, PositionID); });
                SecurityWidget.append(CurrentViewBadge);
                ActionBar.prepend(SecurityWidget);

                var CurrentBadge;

                if (getEditSecurity(oNode) == 'contribute') {

                    CurrentBadge = ContributeBadge.clone();
                    //ThisBull.children('.bull').addClass('ContributeNode');
                }
                else if (getEditSecurity(oNode) == 'locked') {
                    CurrentBadge = LockedBadge.clone();

                }

                var EditSecurityWidget = $("<div class='NodeEditSecurity ActionIcon'></div>");
                EditSecurityWidget.click(function () { SwitchEditSecurity(NodeID, PositionID); });
                EditSecurityWidget.append(CurrentBadge);
                ActionBar.prepend(EditSecurityWidget);





                var DoneWidget = $("<div class='NodeDone ActionIcon'>Mark Complete</div>");
                DoneWidget.click(function () { SwitchDone(NodeID, PositionID); });

                if (oNode.bComplete != null && oNode.bComplete == true) {
                    DoneWidget.addClass('completenode');
                    DoneWidget.text('Remove Mark');
                }
                ActionBar.prepend(DoneWidget);

                //add fbpost 

                var FBBadge = $('<div />', { "class": "nodefbPost ActionIcon", "text": "Make this a Facebook post."
                }).click(function () {
                    var appName = "fb_post";
                    _MW.apps[appName.toUpperCase()].onActivate(oNode);
                    //obtain a key for the call
                    //call out to app with info.

                });

                ActionBar.prepend(FBBadge);

                var TWBadge = $('<div />', { "class": "nodetwPost ActionIcon", "text": "Tweet this."
                }).click(function () {

                    TestNodeChange(Node)
                    var appName = "tw_post";
                    _MW.apps[appName.toUpperCase()].onActivate(oNode);
                    //obtain a key for the call
                    //call out to app with info.

                });

                ActionBar.prepend(TWBadge);
            }
            else if (isAuthenticated) {
                //add meld controls
                var MeldBadge = $('<div />', { "class": "nodeMeld ActionIcon"
                }).click(function () {
                    var appName = "mindmeld";
                    _MW.apps[appName.toUpperCase()].onActivate(oNode);
                    //obtain a key for the call
                    //call out to app with info.

                });
                MeldBadge.append('meld / follow');

                ActionBar.prepend(MeldBadge);
            }


            var LikeBadge = $('<div/>', { "class": "FacebookLike" });
            LikeBadge.append('<fb:like href="http://www.mindwallet.com/Home/Index/' + CurrentSheetID + '/' + oNode.NodeID + '"  show_faces="true" width="85"></fb:like>');
            ActionBar.append(LikeBadge);

        }
    
}



function AddBaseItem() {

    AddNewItem(null, null);

}

function KeepAlive() {
    var FirstGuid = GuidPool[0];
    var FirstGuidb = GuidPool[0];
    GuidPool = new Array();
    GuidPool.push(FirstGuid);
    GuidPool.push(FirstGuidb);
    GetGuid();
    setTimeout(KeepAlive, 600000);
    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'KeepAlive', CurrentSheetID, 1]);
}

setTimeout(KeepAlive, 600000);

function ProcessAddedNodeError(XMLHttpRequest, textStatus, errorThrown) {
    var Warning = $("<div/>", { "class": "Warning", "text": 'Something fishy is going on.  Something may have gone wrong. ' + textStatus + errorThrown });
    $('#Header').append(Warning);
    Warning.fadeOut(10000, function () { Warning.remove(); });
}

function MarkDirty(Node) {
    if(Node.Dirty ==null || Node.Dirty==false)
    {
        Node.NewDataTime = new Date();
    }
    Node.Dirty = true;
    
}



var LockedBadge = $("<div>let others con- tribute</div>");
var ContributeBadge = $("<div>lock this item</div>");
var PublicBadge = $("<div>make item private</div>");
var PrivateBadge = $("<div>make item public</div>");



function SetUpBull(NodePositionID) {
    var Parent = $(".node" + NodePositionID);
    $.each(Parent, function (idx, value) {
        var ThisParent = $(value);
        var ParentBull = ThisParent.children('.bullet').first();
        if (ParentBull.children(".expand").length == 0) {
            if (Parent.attr('NodeID') != null) {
                var oParent = gNodeList[ThisParent.attr('NodeID')].Positions[ThisParent.attr('PositionID')];

                var Expander = $("<div class='expand' style='display:none;'>" + ((oParent.Position.bExpanded != null && oParent.Position.bExpanded) ? "-" : "+") + "</div>");

                Expander.appendTo(ParentBull);
                if ((oParent.Position.bExpanded != null && oParent.Position.bExpanded)) {
                    Expander.click(function () { HideChildren($(value)); });
                }
                else {
                    Expander.click(function () { ShowChildren($(value)); });
                }

                ParentBull.children('.bull').addClass('bullbold');
            }
        }
    });


}

function SwitchSecurity(NodeID, PositionID) {
    var oNode = gNodeList[NodeID].Positions[PositionID];
    var CurrentViewSecu = "locked";
    if (oNode.Dirty) {
        CurrentViewSecu = oNode.NewViewSecurityType;
    }
    else {
        CurrentViewSecu = oNode.ViewSecurityType;
    }

    var NewViewSecu = (CurrentViewSecu == "locked" ? "view" : "locked");
    oNode.NewViewSecurityType = NewViewSecu;
    MarkDirty(oNode);
    var BullIcon = $('.node' + PositionID).children('.ActionBar').children('.NodeSecurity').children('div').first();
    var CurrentBadge;
    if (NewViewSecu == 'locked') {

        CurrentBadge = PrivateBadge.clone();
        $('.node' + PositionID).find('.bullet > .bull').first().removeClass('ViewNode');
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeMadePrivate', CurrentSheetID, 1]);
    }
    else if (NewViewSecu == 'view') {
        CurrentBadge = PublicBadge.clone();
        $('.node' + PositionID).find('.bullet > .bull').first().addClass('ViewNode');
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeMadePublic', CurrentSheetID, 1]);
    }
    //CurrentBadge.click(function () { SwitchSecurity(NodeID, PositionID); });

    if (NewViewSecu == "locked") {
        BullIcon.replaceWith(CurrentBadge);
    }
    else {
        BullIcon.replaceWith(CurrentBadge);
    }

}

function SwitchEditSecurity(NodeID, PositionID) {
    var oNode = gNodeList[NodeID].Positions[PositionID];
    var CurrentViewSecu = "contribute";
    if (oNode.Dirty) {
        CurrentViewSecu = oNode.NewEditSecurityType;
    }
    else {
        CurrentViewSecu = oNode.EditSecurityType;
    }

    var NewViewSecu = (CurrentViewSecu == "contribute" ? "locked" : "contribute");
    oNode.NewEditSecurityType = NewViewSecu;
    MarkDirty(oNode);
    var BullIcon = $('.node' + PositionID).children('.ActionBar').children('.NodeEditSecurity').children('div').first();
    var CurrentBadge;
    if (NewViewSecu == 'contribute') {

        CurrentBadge = ContributeBadge.clone();
        
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeLocked', CurrentSheetID, 1]);
    }
    else if (NewViewSecu == 'locked') {
        CurrentBadge = LockedBadge.clone();
        
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeUnLocked', CurrentSheetID, 1]);
    }
    //CurrentBadge.click(function () { SwitchSecurity(NodeID, PositionID); });

    
        BullIcon.replaceWith(CurrentBadge);
  

}

function SwitchDone(NodeID, PositionID) {
    var oNode = gNodeList[NodeID].Positions[PositionID];
    var CurrentDone = false;
    if (oNode.Dirty) {
        CurrentDone = oNode.NewbComplete;

    }
    else {
        CurrentDone = oNode.bComplete;
    }

    var NewDone = (CurrentDone ? false : true);
    oNode.NewbComplete = NewDone;
    MarkDirty(oNode);
    var IconText = $('.node' + PositionID).find('.ActionBar > .NodeDone').first();

    if (NewDone) {

        IconText.addClass('completenode');
        $('.node' + oNode.Position.PositionID).children('.nodeContent').addClass('completenode');
        IconText.text('Remove mark');
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeComplete', CurrentSheetID, 1]);
    }
    else {
        IconText.removeClass('completenode');
        $('.node' + oNode.Position.PositionID).children('.nodeContent').removeClass('completenode');
        IconText.text('Mark Complete')
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeCompleteRemoved', CurrentSheetID, 1]);
    }


}

function GetGuid() {
    var ret = GuidPool.pop();
    if (GuidPool.length < 5) {
        //get some more guids
        $.ajax({
            url: '/api/guid',
            cache: false,
            type: 'get',
            success: function (data) {
                $.each(data, function (idx, value) {
                    GuidPool.push(value);
                });
            },
            error: function () {
                setTimeout(
                                    function () {
                                        GetGuid();
                                    }, 60000);
            }
        });
    }
    return ret;
}

function BullIn() {
    //    $(this).children('.nodeMove').show();
    //    $(this).children('.NodeSecurity').show();
    //    $(this).children('.expand').show();


    $(this).children('.bullet').children('.expand').stop(true, true).animate({ opacity: '100' }).show();

}

function BullOut() {
    //    $(this).children('.nodeMove').hide();
    //    $(this).children('.NodeSecurity').hide();
    //    $(this).children('.expand').hide();
    
    $(this).children('.bullet').children('.expand').fadeOut(10000);

}



function ShowChildren(ParentNode) {


    var Parent = $(ParentNode)
    var CurrentState = Parent.children('.bullet').children('.expand').text();

    Parent.children('.SubNodes').show();
    Parent.children('.bullet').children('.expand').text('-');
    Parent.children('.bullet').children('.expand').unbind('click');
    Parent.children('.bullet').children('.expand').click(function () { HideChildren(ParentNode); });

    var ParentID = Parent.attr('NodeID');
    var ParentPositionID = Parent.attr('PositionID');

    var Node = gNodeList[ParentID].Positions[ParentPositionID];
    var CurrentExpanded = isExpanded(Node);

    if (CurrentExpanded == false) {

        if (CurrentUserID == gNodeList[ParentID].Positions[ParentPositionID].Position.AddedByUserID) {
            gNodeList[ParentID].Positions[ParentPositionID].NewExpanded = true;
            MarkDirty(gNodeList[ParentID].Positions[ParentPositionID]);
        }
        else {
            //go ahead and set the core expanded to true
            gNodeList[ParentID].Positions[ParentPositionID].Position.bExpanded = true;
        }
    }

    //get the next level down
    var SubNodes = Parent.children('.SubNodes').children('.node');



    var foundNodeList = "";
    $.each(SubNodes, function (idx, value) {
        //if (gNodeList[$(value).attr('NodeID')] == null || gNodeList[$(value).attr('NodeID')].Positions[$(value).attr('PositionID')] == null) {
        var oThisChild = $(value);
        oThisChild.children('textarea.nodeContent').elastic();
        var nodeID = oThisChild.attr('NodeID');
        var positionID = oThisChild.attr('PositionID');
        //if (!isExpanded(gNodeList[nodeID].Positions[positionID])) {
        if (foundNodeList.length > 0) { foundNodeList += ","; }
        foundNodeList += $(value).attr('NodeID');
        //}

        var cNode = gNodeList[nodeID].Positions[positionID];

        //activate the apps
        if (cNode.Apps != null) {

            for (var key in cNode.Apps) {
                if (_MW.apps[key].ActivationNodes[cNode.Position.PositionID] == null) {
                    _MW.apps[key].ActivationNodes[cNode.Position.PositionID] = new Object;
                }
                _MW.apps[key].ActivationNodes[cNode.Position.PositionID].AccessToken = cNode.Apps[key].PublicToken;
                _MW.apps[key].ActivationNodes[cNode.Position.PositionID].AccessTokenOwner = false;
                _MW.apps[key].onActivate(cNode);
            }

        }

        //}
    });

    if (foundNodeList > "") {

        $.ajax({
            url: '/api/node',
            cache: false,
            type: 'get',
            data: 'ItemKey=' + CurrentSheetID + "&ParentID=" + foundNodeList,
            success: function (data) {
                //now add the topic html to the topic
                AddSheetUI(CurrentSheetID, ParentID, data, 0,true);
            },
            error: ProcessAddedNodeError
        });
    }

    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeExpand', CurrentSheetID, 1]);

}

function HideChildren(ParentNode) {

    var Parent = $(ParentNode);
    var ParentID = Parent.attr('NodeID');
    var ParentPositionID = Parent.attr('PositionID');

    var CurrentState = Parent.children('.bullet').children('.expand').text();
    Parent.children('.SubNodes').hide();
    Parent.children('.bullet').children('.expand').text('+');
    Parent.children('.bullet').children('.expand').unbind('click');
    Parent.children('.bullet').children('.expand').click(function () { ShowChildren(ParentNode); });
    var Node = gNodeList[ParentID].Positions[ParentPositionID];
    var CurrentExpanded = false;
    if (CurrentExpanded == null && Node.Dirty != null && Node.Dirty) {
        CurrentExpanded = Node.Position.bExpanded;
    }
    else if (Node.Position.bExpanded != null) {
        CurrentExpanded = Node.Position.bExpanded;
    }

    if (CurrentExpanded == true) {
        if (CurrentUserID == gNodeList[ParentID].Positions[ParentPositionID].Position.AddedByUserID) {
            gNodeList[ParentID].Positions[ParentPositionID].NewExpanded = false;
            MarkDirty(gNodeList[ParentID].Positions[ParentPositionID]);
        }
        else {
            gNodeList[ParentID].Positions[ParentPositionID].Position.bExpanded = false;
        }
    }

    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeCollapse', CurrentSheetID, 1]);

}



function Integrity() {
    var AllNodes = $('.node');
    $.each(AllNodes, function (idx, Node) {
        //test After ID
        var eNode = $(Node);
        var oNode = gNodeList[eNode.attr('NodeID')].Positions[eNode.attr('PositionID')];

        var ePrev = eNode.prev();

        if (ePrev.length > 0) {
            var oPrev = gNodeList[ePrev.attr('NodeID')].Positions[ePrev.attr('PositionID')];
            if (oNode.Position.AfterID != oPrev.NodeID) {
                eNode.css('background-color', 'black');
                oNode.NewAfterID = oPrev.NodeID
                MarkDirty(oNode);
            }

        }
        else {
            if (oNode.Position.AfterID != EmptyGUID) {
                eNode.css('background-color', 'black');
                oNode.NewAfterID = EmptyGUID;
                MarkDirty(oNode);
            }
        }
    });


}

var SelectedPositionID = null;



function StartEditorTracking(e) {

    //    if(SelectedPositionID!=CurrentParentID)
    //    {
    //        //$('.node' + SelectedPositionID).first().css('background-color','white');
    //    }

    var PositionID = $(this).attr('PositionID');

    if (SelectedPositionID != PositionID) {
        $('body').prepend($('#movearrows').first());
        $('.ActionBar').hide();
    }
    SelectedPositionID = PositionID;



    var SourceNode = $(this).parent();
    BuildActionBar(SourceNode)
    //SourceNode.css('background-color', '#E0E0E0');
    SourceNode.children('.ActionBar').show();
    FB.XFBML.parse(SourceNode.children('.ActionBar')[0]);
    if (QuickMove != null && QuickMove) {
         SourceNode.children('.ActionBar').prepend($('#movearrows'));
        //SourceNode.first().prepend($('#movearrows').first());
    }
    else {

    }
    var StartValue = SourceNode.contents('.nodeContent').first().val();
    setTimeout(function () {
        TestNodeChange(SourceNode);
    }, 8000);

    $(this).unbind('blur');
    $(this).blur(function () {
        StopEditorTracking(SourceNode, StartValue);
    });

}

function TestNodeChange(SourceNode) {
    var CurrentNode = $(SourceNode);
    var NodeID = CurrentNode.attr('NodeID');
    var PositionID = CurrentNode.attr('PositionID');
    var CurrentValue = CurrentNode.contents('.nodeContent').first().val();
    var StartValue = gNodeList[NodeID].Positions[PositionID].NodeText;
    if (CurrentValue != StartValue && (gNodeList[NodeID].Positions[PositionID].CanUpdate == null || gNodeList[NodeID].Positions[PositionID].CanUpdate)) {
        //Process the Potential save
        //CurrentNode.after('new value');
        //capture the new data

        gNodeList[NodeID].Positions[PositionID].NewValue = CurrentValue;
        MarkDirty(gNodeList[NodeID].Positions[PositionID]);
        if (SelectedPositionID == PositionID) {
            setTimeout(function () {
                TestNodeChange(SourceNode);
            }, 5000);
        }
        //set a timer to save it in 20 seconds if no additional change
        //        setTimeout(function () {
        //            AttemptSave(NodeID);
        //        }, 20000);
    }
    else {
        //if the node still has focus then re timer
        if (PositionID == SelectedPositionID) {
            setTimeout(function () {
                TestNodeChange(SourceNode);
            }, 5000);
        }
    }

}


function SetSaveCycle() {
    setTimeout(function () { SaveCycle(); }, 10000);
}



function SaveCycle() {
    var CycleDate = new Date();
    for (var key in gNodeList) {
        for (var pkey in gNodeList[key].Positions) {
            var item = gNodeList[key].Positions[pkey];
            if (item.Dirty != null && item.Dirty && (item.CanUpdate == null || item.CanUpdate) && item.NewDataTime < CycleDate - new Date(2000)) {

                SaveNode(item);
                var x = 0;
            }
        }
    }

    SetSaveCycle();
}



//function Clone() { }
//function clone(obj) {
//    Clone.prototype = obj;
//    return new Clone();
//}


//start the save cycle.
SetSaveCycle();


function SyncSavedNode(ReturnData) {

    if (ReturnData.errorNumber != null && ReturnData.errorNumber > 0) {

        if (ReturnData.SourcePositionID != null && ReturnData.SourceNodeID != null) {
            //var PositionID = ReturnData.Node[0].Position.PositionID;
            gNodeList[ReturnData.SourceNodeID].Positions[ReturnData.SourcePositionID].CanUpdate = true;
            $('.node' + ReturnData.SourcePositionID).children('.nodeContent').css('background-color', 'Pink');

        }
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeSaveError', CurrentSheetID, 1]);

    }
    else {
        for (var key in gNodeList[ReturnData.Node[0].NodeID].Positions) {
            if (ReturnData.Node[0].Position.PositionID == key) {
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].Position.ItemKey = ReturnData.Node[0].Position.ItemKey;
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].Position.ParentID = ReturnData.Node[0].Position.ParentID;
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].Position.AfterID = ReturnData.Node[0].Position.AfterID;
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].Position.bComplete = ReturnData.Node[0].Position.bComplete;
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].Position.bExpanded = ReturnData.Node[0].Position.bExpanded;
                gNodeList[ReturnData.Node[0].NodeID].Positions[key].CanUpdate = true;

            }


            gNodeList[ReturnData.Node[0].NodeID].Positions[key].NodeText = ReturnData.Node[0].NodeText;
            gNodeList[ReturnData.Node[0].NodeID].Positions[key].NodeNote = ReturnData.Node[0].NodeNote;
            gNodeList[ReturnData.Node[0].NodeID].Positions[key].bComplete = ReturnData.Node[0].bComplete;
            gNodeList[ReturnData.Node[0].NodeID].Positions[key].DateUpdated = ReturnData.Node[0].DateUpdated;
            gNodeList[ReturnData.Node[0].NodeID].Positions[key].ViewSecurityType = ReturnData.Node[0].ViewSecurityType;
            gNodeList[ReturnData.Node[0].NodeID].Positions[key].EditSecurityType = ReturnData.Node[0].EditSecurityType;



            var PositionID = ReturnData.Node[0].Position.PositionID;
            $('.node' + PositionID).children('.nodeContent').css('background-color', 'Green');

            //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
            $('.node' + PositionID).children('.nodeContent').stop().animate(
        { backgroundColor: 'White' }, 6000);

            //$('.node' + ReturnData.Node[0].Position.PositionID).after('Saved');
        }

        SetUpLinks($('.node' + PositionID));
        if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'NodeSave', CurrentSheetID, 1]);
    }

}

function StopEditorTracking(SourceNode, StartValue) {


    // var SourceNode = $('.node' + PositionID).first();

    //$('.node' + SelectedPositionID).first().css('background-color', 'white');

    var PositionID = $(SourceNode).attr('PositionID');
    TestNodeChange(SourceNode);


    //lets look for links

    //    if (SelectedPositionID == PositionID) {
    //        SelectedPositionID = null;
    //    }

}

function SetUpLinks(SourceNode) {

    $.each(SourceNode, function (sidx, sval) {
        var ThisNode = $(sval);
        var str = ThisNode.children('.nodeContent').val();
        var patt1 = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
        var Matches = str.match(patt1);
        if (Matches != null && Matches.length > 0) {
            var LinkArea = ThisNode.find('.LinkArea');
            if (LinkArea.length > 0) {
                LinkArea.remove();
            }

            var NewLinkArea = $("<div/>", { "class": "LinkArea" });
            ThisNode.append(NewLinkArea);
            $.each(Matches, function (idx, value) {
                var strValue = value.replace('/', '-').replace('/', '-');
                if (ThisNode.find('#nodelink' + idx).length == 0) {
                    var NewLink = $("<a id='nodelink" + idx + "' href='" + value + "' target=_blank >" + value + "</a>");
                    NewLinkArea.append(NewLink);
                    NewLinkArea.append("<br/>");
                    NewLink.embedly({
                        maxWidth: 450,
                        wmode: 'transparent',
                        method: 'after'
                    }
);
                }
            });
        }
    });
}

function GetParentNode(Node) {
    if ($(Node).closest('.SubNodes').closest('.node').length == 0) {
        return null;
    }
    else {
        return $(Node).closest('.SubNodes').closest('.node').first();
    }
}

function GetLastChild(Node) {
    if ($(Node).children('.SubNodes').children('.node').last().length == 0) {
        return null;
    }
    else {
        return $(Node).children('.SubNodes').children('.node').last();
    }
}

function GetAfterNode(Node) {
    if ($(Node).prev().length == 0) {
        return null;
    }
    else {
        return $(Node).prev().first();
    }

}

function GetNextNode(Node) {
    if ($(Node).next().length == 0) {
        return null;
    }
    else {
        return $(Node).next().first();
    }

}



//       function GetParentNodeID(Node) {
//           if ($(Node).closest('.SubNodes').closest('.node').length == 0) {
//               return CurrentParentID;
//           }
//           else {
//               return $(Node).closest('.SubNodes').closest('.node').first().attr('NodeID');
//           }
//       }

//       function GetAfterNodeID(Node) {
//           if ($('.node' + PositionID).first().prev().length == 0) {
//               return EmptyGUID;
//           }
//           else {
//               return $(Node).prev().first().attr('NodeID');
//           }

//       }

//       function GetParentPositionID(Node) {
//           if ($(Node).closest('.SubNodes').closest('.node').length == 0) {
//               return EmptyGUID;
//           }
//           else {
//               return $(Node).closest('.SubNodes').closest('.node').first().attr('PositionID');
//           }
//       }

//       function GetAfterPositionID(Node) {
//           if ($(Node).prev().length == 0) {
//               return EmptyGUID;
//           }
//           else {
//               return $(Node).prev().first().attr('PositionID');
//           }

//       }


//       function MoveNode(divNode, NewParentID, NewParentPositionID, NewAfterID, NewAfterPositionID, Manipulate) {

//           
//           if (NewParentID == NewAfterID && NewParentID!=EmptyGUID) {
//               alert('boom goes the data model');
//           }
//           var NodeID = divNode.attr('NodeID');
//           var PositionID = divNode.attr('PositionID');

//           var Node = gNodeList[NodeID].Positions[PositionID];
//           
//           
//           //See if the Node has a follower

//           var Follower = divNode.next();
//           if (Follower.length == 0 || Follower.attr('NodeID')==null) {
//               //no follower
//           }
//           else {
//               //update the follower's after ID with my after ID
//               var FollowerNodeID = Follower.attr('NodeID');
//               var FollowerPositionID = Follower.attr('PositionID');

//               FollowerNode = gNodeList[FollowerNodeID].Positions[FollowerPositionID];
//               if (Node.Dirty) {
//                   if (Manipulate && FollowerNode.NewAfterID != Node.NewAfterID) {
//                       FollowerNode.NewAfterID = Node.NewAfterID;
//                       MarkDirty(FollowerNode);
//                   }
//               }
//               else {
//                   if (Manipulate && FollowerNode.Position.AfterID != Node.Position.AfterID) {
//                       FollowerNode.NewAfterID = Node.Position.AfterID;
//                       MarkDirty(FollowerNode);
//                   }
//               }
//              
//           }

//           //find the Node to Move after

//           //see if the new after node has a follower
//           var AfterFollower = null;
//           if (NewAfterID == EmptyGUID) {
//               //we are moving to the top of the parent
//               if (NewParentID == CurrentParentID ) {
//                   AfterFollower = $('.SplitPaneLeft').first().children('.node').first();
//               }
//               else
//               {
//                   AfterFollower = $('.node' + NewParentPositionID).children('.SubNodes').children('.node').first();
//               }
//           }
//           else {
//               AfterFollower = $('.node' + NewAfterPositionID).next();
//           }

//           if (AfterFollower.length == 0 || AfterFollower.attr("NodeID") == null || AfterFollower.attr("NodeID")==NodeID) {
//               //no follower
//           }
//           else {
//               var AfterFollowerNodeID = AfterFollower.attr('NodeID');
//               var AfterFollowerPositionID = AfterFollower.attr('PositionID');

//               var AfterFollowerNode = gNodeList[AfterFollowerNodeID].Positions[AfterFollowerPositionID];
//               if (Manipulate && AfterFollowerNode.Dirty && AfterFollowerNode.NewAfterID != Node.NodeID) {
//                   AfterFollowerNode.NewAfterID = Node.NodeID;
//                   MarkDirty(AfterFollowerNode);
//               }
//               else if (Manipulate && AfterFollowerNode.Position.AfterID != Node.NodeID)
//               {
//                   AfterFollowerNode.NewAfterID = Node.NodeID;
//                   MarkDirty(AfterFollowerNode);
//               }
//           }

//           //find where to move
//           if (NewAfterID == EmptyGUID) {
//               if (NewParentID == CurrentParentID) {
//                   $('.SplitPaneLeft').first().prepend(divNode);
//               }
//               else {
//                   $('.node' + NewParentPositionID).children('.SubNodes').prepend(divNode);
//               }
//           }
//           else {
//               $('.node' + NewAfterPositionID).after(divNode);
//           }

//           if (Manipulate && Node.Dirty && (Node.NewParentID != NewParentID || Node.NewAfterID != NewAfterID))
//           {
//                Node.NewParentID = NewParentID;
//                Node.NewAfterID = NewAfterID;
//               MarkDirty(Node);
//           }
//           else if (Manipulate && Node.Position.ParentID != NewParentID || Node.Position.AfterID != NewAfterID)
//           {
//                Node.NewParentID = NewParentID;
//                Node.NewAfterID = NewAfterID;
//               MarkDirty(Node);
//           }

//           divNode.children('.nodeContent').first().triggerHandler('blur');
//       }

function MoveNode(divNode, NewParentNode, NewAfterNode, Manipulate) {

    var NewParentID = CurrentParentID;

    if (NewParentNode != null) {
        NewParentID = NewParentNode.attr('NodeID');
    }


    var NewAfterID = EmptyGUID;
    if (NewAfterNode != null) {
        NewAfterID = NewAfterNode.attr('NodeID');
    }

    if (NewParentID == NewAfterID && NewParentID != EmptyGUID) {
        alert('boom goes the data model');
    }

    var NodeID = divNode.attr('NodeID');
    var PositionID = divNode.attr('PositionID');

    var Node = gNodeList[NodeID].Positions[PositionID];


    //See if the Node has a follower

    var Follower = divNode.next();
    if (Follower.length == 0 || Follower.attr('NodeID') == null) {
        //no follower
    }
    else {
        //update the follower's after ID with my after ID
        var FollowerNodeID = Follower.attr('NodeID');
        var FollowerPositionID = Follower.attr('PositionID');

        FollowerNode = gNodeList[FollowerNodeID].Positions[FollowerPositionID];
//        if (Node.Dirty) {
//            if (Manipulate && FollowerNode.NewAfterID != Node.NewAfterID) {
//                FollowerNode.NewAfterID = Node.NewAfterID;
//                MarkDirty(FollowerNode);
//            }
//        }
//        else {
//            if (Manipulate && FollowerNode.Position.AfterID != Node.Position.AfterID) {
//                FollowerNode.NewAfterID = Node.Position.AfterID;
//                MarkDirty(FollowerNode);
//            }
        //        }

        if (Manipulate) {
            var OldAfter = GetAfterNode(divNode);
            if (OldAfter == null) {
                FollowerNode.NewAfterID = EmptyGUID;
                MarkDirty(FollowerNode);
            }
            else {
                FollowerNode.NewAfterID = OldAfter.attr('NodeID');
                MarkDirty(FollowerNode);
            }
        }

    }

    //find the Node to Move after

    //see if the new after node has a follower
    var AfterFollower = null;
    if (NewAfterID == EmptyGUID) {
        //we are moving to the top of the parent
        if (NewParentID == EmptyGUID) {
            AfterFollower = $('.SplitPaneLeft').first().children('.node').first();
        }
        else {
            AfterFollower = NewParentNode.children('.SubNodes').children('.node').first();
        }
    }
    else {
        AfterFollower = NewAfterNode.next();
    }

    if (AfterFollower.length == 0 || AfterFollower.attr("NodeID") == null || AfterFollower.attr("NodeID") == NodeID) {
        //no follower
    }
    else {
        var AfterFollowerNodeID = AfterFollower.attr('NodeID');
        var AfterFollowerPositionID = AfterFollower.attr('PositionID');

        var AfterFollowerNode = gNodeList[AfterFollowerNodeID].Positions[AfterFollowerPositionID];
        //if (Manipulate && AfterFollowerNode.Dirty && AfterFollowerNode.NewAfterID != Node.NodeID) {
        if (Manipulate) {
            AfterFollowerNode.NewAfterID = Node.NodeID;
            MarkDirty(AfterFollowerNode);
        }
        //}
//        //else if (Manipulate && AfterFollowerNode.Position.AfterID != Node.NodeID) {
//            AfterFollowerNode.NewAfterID = Node.NodeID;
//            MarkDirty(AfterFollowerNode);
//        }
    }

    //find where to move
    if (NewAfterID == EmptyGUID) {
        if (NewParentID == EmptyGUID) {
            $('.SplitPaneLeft').first().prepend(divNode);
        }
        else {
            NewParentNode.children('.SubNodes').prepend(divNode);
        }
    }
    else {
        NewAfterNode.after(divNode);
    }

    //if (Manipulate && Node.Dirty && (Node.NewParentID != NewParentID || Node.NewAfterID != NewAfterID)) {
//        Node.NewParentID = NewParentID;
//        Node.NewAfterID = NewAfterID;
//        MarkDirty(Node);
    //}
        //else if (Manipulate && Node.Position.ParentID != NewParentID || Node.Position.AfterID != NewAfterID) {
        if (Manipulate) {
            Node.NewParentID = NewParentID;
            Node.NewAfterID = NewAfterID;
            MarkDirty(Node);
        }
    //}

    divNode.children('.nodeContent').first().triggerHandler('blur');
}

function EditorKeyDown(event) {

    //var src = event.target ? e.srcElement : e.target;
    if ($(event.target).hasClass("nodeContent")) {
        if (event.keyCode == '9') {

            if (event.shiftKey) {
                //dedent

                var txArea = $(event.target);
                if (isAuthenticated) {
                    SourcePutMeBack = new Object;
                    SourcePutMeBack.ParentNode = GetParentNode(txArea.parent());
                    SourcePutMeBack.AfterNode = GetAfterNode(txArea.parent());
                    MoveOut(txArea.parent());
                }
                if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'ComboDedent', CurrentSheetID, 1]);
                event.preventDefault();
                return false;
            }
            else if (event.controllKey) {

            } else {
                //indent
                var txArea = $(event.target);
                if (isAuthenticated) {
                    SourcePutMeBack = new Object;
                    SourcePutMeBack.ParentNode = GetParentNode(txArea.parent());
                    SourcePutMeBack.AfterNode = GetAfterNode(txArea.parent());
                    MoveIn(txArea.parent());
                }
                if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'ComboIndent', CurrentSheetID, 1]);
                event.preventDefault();
                return false;
            }
        }
    }

}

function GetNodeObject(Node) {
    if (Node.attr('NodeID') != null) {
        return gNodeList[Node.attr('NodeID')].Positions[Node.attr('PositionID')];
    }
    return null;
}

function isExpanded(Node) {
    if (Node.Dirty != null && Node.Dirty && Node.NewExpanded != null && Node.NewExpanded) {
        return true;
    }
    if (Node.Dirty != null && Node.Dirty && Node.NewExpanded != null && !Node.NewExpanded) {
        return false;
    }
    return Node.Position.bExpanded;
}

function getViewSecurity(Node) {
    if (Node.Dirty != null && Node.Dirty && Node.NewViewSecurityType != null) {
        return Node.NewViewSecurityType;
    }
    if (Node.ViewSecurityType == null) {
        return "view";
    }
    return Node.ViewSecurityType;
}

function getEditSecurity(Node) {
    if (Node.Dirty != null && Node.Dirty && Node.NewEditSecurityType != null) {
        return Node.NewEditSecurityType;
    }
    if (Node.EditSecurityType == null) {
        return "contribute";
    }
    return Node.EditSecurityType;
}

function CanMove(Node) {
    //You can move a node if

    //You own the node and the parent isn't edit locked
    var ThisNode = $(Node);
    var PSecu = null;
    var Parent = GetParentNode(ThisNode);
    var oParent=null;
    if (Parent != null) {
        oParent = gNodeList[Parent.attr("NodeID")].Positions[Parent.attr("PositionID")];
        if (oParent.EditSecurityType != null) {
            PSecu = oParent.EditSecurityType;
        }
    }
    else {
        //top levels are always locked except for owner
        if (UserSheetID != CurrentSheetID) {
            PSecu = "locked";
        }
        else {
            PSecu = "contribute";
        }
    }

    if (PSecu == null) {
        PSecu = "contribute";
    }


    var oNode = gNodeList[ThisNode.attr("NodeID")].Positions[ThisNode.attr("PositionID")]
    if(oNode.Position.AddedByUserID == CurrentUserID && (Parent == null || oParent.Position.AddedByUserID != CurrentUserID))
    {
        return true;
    }
    else if (oNode.Position.AddedByUserID != CurrentUserID && PSecu == "contribute") {
        return true;
    }
    else if (Parent == null || oParent.AddedByUserID == CurrentUserID) {
        return true;
    }

    return false;

}

function MoveDown(Node) {

    var ThisNode = $(Node);
    var NodeID = ThisNode.attr("NodeID");
    var PositionID = ThisNode.attr("PositionID");
    var oNode = gNodeList[NodeID].Positions[PositionID];
    if (CanMove(ThisNode)) {

        var NextNode = GetNextNode(ThisNode);
        var CurrentParent = GetParentNode(ThisNode);
        if (NextNode == null || NextNode.length == 0 || NextNode.attr('NodeID') == null) {
            //if no next sibling then dedent below parent



            if (CurrentParent == null || CurrentParent.length == 0 || CurrentParent.attr('NodeID') == null) {

                //we are already at the top and can't go anywhere

            }
            else {

                var NextParent = GetParentNode(CurrentParent);
                if (NextParent == null || NextParent.length == 0 || NextParent.attr('NodeID') == null) {

                    //weneed to move to the top leveel
                    MoveNode(ThisNode, null, CurrentParent, true);

                }
                else {

                    MoveNode(ThisNode, NextParent, CurrentParent, true);
                }

            }



        }
        else {
            //move down4
            //if Next Node is expanded then we need to dedent below
            var NextNodeObject = gNodeList[NextNode.attr('NodeID')].Positions[NextNode.attr('PositionID')];
            if (isExpanded(NextNodeObject)) {


                MoveNode(ThisNode, NextNode, null, true);


            }
            else {


                if (CurrentParent == null || CurrentParent.length == 0 || CurrentParent.attr('NodeID') == null) {
                    //top level
                    MoveNode(ThisNode, null, NextNode, true);
                }
                else {
                    //if Current Parent 

                    MoveNode(ThisNode, CurrentParent, NextNode, true);

                }
            }




        }
        ThisNode.contents('.nodeContent').first().focus();
    }

}

function CanMoveTo(Node, ParentNode) {
    if (ParentNode == null) {
        if (UserSheetID == CurrentSheetID) {
            return true;
        }
        else {
            return false;
            //you can't move something to someone's top level
        }
    }
    
    var oParent = gNodeList[ParentNode.attr('NodeID')].Positions[ParentNode.attr('PositionID')];

    var NewNodeAddedByUserID = CurrentUserID;
    if(Node!=null)
    {
        var oNode = gNodeList[Node.attr('NodeID')].Positions[Node.attr('PositionID')];
        NewNodeAddedByUserID= oNode.AddedByUserID;
    }

    if (NewNodeAddedByUserID != oParent.AddedByUserID && (oParent.EditSecurityType == null || oParent.EditSecurityType == 'contribute')) {
        return true;
    }
    else if (NewNodeAddedByUserID == oParent.AddedByUserID) { 
    return true; }
    else {
        return false;
    }
}

var CheatOriginalNodeAfter = null;

function MoveUp(Node) {

    var txArea = Node;
    var NodeID = txArea.attr("NodeID");
    var PositionID = txArea.attr("PositionID");
    var ThisNode = $(Node);
    var Node = gNodeList[NodeID].Positions[PositionID];
    if (CanMove(ThisNode) || CanMoveOverride) {

        var NextNode =GetAfterNode(ThisNode);
        if (NextNode ==null || NextNode.length == 0) {
            //if no next sibling then dedent below parent
            var CurrentParent =GetParentNode(ThisNode);


            if (CurrentParent == null || CurrentParent.length == 0 || CurrentParent.attr('NodeID') == null || CurrentParent.attr('NodeID') == CurrentParentID) {

                //we are already at the top and can't go anywhere

            }
            else {

                var NextParent = GetParentNode(CurrentParent);
                var CurrentParentAfter = GetAfterNode(CurrentParent);

                if ((NextParent ==null ||NextParent.length == 0 || NextParent.attr('NodeID') == null) && (CurrentParentAfter==null ||CurrentParentAfter.length == 0 || CurrentParentAfter.attr('NodeID') == null)) {


                    //top level
                    
                    MoveNode(ThisNode,null,null,true);
                    if (!CanMoveTo(ThisNode, CurrentParent)) {
                        CanMoveOverride = true;
                        return MoveUp(ThisNode);
                    }
                    else {
                        CanMoveOverride = false;
                    }

                }
                else {
                    
                    

                    var NextAfter = GetAfterNode(CurrentParent);
                    if (NextAfter == null || NextAfter.length == 0 || NextAfter.attr('NodeID') == null) {
                        //top level
                        MoveNode(ThisNode, NextParent, null, true);
                        if (!CanMoveTo(ThisNode, NextParent)) {
                            $('#moveup').css('background-color', 'yellow');

                            //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                            $('#moveup').stop().animate(
        { backgroundColor: 'White' }, 6000);
                            return PutMeBack(ThisNode);
                        }
                        else {
                            CanMoveOverride = false;
                        }

                    }
                    else {

                        MoveNode(ThisNode, NextParent, NextAfter, true);
                        if (!CanMoveTo(ThisNode, NextParent)) {
                            CanMoveOverride = true;
                            $('#moveup').css('background-color', 'yellow');

                            //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                            $('#moveup').stop().animate(
        { backgroundColor: 'White' }, 6000);
                            return PutMeBack(ThisNode);
                        }
                        else {
                            CanMoveOverride = false;
                        }

                    }
                }



            }



        }
        else {
            //move up
            var NextNodeObject = gNodeList[NextNode.attr('NodeID')].Positions[NextNode.attr('PositionID')];
            if (isExpanded(NextNodeObject) && NextNode.children('.SubNodes').children('.node').last().length > 0) {
                //move to the bottom of the expansion

                var ThisSib = NextNode;
                var SibNodeID = ThisSib.attr('NodeID');
                var SibPos = ThisSib.attr('PositionID');
                var SibNode = gNodeList[SibNodeID].Positions[SibPos];
                while (isExpanded(SibNode)) {

                    if (ThisSib.children('.SubNodes').children('.node').last().length > 0) {
                        ThisSib = GetLastChild(ThisSib);
                        SibNodeID = ThisSib.attr('NodeID');
                        SibPos = ThisSib.attr('PositionID');
                        SibNode = gNodeList[SibNodeID].Positions[SibPos];
                    }
                    else {
                        break;
                    }
                }
                var SibParent = GetParentNode(ThisSib);


                MoveNode(ThisNode, SibParent, ThisSib, true);
                if (!CanMoveTo(ThisNode, SibParent)) {
                    CanMoveOverride = true;
                    return MoveUp(ThisNode);
                }
                else {
                    CanMoveOverride = false;
                }





            }
            else {
                //move below after's after
                var NextAfter = GetAfterNode(NextNode);
                var CurrentParent = GetParentNode(ThisNode);
                if (NextAfter ==null || NextAfter.length == 0 || NextAfter.attr('NodeID') == null) {
                    //top level
                    


                    if (CurrentParent==null || CurrentParent.length == 0 || CurrentParent.attr('NodeID') == null) {
                        //tippy top
                        MoveNode(ThisNode, null, null, true);
                        if (!CanMoveTo(ThisNode, null)) {
                            $('#moveup').css('background-color', 'yellow');

                            //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                            $('#moveup').stop().animate(
        { backgroundColor: 'White' }, 6000);
                            return PutMeBack(ThisNode);
                        }
                    }
                    else {
                        MoveNode(ThisNode, CurrentParent, null, true);
                        if (!CanMoveTo(ThisNode, CurrentParent)) {
                            CanMoveOverride = true;
                            return MoveUp(ThisNode);
                        }
                        else {
                            CanMoveOverride = false;
                        }
                    }

                }
                else {
                    //if Current Parent 
                    
                    if (CurrentParent ==null || CurrentParent.length == 0 || CurrentParent.attr('NodeID') == null) {

                        MoveNode(ThisNode, null, NextAfter, true);
                        if (!CanMoveTo(ThisNode, null)) {
                            $('#moveup').css('background-color', 'yellow');

                            //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                            $('#moveup').stop().animate(
        { backgroundColor: 'White' }, 6000);
                            return PutMeBack(ThisNode);
                        }
                    }
                    else {
                        MoveNode(ThisNode, CurrentParent, NextAfter, true)
                        if (!CanMoveTo(ThisNode, CurrentParent)) {
                            CanMoveOverride = true;
                            return MoveUp(ThisNode);
                        }
                        else {
                            CanMoveOverride = false;
                        }
                    }

                }
            }

        }

        //event.preventDefault();
        
        ThisNode.contents('.nodeContent').first().focus();
        return false;
    }

}

function MoveIn(Node) {

    var ThisNode = $(Node);
    var NodeID = ThisNode.attr("NodeID");
    var PositionID = ThisNode.attr("PositionID");
    var oNode = gNodeList[NodeID].Positions[PositionID];
    if (CanMove(ThisNode)) {
        //if the current node has an after ID then we can indent it to the bottom of the list of the after node
        var CurrentAfterNode = GetAfterNode(ThisNode);
        var CurrentParentNode = GetParentNode(ThisNode);


        if (CurrentAfterNode == null) {
            event.preventDefault();
            return false;
        }

        var LastAfterChild = GetLastChild(CurrentAfterNode);

        var LastAfterChildID = null;
        var LastAfterChildPos = null;

        if (LastAfterChild == null || LastAfterChild.length == 0) {
            LastAfterChildID = EmptyGUID;
            // $('.node' + CurrentAfter).children('.SubNodes').first().append($('.node' + NodeID).first());
        }
        else {
            LastAfterChildID = LastAfterChild.attr('NodeID');
            LastAfterChildPos = LastAfterChild.attr('PositionID');
            //LastAfterChild.after($('.node' + NodeID).first());
        }





        //$('.node'+ Node.NodeID).remove();
        //SetUpNode(Node.NewParentID,Node.NewAfterID,Node.Position.PositionID, Node.NodeID,Node.NodeText,Node.NodeNote);
        MoveNode(ThisNode, CurrentAfterNode, LastAfterChild, true);
        SetUpBull(CurrentAfterNode.attr('PositionID'));

        //check to see if the new parent needs to be exdpanded
        ShowChildren(CurrentAfterNode);
        ThisNode.children('.nodeContent').first().focus();
    }
}

var CanMoveOverride = false;
var SourcePutMeBack = null;

function PutMeBack(ThisNode) {
    MoveNode(ThisNode, SourcePutMeBack.ParentNode, SourcePutMeBack.AfterNode, true);
    CanMoveOverride = false;
    $(ThisNode).children('.nodeContent').css('background-color', 'yellow');

    //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
    $(ThisNode).children('.nodeContent').stop().animate(
        { backgroundColor: 'White' }, 6000);
}

function MoveOut(Node) {
    var ThisNode = $(Node);
    var NodeID = ThisNode.attr("NodeID");
    var PositionID = ThisNode.attr("PositionID");
    var oNode = gNodeList[NodeID].Positions[PositionID];
    if (CanMove(ThisNode) || CanMoveOverride) {

        //if the current node has an after ID then we can indent it to the bottom of the list of the after node
        var CurrentAfterNode = GetAfterNode(ThisNode);
        var CurrentParentNode = GetParentNode(ThisNode);


        if (CurrentParentNode == null) {
            event.preventDefault();
            return false;
        }

        //put after the parent
         ParentParent = GetParentNode(CurrentParentNode);


         //ParentParentPos = GetParentPositionID(CurrentParentPosition);

         if (ParentParent != null || (ParentParent == null && UserSheetID == CurrentSheetID)) {

         }
         else {
             //we can't put things at the top level
             

             $('#moveout').css('background-color', 'yellow');

             //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
             $('#moveout').stop().animate(
        { backgroundColor: 'White' }, 6000);

             return PutMeBack(ThisNode);
         }

            MoveNode(ThisNode, ParentParent, CurrentParentNode, true);
            if (!CanMoveTo(ThisNode, ParentParent)) {
                CanMoveOverride = true;
                MoveOut(ThisNode);
            }

            else {
                CanMoveOverride = false;
            }
         
        //SetUpNode(Node.NewParentID,Node.NewAfterID,Node.Position.PositionID, Node.NodeID,Node.NodeText,Node.NodeNote);
        ThisNode.children('.nodeContent').first().focus();
    }
}


function MenuMoveUp(e) {
    var Node = $(e).closest('.node');
    if (Node.length > 0) {
        SourcePutMeBack = new Object;
        SourcePutMeBack.ParentNode = GetParentNode(Node);
        SourcePutMeBack.AfterNode= GetAfterNode(Node);
        MoveUp(Node);
    }
    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'MenuMoveUp', CurrentSheetID, 1]);

}

function MenuMoveDown(e) {
    var Node = $(e).closest('.node');
    if (Node.length > 0) {
        SourcePutMeBack = new Object;
        SourcePutMeBack.ParentNode = GetParentNode(Node);
        SourcePutMeBack.AfterNode= GetAfterNode(Node);
        MoveDown(Node);
    }
    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'MenuMoveDown', CurrentSheetID, 1]);
}



function MenuMoveIn(e) {
    var Node = $(e).closest('.node');
    if (Node.length > 0) {
        SourcePutMeBack = new Object;
        SourcePutMeBack.ParentNode = GetParentNode(Node);
        SourcePutMeBack.AfterNode= GetAfterNode(Node);
        MoveIn(Node);
    }
    if (_gaq) _gaq.push(['_trackEvent', 'mindwallet', 'MenuMoveIn', CurrentSheetID, 1]);

}

function MenuMoveOut(e) {
    var Node = $(e).closest('.node');
    if (Node.length > 0) {
        SourcePutMeBack = new Object;
        SourcePutMeBack.ParentNode = GetParentNode(Node);
        SourcePutMeBack.AfterNode= GetAfterNode(Node);
        MoveOut(Node);
    }
    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'MenuMoveOut', CurrentSheetID, 1]);

}

function InsertNodeAction(Node) {
    var ThisNode = $(Node);
    var ParentNode = GetParentNode(ThisNode);
    var txArea = ThisNode.children('textarea');

    //see if the next node has a parent equal to this item..if so then we need to add at the next level...other wise at this level
    var NodeID = ThisNode.attr("NodeID");
    var PositionID = ThisNode.attr("PositionID");
    var Node = gNodeList[NodeID].Positions[PositionID];

    var ParentPosition = null;      
      var ParentNodeID = null;
       var oParentNode = null;

       if (ParentNode != null) {
           ParentPosition = (ParentNode.attr('PositionID') != null ? ParentNode.attr('PositionID') : null);
           ParentNodeID = (ParentNode.attr('NodeID') != null ? ParentNode.attr('NodeID') : null);
           oParentNode = gNodeList[ParentNodeID].Positions[ParentPosition];
       }


    if ((isExpanded(Node) && Node.AddedByUserID == CurrentUserID) || (!isExpanded(Node) && oParentNode!=null &&  oParentNode.AddedByUserID==CurrentUserID) || (CurrentSheetID == UserSheetID && oParentNode==null)) {
        var txAreaInfo = txArea.getSelection();


        if (txAreaInfo.end == txArea.val().length) {
            //enter at the end fo the line
            txArea.val(txArea.val().replace("\n", "").replace("\r", ""));
            //txArea.val(txArea.val().substring(0, txArea.val().length - 1));
            //add a new item at the same level
        }
        else {
            //enter at the middle of line
            //txArea.val(txArea.val().substring(0, txAreaInfo.start - 1) + txArea.val().substring(txAreaInfo.start));
            txArea.val(txArea.val().replace("\n", "").replace("\r", ""));
        }

        if (isExpanded(Node) || !CanMoveTo(null, ParentNode) || (CurrentParentID == Node.NodeID && CurrentParentID != EmptyGUID)) {
            //add at next level
            //var OldAfter = gNodeList[FindFollower(NodeID,EmptyGUID)];
            var NewNode = AddNewItem(ThisNode, null);
            if (!isExpanded(Node)) {
                SetUpBull(ThisNode.attr('PositionID'));
                ShowChildren(ThisNode);
            }

            //TestNodeChange(ThisNode);
            NewNode.contents('.nodeContent').first().focus();




        }
        else {
            //add at same level
            //var OldAfter = gNodeList[FindFollower(Node.Position.ParentID, NodeID)];
            var ParentNode = GetParentNode(ThisNode);
            //var ParentPosition = (ParentNode.attr('PositionID') != null ? ParentNode.attr('PositionID') : null);

            var NewNode = AddNewItem(ParentNode, ThisNode);
            //TestNodeChange(ThisNode);
            NewNode.contents('.nodeContent').first().focus();

        }
    }
    else {
        var txAreaInfo = txArea.getSelection();


        if (txAreaInfo.end == txArea.val().length) {
            //enter at the end fo the line
            //txArea.val(txArea.val().substring(0, txArea.val().length - 1));
            txArea.val(txArea.val().replace("\n", "").replace("\r", ""));
            //add a new item at the same level
        }
        else {
            //enter at the middle of line
            //txArea.val(txArea.val().substring(0, txAreaInfo.start - 1) + txArea.val().substring(txAreaInfo.start));
            txArea.val(txArea.val().replace("\n", "").replace("\r", ""));
        }


        if ((isExpanded(Node) && CanMoveTo(null, ThisNode)) || (!CanMoveTo(null, ParentNode) && CanMoveTo(null, ThisNode))) {
            //add at next level
            //if I'm adding at the next level then I need the souce Item key of this item
            var FUserSheet = gUserSheetList[FindUser(Node.AddedByUserID, gUserSheetList)].SheetID;
            //var OldAfter = gNodeList[FindFollower(NodeID,EmptyGUID)];
            var NewNode = AddForeignNewItem(FUserSheet, ThisNode, null);
            if (!isExpanded(Node)) {
                SetUpBull(ThisNode.attr('PositionID'));
                ShowChildren(ThisNode);
            }
            //TestNodeChange(ThisNode);
            NewNode.contents('.nodeContent').first().focus();


        }
        else if (CanMoveTo(null, ParentNode)) {
            //add at same level
            //var OldAfter = gNodeList[FindFollower(Node.Position.ParentID, NodeID)];
            var ParentNode = GetParentNode(ThisNode);
            if (ParentNode == null) {

            }
            else {
                var ParentPosition = (ParentNode == null || ParentNode.attr('PositionID') != null ? ParentNode.attr('PositionID') : null);
                var ParentNodeID = (ParentNode == null || ParentNode.attr('NodeID') != null ? ParentNode.attr('NodeID') : null);

                var oParent = gNodeList[ParentNodeID].Positions[ParentPosition];
                if (oParent.AddedByUserID != CurrentUserID) {
                    var FUserSheet = gUserSheetList[FindUser(oParent.AddedByUserID, gUserSheetList)].SheetID;

                    var NewNode = AddForeignNewItem(FUserSheet, ParentNode, ThisNode);
                    //                        if (!isExpanded(Node)) {
                    //                            SetUpBull(ThisNode.attr('PositionID'));
                    //                            ShowChildren(ThisNode);
                    //                        }
                    //TestNodeChange(ThisNode);
                    NewNode.contents('.nodeContent').first().focus();
                }
                else {
                    //we shouldn't be in here, we got bummped by the lower nod and we just need to go add the items elsewhere...by
                    //HideChildren(ThisNode);
                    $(ThisNode).children('.nodeContent').css('background-color', 'yellow');

                    //$('.node' + PositionID).children('.nodeContent').val(ReturnData.Node[0].NodeText);
                    $(ThisNode).children('.nodeContent').stop().animate(
        { backgroundColor: 'White' }, 6000);
                    //InsertNodeAction(ThisNode);
                }
            }

        }
        //we want to contribute to this node

        //add the node via mindmeld

        //stick that node here as a melded node


    }


}

function EditorKeyUp(event) {

    if ($(event.target).hasClass("nodeContent")) {
        if (event.keyCode == '13') {
            if (event.shiftKey) {

            }
            else if (event.controllKey) {

            } else {



                var ThisNode = $(event.target).parent();
                if (isAuthenticated) {
                    InsertNodeAction(ThisNode);
                }

                event.preventDefault();
                return false;
            }
        }
        else if (event.keyCode == '40') { //down arrow
            if (event.shiftKey) {

                //move the item down the heiarchy
                //find next sibling
                var txArea = $(event.target);



                if (isAuthenticated) {
                    SourcePutMeBack = new Object;
                    SourcePutMeBack.ParentNode = GetParentNode(txArea.parent());
                    SourcePutMeBack.AfterNode = GetAfterNode(txArea.parent());
                    MoveDown(txArea.parent());
                }
                if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'ComboKeyDown', CurrentSheetID, 1]);
                event.preventDefault();
                return false;
            }
            else if (event.controllKey) {

            } else {


                var txArea = $(event.target);
                var NodeID = txArea.attr('NodeID');
                var Pos = txArea.attr('PositionID');
                var Node = gNodeList[NodeID].Positions[Pos];

                if (isExpanded(Node) && txArea.parent().children('.SubNodes').children('.node').length > 0) {
                    //move to the next sub item
                    txArea.parent().children('.SubNodes').children('.node').first().children('.nodeContent').first().focus();
                }
                else {
                    //move to the next sibling
                    var NextSib = new Array();
                    var ThisNode = txArea.parent()
                    while (NextSib.length == 0) {
                        NextSib = ThisNode.next()
                        if (NextSib.length != 0) {
                            NextSib.children('.nodeContent').first().focus();
                            break;
                        }
                        else {
                            ThisNode = ThisNode.parent().parent();
                        }
                    }

                }


                event.preventDefault();
                return false;
            }
        }

        else if (event.keyCode == '38') {//Up arrow
            if (event.shiftKey) {

                var txArea = $(event.target);
                if (isAuthenticated) {
                    SourcePutMeBack = new Object;
                    SourcePutMeBack.ParentNode = GetParentNode(txArea.parent());
                    SourcePutMeBack.AfterNode = GetAfterNode(txArea.parent());
                    MoveUp(txArea.parent());
                }
                if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'ComboKeyUp', CurrentSheetID, 1]);
                event.preventDefault();
                return false;

            }
            else if (event.controllKey) {

            } else {


                var txArea = $(event.target);


                if (txArea.parent().prev().length > 0) {
                    //move to the next sibling
                    //see if it is expanded
                    var ThisSib = txArea.parent().prev();
                    var NodeID = ThisSib.attr('NodeID');
                    var Pos = ThisSib.attr('PositionID');
                    var Node = gNodeList[NodeID].Positions[Pos];
                    while ((Node.Dirty && Node.NewExpanded != null && Node.NewExpanded) || Node.Position.bExpanded) {
                        if (ThisSib.children('.SubNodes').children('.node').last().length > 0) {
                            ThisSib = ThisSib.children('.SubNodes').children('.node').last();
                            NodeID = ThisSib.attr('NodeID');
                            Pos = ThisSib.attr('PositionID');
                            Node = gNodeList[NodeID].Positions[Pos];
                        }
                        else {
                            break;
                        }
                    }

                    ThisSib.children('.nodeContent').first().focus();

                }
                else {
                    //move to the parent
                    txArea.parent().parent().parent().children('.nodeContent').first().focus();

                }


                event.preventDefault();
                return false;
            }
        }

        else if (event.keyCode == '9') {
            //ignoretab
        }
        else {
            var ThisNode = $(event.target).parent();
            var oNode = gNodeList[ThisNode.attr('NodeID')].Positions[ThisNode.attr('PositionID')];
            MarkDirty(oNode);
        }

        }
    

}


function AddNewItem(ParentNode, AfterNode) {


    var ParentID = CurrentParentID;
    var ParentPositionID = null;
    var AfterID = EmptyGUID;
    var AfterPositionID = null;
    var oParentNode = null;
    var NewItemSheet = CurrentSheetID;


    

    if (ParentNode != null) {
        ParentID = ParentNode.attr('NodeID');
        ParentPositionID = ParentNode.attr('PositionID');
    }

    if (ParentPositionID != null) {
        oParentNode = gNodeList[ParentID].Positions[ParentPositionID];
        NewItemSheet = gUserSheetList[FindUser(oParentNode.AddedByUserID, gUserSheetList)].SheetID;


        //gUserSheetList[FindUser(Node.AddedByUserID, gUserSheetList)].SheetID;
    }

    if (AfterNode != null) {
        AfterID = AfterNode.attr('NodeID');
        AfterPositionID = AfterNode.attr('PositionID');
    }

    var NewNode = new Object();
    NewNode.DateAdded = "";
    NewNode.DateUpdated = ""
    NewNode.NodeID = GetGuid();
    NewNode.NodeNote = "";
    NewNode.NodeTypeID = 1;
    NewNode.AddedByUserID = CurrentUserID;
    NewNode.Position = new Object();
    NewNode.Position.AddedByUserID = "";
    NewNode.Position.AfterID = AfterID;
    NewNode.Position.DateAdded = "";
    NewNode.Position.DateUpdated = "";
    //this needs to be the sheet of the parent
    NewNode.Position.ItemKey = NewItemSheet,
    NewNode.Position.ParentID = ParentID;
    NewNode.Position.NodeID = NewNode.NodeID;
    NewNode.Position.NodeTypeID = 1;
    NewNode.Position.PositionID = GetGuid();
    NewNode.Position.bComplete = false;
    NewNode.Position.AddedByUserID = CurrentUserID;
    NewNode.bComplete = false;
    NewNode.NewParentID = ParentID;
    NewNode.NewAfterID = AfterID;
    NewNode.NewValue = "";
    MarkDirty(NewNode);

    if (ParentPositionID != null) {

        //set default security
        
        if (oParentNode == null) {
            //odd
            var breakhere = 0;
        }

        var Secu = "";
        if (typeof oParentNode.Dirty != 'undefined' && oParentNode.Dirty != null && oParentNode.Dirty && oParentNode.NewViewSecurityType != null) {

            Secu = oParentNode.NewViewSecurityType;
        }
        else {
            Secu = oParentNode.ViewSecurityType;
        }

        NewNode.ViewSecurityType = null;
        NewNode.NewViewSecurityType = Secu;

        var ESecu = "";
        if (typeof oParentNode.Dirty != 'undefined' && oParentNode.Dirty != null && oParentNode.Dirty && oParentNode.NewEditSecurityType != null) {

            ESecu = oParentNode.NewEditSecurityType;
        }
        else {
            ESecu = oParentNode.EditSecurityType;
        }

        NewNode.EditSecurityType = null;
        NewNode.NewEditSecurityType = ESecu;
    }
    else {
        NewNode.ViewSecurityType = null;
        NewNode.NewViewSecurityType = "locked";

        NewNode.EditSecurityType = null;
        NewNode.NewEditSecurityType = "contribute";
    }

    if (gNodeList[NewNode.NodeID] == null) {
        gNodeList[NewNode.NodeID] = new Object;
    }
    if (gNodeList[NewNode.NodeID].Positions == null) {
        gNodeList[NewNode.NodeID].Positions = new Array();
    }
    if (gNodeList[NewNode.NodeID].Positions[NewNode.Position.PositionID] == null) {
        gNodeList[NewNode.NodeID].Positions[NewNode.Position.PositionID] = NewNode;
    }




    var ThisNode = CreateNode($('.SplitPaneLeft').first(), NewNode.NodeID, NewNode.Position.PositionID, "");
    MoveNode(ThisNode, ParentNode, AfterNode, true);



    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'AddItem', CurrentSheetID, 1]);

    return ThisNode;

}

function AddForeignNewItem(ForeignSheet, ParentNode, AfterNode) {

    var ParentID = CurrentParentID;
    var ParentPositionID = null;
    var AfterID = EmptyGUID;
    var AfterPositionID = null;

    if (ParentNode != null) {
        ParentID = ParentNode.attr('NodeID');
        ParentPositionID = ParentNode.attr('PositionID');
    }

    if (AfterNode != null) {
        AfterID = AfterNode.attr('NodeID');
        AfterPositionID = AfterNode.attr('PositionID');
    }

    var oParentNode = null;
    var NewPositionUser = CurrentUserID;
    if (ParentPositionID != null) {
        oParentNode = gNodeList[ParentID].Positions[ParentPositionID];
        NewPositionUser = oParentNode.AddedByUserID;
    }
    //we create the item

    var NewNode = new Object();
    NewNode.DateAdded = "";
    NewNode.DateUpdated = ""
    NewNode.NodeID = GetGuid();
    NewNode.NodeNote = "";
    NewNode.NodeTypeID = 1;
    NewNode.AddedByUserID = CurrentUserID;
    NewNode.Position = new Object();
    NewNode.Position.AddedByUserID = "";
    NewNode.Position.AfterID = AfterID;
    NewNode.Position.DateAdded = "";
    NewNode.Position.DateUpdated = "";
    NewNode.Position.ItemKey = ForeignSheet,
    NewNode.Position.ParentID = ParentID;
    NewNode.Position.NodeID = NewNode.NodeID;
    NewNode.Position.NodeTypeID = 3;
    NewNode.Position.PositionID = GetGuid();
    NewNode.Position.bComplete = false;
    NewNode.Position.AddedByUserID = NewPositionUser;
    NewNode.bComplete = false;
    NewNode.NewParentID = ParentID;
    NewNode.NewAfterID = AfterID;
    NewNode.NewPositionNodeTypeID = 3;
    NewNode.NewValue = "";
    MarkDirty(NewNode);

    if (ParentPositionID != null) {
        //set default security
        
        if (oParentNode == null) {
            //odd
            var breakhere = 0;
        }
        var Secu = "";
        if (typeof oParentNode.Dirty != 'undefined' && oParentNode.Dirty != null && oParentNode.Dirty && oParentNode.NewViewSecurityType != null) {

            Secu = oParentNode.NewViewSecurityType;
        }
        else {
            Secu = oParentNode.ViewSecurityType;
        }

        NewNode.ViewSecurityType = null;
        NewNode.NewViewSecurityType = "view";

        NewNode.EditSecurityType = null;
        NewNode.NewEditSecurityType = "contribute";
    }
    else {
        NewNode.ViewSecurityType = null;
        NewNode.NewViewSecurityType = "view";

        NewNode.EditSecurityType = null;
        NewNode.NewEditSecurityType = "contribute";
    }

    if (gNodeList[NewNode.NodeID] == null) {
        gNodeList[NewNode.NodeID] = new Object;
    }
    if (gNodeList[NewNode.NodeID].Positions == null) {
        gNodeList[NewNode.NodeID].Positions = new Array();
    }
    if (gNodeList[NewNode.NodeID].Positions[NewNode.Position.PositionID] == null) {
        gNodeList[NewNode.NodeID].Positions[NewNode.Position.PositionID] = NewNode;
    }




    var ThisNode = CreateNode($('.SplitPaneLeft').first(), NewNode.NodeID, NewNode.Position.PositionID, "");
    MoveNode(ThisNode, ParentNode, AfterNode, true);

    //now we must create the meld and the source node.

    //create the node in super secret hidden node


    var SecretNode = new Object();
    SecretNode.DateAdded = "";
    SecretNode.DateUpdated = ""
    SecretNode.NodeID = NewNode.NodeID;
    SecretNode.NodeNote = "";
    SecretNode.NodeTypeID = 1;
    SecretNode.AddedByUserID = CurrentUserID;
    SecretNode.Position = new Object();
    //SecretNode.Position.AddedByUserID = "";
    SecretNode.Position.AfterID = EmptyGUID;
    SecretNode.Position.DateAdded = "";
    SecretNode.Position.DateUpdated = "";
    SecretNode.Position.ItemKey = UserSheetID,
    SecretNode.Position.ParentID = EmptyGUID;
    SecretNode.Position.NodeID = SecretNode.NodeID;
    SecretNode.Position.NodeTypeID = 4;
    SecretNode.Position.PositionID = GetGuid();
    SecretNode.Position.bComplete = false;
    SecretNode.Position.AddedByUserID = CurrentUserID;
    SecretNode.bComplete = false;
    SecretNode.NewParentID = ParentID;
    SecretNode.NewAfterID = AfterID;
    SecretNode.NewValue = "";
    SecretNode.NewPositionNodeTypeID = 4;
    MarkDirty(SecretNode);
    SecretNode.ViewSecurityType = null;
    SecretNode.NewViewSecurityType = "view";

    SecretNode.EditSecurityType = null;
    SecretNode.NewEditSecurityType = "contribute";

    SaveNode(SecretNode);

    //     //mind meld the node
    //actually...we'll let the user decide if they want to meld the node.

    //    var oNode = gNodeList[ParentID].Positions[ParentPosition];

    //     var TokenResponse = _MW.getToken(AppHost, oNode);
    //    var ActivateResponse = TokenResponse.success(function (data) {
    //        //call appURL
    //        if (data.isNewToken == true) {
    //   var someResponse = _MW.activateApp(_MW.apps["MINDMELD"], oNode);
    //   _MW.deleteToken(AppHost, oNode)
    //   }

    if (typeof _gaq != "undefined" && _gaq) _gaq.push(['_trackEvent', 'mindwallet', 'AddForeignItem', CurrentSheetID, 1]);

    return ThisNode;

}

function SaveNode(item) {
    //WARINING WARNING WARNING
    //WARNING WARNING WARNING
    //This code is simulated in MWClient.AddNode.  If you change something here do it there
    var SaveData = {
        SourceNodeID: item.NodeID,
        SourceParentID: item.Position.ParentID,
        SourceNodeNote: item.NodeNode,
        SourceNodeText: item.NodeText,
        SourcebComplete: item.bComplete,
        SourceNodeTypeID: item.NodeTypeID,
        SourceDateUpdated: item.DateUpdated,
        SourceViewSecurityType: item.ViewSecurityType,
        SourceEditSecurityType: item.EditSecurityType,
        SourcePositionID: item.Position.PositionID,
        SourcePositionItemKey: item.Position.ItemKey,
        SourcePositionParentID: item.Position.ParentID,
        SourcePositionAfterID: item.Position.AfterID,
        SourcePositionNodeTypeID: item.Position.NodeTypeID,
        SourcePositionbComplete: item.Position.bComplete,
        SourcePositionbExpanded: item.Position.bExpanded,
        SourcePositionAddedByUserID: item.Position.AddedByUserID,

        NewPositionParentID: null,
        NewPositionAfterID: null,
        NewPositionbComplete: null,
        NewbComplete: null,
        NewNodeNote: null,
        NewNodeText: null,
        NewExpanded: null,
        NewViewSecurityType: null,
        NewEditSecurityType: null,
        NewNodeTypeID: null,
        NewPositionNodeTypeID: null
    };

    var ReallyDirty = false;

    if (item.AddedByUserID == CurrentUserID) {

        if (item.NewValue != null && item.NewValue != item.NodeText) {
            SaveData.NewNodeText = item.NewValue;
            ReallyDirty = true;
        }
        if (item.NewViewSecurityType != null && item.NewViewSecurityType != item.ViewSecurityType) {
            SaveData.NewViewSecurityType = item.NewViewSecurityType;
            ReallyDirty = true;
        }
        if (item.NewEditSecurityType != null && item.NewEditSecurityType != item.EditSecurityType) {
            SaveData.NewEditSecurityType = item.NewEditSecurityType;
            ReallyDirty = true;
        }
    }

    if (item.NewAfterID != null && item.NewAfterID != item.Position.AfterID) {
        SaveData.NewPositionAfterID = item.NewAfterID;
        ReallyDirty = true;
    }

    if (item.NewParentID != null && item.NewParentID != item.Position.ParentID) {
        SaveData.NewPositionParentID = item.NewParentID;
        ReallyDirty = true;
    }

    if (item.NewExpanded != null && item.NewExpanded != item.Position.bExpanded) {
        SaveData.NewExpanded = item.NewExpanded;
        ReallyDirty = true;
    }

    if (item.NewbComplete != null && item.NewbComplete != item.bComplete) {
        SaveData.NewbComplete = item.NewbComplete;
        ReallyDirty = true;
    }

    if (item.NewNodeTypeID != null && item.NodeTypeID != item.NodeTypeID) {
        SaveData.NewNodeTypeID = item.NewNodeTypeID;
        ReallyDirty = true;
    }

    if (item.NewPositionNodeTypeID != null && item.NewPositionNodeTypeID != item.Position.NodeTypeID) {
        SaveData.NewPositionNodeTypeID = item.NewPositionNodeTypeID;
        ReallyDirty = true;
    }


    item.Dirty = false;
    if (ReallyDirty) {
        item.CanUpdate = false;
        $.ajax({
            url: '/api/node',
            cache: false,
            type: 'post',
            data: SaveData,
            success: SyncSavedNode,
            error: function () {
                if (SaveData.SourcePositionID != null && SaveData.SourceNodeID != null) {
                    //var PositionID = ReturnData.Node[0].Position.PositionID;
                    gNodeList[SaveData.SourceNodeID].Positions[SaveData.SourcePositionID].CanUpdate = true;
                    $('.node' + SaveData.SourcePositionID).children('.nodeContent').css('background-color', 'Pink');

                }
            }
        });
    }
}



function FindUser(ItemKey, Usr) {
    for (var ThisItem = 0; ThisItem < Usr.length; ThisItem++) {
        if (Usr[ThisItem].UserID == ItemKey) {
            return ThisItem;
        }
    }
}

function FindUserSheet(ItemKey, Usr) {
    for (var ThisItem = 0; ThisItem < Usr.length; ThisItem++) {
        if (Usr[ThisItem].UserID == ItemKey) {
            return ThisItem;
        }
    }
}

function submitSearch()
{
    var q = $('#SearchBox').val();
    window.location = "/home/search?ItemKey=" + CurrentSheetID + "&q=" + escape(q);

}

function runSearch(sItemKey,sSearchQuery) {
    $.ajax({
        url: '/api/search',
        cache: false,
        type: 'post',
        data: { q: sSearchQuery, ItemKey: sItemKey },
        success: ShowSearchResults
        }
    );
}

function ShowSearchResults(data) {
    var disp = $('.SplitPaneLeft');
    $.each(data.Results, function (idx, val) {
        disp.append("<div class='SearchResult'><a href='/home/index/" + val.Item2 + "/" + val.Item3 + "' >" + val.Item4 + "</a></div>");
    });
}



function loadPublicStream(MaxDate) {
    $.ajax({
        url: '/api/publicStream',
        cache: false,
        type: 'post',
        data: { MaxDate:MaxDate},
        success: ShowPublicStream
    }
    );
}

function ShowPublicStream(data) {
    var disp = $('.SplitPaneLeft');
    $.each(data.Results, function (idx, val) {

        ThisUser = data.Users[FindUser(val.addedbyuserid, data.Users)];
        disp.append("<div class='PublicStreamItem'><img title='" + ThisUser.DisplayName + "' class='NodeType3Image' src='https://graph.facebook.com/" + ThisUser.FBID + "/picture'/><a href='/home/index/" + val.UserSheet + "/' >" + ThisUser.DisplayName + "</a><br/> <a href='/home/index/" + val.UserSheet + "/" + val.NodeID + "' >" + val.nodetext + "</a></div>");
    });
}


/*
* jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
* (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
*/

(function () {

    var fieldSelection = {

        getSelection: function () {

            var e = this.jquery ? this[0] : this;

            return (

            /* mozilla / dom 3.0 */
                ('selectionStart' in e && function () {
                    var l = e.selectionEnd - e.selectionStart;
                    return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
                }) ||

            /* exploder */
                (document.selection && function () {

                    e.focus();

                    var r = document.selection.createRange();
                    if (r == null) {
                        return { start: 0, end: e.value.length, length: 0 }
                    }

                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);

                    return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
                }) ||

            /* browser not supported */
                function () {
                    return { start: 0, end: e.value.length, length: 0 };
                }

            )();

        },

        replaceSelection: function () {

            var e = this.jquery ? this[0] : this;
            var text = arguments[0] || '';

            return (

            /* mozilla / dom 3.0 */
                ('selectionStart' in e && function () {
                    e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                    return this;
                }) ||

            /* exploder */
                (document.selection && function () {
                    e.focus();
                    document.selection.createRange().text = text;
                    return this;
                }) ||

            /* browser not supported */
                function () {
                    e.value += text;
                    return this;
                }

            )();

        }

    };

    jQuery.each(fieldSelection, function (i) { jQuery.fn[i] = this; });

})();


/*
Inserts GA using DOM insertion of <script> tag and "script onload" method to
initialize the pageTracker object. Prevents GA insertion from blocking I/O!

As suggested in Steve Souder's talk. See:

http://google-code-updates.blogspot.com/2009/03/steve-souders-lifes-too-short-write.html

*/

/* acct is GA account number, i.e. "UA-5555555-1" */
function gaSSDSLoad(acct) {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
      pageTracker,
      s;
    s = document.createElement('script');
    s.src = gaJsHost + 'google-analytics.com/ga.js';
    s.type = 'text/javascript';
    s.onloadDone = false;
    function init() {
        pageTracker = _gat._getTracker(acct);
        pageTracker._trackPageview();
    }
    s.onload = function () {
        s.onloadDone = true;
        init();
    };
    s.onreadystatechange = function () {
        if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
            s.onloadDone = true;
            init();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}
