// CMS interface objects

/*----------------------------------------------------------------------------->
 
*** AjaxTree 

    Attributes
    
    Methods
        * draw
        * style
        * hide
        * show
        * disable
        * enable
        * isEnabled
        * load
        * container
        * getNodeById(nodeId)
        * getNodesLike
        * methodNodeById
        * methodNodesLike
        * selectNodeById
        * selectNodesLike
        * selectedNodes
        * updateNodesStates
    Events
        * onInit
        * onLoad
        * onFold
        * onUnfold
        * onSelect
        * onBeforeSelect

*** AjaxTreeRoot

    Attributes
        
    Methods
        see AjaxTreeNode methods
    Events
        see AjaxTreeNode events

*** AjaxTreeNode 

    Attributes
    
    Methods
        * container
        * draw
        * load
        * fold
        * unfold
        * select
        * addChild
        * getNodesById(nodeId)
        * getNodesLike(nodeAttributes)
        * setAttributes(nodeAttributes)
        * isSelected
        * isRoot
        * isFirst
        * isLast
        * myOrder
        * moveIn (developing)
        * moveOut (developing)
        * moveUp
        * moveDown
    Events
        * onAfterLoad
        * onAfterLoadAndDraw

<-----------------------------------------------------------------------------*/



var globalCMSPath = (globalCMSPath) ? globalCMSPath : '';
var globalCMSUrl = (globalCMSUrl) ? globalCMSUrl : globalCMSPath;
var isNav4 = (navigator.appName == "Netscape") ? true : false;
var isIE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;


function drawFieldsetBlock_header(title,help,style){
	
	var text = '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="fieldset" style="margin-bottom: 5px; ' + ((style)&&(style['height'])?'height:' + style['height'] + ';':'') + '">\
  <tr height="1">\
    <td width="1"></td>\
    <td class="border"><img src="' + globalCMSUrl + '/images/moby/blank.gif" width="1" height="1"></td>\
    <td width="1"></td>\
  </tr>\
  <tr height="20">\
    <td width="1" class="border"><img src="' + globalCMSUrl + '/images/moby/blank.gif" width="1" height="1"></td>\
    <td class="legend"><table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td>'+title+'</td><td align="right">';
	if (help != 'hidden') {text += '<img src="' + globalCMSUrl + '/images/moby/info.gif" width="14" height="13" class="info" onMouseMove="ave_EdButtonMove(this,event,{\'helpId\':\''+help+'\'});" onMouseOut="ave_EdButtonOut(this,event,{});">';}
	text += '</td></tr></table></td>\
    <td width="1" class="border"><img src="' + globalCMSUrl + '/images/moby/blank.gif" width="1" height="1"></td>\
  </tr>\
  <tr>\
    <td width="1" class="border"></td>\
    <td height="100%" class="body" ' + ((style)&&(style['valign'])?'valign="' + style['valign'] + '"':'') + '>';
	document.write(text);
	//alert(text);
}
function drawFieldsetBlock_footer(){
	var text = '</td>\
    <td width="1" class="border"></td>\
  </tr>\
  <tr height="1">\
    <td width="1"></td>\
    <td class="border"><img src="' + globalCMSUrl + '/images/moby/blank.gif" width="1" height="1"></td>\
    <td width="1"></td>\
  </tr>\
</table>';
	document.write(text);
}

var _idModalWindow = '';
function showModalWindow(title,source,type,attribs){
	// modal mWindow attributes
	var mWindow = {width: ((attribs['width'])&&(attribs['width'] > 0)) ? attribs['width'] : 350,
				  height: ((attribs['height'])&&(attribs['height'] > 0)) ? attribs['height'] : 400,
				  border: '1px solid #666	',
				  backgroundColor: '#e7e7e7'};
	var substrate = {backgroundColor: '#e7e7e7'};
	
	// hiding modal mWindow 
	hideModalWindow();
	
	// showing new modal mWindow
	_idModalWindow = 'lyrModalWindow' + Math.round(100000 * Math.random())
    var lyrModalWindow = document.createElement('DIV');
	lyrModalWindow.id = _idModalWindow;
	lyrModalWindow.style.zIndex = '100';
	lyrModalWindow.style.position = 'absolute';
	lyrModalWindow.style.top = '0px';
	lyrModalWindow.style.left = '0px';
	lyrModalWindow.style.width = '100%';
	lyrModalWindow.style.height = '100%';
	lyrModalWindow.innerHTML = '\
		<div style="width:100%; height:100%; position:relative;">\n'
			+ ((isIE) ? '<iframe style="height:100%; width:100%; position:absolute; filter:alpha(Opacity:0)" src="about:blank" frameborder="1"></iframe>\n' : '') +
			'<div style="width:100%; height: 100%; opacity:0.5; filter: alpha(opacity:50)">\
				<div style="height:100%; width:100%; background-color: ' + substrate.backgroundColor + ';">&nbsp;</div>\
			</div>\
			<div style="position: absolute; top: ' + Math.floor((document.body.clientHeight - mWindow.height) / 2) + 'px; left: ' + Math.floor((document.body.clientWidth - mWindow.width) / 2) + 'px; width:' + mWindow.width + 'px; height:' + mWindow.height + 'px; background-color:' + mWindow.backgroundColor +'; border: ' + mWindow.border + ';">\
				<div style="width:' + (mWindow.width - 2) + 'px; height:' + (mWindow.height - 2) + 'px; border-top: 1px solid #fff; border-left: 1px solid #fff; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc;">\
				<table cellspacing="0" cellpadding="0" style="width:' + (mWindow.width - 8) + 'px; height:' + (mWindow.height - 8) + 'px; margin: 3px;" >\
                    <tr><td id="' + _idModalWindow + ':Title" class="titleValue" style="background:#ddd;padding:3px;"></td></tr>\
                    <tr><td id="' + _idModalWindow + ':Content" height="100%" valign="top" style="padding:2px;">No source passed to modal mWindow</td></tr>\
					<tr><td style="border-bottom:solid 1px #bbbbbb; padding: 0px;">\
						<div style="position:relative; height:15px; float: right;">\
							<div id="' + _idModalWindow + ':Buttons"  style="position:absolute; background-color:#e7e7e7; height:24px; padding:0px; padding-left:3px; right:0px; white-space: nowrap;">\
							</div>\
						</div>\
					</td></tr>\
					<tr><td style="color:#999999; border-top:1px solid #FFFFFF; padding-bottom:0px; font-size: 8px;">\
						&nbsp;\
					</td></tr>\
				</table></div>\
			</div>\
		</div>';
	
	document.body.appendChild(lyrModalWindow);
	// inserting content
	var html = '';
	switch (type){
		case 'iframe':
			html = '<iframe src="' + source + '" frameborder="no" allowtransparency="yes" style="width:100%;height:100%;"></iframe>';
			break;
		default:
			html = source;
	}
    $(_idModalWindow + ':Title').innerHTML = title;
	$(_idModalWindow + ':Content').innerHTML = html;
    $(_idModalWindow + ':Buttons').innerHTML = (attribs['buttons']) ? (attribs['buttons']) : '';
	return ($(_idModalWindow + ':Content'));
}
function hideModalWindow(){
	if((_idModalWindow != '')&&($(_idModalWindow))&&($(_idModalWindow).parentNode)){
		$(_idModalWindow).parentNode.removeChild($(_idModalWindow))
	}
	_idModalWindow = '';
}
function getModalWindowContentContainer(){
    if((_idModalWindow != '')&&($(_idModalWindow))){
        return $(_idModalWindow + ':Content');
    }
    return null;
}
function getModalWindowButtonsContainer(){
    if((_idModalWindow != '')&&($(_idModalWindow))){
        return $(_idModalWindow + ':Buttons');
    }
    return null;
}

var _idModalDialog = '';
function showModalDialog(source,type,attribs){
	// modal dialog attributes
	var dialog = {width: ((attribs['width'])&&(attribs['width'] > 0)) ? attribs['width'] :350,
				  height: ((attribs['height'])&&(attribs['height'] > 0)) ? attribs['height'] :400,
				  border: '1px solid #666	',
				  backgroundColor: '#e7e7e7'};
	var substrate = {backgroundColor: '#e7e7e7'};
	
	// hiding modal dialog 
	hideModalDialog();
	
	// showing new modal dialog
	_idModalDialog = 'lyrModalDialog' + Math.round(100000 * Math.random())
    var lyrModalDialog = document.createElement('DIV');
	lyrModalDialog.id = _idModalDialog;
	lyrModalDialog.style.zIndex = '100';
	lyrModalDialog.style.position = 'absolute';
	lyrModalDialog.style.top = '0px';
	lyrModalDialog.style.left = '0px';
	lyrModalDialog.style.width = '100%';
	lyrModalDialog.style.height = '100%';
	lyrModalDialog.innerHTML = '\
		<div style="width:100%; height:100%; position:relative;">\n'
			+ ((isIE) ? '<iframe style="height:100%; width:100%; position:absolute; filter:alpha(Opacity:0)" src="about:blank" frameborder="1"></iframe>\n' : '') +
			'<div style="width:100%; height: 100%; opacity:0.5; filter: alpha(opacity:50)">\
				<div style="height:100%; width:100%; background-color: ' + substrate.backgroundColor + ';">&nbsp;</div>\
			</div>\
			<div style="position: absolute; top: ' + Math.floor((document.body.clientHeight - dialog.height) / 2) + 'px; left: ' + Math.floor((document.body.clientWidth - dialog.width) / 2) + 'px; width:' + dialog.width + 'px; height:' + dialog.height + 'px; background-color:' + dialog.backgroundColor +'; border: ' + dialog.border + ';">\
				<div style="width:' + (dialog.width - 2) + 'px; height:' + (dialog.height - 2) + 'px; border-top: 1px solid #fff; border-left: 1px solid #fff; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc;">\
				<table cellspacing="0" cellpadding="0" style="width:' + (dialog.width - 8) + 'px; height:' + (dialog.height - 8) + 'px; margin: 3px;" >\
					<tr><td id="' + _idModalDialog + ':Content" height="100%" valign="top">No source passed to modal dialog</td></tr>\
					<tr><td style="border-bottom:solid 1px #bbbbbb; padding: 0px;">\
						<div style="position:relative; height:15px; float: right;">\
							<div style="position:absolute; background-color:#e7e7e7; height:24px; padding:0px; padding-left:3px; right:0px; white-space: nowrap;">\
							<button id="' + _idModalDialog + ':Apply" onclick="hideModalDialog();" style="height:20px; width:35px;">Ok</button>\
							<button id="' + _idModalDialog + ':Close" onclick="hideModalDialog();" style="height:20px; width:35px;">&nbsp;X&nbsp;</button>\
							</div>\
						</div>\
					</td></tr>\
					<tr><td style="color:#999999; border-top:1px solid #FFFFFF; padding-bottom:0px; font-size: 8px;">\
						&nbsp;\
					</td></tr>\
				</table></div>\
			</div>\
		</div>';
	
	document.body.appendChild(lyrModalDialog);
	// inserting content
	var html = '';
	switch (type){
		case 'iframe':
			html = '<iframe src="' + source + '" frameborder="no" allowtransparency="yes" style="width:100%;height:100%;"></iframe>';
			break;
		default:
			html = source;
	}
	$(_idModalDialog + ':Content').innerHTML = html;
	if(typeof(attribs['onApply']) == 'function'){
		$(_idModalDialog + ':Apply').onclick = function(){
			attribs['onApply']();
			hideModalDialog();
		}
	}
	if(typeof(attribs['onClose']) == 'function'){
		$(_idModalDialog + ':Close').onclick = function(){
			attribs['onClose']();
			hideModalDialog();
		}
	}

	return ($(_idModalDialog + ':Content'));
}
function hideModalDialog(){
	if((_idModalDialog != '')&&($(_idModalDialog))&&($(_idModalDialog).parentNode)){
		$(_idModalDialog).parentNode.removeChild($(_idModalDialog))
	}
	_idModalDialog = '';
}
function getModalDialogContentContainer(){
    if((_idModalDialog != '')&&($(_idModalDialog))){
        return $(_idModalDialog + ':Content');
    }
    return null;
}


// -- ProgressBar ------------------------------------------------------------->
function ProgressBar(containerId,arguments){
// attributes
    this._window = window;
    this._document = document;
    this._selfId = 'lyrProgressBar' + Math.round(100000 * Math.random);
    this._containerId = containerId;
    this._value = {'minimum': 0,
                   'maximum': 100,
                   'current': 0};
    this._style = {'height' : '13',
                   'fontSize' : '11',
                   'border':'1px solid #bbbbbb',
                   'backgroundColor':'#ffffff',
                   'backgroundImage' : 'url(\'' + globalCMSPath + '/libraries/interface/images/ProgressBar/background.gif\')',
                   'bar':{'border' : '1px solid #f7f7f7',
                          'backgroundColor' : '#cccccc',
                          'backgroundImage' : 'url(\'' + globalCMSPath + '/libraries/interface/images/ProgressBar/bar.gif\')'
                          }
                   };
    this._caption = {'text':'',
                     'textAlign':'center',
                     'textColor':'#333333',
                     'flagShowValues':false};
// methods
    this._init =
        function (arguments){
        // applying arguments
            if(arguments){
            // progressBar style
                if(arguments['height'])
                    this._style['height'] = arguments['height'];
                if(arguments['font-size'])
                    this._style['fontSize'] = arguments['font-size'];
                if(arguments['border'])
                    this._style['border'] = arguments['border'];
                if(arguments['background-color'])
                    this._style['backgroundColor'] = arguments['background-color'];
            // caption
                if(arguments['caption'])
                    this._caption['text'] = arguments['caption'];
                if(arguments['text-align'])
                    this._caption['textAlign'] = arguments['text-align'];
                if(arguments['text-color'])
                    this._caption['textColor'] = arguments['text-color'];
                if(arguments['show-values'])
                    this._caption['flagShowValues'] = arguments['show-values'];
            }
        // creating html objects
            var html = '<div id="' + this._selfId + '" style="position:relative; width:100%; height:' + this._style.height + 'px; background-color:' + this._style.backgroundColor +'; border: ' + this._style.border + '; background-image: ' + this._style.backgroundImage + ';">'
                    + '<div style="width:100%; top: ' + Math.floor(this._style.height / 2 - this._style.fontSize / 2) + 'px; position:absolute; text-align:' + this._caption.textAlign + '; color:' + this._caption.textColor + '; font-size: ' + this._style.fontSize +'px"></div>'
                    + '<div style="width:0%; height:100%; background-color:' + this._style.bar.backgroundColor + '; border: ' + this._style.bar.border + '; background-image: ' + this._style.bar.backgroundImage + ';"></div>'
                    + '</div>';
        // if containerID is defined
            if((this._containerId)&&(this._containerId != '')){
                var container = this._window.$(this._containerId);
                if((container)&&(container.innerHTML))
                    container.innerHTML = container.innerHTML + html;
            }else{
                this._document.writeln(html);
            }
            this.value(0);
            return true;
        };
    this.show = 
        function (){
            this._window.$(this._selfId).style.display = 'block';
        };
    this.hide = 
        function (){
            this._window.$(this._selfId).style.display = 'none';
        };
    this.value = 
        function (value){
            if((value <= this._value['maximum'])&&(value >= this._value['minimum'])){
                this._value['current'] = value;
                var percentage = 100*(this._value['current'] - this._value['minimum'])/(this._value['maximum'] - this._value['minimum']);
                var obj = this._window.$(this._selfId);
                if((obj)&&(obj.childNodes)){
                    obj.childNodes[0].innerHTML = (this._caption.flagShowValues)? this._value['current'] + ' / ' + this._value['maximum'] : Math.round(percentage) + '%';
                    obj.childNodes[1].style.width = Math.round(percentage) + '%';
                }
            }
            return this._value['current'];
        };

    this.range =
        function (minimum,maximum){
            if(minimum < maximum){
                this._value['minimum'] = minimum;
                this._value['maximum'] = maximum;
                if(this._value['current'] < this._value['minimum'])
                    this._value['current'] = this._value['minimum'];
                if(this._value['current'] > this._value['maximum'])
                    this._value['current'] = this._value['maximum'];
            }
            return new Array(this._value['minimum'],this._value['maximum']);
        };
// initiating
    this._init();
}

// -- TabsBar ------------------------------------------------------------>

var TabsBars = {};

function TabsBar(containerId,attribs,initTabs){
// attributes
    this._selfId = 'lyrTabsBar' + Math.round(100000 * Math.random());
    this._imagesPath = globalCMSPath + '/libraries/interface/images/TabsBar';
    this._imagesType = 'gif';
    this._tabTypes = new Array('content','grab','iframe','ajax');
    this._tabStyles = new Array('','gray');
    this._tabSelectedIndex = -1; 
    this._parameters = {};
    this._scrollDirection = null;
    this._scrollTimerID = null;
    this.items = new Array();
// events
    this.onInit = null;
    this.onTabSelect = null;
    this.onTabClose = null;
// methods
    this._init =
        function(containerId,attribs,initTabs){
            this._parameters = {'maxTabsAmount' : ((attribs)&&(attribs['maxTabsAmount']))? attribs['maxTabsAmount'] : 20,
                                'tabsAlignment' : ((attribs)&&(attribs['tabsAlignment']))? attribs['tabsAlignment'] : 'left',
                                'tabsDirection' : ((attribs)&&(attribs['tabsDirection']))? attribs['tabsDirection'] : 'horizontal',
								'tabsBarMargin' : ((attribs)&&(attribs['tabsBarMargin']))? attribs['tabsBarMargin']  : '3px',
                                'tabsHideButtons' : ((attribs)&&(attribs['tabsHideButtons'] == true)) ? true : false,
                                'tabsHeight' : ((attribs)&&(attribs['tabsHeight']))? attribs['tabsHeight'] : 26,
                                'tabsFontColor' : ((attribs)&&(attribs['tabsFontColor']))? attribs['tabsFontColor'] : '#333333'};
        // if attribs defined
            if(attribs){
            // attributes
                if(attribs['imagesPath']) this._imagesPath = attribs['imagesPath'];
                if(attribs['imagesType']) this._imagesType = attribs['imagesType'];

            // events
                if(attribs['onInit']) this.onInit = attribs['onInit'];
                if(attribs['onSelect']) this.onTabSelect = attribs['onSelect'];
                if(attribs['onClose']) this.onTabClose = attribs['onClose'];
            }
        // creating html objects
            var tabsBarElement;
            if(containerId !=''){
                if(($(containerId))&&($(containerId).appendChild)
                   &&(typeof($(containerId).appendChild) != 'undefined')){
                    tabsBarElement = document.createElement('DIV');
                    tabsBarElement.id = this._selfId; 
                    $(containerId).appendChild(tabsBarElement);
                }else{
                    alert('Error occured while creating TabsBar element:\nCan\'t find container "' + containerId + '"');
                    return false;
                }
            }else{
                document.writeln('<div id="' + this._selfId + '"></div>');
            }
            tabsBarElement = $(this._selfId);
            if(typeof(tabsBarElement) != 'object'){
                alert('Error occured while creating TabsBar element');
                return false;
            }
            tabsBarElement.style.display = 'block';
            tabsBarElement.style.position = 'relative';
            tabsBarElement.style.whiteSpace = 'nowrap';
            tabsBarElement.style.overflow = '';
            tabsBarElement.style.height = '100%';
            tabsBarElement.innerHTML = '<div style="position:absolute; left:0px; top:0px; z-index:2; width:100%; height:100%; background-color: #f8f8f8; display:none;"></div>'
                                     + '<div style="position:absolute; left:0px; top:0px; z-index:1; width:100%; height:26px; background-color: #eeeeee;background-image:url(' + this._imagesPath + '/bar_bg.' + this._imagesType + '); background-position: left bottom; background-repeat: repeat-x; overflow: hidden;"></div>'
                                     + '<div style="position:absolute; left:0px;' + ((isIE)?'z-index:3; top:0px; height:100%; padding-top:26px;' : 'top:26px; bottom:0px;') + ' width:100%; "><div style="height:100%; position:relative; background-color:#f9f9f9;"></div></div>'
                                     + '<div class="TabsBar_ScrollButton" style="position:absolute; border-left:none; left:0px; height:26px; line-height:26px; z-index:4;background-image:url(' + this._imagesPath + '/scrollButton_bg.' + this._imagesType + ');" onmouseover="__TabsBarScrollStart(this,\'' + this._selfId + '\',\'left\');" onmouseout="__TabsBarScrollStop(this,\'' + this._selfId + '\');">&laquo;&nbsp;</div>'
                                     + '<div class="TabsBar_ScrollButton" style="position:absolute; border-right:none; right:-1px; height:26px; line-height:26px; z-index:4;background-image:url(' + this._imagesPath + '/scrollButton_bg.' + this._imagesType + ');" onmouseover="__TabsBarScrollStart(this,\'' + this._selfId + '\',\'right\');" onmouseout="__TabsBarScrollStop(this,\'' + this._selfId + '\');">&nbsp;&raquo;</div>';
        // setting defined attribs
            if((attribs)&&(attribs['style'])){
                if(attribs['style']['width']) tabsBarElement.style.width = attribs['style']['width'];
                if(attribs['style']['height']) tabsBarElement.style.height = attribs['style']['height'];
                if(attribs['style']['border']) tabsBarElement.style.border = attribs['style']['border'];
                if(attribs['style']['background-color']) tabsBarElement.style.backgroundColor = attribs['style']['background-color'];
            }
            if((attribs)&&(attribs['barStyle'])){
                if(attribs['barStyle']['height']){
                    if(!(attribs['barStyle']['height'] >= this._parameters['tabsHeight']))
                        attribs['barStyle']['height'] = this._parameters['tabsHeight'];
                    tabsBarElement.childNodes[1].style.height = attribs['barStyle']['height'];
                    if(isIE)
                        tabsBarElement.childNodes[2].style.paddingTop = attribs['barStyle']['height']
                    else
                        tabsBarElement.childNodes[2].style.top = attribs['barStyle']['height'];
                }
                if(attribs['barStyle']['border']) tabsBarElement.childNodes[1].style.border = attribs['barStyle']['border'];
                if(attribs['barStyle']['background-color']) tabsBarElement.childNodes[1].style.backgroundColor = attribs['barStyle']['background-color'];
            }
            if((attribs)&&(attribs['contentStyle'])){
                if(attribs['contentStyle']['border']){
                    tabsBarElement.childNodes[2].childNodes[0].style.borderLeft = attribs['contentStyle']['border'];
                    tabsBarElement.childNodes[2].childNodes[0].style.borderRight = attribs['contentStyle']['border'];
                    tabsBarElement.childNodes[2].childNodes[0].style.borderBottom = attribs['contentStyle']['border'];
                }
                if(attribs['contentStyle']['background-color']) tabsBarElement.childNodes[2].childNodes[0].style.backgroundColor = attribs['contentStyle']['background-color'];
                if(attribs['contentStyle']['padding']) tabsBarElement.childNodes[2].childNodes[0].style.padding = attribs['contentStyle']['padding'];
            }
        // init tabs
            if((initTabs)&&(initTabs.length > 0)){
                for (var i = 0; i < initTabs.length; i++){
                    this.tabAdd(initTabs[i]['tabId'],
                                initTabs[i]['attribs'],
                                initTabs[i]['flagUnique'],
                                initTabs[i]['flagSelect']);
                }
            }
        // post init
            if(typeof(this.onInit) == 'function') this.onInit(); 
            return true;
        }
    this._container =
        function(){
            return $(this._selfId);
        }
    this._containerBar =
        function(){
            return this._container().childNodes[1];
        }
    this._containerContent =
        function(){
            return this._container().childNodes[2].childNodes[0];
        }
    this._getScrollButton1 =
        function(){
            return this._container().childNodes[3];
        }
    this._getScrollButton2 =
        function(){
            return this._container().childNodes[4];
        }
    this._drawBar =
        function(){
            var html = '<table class="TabsBar_Bar" cellspacing="0" cellpadding="0" align="' + this._parameters.tabsAlignment + '"><tr>';
            html +=  '<td class="TabsBar_BarSpaceStart"  style="width:' + this._parameters['tabsBarMargin'] + ';"></td>';
            for (var i = 0; i < this.items.length; i++){
                html += '<td id="' + this._selfId + 'Item' + i + '" class="TabsBar_BarItem' + ((this.items[i].flagDisabled)?'Disabled':'') + '"';
                if(!(this.items[i].flagDisabled))
                    html += 'onmouseover="__TabsBarItem_onMouseOver(this);" onmouseout="__TabsBarItem_onMouseOut(this);" onclick="__TabsBarItem_onClick(this,\'' + this._selfId + '\',\'' + i + '\')"';
                html += '>' + this.items[i]._drawBarItem() + '</td>';
            }
            html += '<td class="TabsBar_BarSpaceEnd" style="width:' + this._parameters['tabsBarMargin'] + ';"></td>';
            html += '</tr></table>';
            this._containerBar().innerHTML = html;
        // height
            var height = this._containerBar().style.height.substr(0,this._containerBar().style.height.length-2);
            this._containerBar().firstChild.style.marginTop = (height - this._parameters.tabsHeight) + 'px';
        // scroll buttons
            this._drawScrollButtons();
        // if no tab is selected
            if((this._tabSelectedIndex < 0)&&(this.items.length > 0)){
                this.tabSelect(0);
            }else{
            // if selected tab does not exist
                if(this._tabSelectedIndex >= this.items.length){
                    this.tabSelect(this.items.length - 1);
                }else{
                    this.items[this._tabSelectedIndex]._containerContent().style.display = 'block';
                }
            }
        }
    this._drawScrollButtons =
        function(){
            if(this._containerBar().offsetWidth > 0){
                this._getScrollButton1().style.display = (this._containerBar().scrollLeft == 0) ? 'none' : 'block';
                this._getScrollButton2().style.display = (this._containerBar().scrollLeft == (this._containerBar().scrollWidth - this._containerBar().offsetWidth)) ? 'none': '';
            }else{
                setTimeout('TabsBars["' + this._selfId + '"]._drawScrollButtons();',100);
            }
        }
    this._scroll =
        function(){
            if((this._scrollDirection == 'left')&&(this._containerBar().scrollLeft > 0)){
                this._containerBar().scrollLeft = this._containerBar().scrollLeft - 10;
                this._drawScrollButtons();
                return true;
            }
            if((this._scrollDirection == 'right')&&(this._containerBar().scrollLeft < (this._containerBar().scrollWidth - this._containerBar().offsetWidth))){
                this._containerBar().scrollLeft = this._containerBar().scrollLeft + 10;
                this._drawScrollButtons();
                return true;
            }
            if(this._scrollTimerID != null){
                window.clearInterval(this._scrollTimerID);
            }
            return false;
        }
    this.style =
        function (style){
            var tabsBarElement = $(this._selfId);
            if(style){
                if(style['width']) tabsBarElement.style.width = style['width'];
                if(style['height']) tabsBarElement.style.height = style['height'];
                if(style['border']) tabsBarElement.style.border = style['border'];
                if(style['background-color']) tabsBarElement.style.backgroundColor = style['background-color'];
            }
        };
    this.disable =
        function (){
            $(this._selfId).firstChild.style.display = 'block';
            return true;
        };
    this.enable =
        function (){
            $(this._selfId).firstChild.style.display = 'none';
            return true;
        };
    this.tabAdd =
        function(tabId,attribs,flagUnique,flagSelect){
            var newItem = null;
            if(this.items.length >= this._parameters['maxTabsAmount']){
                alert('Can\'t add a tab\nTabs amount has reached maximum value');
                return newItem;
            }
            for(var i = 0; i < this.items.length; i ++){
                if((this.items[i].id == tabId)&&(this.items[i].flagUnique))
                    newItem = this.items[i];
            }
            if(newItem == null){
                newItem = new TabsBarItem(this,tabId,attribs,flagUnique);
            }
            if(flagSelect){
                newItem.select();
            }
            return newItem;
        }
    this.tabSelect =
        function(TabsBarItemIndex){
            var heightToKeep = this._containerContent().offsetHeight;
			if((typeof(TabsBarItemIndex) != 'undefined')&&
			   (TabsBarItemIndex >= 0)&&(TabsBarItemIndex < this.items.length)&&
			   (TabsBarItemIndex != this._tabSelectedIndex)){
			// unselect old
				var objTabItem = $(this._selfId + 'Item' + this._tabSelectedIndex);
				if((objTabItem)&&(objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage.search('tabSelected') >= 0)){
					this.items[this._tabSelectedIndex]._containerContent().style.display = 'none';
					this._tabSelectedIndex = -1;
					objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage.replace('tabSelected','tabUnselected');
					objTabItem.childNodes[0].rows[0].cells[1].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[1].style.backgroundImage.replace('tabSelected','tabUnselected');
					objTabItem.childNodes[0].rows[0].cells[2].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[2].style.backgroundImage.replace('tabSelected','tabUnselected');
				}

			// select new
				objTabItem = $(this._selfId + 'Item' + TabsBarItemIndex);
				if((objTabItem)&&(objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage.search(/(tabUnselected)|(tabHover)/) >= 0)){
					this._tabSelectedIndex = TabsBarItemIndex;
					this.items[this._tabSelectedIndex]._containerContent().style.display = 'block';
					objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[0].style.backgroundImage.replace(/(tabUnselected)|(tabHover)/,'tabSelected');
					objTabItem.childNodes[0].rows[0].cells[1].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[1].style.backgroundImage.replace(/(tabUnselected)|(tabHover)/,'tabSelected');
					objTabItem.childNodes[0].rows[0].cells[2].style.backgroundImage = objTabItem.childNodes[0].rows[0].cells[2].style.backgroundImage.replace(/(tabUnselected)|(tabHover)/,'tabSelected');
				}
                if(typeof(this.onTabSelect) == 'function'){
                    this.onTabSelect(TabsBarItemIndex,this.items[TabsBarItemIndex]);
                }
			}
            if(this._containerContent().offsetHeight != heightToKeep){
                //alert(heightToKeep + ' ' + this._container().offsetHeight);
                //this._containerContent().style.height = heightToKeep + 'px';
            }
        }
	this.tabAction =
		function(TabsBarItemIndex,action){
			switch(action) {
				case 'close':
					this.tabClose(TabsBarItemIndex);
					break;
				default:
					break;
			}
		}
    this.tabClose =
        function(TabsBarItemIndex){
			if((TabsBarItemIndex)&&(TabsBarItemIndex >= 0)&&(TabsBarItemIndex < this.items.length)){
				this.items[TabsBarItemIndex]._removeContainer();
				this.items.splice(TabsBarItemIndex,1);
				this._drawBar();
			}
        }
    this.selectedIndex =
        function(){
            return this._tabSelectedIndex;
        }
    this.selectedTab =
        function(){
            return this.items[this._tabSelectedIndex];
        }
    this.scrollStart =
        function(direction){
            if(this._scrollTimerID != null){
                window.clearInterval(this._scrollTimerID);
            }
            this._scrollDirection = direction;
            this._scrollTimerID = window.setInterval('TabsBars["' + this._selfId + '"]._scroll()',100);
        }
    this.scrollStop =
        function(){
            if(this._scrollTimerID != null){
                window.clearInterval(this._scrollTimerID);
                this._scrollTimerID = null;
            }
        }
// initiating
	TabsBars[this._selfId] = this;
    this._init(containerId,attribs,initTabs);
}

function TabsBarItem(tabsBar,id,attribs,flagUnique){
    this._tabsBar = null;
	this._selfId = '';
    this._style = {};
    this.id = '';
    this.type = '';
    this.flagUnique = false;
    this.flagDisabled = false;
    this.icon = 'blank';
    this.caption = '';
    this.title = '';
    this.source = '';
	this.buttons = new Array({'image':'close','action':'close','title':'Close'});
// method
    this._init =
        function(tabsBar,id,attribs,flagUnique){
        // item properties
            this._tabsBar = tabsBar;
			this._tabsBar.items.push(this);
            this._selfId = tabsBar._selfId + ':' + Math.round(100000 * Math.random());;
            this.id = id;
            this.flagUnique = (flagUnique == true) ? true: false;
            this.type = this._tabsBar._tabTypes[0]; 
        // setting attributes
            if(attribs) this.setAttributes(attribs);
            this.draw();
            return true;
        }
	this._removeContainer =
		function (){
			var objContent = this._containerContent();
			if(objContent) objContent.parentNode.removeChild(objContent);
		}
	this._containerContent =
		function (){
			return $(this._selfId + ':Content');
		}
	this._drawBarItem =
        function(){
            var iAdd = (this.isSelected()) ? 'Selected' : 'Unselected';
			var html = '<table style="height: ' + this._tabsBar._parameters.tabsHeight + 'px;"><tr>';
            html += '<td style="background-image:url(' + this._tabsBar._imagesPath + '/tab' + iAdd + '_start.' + this._tabsBar._imagesType + ');padding: 3px 3px 0px 10px;">';
            html += '<img src="' + this._tabsBar._imagesPath + '/icons/' + this.icon + '.' + this._tabsBar._imagesType + '">';
            html += '</td>';
			html += '<td title="' + this.title + '" style="background-image:url(' + this._tabsBar._imagesPath + '/tab' + iAdd + '_bg.' + this._tabsBar._imagesType + '); color:' + this._tabsBar._parameters.tabsFontColor + ';">';
			html += this.caption;
            if((this._tabsBar._parameters['tabsHideButtons'])||(this.flagDisabled)){
                html += '&nbsp;&nbsp;&nbsp;';
            }else{
                for(var i = 0; i < this.buttons.length; i ++){
                    html += '<img class="TabsBar_BarItemButton" src="' + this._tabsBar._imagesPath + '/buttons/' + this.buttons[i].image + 'Gray.' + this._tabsBar._imagesType + '" align="absmiddle" onmouseover="__TabsBarItemButton_onMouseOver(this)" onmouseout="__TabsBarItemButton_onMouseOut(this)" onclick="return __TabsBarItemButton_onClick(this,\'' + this._tabsBar._selfId + '\',\'' + this.myOrder() + '\',\'' + this.buttons[i].action + '\')">';
                }
            }
			html += '</td>';
            html += '<td style=" background-image:url(' + this._tabsBar._imagesPath + '/tab' + iAdd + '_end.' + this._tabsBar._imagesType + ');"><div style="width: 7px;"></div></td>';
            html += '</tr></table>';
            return html;
        }
	this._drawContent =
		function(){
			var objContent;
			if(this._containerContent()){
				objContent = this._containerContent();
			}else{
				var objContent = document.createElement('DIV');
				objContent.id = this._selfId + ':Content';
				this._tabsBar._containerContent().appendChild(objContent);
			}
			objContent.style.height = '100%';
			objContent.style.width = '100%';
			objContent.style.display = 'none';
            objContent.style.padding = this._style['padding'];
            objContent.style.margin = this._style['margin'];
            switch (this.type){
                case 'content':
                    objContent.innerHTML = this.source;
                    break;
                case 'grab':
                    var objGrab = $(this.source);
                    if((objGrab)&&(objGrab.parentNode)){
                        objGrab.parentNode.removeChild(objGrab);
                        objContent.appendChild(objGrab);
                    }else{
                        alert('Error occured while drawing tab content.\n\nElement with id \"' + this.source + '\" not found.');
                    }
                    break;
                case 'iframe':
                    objContent.innerHTML = '<iframe src="' + this.source + '" frameborder="no" allowtransparency="yes" style="width:100%;height:100%;"></iframe>';
                    break;
                case 'ajax':
                    objContent.innerHTML = 'ajax';
                    break;
                default:
                    objContent.innerHTML = 'Content for this tab is not defined';
            }
		}
    this.setAttributes =
        function(attribs){
            if(attribs){
                if(attribs['type'])
                    if(typeof(attribs['type']) == 'number'){
                        if((attribs['type'] > 0)&&(attribs['type'] < this._tabsBar._tabTypes.length))
                            this.type = this._tabsBar._tabTypes[attribs['type']]
                    }else{
                        for(var i = 0; i < this._tabsBar._tabTypes.length; i++){
                            if(attribs['type'] == this._tabsBar._tabTypes[i]){
                                this.type = attribs['type'];
                                break;
                            }
                        }
                    }
                if(attribs['icon']) this.icon = attribs['icon'];
                if(attribs['caption']) this.caption = clearHTML(attribs['caption']);
                if(attribs['title']) this.title = clearHTML(attribs['title'].replace(/"/g,'\''));
                if(attribs['source']){
                // if source is to be URL
                    if((this.type == 'iframe')||(this.type == 'ajax')){
                        this.source = (attribs['source'].search(/["']/) < 0) ? attribs['source'] : 'about:blank';
                    }else{
                        this.source = attribs['source'];
                    }
                }
                this._style['padding'] = ((attribs['style'])&&(attribs['style']['padding'])) ? attribs['style']['padding'] : '0px';
                this._style['margin'] = ((attribs['style'])&&(attribs['style']['margin'])) ? attribs['style']['margin'] : '0px';
                this.flagDisabled = (attribs['disabled'] == true) ? true: false;
            }
        }
    this.draw =
        function(){
			this._drawContent();
            this._tabsBar._drawBar();
        }
    this.select =
        function(){
			this._tabsBar.tabSelect(this.myOrder());
        }
    this.close =
        function(){
			this._tabsBar.tabClose(this.myOrder());
        }
    this.isSelected =
        function(){
            return (this.myOrder() == this._tabsBar._tabSelectedIndex);
        }
	this.myOrder =
		function(){
			for(var i = 0; i < this._tabsBar.items.length; i++){
				if(this._tabsBar.items[i]._selfId == this._selfId)
					return i;
			}
		}
// initializing
    if(typeof(tabsBar) != 'undefined') this._init(tabsBar,id,attribs,flagUnique);

}

function __TabsBarScrollStart(objButton,TabsBarId,direction){
    if((TabsBars[TabsBarId])&&(TabsBars[TabsBarId]._selfId = TabsBarId)){
        objButton.className = 'TabsBar_ScrollButtonHover';
        TabsBars[TabsBarId].scrollStart(direction);
    }
}

function __TabsBarScrollStop(objButton,TabsBarId){
    if((TabsBars[TabsBarId])&&(TabsBars[TabsBarId]._selfId = TabsBarId)){
        objButton.className = 'TabsBar_ScrollButton';
        TabsBars[TabsBarId].scrollStop();
    }    
}

function __TabsBarItem_onMouseOver(objTab){
	if((objTab)&&(objTab.childNodes[0].rows[0].cells[0].style.backgroundImage.search('tabUnselected') >= 0)){
		objTab.childNodes[0].rows[0].cells[0].style.backgroundImage = objTab.childNodes[0].rows[0].cells[0].style.backgroundImage.replace('tabUnselected','tabHover');
		objTab.childNodes[0].rows[0].cells[1].style.backgroundImage = objTab.childNodes[0].rows[0].cells[1].style.backgroundImage.replace('tabUnselected','tabHover');
		objTab.childNodes[0].rows[0].cells[2].style.backgroundImage = objTab.childNodes[0].rows[0].cells[2].style.backgroundImage.replace('tabUnselected','tabHover');
	}
}

function __TabsBarItem_onMouseOut(objTab){
	if((objTab)&&(objTab.childNodes[0].rows[0].cells[0].style.backgroundImage.search('tabHover') >= 0)){
		objTab.childNodes[0].rows[0].cells[0].style.backgroundImage = objTab.childNodes[0].rows[0].cells[0].style.backgroundImage.replace('tabHover','tabUnselected');
		objTab.childNodes[0].rows[0].cells[1].style.backgroundImage = objTab.childNodes[0].rows[0].cells[1].style.backgroundImage.replace('tabHover','tabUnselected');
		objTab.childNodes[0].rows[0].cells[2].style.backgroundImage = objTab.childNodes[0].rows[0].cells[2].style.backgroundImage.replace('tabHover','tabUnselected');
	}	
}

function __TabsBarItem_onClick(objTab,TabsBarId,TabsBarItemIndex){
	if((TabsBars[TabsBarId])&&(TabsBars[TabsBarId]._selfId = TabsBarId))
		TabsBars[TabsBarId].tabSelect(TabsBarItemIndex);
}

function __TabsBarItemButton_onMouseOver(objButton){
	if((objButton)&&(objButton.src)&&(objButton.src.search('Gray.') >= 0)){
		objButton.src = objButton.src.replace('Gray.','Hover.');
	}
}

function __TabsBarItemButton_onMouseOut(objButton){
	if((objButton)&&(objButton.src)&&(objButton.src.search('Hover.') > 0)){
		objButton.src = objButton.src.replace('Hover.','Gray.');
	}
}
function __TabsBarItemButton_onClick(objButton,TabsBarId,TabsBarItemIndex,action){
	if((TabsBars[TabsBarId])&&(TabsBars[TabsBarId]._selfId = TabsBarId))
		TabsBars[TabsBarId].tabAction(TabsBarItemIndex,action);
	return false;
}

// -- Ajax Trees -------------------------------------------------------------->

var AjaxTrees = {};

// -- Tree object ------------------------------------------------------------->
function AjaxTree(containerId,source,attribs){
// attributes
	this._selfId = 'lyrAjaxTree' + Math.round(100000 * Math.random()); 
	this._source = source;
    this._sourceWithoutQuery = null;
	this._imagesPath = globalCMSPath + '/libraries/interface/images/AjaxTree';
	this._imagesType = 'gif';
	this._nodeTypes = new Array('folder','document','module');
	this._nodeStyles = new Array('','gray');
    this._parameters = {'rootId' : '',
                       'hideRoot' : false,
                       'nodesUnselectable' : false,
                       'nodesInheritStyle' : false,
                       'nodesListLimit' : 20,
                       'nodesListWhere' : ''
                       };
    this._focusedInputElementId = '';
    this._selectedNodesIds = new Array();
    this._unfoldedNodesIds = new Array();
	this.rootNode = new AjaxTreeRoot(this);

// events
    this.onInit = null;
    this.onNodeSelect = null;
    this.onNodeLoad = null;
    this.onNodeMove = null;
    this.onNodeFold = null;
    this.onNodeUnfold = null;
    this.onBeforeNodeSelect = null;

// methods
    this._init =
        function (containerId,source,attribs){
            this._sourceWithoutQuery = (this._source.indexOf('?') >= 0) ? this._source.substr(0,this._source.indexOf('?')) : this._source;
            this._parameters = {'rootId' : ((attribs)&&(attribs['rootId']))? attribs['rootId'] : '',
                               'hideRoot' : ((attribs)&&(attribs['hideRoot']))? true : false,
                               'nodesUnselectable' : ((attribs)&&(attribs['nodesUnselectable']))? true : false,
                               'nodesInheritStyle' : ((attribs)&&(attribs['nodesInheritStyle']))? true : false,
                               'nodesListLimit' : ((attribs)&&(attribs['nodesListLimit'] > 0)) ? attribs['nodesListLimit'] : 20,
                               'nodesListWhere' : ((attribs)&&(typeof(attribs['nodesListWhere']) != 'undefined')&&(attribs['nodesListWhere'] != '')) ? attribs['nodesListWhere'] : ''
                               };
            this.rootNode = new AjaxTreeRoot(this);
            this._selectedNodesIds = ((attribs)&&(attribs['selectedNodesIds'])&&(attribs['selectedNodesIds'].length)) ? attribs['selectedNodesIds'] : new Array();
        // if attribs defined
            if(attribs){
            // attributes
                if(attribs['imagesPath']) this._imagesPath = attribs['imagesPath'];
                if(attribs['imagesType']) this._imagesType = attribs['imagesType'];

            // events
                if(attribs['onInit']) this.onInit = attribs['onInit'];
                if(attribs['onSelect']) this.onNodeSelect = attribs['onSelect'];
                if(attribs['onLoad']) this.onNodeLoad = attribs['onLoad'];
                if(attribs['onMove']) this.onNodeMove = attribs['onMove'];
                if(attribs['onFold']) this.onNodeFold = attribs['onFold'];
                if(attribs['onUnfold']) this.onNodeUnfold = attribs['onUnfold'];
                if(attribs['onBeforeSelect']) this.onBeforeNodeSelect = attribs['onBeforeSelect'];
            }
        // creating html objects
            var treeElement;
            if(containerId !=''){
                if(($(containerId))&&($(containerId).appendChild)
                   &&(typeof($(containerId).appendChild) != 'undefined')){
                    treeElement = document.createElement('DIV');
                    treeElement.id = this._selfId; 
                    $(containerId).appendChild(treeElement);
                }else{
                    alert('Error occured while creating AjaxTree element:\nCan\'t find container "' + containerId + '"');
                    return false;
                }
            }else{
                document.writeln('<div id="' + this._selfId + '"></div>');
            }
            treeElement = $(this._selfId);
            if(typeof(treeElement) != 'object'){
                alert('Error occured while creating AjaxTree element');
                return false;
            }
            treeElement.style.display = 'block';
            treeElement.style.position = 'relative';
            treeElement.style.whiteSpace = 'nowrap';
            treeElement.style.overflow = 'auto';
            treeElement.style.height = '100%';
            treeElement.innerHTML="<div style=\"position:absolute; z-index:2; width:100%; height:100%; background-color: #f8f8f8; -moz-opacity:0.5; display:none;\"></div>";
            if((attribs)&&(attribs['style'])){
                if(attribs['style']['width']) treeElement.style.width = attribs['style']['width'];
                if(attribs['style']['height']) treeElement.style.height = attribs['style']['height'];
                if(attribs['style']['border']) treeElement.style.border = attribs['style']['border'];
                if(attribs['style']['background-color']) treeElement.style.backgroundColor = attribs['style']['background-color'];
            }
            if(typeof(this.onInit) == 'function') this.onInit();
            this.draw();
            return true;
        };
    this.source =
        function (source){
            this._source = source; 
            this._sourceWithoutQuery = (this._source.indexOf('?') >= 0) ? this._source.substr(0,this._source.indexOf('?')) : this._source;
            this.rootNode._source = source;
            this.rootNode.load();
        }
    this.draw =
        function (){
            this.rootNode.draw();
        };
    this.style =
        function (style){
            var treeElement = $(this._selfId);
            if(style){
                if(style['width']) treeElement.style.width = style['width'];
                if(style['height']) treeElement.style.height = style['height'];
                if(style['border']) treeElement.style.border = style['border'];
                if(style['background-color']) treeElement.style.backgroundColor = style['background-color'];
            }
        };
    this.hide =
        function(){
            $(this._selfId).style.display = 'none';
            return true;
        }
    this.show =
        function(){
            $(this._selfId).style.display = 'block';
            return true;
        }
    this.disable =
        function (){
            $(this._selfId).firstChild.style.display = 'block';
            return true;
        };
    this.enable =
        function (){
            $(this._selfId).firstChild.style.display = 'none';
            return true;
        };
    this.isEnabled=
        function (){
            return ($(this._selfId).firstChild.style.display != 'none');
        };
    this.getNodeById =
        function (nodeId){
            return this.rootNode.getNodeById(nodeId);
        };
    this.getNodesLike =
        function (nodeAttributes){
            var result = new Array; 
            if(typeof(nodeAttributes['id']) != 'undefined'){
                if(nodeAttributes['id'] == '')
                    result.push(this.rootNode)
                else
                    result = this.rootNode.getNodesLike(nodeAttributes);
            }
            return result;
        };
    this.getSelectedNodes =
        function (){
            var result = new Array();
            for(var i = 0; i < this._selectedNodesIds.length;i++){
                var nodeToPush = this.getNodeById(this._selectedNodesIds[i]);
                if(typeof(nodeToPush) != 'undefined')
                    result.push(nodeToPush);
            }
            return result;
        };
    this.methodNodeById =
        function (nodeId,method,arguments){
            return false;
        };
    this.methodNodesLike =
        function (nodeAttributes,method,arguments){
            var nodes = this.getNodesLike(nodeAttributes); 
            if((nodes)&&(nodes.length)&&(nodes.length > 0)){
                for(var i = 0; i < nodes.length; i++){
                    eval('nodes[i].' + method + '(arguments);');
                }
            }
            return false;
        };
    this.selectNodeById =
        function (nodeId,flagUnfoldPath,flagTryToReload,lastReloadedNodeId){
            if(nodeId.indexOf(this.rootNode._selfId) == 0){
            // default parameter values
                flagUnfoldPath = (flagUnfoldPath == false) ? false:true;
                flagTryToReload = (flagTryToReload == false) ? false:true;
                lastReloadedNodeId = (lastReloadedNodeId) ? lastReloadedNodeId : '';
            // proceeding node search through path
                var cNodeId = nodeId.substr(this.rootNode._selfId.length);
                if(cNodeId.substr(0,1) != '/')
                    return false;
                var ids = cNodeId.substr(1).split('/');
                var pNode = this.rootNode;
                for (var i = 0; i < ids.length; i++){
                    var cNode = this.getNodeById(this.rootNode._selfId + '/' + ids.slice(0,i + 1).join('/'));
                // if current node is found
                    if(cNode){
                        pNode.unfold();
                        if(i == ids.length -1){
                            cNode.select();
                            cNode._scrollToIt();
                        }else{
                            pNode = cNode;
                        }
                    }else{
                    // else if parent node is loaded
                        if(pNode._loaded){
                            pNode._scrollToIt();
                            pNode.unfold();
                        // if flagTryToReload And pNode is not last reloaded node
                            if((flagTryToReload)&&(lastReloadedNodeId != pNode._selfId)){
                                eval("pNode.onAfterLoadAndDraw =\
                                    function (){\
                                        this._tree.selectNodeById('" + nodeId + "'," + flagUnfoldPath + "," + flagTryToReload + ", '" + pNode._selfId + "');\
                                    }\
                                    ");
                                pNode.load();
                        // otherwise
                            }else{
                                alert("Can't find node '" + nodeId + "' for select");
                            }
                    // otherwise trying to load
                        }else{
                            pNode._scrollToIt();
                            eval("pNode.onAfterLoadAndDraw =\
                                function (){\
                                    this.unfold();\
                                    this._tree.selectNodeById('" + nodeId + "'," + flagUnfoldPath + "," + flagTryToReload + ", '" + pNode._selfId + "');\
                                }\
                                ");
                            pNode.load();
                        }
                        break;
                    }
                }
            }
            return false;
        };
    this.selectNodesLike =
        function (nodeAttributes){
        }
    this.updateNodesStates =
        function (){
            for(var i = 0; i < this._unfoldedNodesIds.length; i++){
                var node = this.getNodeById(this._unfoldedNodesIds[i]);
                if((node)&&(node._selfId == this._unfoldedNodesIds[i])&&(node._flagFolded)) node.unfold();
            }
            var selectedNodes = this.getSelectedNodes();
            for(var i = 0; i < selectedNodes.length; i++){
                selectedNodes[i].select(false);
                if(typeof(this.onNodeSelect) == 'function')
                    this.onNodeSelect(selectedNodes[i].myId(), selectedNodes[i].myPath(), selectedNodes[i].values);
            }
        };
// initiating
	AjaxTrees[this._selfId] = this;
    if((typeof(containerId) != 'undefined')&&(typeof(source) != 'undefined')) this._init(containerId,source,attribs);
}


//-- Tree node object --------------------------------------------------------->
function AjaxTreeNode(parent,id,source,attribs){
// attributes
    this._tree = null;
	this._parent = null;
	this._selfId = '';
	this._childs = {};
	this._source = '';
    this._styleName = '';
	this._styleCSS = '';
    this._flagLoaded = false;
    this._flagAjaxing = false;
	this._flagFolded = true;
	this.type = '';
	this.icons = new Array();
    this.caption = '';
	this.title = '';
	this.values = {};
// events
    this.onAfterLoad = null;
    this.onAfterLoadAndDraw = null;
// methods
    this._init =
        function (parent,id,source,attribs){
        // node properties
            this._tree = parent._tree;
            this._parent = parent;
            this._selfId = parent._selfId + '/' + id; 
            this._childs = {'list' : new Array(), 'count' : 0, 'found' : 0, 'page' : 0, 'where' : new Array()};
            this._source = (source.substr(0,1) == '?') ? this._tree._sourceWithoutQuery + source : source;
        // draw properties
            this.type = this._tree._nodeTypes[0]; 
            this.title = '[' + id + ']';
        // setting attributes
            if(attribs) this.setAttributes(attribs);
        };
    this._container =
        function (){
            return $(this._tree._selfId + ':' + this._parent._selfId + ':childs');
        };
    this._scrollToIt =
        function (){
            scrollToElement($(this._tree._selfId + ':' + this._selfId),$(this._tree._selfId));
        }
    this.draw =
        function (){ 
            if((isIE)&&(this._container().style.height == ''))
                this._container().style.height = '2px';
                
            var htmlAddIcons = '';
            for(var i = 0; i < this.icons.length; i++ ){
                htmlAddIcons = htmlAddIcons + '<img src="' + this._tree._imagesPath + '/icons/' + this.icons[i] + '.' + this._tree._imagesType + '" alt="' + this.icons[i] + '">';
            }
            var htmlTreeNode = '<div class="TreeNodeIcons" \
                    style="background-image:url(' + this._tree._imagesPath + '/' + this.type + ((this._childs.count == 0)?((this.type != 'document')?'Empty':''):((this._flagFolded)?'':'Unfolded')) + ((this.myStyle() != '')? '.' + this.myStyle() : '') + '.' + this._tree._imagesType + ');"\
                    onClick="__AjaxTreeNode_onIconClick(\'' + this._tree._selfId + '\',\'' + this._selfId + '\')">'
                + htmlAddIcons + '</div>'
                + '<div class="TreeNodeCaption' + ((this.isSelected())?'Active':'') + '" title="' + shorten(this.title,255) + '"'
                + ((this._tree._parameters.nodesUnselectable)?' ':' onMouseOver="__AjaxTreeNode_onMouseOver(this)" onMouseOut="__AjaxTreeNode_onMouseOut(this)"')
                + ' onClick="__AjaxTreeNode_onClick(\'' + this._tree._selfId + '\',\'' + this._selfId + '\')"><span class="TreeNodeCaptionS' + ('tyle-' + this.myStyle()).camelize() + '"' + ((this._styleCSS != '') ? ' style="' + this._styleCSS + '"' : '') + '>' + shorten(this.caption,100) + '&nbsp;</span></div>';
        // drawing node Element
            var nodeElement;
            if($(this._tree._selfId + ':' + this._selfId)){
                nodeElement = $(this._tree._selfId + ':' + this._selfId)
            }else{
                nodeElement = document.createElement('DIV');
                nodeElement.id = this._tree._selfId + ':' + this._selfId;
                this._container().appendChild(nodeElement);
            }
            nodeElement.className = 'TreeNode';
            nodeElement.innerHTML = htmlTreeNode;
        // drawing childs Element
            var childsElement;
            if($(this._tree._selfId + ':' + this._selfId + ':childs')){
                childsElement = $(this._tree._selfId + ':' + this._selfId + ':childs');
                childsElement.innerHTML = '';
            }else{
                childsElement = document.createElement('DIV');
                childsElement.id = this._tree._selfId + ':' + this._selfId + ':childs';
                this._container().appendChild(childsElement);
            }
            childsElement.className = 'TreeNodeChilds';
        // drawing childs list's header if needed
            if(this._childs.count > this._tree._parameters.nodesListLimit){
                var htmlAddHeader = '<div class="TreeNodeChildsHeader" style="background-image:url(' + this._tree._imagesPath + '/' + 'branch.' + this._tree._imagesType + ')" >';
            // where form
                var htmlAddWhere = '';
                for (var i = 0; i < this._childs.where.length; i++){
                    htmlAddWhere += '<tr><td height="20">' + this._childs.where[i].caption + '</td><td><input id="' + this._tree._selfId + ':' + this._selfId + ':input' + i + '" name="' + this._childs.where[i].name +'" type="text" value="' + this._childs.where[i].value + '" onKeyPress="__AjaxTreeNode_onWhereInputKeyPress(\'' + this._tree._selfId + '\', \'' + this._selfId + '\',event,this);"></td></tr>';
                }
                if(htmlAddWhere != ''){
                    htmlAddWhere = '<table cellspacing="2" cellpadding="0" border="0" class="TreeNodeChildsWhere">' + htmlAddWhere + '<tr><td align="right" colspan="3"><a href="javascript: void __AjaxTreeNodeWhereSubmit(\'' + this._tree._selfId + '\', \'' + this._selfId + '\')">Найти</a> | <a href="javascript: void __AjaxTreeNode_reload(\'' + this._tree._selfId + '\', \'' + this._selfId + '\', {\'childsPage\' : \'0\',\'childsWhere\':{}});">Показать все</a></td></tr></table><span class="TreeNodeChildsCountFoundCaption">&nbsp;&nbsp;показано ' + this._childs.found + ' по ' + this._tree._parameters.nodesListLimit + ' (всего ' + this._childs.count +')</span>';
                    htmlAddHeader += htmlAddWhere;
                }
            // paged list
                if(this._childs.found > this._tree._parameters.nodesListLimit){
                    
                    htmlAddHeader += '<table cellspacing="0" cellpadding="0" border="0"><tr><td style="background-position: -4px;background-image:url(\'' + this._tree._imagesPath + '/' + 'pages.' + this._tree._imagesType + '\');">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>';
                    var start = 0;
                    var end = 0;
                    if((this._childs.found / this._tree._parameters.nodesListLimit) < 12){
                        start = 0;
                        end = Math.ceil(this._childs.found / this._tree._parameters.nodesListLimit);
                        for(var i = 0; i < end; i++){
                            htmlAddHeader += '<td class="TreeNodeChildsPage'
                                + ((i == this._childs.page)?'Active" ':'" onMouseOver="this.className = \'TreeNodeChildsPageHover\';" onMouseOut="this.className = \'TreeNodeChildsPage\';" onclick="__AjaxTreeNode_reload(\'' + this._tree._selfId + '\',\'' + this._selfId + '\',{\'childsPage\':\'' + i + '\'});"')
                                + '>&nbsp;' + (i + 1) + '&nbsp;</td>';
                        }
                    }else{
                        if(this._childs.page > 6){
                            htmlAddHeader += '<td class="TreeNodeChildsPage'
                                + '" onMouseOver="this.className = \'TreeNodeChildsPageHover\';" onMouseOut="this.className = \'TreeNodeChildsPage\';" onclick="__AjaxTreeNode_reload(\'' + this._tree._selfId + '\',\'' + this._selfId + '\',{\'childsPage\':\'0\'});"'
                                + '>&nbsp;1&nbsp;</td><td class="TreeNodeChildsPage">...</td>';
                        }
                        if(this._childs.page < 7){
                            start =  0;
                            end = (this._childs.page < (this._childs.found / this._tree._parameters.nodesListLimit - 6)) ? 10 : (this._childs.found / this._tree._parameters.nodesListLimit - 11);
                        }else{
                            start = (this._childs.page < (this._childs.found / this._tree._parameters.nodesListLimit - 6)) ? this._childs.page - 4 : this._childs.page - 11 + (Math.round(this._childs.found / this._tree._parameters.nodesListLimit) - this._childs.page);
                            end = (this._childs.page < (this._childs.found / this._tree._parameters.nodesListLimit - 6)) ? (this._childs.page -1 + 6) : (this._childs.found / this._tree._parameters.nodesListLimit);
                        }
                        for(var i = start; i < end; i++){
                            htmlAddHeader += '<td class="TreeNodeChildsPage'
                                + ((i == this._childs.page)?'Active" ':'" onMouseOver="this.className = \'TreeNodeChildsPageHover\';" onMouseOut="this.className = \'TreeNodeChildsPage\';" onclick="__AjaxTreeNode_reload(\'' + this._tree._selfId + '\',\'' + this._selfId + '\',{\'childsPage\':\'' + i + '\'});"')
                                + '>&nbsp;' + (i + 1) + '&nbsp;</td>';
                        }
                        if(this._childs.page < (this._childs.found / this._tree._parameters.nodesListLimit - 6)){
                            htmlAddHeader += '<td class="TreeNodeChildsPage">...</td><td class="TreeNodeChildsPage'
                                + '" onMouseOver="this.className = \'TreeNodeChildsPageHover\';" onMouseOut="this.className = \'TreeNodeChildsPage\';" onclick="__AjaxTreeNode_reload(\'' + this._tree._selfId + '\',\'' + this._selfId + '\',{\'childsPage\':\'' + Math.floor(this._childs.found / this._tree._parameters.nodesListLimit) + '\'});"'
                                + '>&nbsp;' + (Math.floor(this._childs.found / this._tree._parameters.nodesListLimit) + 1) + '&nbsp;</td>';
                        }
                    }
                    htmlAddHeader += '</td></table>';
                    
                }
                htmlAddHeader += '</div>';
                childsElement.innerHTML = htmlAddHeader;
                if($(this._tree._focusedInputElementId))
                    $(this._tree._focusedInputElementId).focus();
            }
        // drawing childs
            childsElement.style.display = (this._flagFolded) ? 'none' : ''; 
            if(this._flagLoaded > 0){
                if(this._childs.list.length > 0){
                    for(var i = 0; i < this._childs.list.length; i++)
                        this._childs.list[i].draw();
                }else{
                    childsElement.innerHTML += '<table cellspacing="0" cellpadding="0" border="0" style="height:20px; background-repeat:no-repeat; background-position: 3px top;background-image:url(\'' + this._tree._imagesPath + '/' + 'branch.' + this._tree._imagesType + '\'); color:#444444;"><tr><td style="width:32px;background-position: 1px;background-image:url(\'' + this._tree._imagesPath + '/' + 'pages.' + this._tree._imagesType + '\');"><img src="' + node._tree._imagesPath + '/' + 'blank.' + node._tree._imagesType + '" width="32" height="1"></td><td>ничего не найдено</td></tr></table>';
                }
            }else{
                childsElement.innerHTML = '<img align="absmiddle" src="' + this._tree._imagesPath + '/loading.gif"> loading';
            }
        // if current node is a root node
            if(this._parent == null){
                nodeElement.style.left = '-10px';
                nodeElement.firstChild.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + 'root.' + this._tree._imagesType + ')';
                nodeElement.firstChild.onclick = '';
                childsElement.style.left = '-10px';
                if(this._tree._parameters.hideRoot)
                    nodeElement.style.display = 'none';
            }
        // if this node is last in list
            if(!(this.isLast())){
                nodeElement.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + 'branch.' + this._tree._imagesType + ')';
                childsElement.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + 'branch.' + this._tree._imagesType + ')';
            }else{
                nodeElement.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + 'branch.' + this._tree._imagesType + ')';
                nodeElement.style.backgroundRepeat = 'no-repeat';
            }
        // load childs list if its' necessary
            if((!(this._flagFolded))&&(!(this._flagLoaded))) this.load();
        };
    this.load =
        function (){ 
            if(this._source == '') {
                if((this._parent != null)&&(this._parent != this)&&(typeof(this._parent.load) == 'function'))
                    return this._parent.load()
                else
                    return false;
            }
            var url = this._source + ((this._source.indexOf('?') >= 0) ? '&': '?')
                    + 'limit=' + (this._tree._parameters.nodesListLimit * this._childs.page) + ',' + this._tree._parameters.nodesListLimit
                    + '&AjaxTreeId=' + this._tree._selfId + '&AjaxTreeNodeId=' + this._selfId + '&AjaxRequestForSerializedData=1';
            if(this._childs.where.length > 0){
                var urlAddWhere = new Array();
                for(var i = 0; i < this._childs.where.length; i++)
                    if((this._childs.where[i].value)&&(this._childs.where[i].value != ''))
                        urlAddWhere.push(this._childs.where[i].name + '=' + encodeURI(this._childs.where[i].value))
                if(urlAddWhere.join(')AND(') != '')
                    url += '&where=(' + urlAddWhere.join(')AND(') + ')';
            }
            if(this._tree._parameters['nodesListWhere'] != ''){
                url += '&only=' + this._tree._parameters['nodesListWhere'];
            }
            this._flagAjaxing = true; 
            var req = new Ajax.Request(url,
                                       {'method':'get',
                                        'onSuccess': __AjaxTreeNodeHandleAjaxResponse,
                                        'onFailure': __AjaxTreeNodeReturnAjaxError
                                        }); 
            //
            return true;
        };
    this.fold =
        function (){
            var objIcon = $(this._tree._selfId + ':' + this._selfId).firstChild;
            var objChilds = $(this._tree._selfId + ':' + this._selfId + ':childs');
            for(var i = 0; i < this._tree._unfoldedNodesIds.length; i++)
                if(this._tree._unfoldedNodesIds[i] == this._selfId)
                    this._tree._unfoldedNodesIds.splice(i,1);
            objIcon.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + this.type + ((this.myStyle() != '') ? '.' + this.myStyle() : '') + '.' + this._tree._imagesType + ')';
            objChilds.style.display = 'none';
            this._flagFolded = true;
        // event handler
            var path = this._selfId.split('/');
            var id = path.pop();
            if(typeof(this._tree.onNodeFold) == 'function')
                this._tree.onNodeFold(id,path.join('/'),this.values);
            return true;
        };
    this.unfold =
        function (){ 
            if((this.type == 'document')||(this._childs.count == 0)) return false;
            var objIcon = $(this._tree._selfId + ':' + this._selfId).firstChild;
            var objChilds = $(this._tree._selfId + ':' + this._selfId + ':childs');
            for(var i = 0; i < this._tree._unfoldedNodesIds.length; i++)
                if(this._tree._unfoldedNodesIds[i] == this._selfId)
                    this._tree._unfoldedNodesIds.splice(i,1);
            this._tree._unfoldedNodesIds.push(this._selfId);
            objIcon.style.backgroundImage = 'url(' + this._tree._imagesPath + '/' + this.type + 'Unfolded' + ((this.myStyle() != '') ? '.' + this.myStyle() : '') + '.' + this._tree._imagesType + ')';
            objChilds.style.display = '';
            this._flagFolded = false;
        // event handler
            var path = this._selfId.split('/');
            var id = path.pop();
            if(typeof(this._tree.onNodeUnfold) == 'function')
                this._tree.onNodeUnfold(id,path.join('/'),this.values);
            if((!(this._flagLoaded))&&(!(this._flagAjaxing))) this.load();
            return true;
        };
    this.select =
        function (flagClearSelectedNodes){
            if(typeof(this._tree.onBeforeNodeSelect) == 'function'){
                var path = String(this._selfId).split('/');
                var id = path.pop();
                if(!(this._tree.onBeforeNodeSelect(id,path.join('/'),this.values)))
                   return false;
            }
            if(flagClearSelectedNodes != false)
                flagClearSelectedNodes = true;
            if(flagClearSelectedNodes){
                if((this._tree._selectedNodesIds.length == 1)&&(this._tree._selectedNodesIds[0] == this._selfId))
                    return false;
                for(var i = 0; i < this._tree._selectedNodesIds.length; i++){
                    var nodeElement = $(this._tree._selfId + ':' + this._tree._selectedNodesIds[i]);
                    if((nodeElement)&&(nodeElement.lastChild))
                        nodeElement.lastChild.className = 'TreeNodeCaption';
                }
                this._tree._selectedNodesIds.splice(0,this._tree._selectedNodesIds.length);
            }else{
                for(var i = 0; i < this._tree._selectedNodesIds.length; i++){
                    if(this._tree._selectedNodesIds[i] == node._selfId)
                        this._tree._selectedNodesIds.splice(i,1);
                }
            } 
            this._tree._selectedNodesIds.push(this._selfId);
            for(var i = 0; i < this._tree._selectedNodesIds.length; i++){
                var nodeElement = $(this._tree._selfId + ':' + this._tree._selectedNodesIds[i]);
                if((nodeElement)&&(nodeElement.lastChild))
                    nodeElement.lastChild.className = 'TreeNodeCaptionActive';
            }
            return true;
        }
    this.addChild =
        function (id,source,attribs,flagDoNotRedraw){
            if(this.type == 'document') return false;
            if(typeof(id) == 'undefined') return false;
            var child = new AjaxTreeNode(this,id,source,attribs);
            this._childs.list.push(child);
            if(this._childs['count'] < this._childs.list.length)
                this._childs['count'] = this._childs.list.length
            if(!(flagDoNotRedraw)){
                this.draw();
            }
            return child;
        };
    this.getNodeById =
        function (nodeId){ 
            if(nodeId == this._selfId)
                return this
            else
                if(nodeId.indexOf(this._selfId) == 0)
                    for(var i=0; i < this._childs.list.length; i++){
                        var node = this._childs.list[i].getNodeById(nodeId);
                        if(node) return node;
                    }
            return undefined;
        };
    this.getNodesLike =
        function (nodeAttributes){
            var result = new Array(); 
            for (var i = 0; i < this._childs.list.length; i ++){
                if((nodeAttributes['id'])&&(nodeAttributes['id'] != '')){
                    if((this._childs.list[i]._selfId.indexOf('/' + nodeAttributes['id']) >= 0)
                       &&(this._childs.list[i]._selfId.indexOf('/' + nodeAttributes['id']) == (this._childs.list[i]._selfId.length - nodeAttributes['id'].length - 1))){
                        result.push(this._childs.list[i]);
                    }
                    var childResult = this._childs.list[i].getNodesLike(nodeAttributes);
                    if(childResult.length > 0)
                        result = result.concat(childResult);
                }
            }
            return result;
        };
    this.setAttributes =
        function (attribs){
            if(attribs){
                if(attribs['type'])
                    if(typeof(attribs['type']) == 'number'){
                        if((attribs['type'] > 0)&&(attribs['type'] < this._tree._nodeTypes.length))
                            this.type = this._tree._nodeTypes[attribs['type']]
                    }else{
                        for(var i = 0; i < this._tree._nodeTypes.length; i++){
                            if(attribs['type'] == this._tree._nodeTypes[i]){
                                this.type = attribs['type'];
                                break;
                            }
                        }
                    }
                if(attribs['styleName']) this._styleName = attribs['styleName'];
				if(attribs['styleCSS']) this._styleCSS = attribs['styleCSS'];
				if(attribs['caption']) this.caption = clearHTML(attribs['caption']);
				if(attribs['title']) this.title = clearHTML(attribs['title'].replace(/"/g,'\''));
                if(attribs['icons']) this.icons = attribs['icons'];
                if(attribs['values']) this.values = attribs['values'];
                if(attribs['childsCount']) this._childs['count'] = attribs['childsCount'];
                if(attribs['childsFound']) this._childs['found'] = attribs['childsFound'];
            }
        };
    this.isSelected =
        function(){
            for(var i = 0; i < this._tree._selectedNodesIds.length; i++)
                if(this._tree._selectedNodesIds[i] == this._selfId)
                    return true;
            return false;
        }
    this.isRoot =
        function(){
            return ((this._parent == null)&&(this._tree.rootNode == this));
        }
    this.isFirst =
        function(){
            if(this.isRoot())
                return true
            else
                return (this.myOrder() == 0)
        }
    this.isLast =
        function(){
            if(this.isRoot())
                return true
            else
                return (this.myOrder() == (this._parent._childs.list.length - 1))
        }
	this.myChilds =
		function(){
			return this._childs.list;
		}
    this.myOrder =
        function(){
            if(this.isRoot()){
                return 0
            }else{
                if(this._parent != null)
                    for(var i = 0; i <  this._parent._childs.list.length; i++)
                        if(this == this._parent._childs.list[i]) return i;
                return null;
            }
        }
    this.myId =
        function(){
            return this._selfId.split('/').pop();
        }
    this.myPath =
        function(){
            var path = this._selfId.split('/');
            var id = path.pop();
            return path.join('/');
        }
    this.myType =
        function(setType){
            if(this._tree._nodeTypes.indexOf(setType) >= 0){
                this.type = setType;
                this.draw();
            }
            return this.type;
        }
    this.myStyle =
        function(setStyle){
            if(this._tree._nodeStyles.indexOf(setStyle) >= 0){
                this._styleName = setStyle;
                this.draw();
            }
            if((!this._tree._parameters['nodesInheritStyle'])||(this._styleName != '')||(this.isRoot())){
                return this._styleName;
            }else{
                return this._parent.myStyle();
            }
        }
    this.moveIn =
        function(){
            return false;
        }
    this.moveOut =
        function(){
            return false;
        }  
    this.moveUp =
        function(){
            var myOrder = this.myOrder(); 
            if((myOrder != null)&&(myOrder > 0)){
                this._parent._childs.list[myOrder] = this._parent._childs.list[myOrder - 1];
                this._parent._childs.list[myOrder - 1] = this;
                this._parent.draw();
                if(typeof(this._tree.onNodeMove) == 'function')
                    this._tree.onNodeMove(this._parent.selfId, myOrder - 1);
                return true;
            }
            return false;
        }
    this.moveDown =
        function(){
            if(!(this.isLast())){
                var myOrder = this.myOrder(); 
                if((myOrder != null)&&(myOrder < (this._parent._childs.list.length - 1))){
                    this._parent._childs.list[myOrder] = this._parent._childs.list[myOrder + 1];
                    this._parent._childs.list[myOrder + 1] = this;
                    this._parent.draw();
                    if(typeof(this._tree.onNodeMove) == 'function')
                        this._tree.onNodeMove(this._parent.selfId, myOrder + 1);
                    return true;
                }
            }
            return false;            
        }
// initializing
    if(typeof(parent) != 'undefined') this._init(parent,id,source,attribs);
}

function AjaxTreeRoot(tree,attribs){
// attributes
    this.constructor(undefined,'',tree._source,attribs);
// methods
    this._init =
        function (tree,attribs){ 
            this._tree = tree;
            this._selfId = tree._parameters.rootId;
            this._childs = {'list' : new Array(), 'count' : 0, 'found' : 0, 'page' :0, 'where' : new Array()};
            this._source = this._tree._source;
            this._flagLoaded = false;
        // draw properties
            this.type = this._tree._nodeTypes[0];
            this._flagFolded = false;
            this._styleName = ((attribs)&&(attribs['styleName']))?attribs['styleName']:'';
            this.icons = new Array();
            this.caption = '/';
            this.title = '[root]';
            this.values = new Array();
        };
    this.fold =
        function (){
            return false
        };
	this.unfold =
        function (){
            return false
        };
    this._container =
        function (){
            return $(this._tree._selfId);
        }
// initializing
    if(typeof(tree) != undefined) this._init(tree,attribs);
}

AjaxTreeRoot.prototype = new AjaxTreeNode; 

function __AjaxTreeNode_onMouseOver(objCaption){
    if(objCaption.className != 'TreeNodeCaptionActive')
        objCaption.className = 'TreeNodeCaptionHover';
}

function __AjaxTreeNode_onMouseOut(objCaption){
    if(objCaption.className != 'TreeNodeCaptionActive')
        objCaption.className = 'TreeNodeCaption';
}
// Fold/Unfold actions
function __AjaxTreeNode_onIconClick(treeId, nodeId){
    if((AjaxTrees[treeId])&&(AjaxTrees[treeId]._selfId == treeId)){
        var AjaxTreeNode = AjaxTrees[treeId].getNodeById(nodeId);
        if((AjaxTreeNode)&&(AjaxTreeNode._selfId == nodeId)&&(!(AjaxTreeNode._childs.count == 0))){
            if(AjaxTreeNode._flagFolded) AjaxTreeNode.unfold()
            else AjaxTreeNode.fold();
        }
    }
}

function __AjaxTreeNode_onClick(treeId, nodeId){
    if((AjaxTrees[treeId])&&(AjaxTrees[treeId]._selfId == treeId)&&(!(AjaxTrees[treeId]._parameters.nodesUnselectable))){
        if(AjaxTrees[treeId].getNodeById(nodeId).select(true)){
            var path = nodeId.split('/');
            var id = path.pop();
            if(typeof(AjaxTrees[treeId].onNodeSelect) == 'function')
                AjaxTrees[treeId].onNodeSelect(id,path.join('/'),AjaxTrees[treeId].getNodeById(nodeId).values);
        }
    }
}

function __AjaxTreeNode_onContext(treeId, nodeId){
    if((AjaxTrees[treeId])&&(AjaxTrees[treeId]._selfId == treeId)){
        var AjaxTreeNode = AjaxTrees[treeId].getNodeById(nodeId);
        if((AjaxTreeNode)&&(AjaxTreeNode._selfId == nodeId)&&(!(AjaxTreeNode._childs.count == 0))){
            
        }
    }
}

function __AjaxTreeNode_reload(treeId, nodeId, attribs){
    if((AjaxTrees[treeId])&&(AjaxTrees[treeId]._selfId == treeId)){
        var AjaxTreeNode = AjaxTrees[treeId].getNodeById(nodeId);
        if((AjaxTreeNode)&&(AjaxTreeNode._selfId == nodeId)&&(!(AjaxTreeNode._childs.count == 0))){
            if((attribs)&&(attribs['childsPage'])) AjaxTreeNode._childs.page = attribs['childsPage'];
            if((attribs)&&(attribs['childsWhere'])) {
                for(var i = 0; i < AjaxTreeNode._childs.where.length; i++)
                    if((AjaxTreeNode._childs.where[i].name)&&(typeof(attribs['childsWhere'][AjaxTreeNode._childs.where[i].name]) != 'undefined'))
                        AjaxTreeNode._childs.where[i].value = attribs['childsWhere'][AjaxTreeNode._childs.where[i].name]
                    else
                        AjaxTreeNode._childs.where[i].value = '';
            }
            AjaxTreeNode.load();
        }
    }
}

function __AjaxTreeNode_onWhereInputKeyPress(treeId,nodeId,event,objInput){
    var keynum;
    if(typeof(event.keyCode) != 'undefined'){
        keynum = event.keyCode;
    }else if(typeof(event.which) != 'undefined'){
        keynum = event.which;
    }
    if(keynum == 13){
        __AjaxTreeNodeWhereSubmit(treeId, nodeId);
        AjaxTrees[treeId]._focusedInputElementId = objInput.id;
    }
}

function __AjaxTreeNodeWhereSubmit(treeId, nodeId){
    var where = {};
    for(var i = 0; i < AjaxTrees[treeId].getNodeById(nodeId)._childs.where.length; i++){
        var objInput = $(treeId + ':' + nodeId + ':input' + i);
        if(objInput.name) where[objInput.name] = objInput.value;
    }
    __AjaxTreeNode_reload(treeId, nodeId, {'childsPage' : '0', 'childsWhere' : where});
    return false;
}

function __AjaxTreeNodeHandleAjaxResponse(transport){
    var result = unserialize(transport.responseText);
    if(typeof(result['AjaxTreeNodeId']) != 'undefined'){
        if(typeof(AjaxTrees[result['AjaxTreeId']]) == 'undefined'){
            alert('Error occured while processing tree branch load:\n\n' + "Can't find AjaxTree with ID '" + result['AjaxTreeId'] + "'");
            return false;
        }
        var node = AjaxTrees[result['AjaxTreeId']].getNodeById(result['AjaxTreeNodeId']);
        if((node)&&(node._selfId == result['AjaxTreeNodeId'])){ 
            node._flagAjaxing = false;
            node._flagLoaded = true;
            // if message returned then printing error message
            if((typeof(result['AjaxRequestReturnedMessage']) != 'undefined')&&(result['AjaxRequestReturnedMessage'] != '')){
                $(node._tree._selfId + ':' + node._selfId + ':childs').innerHTML =
                    '<img align="absmiddle" src="' + node._tree._imagesPath + '/warning.gif">'
                    + '<span style="color:#cc0000;">' + clearHTML(result['AjaxRequestReturnedMessage']) + '</span>';
            }else{
            // reading received data
                node._childs.count = result['AjaxTreeNodeChildsCount'];
                node._childs.found = result['AjaxTreeNodeChildsFound'];
                node._childs.where = result['AjaxTreeNodeChildsWhere'];
                node._childs.list.splice(0,node._childs.list.length);
                if(result['AjaxTreeNodeAttributes']){
                    node.setAttributes(result['AjaxTreeNodeAttributes']);
                }
                if(result['AjaxTreeNodeChilds'].length){ 
                    for(var i = 0; i < result['AjaxTreeNodeChilds'].length; i++)
                        node.addChild(result['AjaxTreeNodeChilds'][i]['id'],result['AjaxTreeNodeChilds'][i]['source'],result['AjaxTreeNodeChilds'][i]['attributes'],1)
                }
            // event after load
                if(typeof(node.onAfterLoad) == 'function'){
                    node.onAfterLoad();
                    node.onAfterLoad = null;
                }
            // drawing changes
                node.draw();
            // event after load
                if(typeof(node.onAfterLoadAndDraw) == 'function'){
                    node.onAfterLoadAndDraw();
                    node.onAfterLoadAndDraw = null;
                }
            // updating nodes status
                AjaxTrees[result['AjaxTreeId']].updateNodesStates();
            // event on tree node load
                if(typeof(node._tree.onNodeLoad) == 'function'){
                    node._tree.onNodeLoad(node);
                }
            }
        }else{
            alert('Error occured while processing tree branch load:\n\n' + "Can't find AjaxTreeNode with ID '" + result['AjaxTreeNodeId'] + "'");
        }
    }else{
        if(typeof(result['ReturnedMessage']) != 'undefined'){
            if((typeof(result['RequestParams']) != 'undefined')
               &&(typeof(result['RequestParams']['AjaxTreeId']) != 'undefined')
               &&(typeof(result['RequestParams']['AjaxTreeNodeId']) != 'undefined')){
                var node = AjaxTrees[result['RequestParams']['AjaxTreeId']].getNodeById(result['RequestParams']['AjaxTreeNodeId']);
                if((node)&&(node._selfId == result['RequestParams']['AjaxTreeNodeId'])){
                    node._flagAjaxing = false;
                    node._flagLoaded = true;
                    $(node._tree._selfId + ':' + node._selfId + ':childs').innerHTML = 
                        '<table cellspacing="0" cellpadding="0" border="0" style="height:20px; background-repeat:no-repeat; background-position: 3px top;background-image:url(\'' + node._tree._imagesPath + '/' + 'branch.' + node._tree._imagesType + '\'); color:#cc0000;"><tr><td style="width:32px;background-position: 1px;background-image:url(\'' + node._tree._imagesPath + '/' + 'pages.' + node._tree._imagesType + '\');"><img src="' + node._tree._imagesPath + '/' + 'blank.' + node._tree._imagesType + '" width="32" height="1"></td><td nowrap>' + clearHTML(result['ReturnedMessage']) +'</td></tr></table>';
                }
            }else{
                alert('Error occured while processing tree branch load:\n\n' + clearHTML(result['ReturnedMessage']));
            }
        }else{
            alert('Server returned not serialized data:\n\n' + clearHTML(transport.responseText));
        }
    }
}
function __AjaxTreeNodeReturnAjaxError(transport){
    alert('Server return error: \n\n' + transport.status);
}

// -- Ajax Trees -------------------------------------------------------------->

var AjaxTables = {};

// -- Table object ------------------------------------------------------------>
function AjaxTable(containerId,source,attribs){
// attributes
	this._selfId = 'tblAjaxTable' + Math.round(100000 * Math.random()); 
	this._source = source;
    this._sourceWithoutQuery = (this._source.indexOf('?') > 0) ? this._source.substr(0,this._source.indexOf('?')) : this._source;
	this._imagesPath = globalCMSPath + '/libraries/interface/images/AjaxTable';
	this._imagesType = 'gif';
    this._parameters = {'itemsUnselectable' : false,
						'itemsInheritStyle' : false,
						'columnsDefaultWidth': 100,
                        'columnsWidths' : [],
						'listLimit' : 25,
                        'listLimitOptions' : [10,25,50,100],
						'listWhere' : ''};
    this._style = { 'height' : 300,
                    'headHeight' : 30,
                    'footHeight' : 30};
	this._listArray = [];
	this._listState = { page : 0,
						count : 0,
						found : 0,
                        order : '',
						where : []};
	this._listGroups = [];
	this._listColumns = [];
    this._selectedItemsOffsets = [];
    this._flagLoaded = false;
    this._flagAjaxing = false;

// events
    this.onInit = null;
    this.onSelect = null;
    this.onHover = null;

// methods
    this._init =
        function (containerId,source,attribs){
		// setting attributes if defined
			if(typeof(attribs) != 'undefined'){
				if((attribs['columns'])&&(attribs['columns'].length > 0)){
					this._listColumns = attribs['columns'];
				}
                if((attribs['columnsDefaultWidth'])&&(attribs['columnsDefaultWidth'] > 0)){
                    this._parameters['columnsDefaultWidth'] = attribs['columnsDefaultWidth'];
                }
                if((attribs['columnsWidths'])&&(attribs['columnsWidths'].length > 0)){
                    this._parameters['columnsWidths'] = attribs['columnsWidths'];
                }
                if(attribs['style']){
                    if(attribs['style']['height']) this._style['height'] = attribs['style']['height'];
                    if(attribs['style']['headHeight']) this._style['headHeight'] = attribs['style']['headHeight'];
                    if(attribs['style']['footHeight']) this._style['footHeight'] = attribs['style']['footheight'];
                }
            // events
                if(attribs['onInit']) this.onInit = attribs['onInit'];
                if(attribs['onSelect']) this.onSelect = attribs['onSelect'];
                if(attribs['onHover']) this.onHover = attribs['onHover'];
			}
        // creating html objects
            var tableElement;
            if(containerId !=''){
                if(($(containerId))&&($(containerId).appendChild)
                   &&(typeof($(containerId).appendChild) != 'undefined')){
                    tableElement = document.createElement('TABLE');
                    tableElement.id = this._selfId;
                    $(containerId).appendChild(tableElement);
                }else{
                    alert('Error occured while creating AjaxTree element:\nCan\'t find container "' + containerId + '"');
                    return false;
                }
            }else{
                document.writeln('<table id="' + this._selfId + '"></table>');
            }
            tableElement = $(this._selfId);
			tableElement.className = 'AjaxTable';
			tableElement.height = this._style['height'];
            tableElement.style.height = this._style['height'] + 'px';
			tableElement.insertRow(0);
			tableElement.rows[0].insertCell(0);
			tableElement.insertRow(0);
			tableElement.rows[0].insertCell(0);
			tableElement.rows[0].cells[0].height = '100%';
			tableElement.rows[0].cells[0].style.verticalAlign = 'top';
			tableElement.rows[0].cells[0].innerHTML = '<div style="overflow: auto;' + ((isIE) ? 'height:100%' : '') + '"></div>';
			tableElement.insertRow(0);
			tableElement.rows[0].insertCell(0);
			this.draw(); 
		}
	this._container =
		function (){
			return $(this._selfId);
		}
	this._containerHead =
		function (){
			return $(this._selfId).rows[0].cells[0];
		}
	this._containerList =
		function (){
			return $(this._selfId).rows[1].cells[0].childNodes[0];
		}
	this._containerFoot =
		function (){
			return $(this._selfId).rows[2].cells[0];
		}
	this._drawHead =
		function (){
            var aTable = this;
			var innerHTML = '<div style="overflow:hidden; height:' + this._style['headHeight'] + 'px;">';
            innerHTML += '<table class="AjaxTableHead" cellspacing="1" width="100%" height="' + (this._style['headHeight'] + 1) + '"><tr>';
			innerHTML += '<td style="width:20px;"><input id="' + aTable._selfId + ':cbAll" type="checkbox" onclick="__AjaxTable_onSelectAllClick(this,\'' + aTable._selfId + '\')" /></td>';
			var defaultWidth = this._parameters.columnsDefaultWidth;
			this._listColumns.each(function (column, index){
				if(column['caption'].search(/^\s+/) == 0){
					column['caption'] = column['caption'].replace(/^\s+/,'');
				}
				if(typeof(column['title']) == 'undefined'){
					column['title'] = column['caption'];
				}
				if(column['title'].search(/"/) >= 0){
					column['title'] = column['title'].replace(/"/,'');
				}
				if(column['title'].search(/^\s+/) == 0){
					column['title'] = column['title'].replace(/^\s+/,'');
				}
                if(!((typeof(column['width']) != 'undefined')&&(column['width'] > 0))){
                    column['width'] = defaultWidth;
                }
                column['width'] = ((typeof(aTable._parameters['columnsWidths'][index]) != 'undefined')&&(aTable._parameters['columnsWidths'][index] >= 0)) ? aTable._parameters.columnsWidths[index] : column['width'];
                if(column['width'] != 0){
                    innerHTML += '<td width="' + column['width'] + '"><div style="width: ' + column['width'] + 'px;">'
                        + ((column['flagOrder']) ? '<div class="AjaxTableHeadOrder" title="' + column['title'] + '"><img src="' + aTable._imagesPath + '/orderUp.gif" onclick="__AjaxTable_reload(\'' + aTable._selfId + '\',{\'listOrder\':\'' + column['name'] + '\'})"><img src="' + aTable._imagesPath + '/orderDown.gif" onclick="__AjaxTable_reload(\'' + aTable._selfId + '\',{\'listOrder\':\'' + column['name'] + ' DESC\'})"></div>' : '')
                        + ((column['icon']) ? '<img src="' + aTable._imagesPath + '/icons/' + column['icon'] + '.' + aTable._imagesType + '">' : '') + column['caption'] + '</div></td>';
                }
            })
			innerHTML += '<td></td>';
			innerHTML += '</tr></table></div>';
			this._containerHead().innerHTML = innerHTML;
			return 1;
		}
	this._drawFoot =
		function (){
			var innerHTML = '<div style="overflow:hidden; height:' + this._style['footHeight'] + 'px;">';
            innerHTML += '<table class="AjaxTablePages" cellspacing="1" width="100%" height="' + this._style['footHeight'] + '"><tr>';
			innerHTML += '<td width="100%">';
			if(this._listState.found > this._parameters.listLimit){
				innerHTML += '<table class="AjaxTablePagesList" cellspacing="0" cellpadding="0"><tr><td>Страницы:&nbsp;</td><td width="100%">';
				var start = 0;
				var end = 0;
                if((this._listState.found / this._parameters.listLimit) < 12){
                    start = 0;
                    end = Math.ceil(this._listState.found / this._parameters.listLimit);
                    for(var i = start; i < end; i++){
                        innerHTML += (i == this._listState.page) ? ' <strong>' + (i + 1) + '</strong> ' : ' <a href="#" onclick="return __AjaxTable_reload(\'' + this._selfId + '\',{\'listPage\':' + i + '});">' + (i + 1) + '</a> ';
                    }
                }else{
                    if(this._listState.page > 6){
                        innerHTML += '<a href="#" onclick="return __AjaxTable_reload(\'' + this._selfId + '\',{\'listPage\':0});">1</a> <a href="#" onclick="return false;">...</a>';
                    }
                    if(this._listState.page < 7){
                        start =  0;
                        end = (this._listState.page < (this._listState.found / this._parameters.listLimit - 6)) ? 10 : (this._listState.found / this._parameters.listLimit - 11);
                    }else{
                        start = (this._listState.page < (this._listState.found / this._parameters.listLimit - 6)) ? this._listState.page - 4 : this._listState.page - 11 + (Math.round(this._listState.found / this._parameters.listLimit) - this._listState.page);
                        end = (this._listState.page < (this._listState.found / this._parameters.listLimit - 6)) ? (this._listState.page + 5) : (this._listState.found / this._parameters.listLimit);
                    }
                    for(var i = start; i < end; i++){
                        innerHTML += (i == this._listState.page) ? ' <strong>' + (i + 1) + '</strong> ' : ' <a href="#" onclick="return __AjaxTable_reload(\'' + this._selfId + '\',{\'listPage\':' + i + '});">' + (i + 1) + '</a> ';
                    }
                    if(this._listState.page < (this._listState.found / this._parameters.listLimit - 6)){
                        innerHTML += '... <a href="#" onclick="return __AjaxTable_reload(\'' + this._selfId + '\',{\'listPage\':' + Math.floor(this._listState.found / this._parameters.listLimit) + '});">' + (Math.floor(this._listState.found / this._parameters.listLimit) + 1) + '</a>';
                    }
                }
				innerHTML += '</td></tr></table>';
			}
			innerHTML += '</td>';
            innerHTML += '<td nowrap>Показывать по <select onchange="__AjaxTable_reload(\'' + this._selfId + '\',{\'listLimit\': this.options[this.selectedIndex].value})">';
            for(var i = 0; i < this._parameters.listLimitOptions.length; i++){
                innerHTML += '<option value="' + this._parameters.listLimitOptions[i] + '"' + ((this._parameters.listLimitOptions[i] == this._parameters.listLimit) ? ' selected' : '') + '>' + this._parameters.listLimitOptions[i] + '</option>';
            }
            innerHTML += '</select></td>';
			innerHTML += '<td nowrap>Всего ' + this._listState.count + '</td>';
			if((this._listState.found > 0)&&(this._listState.found != this._listState.count)){
				innerHTML += '<td nowrap>В списке ' + this._listState.found +'</td>';
			}
			innerHTML += '</tr></table></div>';
			this._containerFoot().innerHTML = innerHTML;
			return 1;
		}
	this._drawList =
		function (){
            this._containerList().style.height = (((this._style['height'] - this._style['headHeight'] - this._style['footHeight']) > 0) ? (this._style['height'] - this._style['headHeight'] - this._style['footHeight']) : 1) + 'px';
            
			if(!(this._flagLoaded)) this.load();
			var innerHTML = '<table class="AjaxTableList" cellspacing="1">';
			if(this._listArray.length > 0){
				var aTable = this;
				this._listArray.each( function (item, index){
                    innerHTML += '<tr id="' + aTable._selfId + ':tr' + index + '" class="' + (((index % 2) != 0) ? 'even' : 'odd') + ((item['AjaxTableFlagDisabled'] != 1) ? '" onmouseover="__AjaxTable_onMouseOver(this);" onmouseout="__AjaxTable_onMouseOut(this);" onclick="__AjaxTable_onClick(this,\'' + aTable._selfId + '\',' + index + ')">' : 'Disabled">')
                        +'<td style="width:20px;"><input id="' + aTable._selfId + ':cb' + index + '" type="checkbox" ' + ((item['AjaxTableFlagDisabled'] != 1) ? '' : 'disabled') + '></td>';
                    aTable._listColumns.each(function (column,index){
                        if(column['width'] > 0){
                            innerHTML += '<td><div style="width:' + column['width'] + 'px;">' + item[column.name] + '</div></td>';
                        }
                    });
                    innerHTML += '</tr>';
                });
			}else{
				if(this._flagLoaded){
					innerHTML += '<tr><td></td></tr>';
				}else{
					innerHTML += '<tr><td><img src="' + this._imagesPath + '/loading.gif" align="absmiddle" /> loading</td></tr>';
				}
			}
			innerHTML += '</table>'
			this._containerList().innerHTML = innerHTML;
			return 1;
		}
    this.source =
        function (source){
            this._source = source; 
            this._sourceWithoutQuery = (this._source.indexOf('?') >= 0) ? this._source.substr(0,this._source.indexOf('?')) : this._source;
            this.load();
        }
	this.draw =
		function (){
			this._drawHead();
			this._drawFoot();
			this._drawList();
		}
    this.style =
        function (style){
            if(style){
                if((style['height'])) this._style['height'] = (style['height'] > 0) ? style['height'] : 1;
                var tableElement = $(this._selfId);
                tableElement.height = this._style['height'];
                tableElement.style.height = this._style['height'] + 'px';
                if(style['headHeight']) this._style['headHeight'] = (style['headHeight'] > 0) ? style['headHeight'] : 1;
                if(style['footHeight']) this._style['footHeight'] = (style['footHeight'] > 0) ? style['footHeight'] : 1;
                this.draw();
            }
        };
    this.load =
        function (){ 
            if(this._source == '') {
                if((this._parent != null)&&(this._parent != this)&&(typeof(this._parent.load) == 'function'))
                    return this._parent.load()
                else
                    return false;
            }
            var url = this._source + ((this._source.indexOf('?') >= 0) ? '&': '?')
                    + 'order=' + this._listState.order
                    + '&limit=' + (this._parameters.listLimit * this._listState.page) + ',' + this._parameters.listLimit
                    + '&AjaxTableId=' + this._selfId + '&AjaxRequestForSerializedData=1';
            //if(this._childs.where.length > 0){
            //    var urlAddWhere = new Array();
            //    for(var i = 0; i < this._childs.where.length; i++)
            //        if((this._childs.where[i].value)&&(this._childs.where[i].value != ''))
            //            urlAddWhere.push(this._childs.where[i].name + '=' + encodeURI(this._childs.where[i].value))
            //    if(urlAddWhere.join(')AND(') != '')
            //        url += '&where=(' + urlAddWhere.join(')AND(') + ')';
            //}
            //if(this._tree._parameters['nodesListWhere'] != ''){
            //    url += '&only=' + this._tree._parameters['nodesListWhere'];
            //}
            this._flagAjaxing = true;
            var req = new Ajax.Request(url,
                                       {'method':'get',
                                        'onSuccess': __AjaxTableHandleAjaxResponse,
                                        'onFailure': __AjaxTableReturnAjaxError
                                        }); 
            //
            return true;
        };

    this.select = function(itemIndex,flagClearSelectedItems){
        $(this._selfId + ':cb' + itemIndex).checked = true;
        var obj = $(this._selfId + ':tr' + itemIndex);
        if(obj.className.indexOf('Selected') < 0 )
            obj.className += 'Selected';
        // selecting
        if(flagClearSelectedItems){
            this.unselectAll();
        }
        this._selectedItemsOffsets.push(itemIndex);
        if(this._selectedItemsOffsets.length == this._listArray.length)
            $(this._selfId + ':cbAll').checked = true;
        // if onSelect defined
        if(typeof(this.onSelect) == 'function'){
            this.onSelect(this.getSelectedList());
        }
    }

    this.unselect = function(itemIndex,flagClearSelectedItems){
        $(this._selfId + ':cb' + itemIndex).checked = false;
        var obj = $(this._selfId + ':tr' + itemIndex);
        if(obj.className.indexOf('Selected') > 0 )
            obj.className = obj.className.substr(0,obj.className.length - 8);
        // unselecting
        if(flagClearSelectedItems){
            this.unselectAll();
        } else if(this._selectedItemsOffsets.indexOf(itemIndex) >= 0){
            this._selectedItemsOffsets.splice(this._selectedItemsOffsets.indexOf(itemIndex),0);
        }
        // if onSelect defined
        if(typeof(this.onSelect) == 'function'){
            this.onSelect(this.getSelectedList());
        }
    }
    
    this.selectAll = function(){
        for (var i = 0; i < this._listArray.length; i++){
            if(this._listArray[i]['AjaxTableFlagDisabled'] != 1){
                $(this._selfId + ':cb' + i).checked = true;
                var obj = $(this._selfId + ':tr' + i);
                if(obj.className.indexOf('Selected') < 0 )
                    obj.className += 'Selected';
                this._selectedItemsOffsets.push(i);
            }
        }
        // if onSelect defined
        if(typeof(this.onSelect) == 'function'){
            this.onSelect(this.getSelectedList());
        }
    }
    
    this.unselectAll = function(){
        for(var i = 0; i < this._selectedItemsOffsets.length; i++){
            $(this._selfId + ':cb' + this._selectedItemsOffsets[i]).checked = false;
            var obj = $(this._selfId + ':tr' + this._selectedItemsOffsets[i]);
            if(obj.className.indexOf('Selected') > 0 )
                obj.className = obj.className.substr(0,obj.className.length - 8);
        }
        this._selectedItemsOffsets = [];
        // if onSelect defined
        if(typeof(this.onSelect) == 'function'){
            this.onSelect(this.getSelectedList());
        }
    }
    
	this.getColumnsList = function(){
		return this._listColumns;
	}
    this.getSelectedList = function(){
        var aTable = this;
        var selectedItems = new Array;
        this._selectedItemsOffsets.sort();
        this._selectedItemsOffsets.each(
            function (offset){
                selectedItems.push(aTable._listArray[offset]);
            }
        )
        return selectedItems;
    }
    
// initiating
	AjaxTables[this._selfId] = this;
    this._init(containerId,source,attribs);
}

function __AjaxTableHandleAjaxResponse(transport){
    var result = unserialize(transport.responseText);
	
    if(typeof(result['AjaxTableId']) != 'undefined'){
        if(typeof(AjaxTables[result['AjaxTableId']]) == 'undefined'){
            alert('Error occured while processing table list load:\n\n' + "Can't find AjaxTable with ID '" + result['AjaxTableId'] + "'");
            return false;
        }
        var aTable = AjaxTables[result['AjaxTableId']];
		
		aTable._flagAjaxing = false;
		aTable._flagLoaded = true;
        // if message returned then printing error message
        if((typeof(result['AjaxRequestReturnedMessage']) != 'undefined')&&(result['AjaxRequestReturnedMessage'] != '')){
            aTable._containerList().innerHTML =
                '<img align="absmiddle" src="' + aTable._imagesPath + '/warning.gif">'
                + '<span style="color:#cc0000;">' + clearHTML(result['AjaxRequestReturnedMessage']) + '</span>';
        }else{
            
            // reading received data
            aTable._listArray = result['AjaxTableList'];
            aTable._listState.count = result['AjaxTableListCount'];
            aTable._listState.found = result['AjaxTableListFound'];
            aTable._listState.where = result['AjaxTableListWhere'];
            //if(!(aTable._listColumns.length > 0)){
                aTable._listColumns = result['AjaxTableListColumns'];
            //}
            
            // event after load
            if(typeof(aTable.onAfterLoad) == 'function'){
                aTable.onAfterLoad();
                aTable.onAfterLoad = null;
            }
            
            // drawing changes
            aTable.draw();
            
            // event after load
            if(typeof(aTable.onAfterLoadAndDraw) == 'function'){
                aTable.onAfterLoadAndDraw();
                aTable.onAfterLoadAndDraw = null;
            }
        }
    }else{
        if(typeof(result['ReturnedMessage']) != 'undefined'){
            if((typeof(result['RequestParams']) != 'undefined')
               &&(typeof(result['RequestParams']['AjaxTableId']) != 'undefined')){
				return 1;
            }else{
                alert('Error occured while processing tree branch load:\n\n' + clearHTML(result['ReturnedMessage']));
            }
        }else{
            alert('Server returned not serialized data:\n\n' + clearHTML(transport.responseText));
        }
    }
}
function __AjaxTableReturnAjaxError(transport){
    alert('Server return error: \n\n' + transport.status);
}

function __AjaxTable_reload(tableId,attribs){
    if((AjaxTables[tableId])&&(AjaxTables[tableId]._selfId == tableId)){
		var aTable = AjaxTables[tableId];
        if((attribs)){
            if((typeof(attribs['listOrder']) != 'undefined')&&(attribs['listOrder'] != '')){
                aTable._listState.order = attribs['listOrder'];
            }
            if((typeof(attribs['listLimit']) != 'undefined')&&(attribs['listLimit'] > 0)){
                var oldLimit = aTable._parameters.listLimit;
                aTable._parameters.listLimit = attribs['listLimit'];
                if((typeof(attribs['listPage']) != 'undefined')&&(attribs['listPage'] >= 0)){
                    if(attribs['listPage'] > (aTable._listState.found / aTable._listState.limit))
                        attribs['listPage'] = Math.ceil((attribs['listPage'] / (aTable._listState.found / oldLimit)) * (aTable._listState.found / aTable._parameters.listLimit));
                }else{
                    aTable._listState.page = Math.ceil((aTable._listState.page / (aTable._listState.found / oldLimit)) * (aTable._listState.found / aTable._parameters.listLimit));
                }
            }
            if((typeof(attribs['listPage']) != 'undefined')&&(attribs['listPage'] >= 0))
                aTable._listState.page = attribs['listPage'];
            if(attribs['listWhere']) {
                for(var i = 0; i < aTable._listState.where.length; i++)
                    if((aTable._listState.where[i].name)&&(typeof(attribs['listWhere'][aTable._listState.where[i].name]) != 'undefined'))
                        aTable._listState.where[i].value = attribs['listWhere'][aTable._listState.where[i].name]
                    else
                        aTable._listState.where[i].value = '';
            }
        }
		aTable.load();
    }
	return false;
}

function __AjaxTable_onMouseOver(obj){
    if((obj.className.indexOf('Selected') < 0)&&(obj.className.indexOf('Hover') < 0))
        obj.className += 'Hover';
    return true;
}

function __AjaxTable_onMouseOut(obj){
    if(obj.className.indexOf('Hover') == (obj.className.length - 5))
        obj.className = obj.className.substr(0,obj.className.length - 5);
    return true;
}

function __AjaxTable_onClick(obj,tableId, itemIndex){
    if((AjaxTables[tableId])&&(AjaxTables[tableId]._selfId == tableId)){
        if((obj.className.indexOf('Selected') < 0)&&(obj.className.indexOf('Selected') < 0)){
            // unhover
            if(obj.className.indexOf('Hover') == (obj.className.length - 5))
                obj.className = obj.className.substr(0,obj.className.length - 5);
            // select
            AjaxTables[tableId].select(itemIndex,1);
        }else{
            // deselect
            AjaxTables[tableId].unselect(itemIndex,1);
            // hover
            obj.className += 'Hover';
        }
    }
    return true;
}

function __AjaxTable_onSelectAllClick(obj,tableId){
    if((AjaxTables[tableId])&&(AjaxTables[tableId]._selfId == tableId)){
        if(obj.checked){
            AjaxTables[tableId].selectAll();
        }else{
            AjaxTables[tableId].unselectAll();
        }
    }
    return true;
}

var SelectorsUsingAjaxTree = {};
function SelectorUsingAjaxTree(containerId,source,attribs){
// attributes
	this._selfId = 'lyrSelectorUsingAjaxTree' + Math.round(100000 * Math.random());
	this._source = source;
	this._style = {'width':300,
				   'height':300,
				   'border':'1px solid #444',
                   'background-color':'#eeeeee'};
	this._parameters = {'flagFramed' : false,
						'delayHide' : 1000};
	//this._ajaxTree = new AjaxTree;
	this._timerHide = 0;
	this.onSelect = null;
	this.onShow = null;
	this.onHide = null;
	this._init =
		function (containerId,source,attribs){
            this._qualifySource();
			this._parameters['flagFramed'] = (isIE);
			if(attribs){
                if(attribs['style']){
                    if(attribs['style']['width']) this._style.width = attribs['style']['width'];
                    if(attribs['style']['height']) this._style.height = attribs['style']['height'];
                    if(attribs['style']['border']) this._style.border = attribs['style']['border'];
                    if(attribs['style']['background-color']) this._style.backgroundColor = attribs['style']['background-color'];
                }
			// events
				if(attribs['onSelect']) this.onSelect = attribs['onSelect'];
				if(attribs['onShow']) this.onShow = attribs['onShow'];
				if(attribs['onHide']) this.onHide = attribs['onHide'];
			}
			 // creating html objects
            var selfElement;
            if(containerId !=''){
                if(($(containerId))&&($(containerId).appendChild)
                   &&(typeof($(containerId).appendChild) != 'undefined')){
                    selfElement = document.createElement('DIV');
                    selfElement.id = this._selfId;
                    $(containerId).appendChild(selfElement);
                }else{
                    alert('Error occured while creating SelectAjaxTree element:\nCan\'t find container "' + containerId + '"');
                    return false;
                }
            }else{
                document.writeln('<div id="' + this._selfId + '"></div>');
                
            }
            selfElement = $(this._selfId);
			selfElement.hide();
			selfElement.style.zIndex = '10';
			selfElement.style.position = 'absolute';
			selfElement.style.width = this._style['width'] + 'px';
			selfElement.style.height = this._style['height'] + 'px';
			var selectorId = this._selfId;
			selfElement.onmouseover =
				function(){
					_SelectorUsingAjaxTree_onMouseOver(selectorId);
				};
			selfElement.onmouseout =
				function(){
					_SelectorUsingAjaxTree_onMouseOut(selectorId);
				};
			if(this._parameters['flagFramed']){
				selfElement.innerHTML = '<iframe id="ifrm' + this._selfId + '" name="ifrm' + this._selfId + '" src="' + globalCMSPath + '/libraries/interface/blank.html" frameborder="0" scrollbars="no" style="width:' + this._style['width'] + 'px; height:' + this._style['height'] + 'px;"></iframe>';
                
//				var doc = frames['ifrm' + this._selfId].document;
//				doc.open();
//				doc.writeln('\
//                    <html>\
//                    <head>\
//                    <link href="<TMPL_VAR CMS_PATH>/systemplates/manager/standart/share.files/styles.css" rel="stylesheet" type="text/css" >\
//                    <link href="<TMPL_VAR CMS_PATH>/libraries/interface/styles.css" rel="stylesheet" type="text/css">\
//					<script language="Javascript"> var globalCMSPath = \'<TMPL_VAR CMS_PATH>\'; <\/script>\
//					<script type="text/javascript" src="<TMPL_VAR CMS_PATH>/libraries/common.js" defer><\/script>\
//					<script type="text/javascript" src="<TMPL_VAR CMS_PATH>/libraries/interface.js" defer><\/script>\
//					<script type="text/javascript" src="<TMPL_VAR CMS_PATH>/libraries/prototype.js" defer><\/script>\
//                    </head>\
//					<body style="margin:0px; overflow:hidden;" onload="drawTree();">\
//					<div id="lyrAjaxTree" style="width:' + this._style['width'] + 'px; height:' + this._style['height'] + 'px; border:' + this._style['border'] + '; overflow:auto;"></div>\
//					<script type="text/javascript" defer>\
//                    function drawTree(){\
//					new AjaxTree("lyrAjaxTree","' + this._source + '",\
//								 {"style":{"background-color":"#f7f7f7","height":"200px","width":"325px"},\
//								  "nodesListLimit": 20,\
//								  "hideRoot": true,\
//								  "onSelect": function(id,path,values){\
//												parent.SelectorsUsingAjaxTree["' + selectorId + '"]._onAjaxTreeNodeSelect(id,path,values);\
//												}\
//								 });\
//					}\
//					<\/script>\
//					</body>\
//                    </html>\
//					');
//				doc.close();
                var thisSelector = this;
                if(attribs['initUsingTimeout']){
                    setTimeout(function(){
                        if(typeof(onloadHandler) == 'function') onloadHandler();
                        frames['ifrm' + selectorId].document.body.innerHTML = '<div id="lyrAjaxTree" style="width:' + thisSelector._style['width'] + 'px; height:' + thisSelector._style['height'] + 'px; border:' + thisSelector._style['border'] + '; overflow:auto;"></div>';
                        new frames['ifrm' + selectorId].AjaxTree('lyrAjaxTree',thisSelector._source,
                                 {'style':{'background-color':'#f7f7f7'},
                                  'nodesListLimit': 20,
                                  'nodesListWhere' : (attribs['nodesListWhere']) ? attribs['nodesListWhere'] : '',
                                  'hideRoot': true,
                                  'onSelect':
                                    function(id,path,values){
                                        SelectorsUsingAjaxTree[selectorId]._onAjaxTreeNodeSelect(id,path,values);
                                    }
                                 });
                    },attribs['initUsingTimeout']);
                }else{
                    var onloadHandler = window.onload;
                    window.onload = function(){
                        if(typeof(onloadHandler) == 'function') onloadHandler();
                        frames['ifrm' + selectorId].document.body.innerHTML = '<div id="lyrAjaxTree" style="width:' + thisSelector._style['width'] + 'px; height:' + thisSelector._style['height'] + 'px; border:' + thisSelector._style['border'] + '; overflow:auto;"></div>';
                        new frames['ifrm' + selectorId].AjaxTree('lyrAjaxTree',thisSelector._source,
                                 {'style':{'background-color':'#f7f7f7'},
                                  'nodesListLimit': 20,
                                  'nodesListWhere' : (attribs['nodesListWhere']) ? attribs['nodesListWhere'] : '',
                                  'hideRoot': true,
                                  'onSelect':
                                    function(id,path,values){
                                        SelectorsUsingAjaxTree[selectorId]._onAjaxTreeNodeSelect(id,path,values);
                                    }
                                 });
                    }
                }
			}else{
				new AjaxTree(this._selfId,this._source,
						 {'style':{'background-color':'#f7f7f7',
									'height':this._style['height'] + 'px',
									'width':this._style['width'] + 'px',
									'border': this._style['border']},
                          'nodesListLimit': 20,
                          'nodesListWhere' : (attribs['nodesListWhere']) ? attribs['nodesListWhere'] : '',
                          'hideRoot': true,
                          'onSelect':
                            function(id,path,values){
                                SelectorsUsingAjaxTree[selectorId]._onAjaxTreeNodeSelect(id,path,values);
                            }
						 });
			}
		}
    this._qualifySource =
        function(){
            var cleanUri = window.location.href.substr(0,window.location.href.indexOf('?'));
            this._source = (this._source.charAt(0) == '?') ? (cleanUri + this_source) : ((this._source.charAt(0) != '/') ? cleanUri.substr(0,cleanUri.lastIndexOf('/') + 1) + this._source : this._source);
        }
	this._setHideTimer =
		function(){
			this._timerHide = setTimeout('SelectorsUsingAjaxTree[\'' + this._selfId + '\'].hide();',this._parameters['delayHide']);
		}
	this._clearHideTimer =
		function(){
			if(this._timerHide > 0){
				clearTimeout(this._timerHide);
				this._timerHide = 0;
			}
		}
	this._onAjaxTreeNodeSelect =
		function(id,path,values){
			if(typeof(this.onSelect) == 'function'){
				if(this.onSelect(id,path,values) != false){
                    this.hide();
                }
			}else{
                this.hide();
            }
		}
	this.show =
		function(){
			this._clearHideTimer();
			$(this._selfId).show();
			this._setHideTimer();
			if(typeof(this.onShow) == 'function') this.onShow();
		}
	this.hide =
		function(){
			this._clearHideTimer();
			$(this._selfId).hide();
			if(typeof(this.onHide) == 'function') this.onHide();
		}
    this.position =
        function(left,top){
            $(this._selfId).style.top = top + 'px';
            $(this._selfId).style.left = left + 'px';
        }
// initiating
	SelectorsUsingAjaxTree[this._selfId] = this;
	this._init(containerId,source,attribs);
}

function _SelectorUsingAjaxTree_onMouseOver(selectorId){
	if((SelectorsUsingAjaxTree[selectorId])&&(SelectorsUsingAjaxTree[selectorId].selfId = selectorId)){
		SelectorsUsingAjaxTree[selectorId]._clearHideTimer();
	}
}
function _SelectorUsingAjaxTree_onMouseOut(selectorId){
	if((SelectorsUsingAjaxTree[selectorId])&&(SelectorsUsingAjaxTree[selectorId].selfId = selectorId)){
		SelectorsUsingAjaxTree[selectorId]._clearHideTimer();
		SelectorsUsingAjaxTree[selectorId]._setHideTimer();
	}
}

