protected function insertIntoTree(&$node, $existingNode = null)
    {

        $treeOriginTagDef = $node->getNodeRef()->getElement()->getSchema()->getTreeOriginTagDef();

        if(empty($treeOriginTagDef))
            throw new NodeException('Cannot insert a node in tree order mode without a tree origin tag definition');

        if($treeOriginTagDef->isMultiple())
            throw new NodeException('Cannot have more than 1 tree origin tag');

        if($treeOriginTagDef->Direction == 'out')
            $treeOrigin = $node->getOutTag($treeOriginTagDef->Id);
        else
            $treeOrigin = $node->getInTag($treeOriginTagDef->Id);

        if(empty($treeOrigin))
            throw new NodeException('Cannot insert a node into the tree without the tree origin tag');

        $treeOriginPartial = $treeOrigin->toPartial();

        $parentTreeID = '';
        if($node->getTreeParent() != false)
        {
            $parentNode = $this->NodeLookupDAO->getByNodeRef(new NodeRef($node->getNodeRef()->getElement(), $node->getTreeParent()));

            $parentTreeID = $parentNode->TreeID;
        }

        // fetch max tree id (if parentTreeID is blank, return last top-level tree id)
        $maxChildTreeID = $this->fetchMaxChildTreeID($node, $treeOriginTagDef, $treeOriginPartial, $parentTreeID);

        if(!is_null($existingNode) && $maxChildTreeID == $existingNode->TreeID)
        {
            $node->TreeID = $existingNode->TreeID;
            return;
        }

        if(empty($maxChildTreeID))
        {
            $newTreeID = $parentTreeID . '0001';

        // add this to the children
        } else {

            $last4 = substr($maxChildTreeID, -4);
            if(strtolower($last4) == 'ffff')
                throw new NodeException('This tree leaf has reached the limit of its children');

            $newTreeID = $parentTreeID . str_pad(dechex(hexdec($last4)+1), 4, '0', STR_PAD_LEFT);
        }

        while(!$this->Locks->getLock('treeid:'.$treeOriginPartial.':'.$newTreeID, 0)) {

            $last4 = substr($newTreeID, -4);
            if(strtolower($last4) == 'ffff')
                throw new NodeException('This tree leaf has reached the limit of its children');

            $newTreeID = $parentTreeID . str_pad(dechex(hexdec($last4)+1), 4, '0', STR_PAD_LEFT);

        }

        $node->TreeID = $newTreeID;
    }