/***
 * modyfikacja kodu
 * 
 * wymaga dolaczenia biblioteki prototype.js, scriptaculous.js, window.js as prototype
 * 
 * dla potrzeb skryptu w stronie nalezy umiescic

	kontenery paneli edycyjnych
                        <div id="container" style="visibility:hidden;height:0px;">
                            <div id="winContext" style="width:450px;height:60px;padding:5px;text-align:center;">
                                <!-- div from winow alert or editor context, this id=winContext from configure script tree -->
                            </div>
                        </div>
                        <div id="editContainer" style="visibility:hidden;height:0px;">
                            <div id="editContext" style="width:520px;height:320px;padding:5px;">
                            </div>
                        </div>

  	kontener danych o id=editorTreeContainer zawiera caly edytor drzew danych, 
  	do niego nalezy wpisac drzewo danych, kontenery paneli edycyjnych powinny byc poza nim.
  	w przpadku utworzenia nowego drzea danych cala zawartosc kontenera danych jest usuwana, 
  	a nowe drzewo danych otrzymuje poprzednie id
  	
  	
  	nowe drzewo danych nalezy przekazac z serwera i ponownie zainicjowac klase obslugi drzew danych



;funkcja inicjowania tree edit

function editTreeInit(idName){
    treeObj = null;
	treeObj = new JSDragDropTree('lib/tree/images/');
    treeObj.setTreeId(idName);
    treeObj.setMaximumDepth(5);
    treeObj.setMessageMaximumDepthReached("Koniec mozliwosci zagniezdzania,\n maximum to 5 poziomow");
    
	treeObj.my_setLogsContainter("messageSites"); // id kontenera na logi z przetwarzania drzewa danych do posaci wymaganej przez server
	treeObj.my_setNaviButton(['save','colapse','expand','edittree','newtree','deltree']); // buttony nawigatora nad drzewem danych
	treeObj.my_setIsNavigate(true); // czy pokazywac nawigator nad drzewem danych
	treeObj.my_setIsEdit(true); // czy uruchamiac edytor drzewa danych
	treeObj.my_setListTree([
		{'_tName':'menuAdmin','_tLabel':'Administrator','_tContext':'opis','value':'1'},
		{'_tName':'menuRed','_tLabel':'Redaktor','_tContext':'opis','value':'2'},
		{'_tName':'menuPowiat','_tLabel':'Powiat','_tContext':'opis','value':'3','selected':'selected'},
		{'_tName':'menuGalery','_tLabel':'Galeria','_tContext':'opis','value':'4'}
	]);
	treeObj.my_setCommandItem([
		{'_tName':'dispDocument','_tLabel':'Dokumenty','_tContext':'opis','value':'1'},
		{'_tName':'funcGal','_tLabel':'Galeria','_tContext':'opis','value':'2'},
		{'_tName':'funcKat','_tLabel':'Katalog','_tContext':'opis','value':'3'},
		{'_tName':'funcNews','_tLabel':'News-y','_tContext':'opis','value':'4'}
	]);
	treeObj.initTree();

}

*/


/************************************************************************************************************
 Drag and drop folder tree
 Copyright (C) 2006  DTHMLGoodies.com, Alf Magne Kalleland
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.
 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
 written by Alf Magne Kalleland.
 Alf Magne Kalleland, 2006
 Owner of DHTMLgoodies.com
 ************************************************************************************************************/
var JSTreeObj;
var treeUlCounter = 0;
var nodeId = 1;
var contentWin;
var contentEdit;

/* Constructor */
function JSDragDropTree(imgPath){
    var idOfTree;
    var imageFolder;
    var folderImage;
    var plusImage;
    var minusImage;
    var maximumDepth;
    var dragNode_source;
    var dragNode_parent;
    var dragNode_sourceNextSib;
    var dragNode_noSiblings;
    var ajaxObjects;
    
    var dragNode_destination;
    var floatingContainer;
    var dragDropTimer;
    var dropTargetIndicator;
    var insertAsSub;
    var indicator_offsetX;
    var indicator_offsetX_sub;
    var indicator_offsetY;
    
    this.imageFolder = imgPath;
    this.folderImage = 'dhtmlgoodies_folder.gif';
    this.plusImage = 'dhtmlgoodies_plus.gif';
    this.minusImage = 'dhtmlgoodies_minus.gif';
    this.maximumDepth = 6;
    var messageMaximumDepthReached;
    var filePathRenameItem;
    var filePathDeleteItem;
    var additionalRenameRequestParameters = {};
    var additionalDeleteRequestParameters = {};
    
    var renameAllowed;
    var deleteAllowed;
    var currentlyActiveItem;
    var contextMenu;
    var currentItemToEdit; // Reference to item currently being edited(example: renamed)
    var helpObj;
	/* zmienne dla funkcji zapisu do postaci urlencode drzewa danych */
	var gbj;
	var left=0;
	var level = 0;
    var ltb;
	var logsContainer;
	var cssDivButton;
	var cssButton;
	var isEdit;
	var isnavigate;
	var eName;
	var eLabel;
	var eContent;
	var arrayButton;
	var winContainer;
	var editContext;
	var newID;
	var existTreeList; // list exist tree - array
	var existCommandItem; // list function from item execute - array
	var firstElementTree; // ref. do pierwszego elementu drzewa 
	
	this.cssDivButton='nic';
	this.cssButton='nic';
	this.isEdit=false;
	this.isnavigate=false;
	this.winContainer='winContext';
	this.editContext='editContext';

    this.contextMenu = false;
    this.floatingContainer = document.createElement('UL');
    this.floatingContainer.style.position = 'absolute';
    this.floatingContainer.style.display = 'none';
    this.floatingContainer.id = 'floatingContainer';
    this.insertAsSub = false;
    document.body.appendChild(this.floatingContainer);
    this.dragDropTimer = -1;
    this.dragNode_noSiblings = false;
    this.currentItemToEdit = false;
    
    if (document.all) {
        this.indicator_offsetX = 2; // Offset position of small black lines indicating where nodes would be dropped.
        this.indicator_offsetX_sub = 4;
        this.indicator_offsetY = 2;
    }
    else {
        this.indicator_offsetX = 1; // Offset position of small black lines indicating where nodes would be dropped.
        this.indicator_offsetX_sub = 3;
        this.indicator_offsetY = 2;
    }
    if (navigator.userAgent.indexOf('Opera') >= 0) {
        this.indicator_offsetX = 2; // Offset position of small black lines indicating where nodes would be dropped.
        this.indicator_offsetX_sub = 3;
        this.indicator_offsetY = -7;
    }
    
    this.messageMaximumDepthReached = ''; // Use '' if you don't want to display a message 
    this.renameAllowed = true;
    this.deleteAllowed = true;
    this.currentlyActiveItem = false;
    this.filePathRenameItem = 'folderTree_updateItem.php';
    this.filePathDeleteItem = 'folderTree_updateItem.php';
    this.ajaxObjects = new Array();
    this.helpObj = false;
    
    this.RENAME_STATE_BEGIN = 1;
    this.RENAME_STATE_CANCELED = 2;
    this.RENAME_STATE_REQUEST_SENDED = 3;
    this.renameState = null;
}


/* JSDragDropTree class */
JSDragDropTree.prototype = {
    // {{{ addEvent()
    /**
     *
     *  This function adds an event listener to an element on the page.
     *
     *	@param Object whichObject = Reference to HTML element(Which object to assigne the event)
     *	@param String eventType = Which type of event, example "mousemove" or "mouseup"
     *	@param functionName = Name of function to execute.
     *
     * @public
     */
    addEvent: function(whichObject, eventType, functionName){
        if (whichObject.attachEvent) {
            whichObject['e' + eventType + functionName] = functionName;
            whichObject[eventType + functionName] = function(){
                whichObject['e' + eventType + functionName](window.event);
            }
            whichObject.attachEvent('on' + eventType, whichObject[eventType + functionName]);
        }
        else 
            whichObject.addEventListener(eventType, functionName, false);
    } // }}}	
    ,
    // {{{ removeEvent()
    /**
     *
     *  This function removes an event listener from an element on the page.
     *
     *	@param Object whichObject = Reference to HTML element(Which object to assigne the event)
     *	@param String eventType = Which type of event, example "mousemove" or "mouseup"
     *	@param functionName = Name of function to execute.
     *
     * @public
     */
    removeEvent: function(whichObject, eventType, functionName){
        if (whichObject.detachEvent) {
            whichObject.detachEvent('on' + eventType, whichObject[eventType + functionName]);
            whichObject[eventType + functionName] = null;
        }
        else 
            whichObject.removeEventListener(eventType, functionName, false);
    },
    Get_Cookie: function(name){
        var start = document.cookie.indexOf(name + "=");
        var len = start + name.length + 1;
        if ((!start) && (name != document.cookie.substring(0, name.length))) 
            return null;
        if (start == -1) 
            return null;
        var end = document.cookie.indexOf(";", len);
        if (end == -1) 
            end = document.cookie.length;
        return unescape(document.cookie.substring(len, end));
    },
    // This function has been slightly modified
    Set_Cookie: function(name, value, expires, path, domain, secure){
        expires = expires * 60 * 60 * 24 * 1000;
        var today = new Date();
        var expires_date = new Date(today.getTime() + (expires));
        var cookieString = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
        document.cookie = cookieString;
    },
    setFileNameRename: function(newFileName){
        this.filePathRenameItem = newFileName;
    },
    setFileNameDelete: function(newFileName){
        this.filePathDeleteItem = newFileName;
    },
    setAdditionalRenameRequestParameters: function(requestParameters){
        this.additionalRenameRequestParameters = requestParameters;
    },
    setAdditionalDeleteRequestParameters: function(requestParameters){
        this.additionalDeleteRequestParameters = requestParameters;
    },
    setRenameAllowed: function(renameAllowed){
        this.renameAllowed = renameAllowed;
    },
    setDeleteAllowed: function(deleteAllowed){
        this.deleteAllowed = deleteAllowed;
    },
    setMaximumDepth: function(maxDepth){
        this.maximumDepth = maxDepth;
    },
    setMessageMaximumDepthReached: function(newMessage){
        this.messageMaximumDepthReached = newMessage;
    },
    setImageFolder: function(path){
        this.imageFolder = path;
    },
    setFolderImage: function(imagePath){
        this.folderImage = imagePath;
    },
    setPlusImage: function(imagePath){
        this.plusImage = imagePath;
    },
    setMinusImage: function(imagePath){
        this.minusImage = imagePath;
    },
    setTreeId: function(idOfTree){
        this.idOfTree = idOfTree;
    },
	setListExistTree:function(v){
		this.existTreeList=v;
	},
	setListCommandExist:function(v){
		this.existCommandItem=v;
	},
    expandAll: function(){
        var menuItems = document.getElementById(this.idOfTree).getElementsByTagName('LI');
        for (var no = 0; no < menuItems.length; no++) {
            var subItems = menuItems[no].getElementsByTagName('UL');
            if (subItems.length > 0 && subItems[0].style.display != 'block') {
                JSTreeObj.showHideNode(false, menuItems[no].id);
            }
        }
    },
    collapseAll: function(){
        var menuItems = document.getElementById(this.idOfTree).getElementsByTagName('LI');
        for (var no = 0; no < menuItems.length; no++) {
            var subItems = menuItems[no].getElementsByTagName('UL');
            if (subItems.length > 0 && subItems[0].style.display == 'block') {
                JSTreeObj.showHideNode(false, menuItems[no].id);
            }
        }
    },
    /*
     Find top pos of a tree node
     */
    getTopPos: function(obj){
        var top = obj.offsetTop / 1;
        while ((obj = obj.offsetParent) != null) {
            if (obj.tagName != 'HTML') 
                top += obj.offsetTop;
        }
        if (document.all) 
            top = top / 1 + 13;
        else 
            top = top / 1 + 4;
        return top;
    },
    /*
     Find left pos of a tree node
     */
    getLeftPos: function(obj){
        var left = obj.offsetLeft / 1 + 1;
        while ((obj = obj.offsetParent) != null) {
            if (obj.tagName != 'HTML') 
                left += obj.offsetLeft;
        }
        
        if (document.all) 
            left = left / 1 - 2;
        return left;
    },
    showHideNode: function(e, inputId){
        if (inputId) {
            if (!document.getElementById(inputId)) 
                return;
            thisNode = document.getElementById(inputId).getElementsByTagName('IMG')[0];
        }
        else {
            thisNode = this;
            if (this.tagName == 'A') 
                thisNode = this.parentNode.getElementsByTagName('IMG')[0];
            
        }
        if (thisNode.style.visibility == 'hidden') 
            return;
        var parentNode = thisNode.parentNode;
        inputId = parentNode.id.replace(/[^0-9]/g, '');
        if (thisNode.src.indexOf(JSTreeObj.plusImage) >= 0) {
            thisNode.src = thisNode.src.replace(JSTreeObj.plusImage, JSTreeObj.minusImage);
            var ul = parentNode.getElementsByTagName('UL')[0];
            ul.style.display = 'block';
            if (!initExpandedNodes) 
                initExpandedNodes = ',';
            if (initExpandedNodes.indexOf(',' + inputId + ',') < 0) 
                initExpandedNodes = initExpandedNodes + inputId + ',';
        }
        else {
            thisNode.src = thisNode.src.replace(JSTreeObj.minusImage, JSTreeObj.plusImage);
            parentNode.getElementsByTagName('UL')[0].style.display = 'none';
            initExpandedNodes = initExpandedNodes.replace(',' + inputId, '');
        }
        JSTreeObj.Set_Cookie('dhtmlgoodies_expandedNodes', initExpandedNodes, 500);
        return false;
    },
    /* Initialize drag */
    initDrag: function(e){
        if (document.all) 
            e = event;
        
        var subs = JSTreeObj.floatingContainer.getElementsByTagName('LI');
        if (subs.length > 0) {
            if (JSTreeObj.dragNode_sourceNextSib) {
                JSTreeObj.dragNode_parent.insertBefore(JSTreeObj.dragNode_source, JSTreeObj.dragNode_sourceNextSib);
            }
            else {
                JSTreeObj.dragNode_parent.appendChild(JSTreeObj.dragNode_source);
            }
        }
        
        JSTreeObj.dragNode_source = this.parentNode;
        JSTreeObj.dragNode_parent = this.parentNode.parentNode;
        JSTreeObj.dragNode_sourceNextSib = false;
        
        
        if (JSTreeObj.dragNode_source.nextSibling) 
            JSTreeObj.dragNode_sourceNextSib = JSTreeObj.dragNode_source.nextSibling;
        JSTreeObj.dragNode_destination = false;
        JSTreeObj.dragDropTimer = 0;
        JSTreeObj.timerDrag();
        return false;
    },
    timerDrag: function(){
        if (this.dragDropTimer >= 0 && this.dragDropTimer < 10) {
            this.dragDropTimer = this.dragDropTimer + 1;
            setTimeout('JSTreeObj.timerDrag()', 20);
            return;
        }
        if (this.dragDropTimer == 10) {
            JSTreeObj.floatingContainer.style.display = 'block';
            JSTreeObj.floatingContainer.appendChild(JSTreeObj.dragNode_source);
        }
    },
    moveDragableNodes: function(e){
        if (JSTreeObj.dragDropTimer < 10) 
            return;
        if (document.all) 
            e = event;
        dragDrop_x = e.clientX / 1 + 5 + document.body.scrollLeft;
        dragDrop_y = e.clientY / 1 + 5 + document.documentElement.scrollTop;
        
        JSTreeObj.floatingContainer.style.left = dragDrop_x + 'px';
        JSTreeObj.floatingContainer.style.top = dragDrop_y + 'px';
        
        var thisObj = this;
        if (thisObj.tagName == 'A' || thisObj.tagName == 'IMG') 
            thisObj = thisObj.parentNode;
        
        JSTreeObj.dragNode_noSiblings = false;
        var tmpVar = thisObj.getAttribute('noSiblings');
        if (!tmpVar) 
            tmpVar = thisObj.noSiblings;
        if (tmpVar == 'true') 
            JSTreeObj.dragNode_noSiblings = true;
        
        if (thisObj && thisObj.id) {
            JSTreeObj.dragNode_destination = thisObj;
            var img = thisObj.getElementsByTagName('IMG')[1];
            var tmpObj = JSTreeObj.dropTargetIndicator;
            tmpObj.style.display = 'block';
            
            var eventSourceObj = this;
            if (JSTreeObj.dragNode_noSiblings && eventSourceObj.tagName == 'IMG') 
                eventSourceObj = eventSourceObj.nextSibling;
            
            var tmpImg = tmpObj.getElementsByTagName('IMG')[0];
            if (this.tagName == 'A' || JSTreeObj.dragNode_noSiblings) {
                tmpImg.src = tmpImg.src.replace('ind1', 'ind2');
                JSTreeObj.insertAsSub = true;
                tmpObj.style.left = (JSTreeObj.getLeftPos(eventSourceObj) + JSTreeObj.indicator_offsetX_sub) + 'px';
            }
            else {
                tmpImg.src = tmpImg.src.replace('ind2', 'ind1');
                JSTreeObj.insertAsSub = false;
                tmpObj.style.left = (JSTreeObj.getLeftPos(eventSourceObj) + JSTreeObj.indicator_offsetX) + 'px';
            }
            
            
            tmpObj.style.top = (JSTreeObj.getTopPos(thisObj) + JSTreeObj.indicator_offsetY) + 'px';
        }
        
        return false;
        
    },
    dropDragableNodes: function(){
        if (JSTreeObj.dragDropTimer < 10) {
            JSTreeObj.dragDropTimer = -1;
            return;
        }
        var showMessage = false;
        if (JSTreeObj.dragNode_destination) { // Check depth
            var countUp = JSTreeObj.dragDropCountLevels(JSTreeObj.dragNode_destination, 'up');
            var countDown = JSTreeObj.dragDropCountLevels(JSTreeObj.dragNode_source, 'down');
            var countLevels = countUp / 1 + countDown / 1 + (JSTreeObj.insertAsSub ? 1 : 0);
            
            if (countLevels > JSTreeObj.maximumDepth) {
                JSTreeObj.dragNode_destination = false;
                showMessage = true; // Used later down in this function
            }
        }
        
        
        if (JSTreeObj.dragNode_destination) {
            if (JSTreeObj.insertAsSub) {
                var uls = JSTreeObj.dragNode_destination.getElementsByTagName('UL');
                if (uls.length > 0) {
                    ul = uls[0];
                    ul.style.display = 'block';
                    
                    var lis = ul.getElementsByTagName('LI');
                    
                    if (lis.length > 0) { // Sub elements exists - drop dragable node before the first one
                        ul.insertBefore(JSTreeObj.dragNode_source, lis[0]);
                    }
                    else { // No sub exists - use the appendChild method - This line should not be executed unless there's something wrong in the HTML, i.e empty <ul>
                        ul.appendChild(JSTreeObj.dragNode_source);
                    }
                }
                else {
                    var ul = document.createElement('UL');
                    ul.style.display = 'block';
                    JSTreeObj.dragNode_destination.appendChild(ul);
                    ul.appendChild(JSTreeObj.dragNode_source);
                }
                var img = JSTreeObj.dragNode_destination.getElementsByTagName('IMG')[0];
                img.style.visibility = 'visible';
                img.src = img.src.replace(JSTreeObj.plusImage, JSTreeObj.minusImage);
                
                
            }
            else {
                if (JSTreeObj.dragNode_destination.nextSibling) {
                    var nextSib = JSTreeObj.dragNode_destination.nextSibling;
                    nextSib.parentNode.insertBefore(JSTreeObj.dragNode_source, nextSib);
                }
                else {
                    JSTreeObj.dragNode_destination.parentNode.appendChild(JSTreeObj.dragNode_source);
                }
            }
            /* Clear parent object */
            var tmpObj = JSTreeObj.dragNode_parent;
            var lis = tmpObj.getElementsByTagName('LI');
            if (lis.length == 0) {
                var img = tmpObj.parentNode.getElementsByTagName('IMG')[0];
                img.style.visibility = 'hidden'; // Hide [+],[-] icon
                tmpObj.parentNode.removeChild(tmpObj);
            }
            
        }
        else {
            // Putting the item back to it's original location
            
            if (JSTreeObj.dragNode_sourceNextSib) {
                JSTreeObj.dragNode_parent.insertBefore(JSTreeObj.dragNode_source, JSTreeObj.dragNode_sourceNextSib);
            }
            else {
                JSTreeObj.dragNode_parent.appendChild(JSTreeObj.dragNode_source);
            }
            
        }
        JSTreeObj.dropTargetIndicator.style.display = 'none';
        JSTreeObj.dragDropTimer = -1;
        if (showMessage && JSTreeObj.messageMaximumDepthReached) 
            alert(JSTreeObj.messageMaximumDepthReached);
    },
    createDropIndicator: function(){
        this.dropTargetIndicator = document.createElement('DIV');
        this.dropTargetIndicator.style.position = 'absolute';
        this.dropTargetIndicator.style.display = 'none';
        var img = document.createElement('IMG');
        img.src = this.imageFolder + 'dragDrop_ind1.gif';
        img.id = 'dragDropIndicatorImage';
        this.dropTargetIndicator.appendChild(img);
        document.body.appendChild(this.dropTargetIndicator);
        
    },
    dragDropCountLevels: function(obj, direction, stopAtObject){
        var countLevels = 0;
        if (direction == 'up') {
            while (obj.parentNode && obj.parentNode != stopAtObject) {
                obj = obj.parentNode;
                if (obj.tagName == 'UL') 
                    countLevels = countLevels / 1 + 1;
            }
            return countLevels;
        }
        
        if (direction == 'down') {
            var subObjects = obj.getElementsByTagName('LI');
            for (var no = 0; no < subObjects.length; no++) {
                countLevels = Math.max(countLevels, JSTreeObj.dragDropCountLevels(subObjects[no], "up", obj));
            }
            return countLevels;
        }
    },
    cancelEvent: function(){
        return false;
    },
    cancelSelectionEvent: function(){
    
        if (JSTreeObj.dragDropTimer < 10) 
            return true;
        return false;
    },
    getNodeOrders: function(initObj, saveString){
    
        if (!saveString) 
            var saveString = '';
        if (!initObj) {
            initObj = document.getElementById(this.idOfTree);
            
        }
        var lis = initObj.getElementsByTagName('LI');
        
        if (lis.length > 0) {
            var li = lis[0];
            while (li) {
                if (li.id) {
                    if (saveString.length > 0) 
                        saveString = saveString + ',';
                    var numericID = li.id.replace(/[^0-9]/gi, '');
                    if (numericID.length == 0) 
                        numericID = 'A';
                    var numericParentID = li.parentNode.parentNode.id.replace(/[^0-9]/gi, '');
                    if (numericID != '0') {
                        saveString = saveString + numericID;
                        saveString = saveString + '-';
                        
                        
                        if (li.parentNode.id != this.idOfTree) 
                            saveString = saveString + numericParentID;
                        else 
                            saveString = saveString + '0';
                    }
                    var ul = li.getElementsByTagName('UL');
                    if (ul.length > 0) {
                        saveString = this.getNodeOrders(ul[0], saveString);
                    }
                }
                li = li.nextSibling;
            }
        }
        
        if (initObj.id == this.idOfTree) {
            return saveString;
            
        }
        return saveString;
    },
    highlightItem: function(inputObj, e){
        if (JSTreeObj.currentlyActiveItem) 
            JSTreeObj.currentlyActiveItem.className = '';
        this.className = 'highlightedNodeItem';
        JSTreeObj.currentlyActiveItem = this;
    },
    removeHighlight: function(){
        if (JSTreeObj.currentlyActiveItem) 
            JSTreeObj.currentlyActiveItem.className = '';
        JSTreeObj.currentlyActiveItem = false;
    },
    hasSubNodes: function(obj){
        var subs = obj.getElementsByTagName('LI');
        if (subs.length > 0) 
            return true;
        return false;
    },
    deleteItem: function(obj1, obj2){
        var message = 'Click OK to delete item ' + obj2.innerHTML;
        if (this.hasSubNodes(obj2.parentNode)) 
            message = message + ' and it\'s sub nodes';
        if (confirm(message)) {
            this.__deleteItem_step2(obj2.parentNode); // Sending <LI> tag to the __deleteItem_step2 method	
        }
        
    },
    __refreshDisplay: function(obj){
        if (this.hasSubNodes(obj)) 
            return;
        var img = obj.getElementsByTagName('IMG')[0];
        img.style.visibility = 'hidden';
    },
    __deleteItem_step2: function(obj){
        var saveString = obj.id.replace(/[^0-9]/gi, '');
        
        var lis = obj.getElementsByTagName('LI');
        for (var no = 0; no < lis.length; no++) {
            saveString = saveString + ',' + lis[no].id.replace(/[^0-9]/gi, '');
        }
        // Creating ajax object and send items
        var ajaxIndex = JSTreeObj.ajaxObjects.length;
        JSTreeObj.ajaxObjects[ajaxIndex] = new sack();
        JSTreeObj.ajaxObjects[ajaxIndex].method = "GET";
        JSTreeObj.ajaxObjects[ajaxIndex].setVar("deleteIds", saveString);
        JSTreeObj.__addAdditionalRequestParameters(JSTreeObj.ajaxObjects[ajaxIndex], JSTreeObj.additionalDeleteRequestParameters);
        JSTreeObj.ajaxObjects[ajaxIndex].requestFile = JSTreeObj.filePathDeleteItem; // Specifying which file to get
        JSTreeObj.ajaxObjects[ajaxIndex].onCompletion = function(){
            JSTreeObj.__deleteComplete(ajaxIndex, obj);
        }; // Specify function that will be executed after file has been found
        JSTreeObj.ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function				
    },
    __deleteComplete: function(ajaxIndex, obj){
        if (this.ajaxObjects[ajaxIndex].response != 'OK') {
            alert('ERROR WHEN TRYING TO DELETE NODE: ' + this.ajaxObjects[ajaxIndex].response); // Rename failed
        }
        else {
            var parentRef = obj.parentNode.parentNode;
            obj.parentNode.removeChild(obj);
            this.__refreshDisplay(parentRef);
            
        }
        
    },
    __renameComplete: function(ajaxIndex){
        if (this.ajaxObjects[ajaxIndex].response != 'OK') {
            alert('ERROR WHEN TRYING TO RENAME NODE: ' + this.ajaxObjects[ajaxIndex].response); // Rename failed
        }
    },
    __saveTextBoxChanges: function(e, inputObj){
        if (!inputObj && this) 
            inputObj = this;
        if (document.all) 
            e = event;
        if (e.keyCode && e.keyCode == 27) {
            JSTreeObj.__cancelRename(e, inputObj);
            return;
        }
        inputObj.style.display = 'none';
        inputObj.nextSibling.style.visibility = 'visible';
        if (inputObj.value.length > 0) {
            inputObj.nextSibling.innerHTML = inputObj.value;
            // Send changes to the server.
            if (JSTreeObj.renameState != JSTreeObj.RENAME_STATE_BEGIN) {
                return;
            }
            JSTreeObj.renameState = JSTreeObj.RENAME_STATE_REQUEST_SENDED;
            
            var ajaxIndex = JSTreeObj.ajaxObjects.length;
            JSTreeObj.ajaxObjects[ajaxIndex] = new sack();
            JSTreeObj.ajaxObjects[ajaxIndex].method = "GET";
            JSTreeObj.ajaxObjects[ajaxIndex].setVar("renameId", inputObj.parentNode.id.replace(/[^0-9]/gi, ''));
            JSTreeObj.ajaxObjects[ajaxIndex].setVar("newName", inputObj.value);
            JSTreeObj.__addAdditionalRequestParameters(JSTreeObj.ajaxObjects[ajaxIndex], JSTreeObj.additionalRenameRequestParameters);
            JSTreeObj.ajaxObjects[ajaxIndex].requestFile = JSTreeObj.filePathRenameItem; // Specifying which file to get
            JSTreeObj.ajaxObjects[ajaxIndex].onCompletion = function(){
                JSTreeObj.__renameComplete(ajaxIndex);
            }; // Specify function that will be executed after file has been found
            JSTreeObj.ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function		
        }
    },
    __cancelRename: function(e, inputObj){
        JSTreeObj.renameState = JSTreeObj.RENAME_STATE_CANCELD;
        if (!inputObj && this) 
            inputObj = this;
        inputObj.value = JSTreeObj.helpObj.innerHTML;
        inputObj.nextSibling.innerHTML = JSTreeObj.helpObj.innerHTML;
        inputObj.style.display = 'none';
        inputObj.nextSibling.style.visibility = 'visible';
    },
    __renameCheckKeyCode: function(e){
        if (document.all) 
            e = event;
        if (e.keyCode == 13) { // Enter pressed
            JSTreeObj.__saveTextBoxChanges(false, this);
        }
        if (e.keyCode == 27) { // ESC pressed
            JSTreeObj.__cancelRename(false, this);
        }
    },
    __createTextBox: function(obj){
        var textBox = document.createElement('INPUT');
        textBox.className = 'folderTreeTextBox';
        textBox.value = obj.innerHTML;
        obj.parentNode.insertBefore(textBox, obj);
        textBox.id = 'textBox' + obj.parentNode.id.replace(/[^0-9]/gi, '');
        textBox.onblur = this.__saveTextBoxChanges;
        textBox.onkeydown = this.__renameCheckKeyCode;
        this.__renameEnableTextBox(obj);
    },
    __renameEnableTextBox: function(obj){
        JSTreeObj.renameState = JSTreeObj.RENAME_STATE_BEGIN;
        obj.style.visibility = 'hidden';
        obj.previousSibling.value = obj.innerHTML;
        obj.previousSibling.style.display = 'inline';
        obj.previousSibling.select();
    },
    renameItem: function(obj1, obj2){
        currentItemToEdit = obj2.parentNode; // Reference to the <li> tag.
        if (!obj2.previousSibling || obj2.previousSibling.tagName.toLowerCase() != 'input') {
            this.__createTextBox(obj2);
        }
        else {
            this.__renameEnableTextBox(obj2);
        }
        this.helpObj.innerHTML = obj2.innerHTML;
        
    },
    initTree: function(){
		this.newID=$(this.idOfTree).getElementsBySelector('LI').length;
		this.newID+=1001;
        JSTreeObj = this;
        JSTreeObj.createDropIndicator();
        document.documentElement.onselectstart = JSTreeObj.cancelSelectionEvent;
        document.documentElement.ondragstart = JSTreeObj.cancelEvent;
        document.documentElement.onmousedown = JSTreeObj.removeHighlight;
        
        /* Creating help object for storage of values */
        this.helpObj = document.createElement('DIV');
        this.helpObj.style.display = 'none';
        document.body.appendChild(this.helpObj);

        var nodeId = 0;
        var dhtmlgoodies_tree = document.getElementById(this.idOfTree);
        var menuItems = dhtmlgoodies_tree.getElementsByTagName('LI'); // Get an array of all menu items
        for (var no = 0; no < menuItems.length; no++) {
            // No children var set ?
            var noChildren = false;
            var tmpVar = menuItems[no].getAttribute('noChildren');
            if (!tmpVar) 
                tmpVar = menuItems[no].noChildren;
            if (tmpVar == 'true') 
                noChildren = true;
            // No drag var set ?
            var noDrag = false;
            var tmpVar = menuItems[no].getAttribute('noDrag');
            if (!tmpVar) 
                tmpVar = menuItems[no].noDrag;
            if (tmpVar == 'true') 
                noDrag = true;
            
            nodeId++;
            var subItems = menuItems[no].getElementsByTagName('UL');
            var img = document.createElement('IMG');
            img.src = this.imageFolder + this.plusImage;
            img.onclick = JSTreeObj.showHideNode;
            
            if (subItems.length == 0) 
                img.style.visibility = 'hidden';
            else {
                subItems[0].id = 'tree_ul_' + treeUlCounter;
                treeUlCounter++;
            }
            var aTag = menuItems[no].getElementsByTagName('A')[0];
            aTag.id = 'nodeATag' + menuItems[no].id.replace(/[^0-9]/gi, '');
            //aTag.onclick = JSTreeObj.showHideNode;
            if (!noDrag) aTag.onmousedown = JSTreeObj.initDrag;
            if (!noChildren) aTag.onmousemove = JSTreeObj.moveDragableNodes;
			// aTag.onmouseover = JSTreeObj.highlightItem;
			// aTag.onmouseout = JSTreeObj.removeHighlight;
            menuItems[no].insertBefore(img, aTag);
            //menuItems[no].id = 'dhtmlgoodies_treeNode' + nodeId;
            var folderImg = document.createElement('IMG');
            if (!noDrag) 
                folderImg.onmousedown = JSTreeObj.initDrag;
            folderImg.onmousemove = JSTreeObj.moveDragableNodes;
            if (menuItems[no].className) {
                folderImg.src = this.imageFolder + menuItems[no].className;
            }
            else {
                folderImg.src = this.imageFolder + this.folderImage;
            }
            menuItems[no].insertBefore(folderImg, aTag);
            if(this.isEdit){
				JSTreeObj.addEvent(aTag,'dblclick',JSTreeObj.my_dblClicked);
			}
			document.documentElement.onmousemove = JSTreeObj.moveDragableNodes;	
			document.documentElement.onmouseup = JSTreeObj.dropDragableNodes;
        }
        
        
        
        initExpandedNodes = this.Get_Cookie('dhtmlgoodies_expandedNodes');
        if (initExpandedNodes) {
            var nodes = initExpandedNodes.split(',');
            for (var no = 0; no < nodes.length; no++) {
                if (nodes[no]) 
                    this.showHideNode(false, nodes[no]);
            }
        }
        
        
        document.documentElement.onmousemove = JSTreeObj.moveDragableNodes;
        document.documentElement.onmouseup = JSTreeObj.dropDragableNodes;
		// buttony nawigacyjne nad drzewem danych
		if(JSTreeObj.isnavigate){
			JSTreeObj.my_buttonEdit();
		}
    },
    __addAdditionalRequestParameters: function(ajax, parameters){
        for (var parameter in parameters) {
            ajax.setVar(parameter, parameters[parameter]);
        }
    }, 
	/* ##################################################################### */    
	/* ##################################################################### */
	/* ####################### me function from tree ####################### */
	my_setLogsContainter:function(v){
		this.logsContainer = v;
	},
	my_setCssDivButton:function(v){
		this.cssDivButton=v;
	},
	my_setCssButton:function(v){
		this.cssButton=v;
	},
	my_setIsEdit:function(v){
		this.isEdit=v;
	},
	my_setIsNavigate:function(v){
		this.isnavigate=v;
	},
	my_setNaviButton:function(v){
		this.arrayButton=v;
	},
	my_setWinContainer:function(v){
		this.winContext=v;
	},
	my_setEditContext:function(v){
		this.editContext=v;
	},
	my_setListTree:function(v){
		this.existTreeList=$('treeList').innerHTML;
	},
	my_setCommandItem:function(v){
		this.existCommandItem=$('treeCmd').innerHTML;
	},
	my_firstElements:function(){
		this.firstElementTree=$(this.idOfTree).firstDescendant();
	},
	my_updateNode:function(aId,liId){
		/** aktualizacja attrybutow LI */
		
		// funkcja wykonawcza
		if($('funcname').value!=''){
			$(liId).writeAttribute('link',$('funcname').value);
			$(liId).writeAttribute('type', '0');
		} else {
			$(liId).writeAttribute('type', $('selfntree_1').value);
		}
		/** tylko w przypadku pierwszego elementu */
		if($(liId).readAttribute('id')=='1'){
			if ($('poletpl').value != ''){
				$(liId).writeAttribute('poletpl',$('poletpl').value);
			}
			if($('lpmenu').value!=''){
				$(liId).writeAttribute('lpmenu',$('lpmenu').value);
			}
			if($('isactive2').checked){
				$(liId).writeAttribute('statusr','1');
			} else {
				$(liId).writeAttribute('statusr','0');
			}
		}
		// stale przypisane tylko do pierwszego elementu listy
		$(liId).writeAttribute('funkcjad', $(JSTreeObj.firstElementTree).readAttribute('funkcjad'));
		$(liId).writeAttribute('poletpl',$(JSTreeObj.firstElementTree).readAttribute('poletpl'));
		$(liId).writeAttribute('lpmenu',$(JSTreeObj.firstElementTree).readAttribute('lpmenu'));
		$(liId).writeAttribute('statusr',$(JSTreeObj.firstElementTree).readAttribute('statusr'));
		$(liId).writeAttribute('idtree',$(JSTreeObj.firstElementTree).readAttribute('idtree'));
		$(liId).writeAttribute('ident',$(JSTreeObj.firstElementTree).readAttribute('ident'));
		// etykieta
		$(aId).update($('titleEditElement').value);
	},
	my_readNodeToWindow:function(aId,liId,toAll){
		/** odczyt attrybutow LI */
		if(toAll){
			var isAll=true;
		} else {
			var isAll=false;
		}
		
		$('poletpl').value = $(JSTreeObj.firstElementTree).readAttribute('poletpl');
		$('lpmenu').value = $(JSTreeObj.firstElementTree).readAttribute('lpmenu');
		// aktywne / nie aktywne
		var statusr=$(JSTreeObj.firstElementTree).readAttribute('statusr')
		if(statusr=='1'){
			$('isactive2').checked=true;
		} else {
			$('isactive1').checked=true;
		}
		// funkcja wykonawcza
		if (isAll) {
			$('funcname').value = $(liId).readAttribute('link');
			$('titleEditElement').value = $(aId).innerHTML;
		}
		// UZUPELNIC selekcje funkcji z listy
		// dektywacja elementow aktywnych tylko dla pierwszego elementu
		if($(liId).readAttribute('id')!='1'){
			$('poletpl').disable();
			$('lpmenu').disable();
			$('isactive1').disable();
			$('isactive2').disable();
		}
	},
	/* FUNKCJE EDYTORA */
	/* zmiana nazwy elementu */
    showRenameItemWindow: function(aId,liId){
		/** okno dla zmiany danych */
		
		// prepisanie danych do okna edytora
		$(JSTreeObj.editContext).update();
		$(JSTreeObj.editContext).style.height="260px";
		$(JSTreeObj.editContext).style.width="480px";

		// utworzenie zawartosci formularza
		$(JSTreeObj.editContext).appendChild(JSTreeObj.my_buildFormEditItem());
		
		// odczyt attrybutow
		JSTreeObj.my_readNodeToWindow(aId,liId,true);
		
		// dodanie zdarzen obslugi dla buttonow
		// zapis zmian
		$('saveelementData').observe('click',function(event){
			// aktualizacja atrybutow wezla LI
			JSTreeObj.my_updateNode(aId,liId);
			// zamkniecie okna
			contentEdit.close();
		});
		
		$('closeEditWindow').observe('click',function(event){
			contentEdit.close();
		});
		
		JSTreeObj.my_winContext(JSTreeObj.editContext,aId,liId, 'rename item from tree', 'panel administrator');
		// dodanie listy z funkcjami prezentacji/edycji danych dla pozycji menu do formularza
		$('funcDispElement').innerHTML=JSTreeObj.existCommandItem;
    },
	my_buildFormEditItem:function(){
		/** FORMULARZ EDYCJI ELEMENTU */
		var f=Builder.node('table',{style:'border:1px solid white;width:100%',border:"0",cellpadding:"4",cellspacing:"0"},[
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right'},'etykieta elementu* : '),
				Builder.node('td',{style:'text-align:left;'},[Builder.node('input',{type:'text',id:"titleEditElement",className:'nameData'})])
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right'},'pole formularza: '),
				Builder.node('td',{style:'text-align:left;'},[Builder.node('input',{type:'text',id:"poletpl",className:'commentData'})])
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right;width:50%'},'liczba porzadkowa: '),
				Builder.node('td',{style:'text-align:left;width:50%'},[Builder.node('input',{type:'text',id:"lpmenu",className:'nameData'})])
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right;width:50%'},'czy menu jest aktywne: '),
				Builder.node('td',{style:'text-align:left;width:50%'},[
					'nie: ',Builder.node('input',{type:'radio',id:"isactive1",value:'0',checked:'checked',name:'isactivemenu'}),
					' tak: ',Builder.node('input',{type:'radio',id:"isactive2",value:'1',name:'isactivemenu'})
					])
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right;width:50%'},'nazwa funkcji z poza listy (link): '),
				Builder.node('td',{style:'text-align:left;width:50%'},[Builder.node('input',{type:'text',id:"funcname",className:'nameData'})])
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:right;width:50%'},'lista funkcji wykonawczych (type): '),
				Builder.node('td',{style:'text-align:left;width:50%',id:'funcDispElement'})
			]),
			Builder.node('tr',[
				Builder.node('td',{style:'text-align:center;border-top:1px solid white;',colspan:"2",align:"center"},[
					Builder.node('button',{className:'pBtNormal',id:'saveelementData',type:'button'},'zapisz'),
					Builder.node('button',{className:'pBtNormal',id:'closeEditWindow',type:'button'},'zamknij')				
				])
			])
		]); // id listy funkcji wykonawczych 'selfntree_1'
		return f;
	},
    showNewItemWindow: function(aId,liId){
		/** nowy element utworzenie nowego elementu */
		
		$(JSTreeObj.editContext).update();
		$(JSTreeObj.editContext).style.height="230px";
		$(JSTreeObj.editContext).style.width="480px";
		// formularz edycji nowego elementu
		$(JSTreeObj.editContext).appendChild(JSTreeObj.my_buildFormEditItem());
		JSTreeObj.my_readNodeToWindow(aId,liId,false); // uzupelnienie danych w formularzu
		// dodanie listy z funkcjami prezentacji/edycji danych dla pozycji menu do formularza
		$('funcDispElement').innerHTML=JSTreeObj.existCommandItem;	

		// dodanie zdarzen obslugi dla buttonow
		$('saveelementData').observe('click',function(event){
				var _label = $("titleEditElement").value; // etykieta
				var new_idli = JSTreeObj.newID; // new id
				var new_aid = 'newnodeATag' + JSTreeObj.newID;
				var new_im1id = 'newnodeimg1' + JSTreeObj.newID;
				var new_im2id = 'newnode2mg1' + JSTreeObj.newID;
				// nowy wezel
				// atrybuty nowego wezla
				var fn;
				var tp;
				// funkcja wykonawcza
				if($('funcname').value!=''){
					fn=$('funcname').value;
					tp='0';
				} else {
					tp=$('selfntree_1').value;
				}
				var fnd = $(JSTreeObj.firstElementTree).readAttribute('funkcjad')?$(JSTreeObj.firstElementTree).readAttribute('funkcjad'):'0';
				var plp = $('poletpl').value;
				var lpm = $('lpmenu').value;
				var idn = $(JSTreeObj.firstElementTree).readAttribute('ident')?$(JSTreeObj.firstElementTree).readAttribute('ident'):'0';
				
				var newLi = Builder.node('li',{id:new_idli, 'link':fn, 'type':tp,
						    'funkcjad': fnd,
						    'poletpl':plp,
						    'lpmenu':lpm,
						    'statusr':$(JSTreeObj.firstElementTree).readAttribute('statusr'),
						    'idtree':$(JSTreeObj.firstElementTree).readAttribute('idtree'),
						    'ident':idn,
							'starttree':'0' }); // new LI
				JSTreeObj.newID++;
				// dodanie do listy
				$(liId).insert({after:newLi});
				// var newLi=document.getElementById(new_idli);
				var srci=JSTreeObj.imageFolder + JSTreeObj.plusImage;
				var pimg=Builder.node('img',{src:srci,style:'visibility:hidden;'});
				JSTreeObj.addEvent(pimg,'click',JSTreeObj.showHideNode);
				newLi.appendChild(pimg);
				var srci=JSTreeObj.imageFolder + JSTreeObj.folderImage;
				var fimg=Builder.node('img',{src:srci});
				JSTreeObj.addEvent(pimg,'mousemove',JSTreeObj.moveDragableNodes);
				JSTreeObj.addEvent(pimg,'mousedown',JSTreeObj.initDrag);
				newLi.appendChild(fimg);
				var aTag = Builder.node('A',{href:'#',id:new_aid},_label);
				JSTreeObj.addEvent(aTag,'mousemove',JSTreeObj.moveDragableNodes);
				JSTreeObj.addEvent(aTag,'mousedown',JSTreeObj.initDrag);
				JSTreeObj.addEvent(aTag,'dblclick',JSTreeObj.my_dblClicked);
				newLi.appendChild(aTag);
				// JSTreeObj.__refreshDisplay(newLi); // parentRef.parentNode
				// zamkniecie okna
				contentEdit.close();
				$(JSTreeObj.editContext).update();
		});
		$('closeEditWindow').observe('click',function(event){
			contentEdit.close();
			$(JSTreeObj.editContext).update();
		});
		JSTreeObj.my_winContext(JSTreeObj.editContext,aId,liId,'add new item from tree', 'panel administrator');    	
    },
	/* usuniecie elementu lub fragmentu drzewa danych */
    showDeleteItemWindow: function(aId,liId){
		// sprawdzene czy element ma pod saba kolejne drzewo
		if(document.getElementById(liId)) {
			var next=document.getElementById(liId);
			var ulNode=next.getElementsByTagName('UL');
			if(ulNode.length>0)
			{
				Dialog.confirm('<b>Element zawiera inne elementy czy chcesz go usunac</b>', 
				{width:250, className:'dialog',okLabel: "Tak", cancelLabel:"Nie", ok:function(win){
					var parentRef =  document.getElementById(liId).parentNode;
					parentRef.removeChild(document.getElementById(liId));
					JSTreeObj.__refreshDisplay(parentRef);
					return true;
				}});
			} else {
				var parentRef=next.parentNode;
				parentRef.removeChild(next);
				JSTreeObj.__refreshDisplay(parentRef);
			}
		}
    },
    showNewTreeWindow: function(aId,liId){
		var context=JSTreeObj.editContext;
		alert('inicjalizacja nowego drzewa danych');
    },
	my_winContext:function(idContext, atag, litag, winTitle, statusMessage){
		// pobranie rozmiarow kontekstu okna
		var box=$(idContext).getDimensions();
		if (contentEdit != null) {
		  Dialog.alert("Prosz zamknac aktywne okna",{width:220, height:80}); 
		}
		else {
		  contentEdit = new Window({className:'dialog', width:box.width520, height:box.height, 
		  	zIndex: 999, resizable: true,
			title:winTitle, 
		  	showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, 
			minWidth: 10, destroyOnClose: true});
		  if (statusMessage) {
		  	contentEdit.setStatusBar('<font style="color:black;">'+statusMessage+' [a id='+atag+', li id='+litag+']</font>');
		  }
		  contentEdit.setContent(idContext, true, true);
		  contentEdit.showCenter();	
		  if(atag) $(atag).className='highlightedNodeItem';
		  // Set up a windows observer, check ou debug window to get messages
		  my_editObserver = {
		    onDestroy: function(eventName, win) {
		      if (win == contentEdit) {
		        $('editContainer').appendChild($(idContext));
		        Windows.removeObserver(this);
				contentEdit = null;
				if(atag) $(atag).className='';
				var idWindow = win.getId();
				if($(idWindow)){
					$(idWindow).remove();
				}
		      }
		      debug(eventName + " on " + win.getId())
		    }
		  }
		  Windows.addObserver(my_editObserver);
		}		
	},
	/**
	* obsluga podwojnego klikniecia w etykiete elemntu drzewa danych
	* @param {Object} inputObj
	* @param {Object} e
	*/
	my_dblClicked:function(inputObj,e){
		JSTreeObj.currentlyActiveItem = this;
		var idTree=JSTreeObj.idOfTree;
		var aId = this.id; // id elementu "A"
		var liId= this.parentNode.id; // id element "LI"
		var arBt=new Array();
		var i=0;
		// budowa listy buttonow zaleznie od zawartosci atrybutow elementu "LI"
		// sprawdzenie czy wogole mozna dodawac elementy do drzewa danych
		if($(idTree).readAttribute('noAddNew')){
			var attr=$(idTree).readAttribute('noAddNew');
			if(attr=='false'){
				arBt[i]='addNew';
				i++;
			}
		} else {
			if($(liId).readAttribute('noAddNew')){
				var attr=$(liId).readAttribute('noAddNew');
				if(attr=='false'){
					arBt[i]='addNew';
					i++;
				}
			} else {
				arBt[i]='addNew';
				i++;
			}
		}
		// czy jest mozliwe usuwanie elementow z drzewa danych
		if($(liId).readAttribute('noDelete')){
			var attr=$(idTree).readAttribute('noDelete');
			if(attr=='false'){
				arBt[i]='delete';
				i++;
			}
		} else {
			arBt[i]='delete';
			i++;
		}
		// czy jest mozliwa zmiana etykiety i opisu
		if($(liId).readAttribute('noRename')){
			var attr=$(idTree).readAttribute('noRename');
			if(attr=='false'){
				arBt[i]='edit';
				i++;
			}
		} else {
			arBt[i]='edit';
			i++;
		}
		arBt[i]='close';
		JSTreeObj.my_buildWin(arBt, aId, liId);
	},
	/**
	* buduje zawartosc okna dialogowego do wyboru funkcji edycji danych
	* @param {Object} aButton - lista buttonow w oknie wyboru funkcji [addNew,edit,delete]
	*/
	my_buildWin:function(aButton, aId, liId){
		$(aId).className='highlightedNodeItem';
		var wConext=JSTreeObj.winContainer;
		$(wConext).update(); // wyczyszczenie okna
		// budowa listy buttonow
		aButton.each(function(ibt){
			var idButton = ibt + '00001';
			var cssBt = "pBtNormal"; //JSTreeObj.cssButton;
			if(ibt=='addNew'){
				var b = Builder.node('button',{id:idButton,className:cssBt,type:'button'},'New element');
				$(wConext).appendChild(b);
				$(idButton).observe('click', function(event){
					contentWin.close();
					JSTreeObj.showNewItemWindow(aId, liId);
					$(wConext).update();
				});
			}
			if(ibt=='delete'){
				var b = Builder.node('button',{id:idButton,className:"pBtRed",type:'button'},'Del. element');
				$(wConext).appendChild(b);
				$(idButton).observe('click', function(event){
					contentWin.close();
					JSTreeObj.showDeleteItemWindow(aId, liId);
					$(wConext).update();
				});
			}
			if(ibt=='edit'){
				var b = Builder.node('button',{id:idButton,className:cssBt,type:'button'},'Edit element');
				$(wConext).appendChild(b);
				$(idButton).observe('click', function(event){
					contentWin.close();
					JSTreeObj.showRenameItemWindow(aId, liId);
					$(wConext).update();
				});
			}
			if(ibt=='close'){
				var b = Builder.node('button',{id:idButton,className:cssBt,type:'button'},'close');
				$(wConext).appendChild(b);
				$(idButton).observe('click', function(event){
					contentWin.close();
					$(wConext).update();
					// contentWin.destroy();
				});
			}
		});
		if (contentWin != null) {
		  Dialog.alert("Prosze zamknac aktywne okna",{width:200, height:130}); 
		}
		else {
		  contentWin = new Window({className:'dialog', width:450, height:90, 
		  	zIndex: 100, resizable: true,
			title:"select a function from tree structure edit", 
		  	showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff, 
			minWidth: 10, destroyOnClose: true});
		  contentWin.setStatusBar('<font style="color:black;font-weight:bold;">Administrator: tree element edit. [a id='+aId+', li id='+liId+']</font>');
		  contentWin.setContent(wConext, true, true);
		  contentWin.showCenter();
		  contentWin.setDestroyOnClose();
		  // Set up a windows observer, check ou debug window to get messages
		  myObserver = {
		    onDestroy: function(eventName, win) {
		      if (win == contentWin) {
		        $('container').appendChild($(wConext));
		        Windows.removeObserver(this);
				contentWin = null;
				// $(aId).className='';
				var idWindow = win.getId();
				if($(idWindow)){
					$(idWindow).remove();
				}
		      }
		      debug(eventName + " on " + win.getId())
		    }
		  }
		  Windows.addObserver(myObserver);
		}
	},
	/**
	* generowanie przyciskow pod lista z drzewem
	* @param {Object} arrayButton - [save,colapse,expand]
	* @param {Object} messageId - id elementu w ktory maja zostac wyswietlone wynika zapisu
	* @param {Object} classDiv - klasa css dla div w ktorym sa buttony
	* @param {Object} classButton - klasa css przyciskow
	*/
	my_buttonEdit:function(){
		var classDiv = 'panelEditor';
		var arrayButton = this.arrayButton;
		if(arrayButton){
			// div dla buttonow
			var dvButton=Builder.node('div',{className:classDiv}); // div buttonow
			$(this.idOfTree).insert({before:dvButton}); // dodanie div do dokumentu przed drzewem danych
			// utworzenie w ramach dvButton tabeli z formularzem
			var f=Builder.node('table',{style:'width:100%'},[
				Builder.node('tr',[
					Builder.node('td',{colspan:"2",style:'text-align:center;font-size:18px;color:white;font-family:tahoma;',align:"center"},'tree structure editor')
				]),
				Builder.node('tr',[
					Builder.node('td',{colspan:"2",id:"buttonCellsForm",className:"center",align:"center"})
				]),
				Builder.node('tr',[
					Builder.node('td',{className:'right',align:"right"},'select tree exist to load: '),
					Builder.node('td',{className:'left',align:"left",id:'listExistTreeForm'})
				]),
				Builder.node('tr',[
					Builder.node('td',{colspan:"2",style:'text-align:center;font-size:8px;color:white;font-family:tahoma;',align:"center"},'remigiusz.polaczenko from dhtmlgoodies.com')
				])
			]);
			dvButton.appendChild(f);

			arrayButton.each(function(bt){
				if(bt=='save'){
					var buttonTree=Builder.node('button',{id:'saveButton',className:'pBtNormal',type:'button'},'save');
					$("buttonCellsForm").appendChild(buttonTree);
				    $('saveButton').observe('click', function(event){
				        JSTreeObj.na_saveTreeData();
						// zmiana danych pola hidden
						$('submitButton').name='saveTreeButton';
						$('submitButton').value='saveTreeButton';
						$('paramButton').value = 'adm___saveTreeButton';
						// wyslanie do serwera
						senderAjax();
						$('editContext').update();
				    });
				}
				if(bt=='expand'){
					var buttonTree=Builder.node('button',{id:'expandButton',className:'pBtNormal',type:'button'},'expand');
					$("buttonCellsForm").appendChild(buttonTree);					
				    $('expandButton').observe('click', function(event){
				        JSTreeObj.expandAll();
				    });
				}
				if(bt=='colapse'){
					var buttonTree=Builder.node('button',{id:'colapseButton',className:'pBtNormal',type:'button'},'colapse');
					$("buttonCellsForm").appendChild(buttonTree);
				    $('colapseButton').observe('click', function(event){
				        JSTreeObj.collapseAll();
				    });
				}
				if(bt=='deltree'){
					var buttonTree=Builder.node('button',{id:'deltreeButton',className:'pBtRed',type:'button'},'del tree');
					$("buttonCellsForm").appendChild(buttonTree);
				    $('deltreeButton').observe('click', function(event){
				        JSTreeObj.showNewTreeWindow();
				    });
				}
				if(bt=='newtree'){
					var buttonTree=Builder.node('button',{id:'newtreeButton',className:'pBtNormal',type:'button'},'new tree');
					$("buttonCellsForm").appendChild(buttonTree);
				    $('newtreeButton').observe('click', function(event){
						// zmiana danych pola hidden
						$('submitButton').name='newtreeButton';
						$('submitButton').value='newtreeButton';
						$('paramButton').value = 'adm___newtreeButton';
						// wyslanie do serwera
						senderAjax();
				    });
				}
			});
			// lista dostepnych drzew do edycji
			if(JSTreeObj.existTreeList){
				$('listExistTreeForm').innerHTML=JSTreeObj.existTreeList;
			}
			var b=Builder.node('br');
			dvButton.appendChild(b);
		}
	},
	/**
	 * funkcja odczytania informacji z drzewa i przetworzonia go w strukture tablicowa 
	 * @return (string) - lancuch w znakowy w stylu urlencode z elementami drzewa
	 * 
	 */
    na_saveTreeData: function(){
        if (document.getElementById(this.idOfTree)) {
            $('editContext').update();
			this.gbj = document.getElementById(this.idOfTree); // pobranie elementu
            this.left = 1; // start liczenia elementow
            this.level = 0;
            this.ltb = JSTreeObj.rNode(this.gbj.childNodes); // przetwarzanie
            return JSTreeObj.disp(); // wyswietlanie
        }
        else {
            return false;
        }
    },
	/**
	 * pomocnicza funkcja, ktora w rekurencji przetwarza kolejne elementy drzewa i zamienia je na tablice danych
	 * w postaci rekordow danych
	 * @param {Object} obj refet\rencja di pozycji listy bierzaco przetwarzanej przetwarzane
	 * @return (array) zwraca tablice danych
	 */
    rNode: function(obj){
        var i = 0;
        var ct = new Array();
        var pn = new Array();
        var idnode = '';
        for (i = 0; i < obj.length; i++) {
            if (obj[i].nodeName == 'LI') {
                var anode = '';
                // przeglad elementow w LI
                if (obj[i].getElementsByTagName('A').length > 0) {
                    var a = new Array();
                    var anode = obj[i].getElementsByTagName('A')[0].innerHTML;
                    // ten sam poziom
					var tnameC='['+JSTreeObj.idOfTree+']['+obj[i].id+']';
                    a[0] = { 'lewe':this.left++};
                    a[2] = {'level':this.level};
					a[3] = {'id':obj[i].id};
                    a[4] = {'nazwa':anode.escapeHTML()};

					// atrybuty drzewa
					// dopisanie atrybutow elemenu LI
					
					//$(obj[i]).readAttribute('_tName')?a[5] = {'_tName': $(obj[i]).readAttribute('_tName')}:null;
					//$(obj[i]).readAttribute('_tContext')?a[6]={'_tContext':$(obj[i]).readAttribute('_tContext')}:null;
					$(obj[i]).readAttribute('idfunc')?a[7]={'idfunc':$(obj[i]).readAttribute('idFunc')}:null;
					$(obj[i]).readAttribute('idtree')?a[8]={'idtree':$(obj[i]).readAttribute('idtree')}:null;
					$(obj[i]).readAttribute('funkcjad')?a[9]={'funkcjad':$(obj[i]).readAttribute('funkcjad')}:null;
					$(obj[i]).readAttribute('ident')?a[10]={'ident':$(obj[i]).readAttribute('ident')}:null;
					$(obj[i]).readAttribute('link')?a[11]={'link':$(obj[i]).readAttribute('link')}:null;
					$(obj[i]).readAttribute('type')?a[12]={'type':$(obj[i]).readAttribute('type')}:null;
					$(obj[i]).readAttribute('iduser')?a[13]={'iduser':$(obj[i]).readAttribute('iduser')}:null;
					$(obj[i]).readAttribute('datad')?a[14]={'datad':$(obj[i]).readAttribute('datad')}:null;
					$(obj[i]).readAttribute('czas')?a[15]={'czas':$(obj[i]).readAttribute('czas')}:null;
					$(obj[i]).readAttribute('starttree')?a[16]={'starttree':$(obj[i]).readAttribute('starttree')}:null;
					$(obj[i]).readAttribute('statusr')?a[17]={'statusr':$(obj[i]).readAttribute('statusr')}:null;
					$(obj[i]).readAttribute('poletpl')?a[18]={'poletpl':$(obj[i]).readAttribute('poletpl')}:null;
					$(obj[i]).readAttribute('lpmenu')?a[19]={'lpmenu':$(obj[i]).readAttribute('lpmenu')}:null;

                    // kolejny poziom
                    if (obj[i].getElementsByTagName('UL').length > 0) {
                        var ulElem = obj[i].getElementsByTagName('UL');
                        this.level++;
                        var cc = this.rNode(ulElem[0].childNodes);
                        pn = cc.concat(pn);
                        this.level--;
                    }
                    // saved right
                    a[1] = {'prawe':this.left++};
					/** 
					* utworzenie pol hidden z struktura drzewa danych
					*/
                    pn.push(a);
                }
            }
        }
        // polaczenie tablicy bierzacej z poziomami nizszymi
        return pn; // zwoc tablice z danymi o LI
    },
	/**
	 * funkcja przeksztalcania danych tablicy w ciag znakowy typu  urlencode
	 * @param {Object} tb - wksaznik do pozycji listy - tag LI z kolejnymi drezwami lub danymi
	 * bierzacej galezi
	 * @return (string) lancuch z danymi
	 */
    disp: function(){
        var t;
        var s = '';
        ;
        // prototype.js function
        var tb = $A(this.ltb).uniq().sort();
        tb.each(function(ele){
			/*
			s = s + ('trees[' + JSTreeObj.idOfTree + '][' + ele[3] + "]=" + ele[0] + '__' + ele[1] + '__' + ele[2] + '__' + ele[4]) + 
			((ele[5])?'__'+ele[5]:'__#') + ((ele[6])?'__'+ele[6]:'__#') + ((ele[7])?'__'+ele[7]:'__#') + '&<br/>';
			*/
			ele.each(function(x,i){
				//if(i!=3) s=s+'tress['+JSTreeObj.idOfTree+']['+ele[3]+']'+x+'<br>';
				for(var klucz in x){
					var idObjectTree=JSTreeObj.idOfTree;
					var eName=idObjectTree+'['+ele[3]['id']+']['+klucz+']';
					s=s+eName+'='+x[klucz]+'<br>'; //'tress['+JSTreeObj.idOfTree+']['+ele[3]['id']+']['+klucz+']
					JSTreeObj.my_saveBuilder(eName, x[klucz]);
				}
			});
        });
        if (JSTreeObj.logsContainer) {
			$(JSTreeObj.logsContainer).update(s); // 'messageSites'
		}
        return s;
    },
	my_saveBuilder:function(names,values){
		var nameElem=names;
		var hdTree=Builder.node('input',{type:'hidden',name:nameElem,value:values});
		$('editContext').appendChild(hdTree);
	}
    
}
//tree_ListExist