/***************************/
/* Author: Moskalenko Igor */
/* JSC Prognoz             */
/***************************/

var isMSIE = navigator.userAgent.indexOf('MSIE') >= 0;
var isOpera = navigator.userAgent.indexOf('Opera') >= 0;
var isSafari = navigator.userAgent.indexOf('Safari') >= 0;
var isNNavigator = navigator.userAgent.indexOf('Navigator') >= 0;
var isMozilla = navigator.userAgent.indexOf('Mozilla') >= 0;
var isKHTML = navigator.userAgent.indexOf('KHTML') >= 0;
var isFirefox = navigator.userAgent.indexOf('Firefox') >= 0;
var isChrome = navigator.userAgent.indexOf('Chrome') >= 0;
var isAppleWebKit = navigator.userAgent.indexOf('AppleWebKit') >= 0;
var isFMozilla = isMozilla && isFirefox;

/*
Функции для кроссброузерной обработки
*/
function srcElem(event){
    var elem = event.srcElement ? event.srcElement : event.target;
    return elem;
}

function elemContains(parentElem, childElem){
    var result = false;
    var id = parentElem.id;
    //parentElem = document.getElementById(parentElem.id);
    if (parentElem.contains)
        result = parentElem.contains(childElem);
    else
        while(childElem.tagName != 'HTML'){
            if (childElem == parentElem){
                result = true;
                break;
            }
            childElem = childElem.parentNode;
        }
    return result;
}

function getElemByAttribute(parentElem, childElem, attributeName){
    var result = false;
    while(childElem.tagName != 'HTML'){
        if (childElem == parentElem)
            break;
        if (childElem.getAttribute && childElem.getAttribute(attributeName))
            return childElem;
        childElem = childElem.parentNode;
    }
    return result;
}

function getChildElemByAttribute(parentElem, attributeName){
    var result = false;
    if (parentElem.childNodes)
        for (var i = 0; i < parentElem.childNodes.length; i++){
            if (parentElem.childNodes[i].getAttribute && parentElem.childNodes[i].getAttribute(attributeName))
                return parentElem.childNodes[i];
            else{
                result = getChildElemByAttribute(parentElem.childNodes[i], attributeName);
                if (result) return result;
            }                
        }
    return result;
}

function getChildElemsByAttribute(parentElem, attributeName){
    var result = new Array();
    if (parentElem.childNodes) {
        for (var i = 0; i < parentElem.childNodes.length; i++) {
            if (parentElem.childNodes[i].getAttribute && parentElem.childNodes[i].getAttribute(attributeName)) { result.push(parentElem.childNodes[i]); }
            else { result = result.concat(getChildElemsByAttribute(parentElem.childNodes[i], attributeName)); }
        }
    }
    return result;
}

function getElemHeight(elem){
    var result = NaN;
    elem = (typeof elem == 'string') ? document.getElementById(elem) : elem;
    result = parseInt(elem.style.height);
    if (isNaN(result) || (result == 0)){
        if (elem.clientHeight)
            result = elem.clientHeight;
        if (elem.innerHeight)
            result = elem.innerHeight;
        if (elem.outerHeight)
            result = elem.outerHeight;
    }
    return result;
}

function getElemWidth(elem){
    var result = NaN;
    elem = (typeof elem == 'string') ? document.getElementById(elem) : elem;
    result = parseInt(elem.style.width);
    if (isNaN(result) || (result == 0)){
        if (elem.clientWidth)
            result = elem.clientWidth;
        if (elem.innerWidth)
            result = elem.innerHeight;
        if (elem.outerWidth)
            result = elem.outerWidth;
    }
    return result;
}

function getWindowWidth(){
    var result = NaN;
    if (document.getElementsByTagName('body')[0].offsetWidth)
        result = parseInt(document.getElementsByTagName('body')[0].offsetWidth);
    return result;
}

function getWindowHeight(){
    var result = NaN;
    if (document.getElementsByTagName('html')[0].offsetHeight)
        result = parseInt(document.getElementsByTagName('html')[0].offsetHeight);
    return result;
}

function preloadImg(src){
    (new Image()).src = src;
}

/*<!-- 
Функция делает анимашку:
elem - домовский объект, у него обязательно должен быть id
duration - задержка между шагом увеличения высоты
step - шаг высоты на который постоянно увеличивается, размер элемента
raise - либо 1, либо -1; отвечает за увеличение или уменьшение объекта при анимации соответственно
hide - попадает в свойство style.display если не определено то становиться ''
-->*/
function slideDown(elem, duration, step, raise, displayStyle){
    if (typeof elem == 'string') { elem = document.getElementById(elem); }

    if (!displayStyle) { displayStyle = ''; }
    if (!raise || (raise != 1 && raise != -1)) { raise = 1; }
    if (elem.interval && (elem.interval != null)) { clearInterval(elem.interval); }
    elem.style.overflow = 'hidden';
    elem.style.display = '';
    
    elem.scrollTop = elem.scrollHeight;
    elem.interval = 
        setInterval(new Function("slide('" + elem.id + "'," + step + "," + raise + ",'" + displayStyle + "');"), duration);
}

//Слайдер максимальную высоту можно задавать в аттрибуте elemHeight, иначе пытается считать макс высоту через elemHeight
function slide(id, step, raise, displayStyle){
    elem = (typeof id == 'string') ? document.getElementById(id) : id;
    raise = parseInt(raise);
    step = parseInt(step);
    
    var borderPoint = elem.scrollHeight;
    var a = 0;
    if (elem.getAttribute('elemHeight'))
        a = parseInt(elem.getAttribute('elemHeight'));
    if (!isNaN(a) && a > 0)
        borderPoint = a;
    /*var q = parseInt(elem.style.paddingTop);
    if (!isNaN(q)) borderPoint -= q;
    q = parseInt(elem.style.paddingBottom);
    if (!isNaN(q)) borderPoint -= q;*/
    
    borderPoint += (isMozilla || isNNavigator || isSafari || isKHTML || isFirefox) ? 4 : 0;
    var elemHeight = getElemHeight(elem);
    var delta = borderPoint - (elemHeight + raise * step);
    
    if (raise == -1){
        borderPoint = 1;
        delta = elemHeight + raise * step - borderPoint;
    }
    
    /*if (elemHeight > 500)
        alert(parseInt(elem.style.paddingLeft));*/
        
    if (delta > 0){
        elem.style.height = (elemHeight +  raise * step) + "px";
        elem.scrollTop = elem.scrollHeight;
    }
    else{
       clearInterval(elem.interval);
       elem.style.display = displayStyle;
       elem.style.height = borderPoint;
       elem.interval = null;
    }
}

/*<!--
Это желательно вынести в отдельный скрипт код
-->*/

function MenuBlock(headerObj, bodyObj, type, resizeImg, selectAttribute, searchImg, openSearchSrc, closeSearchSrc) {
    this.headerObj = headerObj;
    this.bodyObj = bodyObj;
    this.type = type;

    if (searchImg) {
        if (typeof searchImg == 'string') { searchImg = document.getElementById(searchImg); }
        if (searchImg) {
            this.searchImg = searchImg;
            if (typeof openSearchSrc == 'string') { this.searchImg.openedImgSrc = closeSearchSrc; }
            if (typeof closeSearchSrc == 'string') { this.searchImg.closedImgSrc = openSearchSrc; }
            this.searchImg.src = this.searchImg.closedImgSrc;
        }
    }

    this.resizeImg = resizeImg;
    this.selectAttribute = 'text';
    if (selectAttribute) {
        if (typeof selectAttribute == 'string') { this.selectAttribute = selectAttribute; }
    }
    /*
    onselectionchange - срабатывает при смене отметки, в аргументе передается выделяемый элемент, тип 'combo'
    */
    this.events = new Array();
}

function resizeEvent(x, y, startWidth, startHeight){
    this.x = x;
    this.y = y;
    this.startHeight = startHeight;
    this.startWidth = startWidth;
}

function ComboManager(attrElem, attrCaption, attrSearch, attrParent, attrChildCount){
    this.headerIDs = new Array();
    this.headerHArray = new Array();
    this.bodyHArray = new Array();
    
    this.events = new Array();
    
    this.selected = new Array();
    this.captionElem = new Array();
    this.overed = new Array();
    this.searchElem = new Array();
    this.parentElems = new Array();
    
    this.attrElem = attrElem;
    this.attrCaption = attrCaption;
    this.attrSearch = attrSearch;
    this.attrParent = attrParent;
    this.attrChildCount = attrChildCount;

    /*Select Attribute принимает значения: color, text, - отвечает за тип комбобокса*/
    this.addCombo = function(headerPane, bodyPane, resizeImg, selectAttribute, searchImg, openSearchSrc, closeSearchSrc) {
        if (typeof headerPane == 'string')
            headerPane = document.getElementById(headerPane);
        if (typeof bodyPane == 'string')
            bodyPane = document.getElementById(bodyPane);
        bodyPane.style.display = 'none';
        //bodyPane.style.height = 1;
        bodyPane.style.position = 'absolute';
        //bodyPane.onmouseout = this.slowClose;
        //this.init(bodyPane);

        //uncomment
        this.selected[bodyPane.id] = null;

        if (!headerPane.getAttribute(this.attrSearch)) { this.searchElem[bodyPane.id] = getChildElemByAttribute(headerPane, this.attrSearch); }
        else { this.searchElem[bodyPane.id] = headerPane; }
        if (this.searchElem[bodyPane.id]) {
            this.searchElem[bodyPane.id].onkeyup = new Function('clearTimeout(window.searchTimeout); window.searchTimeout = setTimeout("BComboManager.searchText(\'" + this.value + "\');", 0);');
            this.searchElem[bodyPane.id].style.display = 'none';
        }
        if (this.onAddComboKeyPress) { this.onAddComboKeyPress(bodyPane); }

        if (!headerPane.getAttribute(this.attrCaption)) { this.captionElem[bodyPane.id] = getChildElemByAttribute(headerPane, this.attrCaption); }
        else { this.captionElem[bodyPane.id] = headerPane; }
        if (this.captionElem[bodyPane.id]) { this.captionElem[bodyPane.id].style.display = ''; }

        this.overed[bodyPane.id] = null;

        if (resizeImg) { if (typeof resizeImg == 'string') resizeImg = document.getElementById(resizeImg); }
        else { resizeImg = false; }

        var height = getElemHeight(bodyPane);
        if (height && this.maxComboHeight) {
            if (height > this.maxComboHeight) { bodyPane.style.height = this.maxComboHeight; }
        }

        var width = getElemWidth(bodyPane);
        if (width && this.maxComboWidth)
            if (width > this.maxComboWidth)
            bodyPane.style.width = this.maxComboWidth;

        var item = new MenuBlock(headerPane, bodyPane, 'combo', resizeImg, selectAttribute, searchImg, openSearchSrc, closeSearchSrc);

        this.headerHArray[headerPane.id] = item;
        this.bodyHArray[bodyPane.id] = item;
        this.headerIDs.push(new MenuBlock(headerPane.id, bodyPane.id, 'combo', resizeImg, selectAttribute));
    }

    this.addSlideMenu = function(headerPane, bodyPane) {
        if (typeof headerPane == 'string') { headerPane = document.getElementById(headerPane); }
        if (typeof bodyPane == 'string') { bodyPane = document.getElementById(bodyPane); }
        bodyPane.style.display = 'none';
        bodyPane.style.height = 1;
        bodyPane.style.position = 'absolute';
        //bodyPane.onmouseout = this.slowClose;

        var item = new MenuBlock(headerPane, bodyPane, 'slide');
        this.headerHArray[headerPane.id] = item;
        this.bodyHArray[bodyPane.id] = item;
        this.headerIDs.push(new MenuBlock(headerPane.id, bodyPane.id, 'slide'));
    }
    
    /*
    Инициализируюет все дочерние элементы содержащие нужный аттрибут
    Сейчас уже не используется.
    */
    this.init = function(elem){
        var elems = getChildElemsByAttribute(elem, this.attrElem);
        for (var i = 0; i < elems.length; i++){
            elems[i].onmouseover = new Function("BComboManager.over(this);");
            elems[i].onmouseout = new Function("BComboManager.out(this);");
            elems[i].onclick = new Function("BComboManager.select(this);");
        }
    }
    
    /*
    Эвенты которые срабатывают для всех объектов
    onselectionchange - срабатывает при смене отметки, в аргументе передается выделяемый элемент, тип 'combo'
    */
    this.addEvent = function(name, eventFunction){
        this.events[name.toString()] = eventFunction;
    }
    
    this.removeEvent = function(name){
        this.events[name.toString()] = null;
    }
    
    /*
        Начало Эвенты для отдельных блоков 
    */
    this.addBlockEvent = function(elem, name, eventFunction) {
        var a = this.getBlockItemByElem(elem);
        if (a) { a.events[name.toString()] = eventFunction; }
    }

    this.removeBlockEvent = function(elem, name) {
        var a = this.getBlockItemByElem(elem);
        if (a) { a.events[name.toString()] = null; }
    }
    
    /*
        Конец Эвенты для отдельных блоков 
    */

    this.hideSearch = function() {
        if (this.currentHead && this.currentHead != null) {
            var item = this.headerHArray[this.currentHead.id];
            if (item.searchImg && item.searchImg.state != item.searchImg.closedImgSrc) {
                var a = this.searchElem[item.bodyObj.id];
                if (a) { a.style.display = 'none'; }
                a = this.captionElem[item.bodyObj.id];
                if (a) { a.style.display = 'block'; }
                item.searchImg.src = item.searchImg.closedImgSrc;
                item.searchImg.state = item.searchImg.closedImgSrc;
                setTimeout('BComboManager.clearSearch("' + item.bodyObj.id + '");', 0);
            }
        }
    }

    this.searchText = function(text, bodyId) {
        var body = BComboManager.currentBody;
        if (body == null && bodyId) {
            if (typeof bodyId == 'string') { body = BComboManager.bodyHArray[bodyId].bodyObj; }
        }
        if (body != null) {
            if (!body.childrenElems) { body.childrenElems = getChildElemsByAttribute(body, BComboManager.attrElem); }
            if (!this.parentElems[body.id]) { this.parentElems[body.id] = new Array(); }
            var ParentElems = null;
            if (this.attrParent) { ParentElems = this.parentElems[body.id]; }
            var Elems = body.childrenElems;
            text = text.replace(/\[/gi, '\\[').replace(/\]/gi, '\\]').replace(/\./gi, '\\.')
                    .replace(/\^/gi, '\\^').replace(/\*/gi, '\\*').replace(/\?/gi, '\\?')
                    .replace(/\+/gi, '\\+').replace(/\{/gi, '\\{').replace(/\}/gi, '\\}')
                    .replace(/\$/gi, '\\$').replace(/\(/gi, '\\(').replace(/\)/gi, '\\)');
            var textArr = text.split(' ');
            var evalReg = '/.*';
            for (var i = 0; i < textArr.length; i++) {
                evalReg += '(' + textArr[i] + ')' + '.*';
            }
            evalReg += '/i';

            var reg = eval(evalReg);
            for (var i = 0; i < Elems.length; i++) {
                var test = false;
                if (ParentElems != null) {
                    var childrenCount = 0;
                    if (Elems[i].getAttribute(this.attrChildCount)) {
                        childrenCount = parseInt(Elems[i].getAttribute(this.attrChildCount));
                    }
                    childrenCount = isNaN(childrenCount) ? 0 : childrenCount;
                    if (childrenCount == 0) {
                        if (Elems[i].innerText) { test = reg.test(Elems[i].innerText); }
                        if (Elems[i].textContent) { test = reg.test(Elems[i].textContent); }
                        this.checkParentVisibility(Elems[i], test, body.id);
                    }
                }
                else {
                    if (Elems[i].innerText) { test = reg.test(Elems[i].innerText); }
                    if (Elems[i].textContent) { test = reg.test(Elems[i].textContent); }
                }
                Elems[i].style.display = test ? '' : 'none';
            }
        }
    }

    this.checkParentVisibility = function(childrenElem, childrenVisibility, bodyId) {
        var ParentElem = null;
        if (childrenElem.getAttribute(this.attrParent)) { ParentElem = document.getElementById(childrenElem.getAttribute(this.attrParent)); }
        if (ParentElem != null) {
            var childrenCount = 0;
            if (ParentElem.getAttribute(this.attrChildCount)) { childrenCount = parseInt(ParentElem.getAttribute(this.attrChildCount)); }
            childrenCount = isNaN(childrenCount) ? 0 : childrenCount;

            if (isNaN(this.parentElems[bodyId][ParentElem.id])) { this.parentElems[bodyId][ParentElem.id] = 0; }
            if (childrenVisibility) {
                if (this.parentElems[bodyId][ParentElem.id] < childrenCount) { this.parentElems[bodyId][ParentElem.id]++; }
            }
            else {
                if (this.parentElems[bodyId][ParentElem.id] > 0) { this.parentElems[bodyId][ParentElem.id]--; }
            }

            if (this.parentElems[bodyId][ParentElem.id] == 0) {
                ParentElem.style.display = 'none';
                if (ParentElem.id != childrenElem.id) { this.checkParentVisibility(ParentElem, false, bodyId); }
            }
            else {
                ParentElem.style.display = '';
                this.checkParentVisibility(ParentElem, true, bodyId);
            }
        }
    }

    this.clearSearch = function(bodyId) {
        var body = BComboManager.currentBody;
        if (body == null && bodyId) {
            if (typeof bodyId == 'string') { body = BComboManager.bodyHArray[bodyId].bodyObj; }
        }
        if (body != null) {
            var Elems = getChildElemsByAttribute(body, BComboManager.attrElem);
            this.parentElems[body.id] = new Array();
            for (var i = 0; i < Elems.length; i++) {
                Elems[i].style.display = '';
                this.checkParentVisibility(Elems[i], true, body.id);
            }
        }
    }
	
    this.select = function(elem) {
       if (typeof elem == 'string') elem = document.getElementById(elem);
        var body = BComboManager.currentBody;
        if (!elem) { return; }
        if (body == null) {
            var r = this.getBlockItemByElem(elem);
            if (r) body = r.bodyObj;
            if (body == null) return;
        }
		
		if (BComboManager.selected[body.id] != elem && body != null) {
            if (BComboManager.selected[body.id] && BComboManager.selected[body.id] != null)
                BComboManager.selected[body.id].className = BComboManager.normalClass;
            BComboManager.selected[body.id] = elem;
			var item = BComboManager.captionElem[body.id];
            if (item) {
				var s = BComboManager.selected[body.id],
					isIE = !!s['innerText'],
					propTitle = isIE ? 'innerText' : 'textContent',
					title = '';
				var pItem = elem;
				/*создаем рекурсивное имя*/
				
				while(pItem){
					title = pItem[propTitle] + ((title)?' // ' + title : '');
					pItem = document.getElementById(pItem.getAttribute('pid'));//pItem.getAttribute необходимо для кросбраузерности
				}
                if (BComboManager.bodyHArray[body.id].selectAttribute == 'text') {
                    item[propTitle] = title;
                }
                if (BComboManager.bodyHArray[body.id].selectAttribute == 'color') {
                    item.style.backgroundColor = s.style.backgroundColor;
                }

                //Возможно изменение размера "заголовка", избегаем этого
                //BComboManager.showAnimation = false;
                BComboManager.currentBody = null;
                BComboManager.currentHead = null;
                BComboManager.showBodyByElem(BComboManager.bodyHArray[body.id].headerObj, 'click');
                //BComboManager.showAnimation = true;
				
            }

            if (elem && elem != null) {
			
                elem.className = BComboManager.selectedClass;

                if (BComboManager.bodyHArray[body.id].events['onselectionchange'] && BComboManager.bodyHArray[body.id].events['onselectionchange'] != null)
                    BComboManager.bodyHArray[body.id].events['onselectionchange'](elem);

                if (BComboManager.events['onselectionchange'] && BComboManager.events['onselectionchange'] != null)
                    BComboManager.events['onselectionchange'](elem);
            }
            BComboManager.hideSearch();
            BComboManager.fastClose();
        }
		
		
    }

	
	this.getelementid = function (xml_id,treeelemid) 
	{
		select_div = getId("div_elems_xml_"+xml_id);
		first =select_div.firstChild;
		child = first;
		while (child)
		{
			if (child.getAttribute && child.getAttribute("treeelemid") == treeelemid){
				return child.id;
			}
			child = child.nextSibling;
		}
	}
	
    this.over = function(elem) {
        if (typeof elem == 'string') { elem = document.getElementById(elem); }
        var body = BComboManager.currentBody;

        if (body != null) {
            if (BComboManager.overed[body.id] == BComboManager.selected[body.id]) { BComboManager.overed[body.id] = null; }
            if (BComboManager.overed[body.id] && BComboManager.overed[body.id] != null) { BComboManager.out(BComboManager.overed[body.id]); }

            if (elem != BComboManager.selected[body.id]) {
                BComboManager.overed[body.id] = elem;
                if (elem && elem != null && elem != BComboManager.selected[body.id]) { elem.className = BComboManager.hoverClass; }
            }
        }
    }

    this.out = function(elem) {
        if (typeof elem == 'string') { elem = document.getElementById(elem); }

        var body = BComboManager.currentBody;

        if (body != null) {
            if (elem != BComboManager.selected[body.id]) {
                if (elem && elem != null) { elem.className = BComboManager.normalClass; }
                if (BComboManager.overed[body.id] == elem) { BComboManager.overed[body.id] = null; }
            }
        }
    }
    
    /*
    Находит блок (заголовок, тело, тип) по элементе содержащемуся в них;
    */
    
    this.getBlockItemByElem = function(elem){
        var result = false;
        if (typeof elem == 'string') elem = document.getElementById(elem);
        
        if (BComboManager.headerHArray[elem.id])
            return BComboManager.headerHArray[elem.id];
        if (BComboManager.bodyHArray[elem.id])
            return BComboManager.bodyHArray[elem.id];
        
        for (var i = 0; i < BComboManager.headerIDs.length; i++){
            var curIds = BComboManager.headerIDs[i];
            if (elemContains(BComboManager.headerHArray[curIds.headerObj].headerObj, elem)){
                result = BComboManager.headerHArray[curIds.headerObj];
                break;
            }
            if (elemContains(BComboManager.bodyHArray[curIds.bodyObj].bodyObj, elem)){
                result = BComboManager.bodyHArray[curIds.bodyObj];
                break;
            }
        }
        
        return result;
    }
    
    /*Begin for resize*/    
    this.enableResize = function(event){
        var result = false;
        var elem = srcElem(event);
        if (elem && BComboManager.currentBody){
            var r = BComboManager.bodyHArray[BComboManager.currentBody.id].resizeImg;
            if (r && r == elem){
                result = true;
                BComboManager.resizeEvent = new resizeEvent(event.clientX, event.clientY, getElemWidth(BComboManager.currentBody), getElemHeight(BComboManager.currentBody));
            }
        }
        return result;
    }
    
    this.doResize = function(event){
        if (BComboManager.currentBody && BComboManager.resizeEvent){
            var deltaX = BComboManager.resizeEvent.startWidth + event.clientX - BComboManager.resizeEvent.x;
            var deltaY = BComboManager.resizeEvent.startHeight + event.clientY - BComboManager.resizeEvent.y;
            if (deltaX < 180) deltaX = 180;
            if (BComboManager.maxComboWidth)
                if (deltaX > BComboManager.maxComboWidth)
                    deltaX = BComboManager.maxComboWidth;
            BComboManager.currentBody.setAttribute('elemWidth', deltaX);
            BComboManager.currentBody.style.width = deltaX + 'px';
            if (deltaY < 50) deltaY = 50;
            if (BComboManager.maxComboHeight)
                if (deltaY > BComboManager.maxComboHeight)
                    deltaY = BComboManager.maxComboHeight;
            BComboManager.currentBody.setAttribute('elemHeight', deltaY);
            BComboManager.currentBody.style.height = deltaY + 'px';
        }
    }
    
    this.disableResize = function(){
        BComboManager.resizeEvent = null;
        return false;
    }
    /*End for resize*/
    
    /*
    Покажет тело если elem содержится либо в теле, либо в заголовке
    */
    this.showBodyByElem = function(elem, type) {
        if (!type) type = 'move';
        var flag = this.getBlockItemByElem(elem);
        if (flag) {
            var a = flag;
            if (a.type == 'combo' && type == 'move') {
                /*if (BComboManager.comboTimeout && !a.headerObj.showTimeout) 
                clearTimeout(BComboManager.comboTimeout);
                else{
                if (a.headerObj.showTimeout && a.headerObj.showTimeout == BComboManager.comboTimeout){
                return;
                }
                else 
                if (BComboManager.comboTimeout){
                clearTimeout(BComboManager.comboTimeout);
                BComboManager.comboTimeout = null;
                }
                }
                var qwe = 3000;
                if (BComboManager.showComboAfter)
                qwe = parseInt(BComboManager.showComboAfter);
                if (isNaN(qwe)) qwe = 3000;
                a.headerObj.showTimeout = BComboManager.comboTimeout = setTimeout("document.getElementById('" + a.headerObj.id + "').click();", qwe);*/
                return;
            }
            if (a.type == 'slide' && type == 'click') return;
            if (this.currentHead != a.headerObj) {
                /*if (a.headerObj.showTimeout){
                clearTimeout(a.headerObj.showTimeout);
                a.headerObj.showTimeout = null;
                }*/
                elem = a.headerObj;
                var top = getElemHeight(elem);
                var left = 0;
                var counter = 0;

                /*if (isFMozilla || isNNavigator || isSafari || isOpera)*/
                //delete
                //if (a.type == 'combo') top += 2;
                while (elem.tagName != 'HTML' && (counter++ < 10000)) {
                    var _offsetTop = parseInt(elem.offsetTop);
                    if (isNaN(_offsetTop)) _offsetTop = 0;
                    var _offsetLeft = parseInt(elem.offsetLeft);
                    if (isNaN(_offsetLeft)) _offsetLeft = 0;

                    var _scrollTop = parseInt(elem.scrollTop);
                    if (isNaN(_scrollTop)) _scrollTop = 0;
                    var _scrollLeft = parseInt(elem.scrollLeft);
                    if (isNaN(_scrollLeft)) _scrollLeft = 0;
                    top = top + _offsetTop - _scrollTop;
                    left = left + _offsetLeft - _scrollLeft;
                    if (elem.offsetParent)
                        elem = elem.offsetParent;
                    else break;
                }

                wWidth = getWindowWidth();
                if (!isNaN(wWidth)) {
                    var eWidth = getElemWidth(a.bodyObj);
                    var wScroll = parseInt(document.getElementsByTagName('html')[0].scrollLeft);
                    if (isNaN(wScroll)) wScroll = 0;
                    wScroll += parseInt(document.body.scrollLeft);
                    if (isNaN(wScroll)) wScroll = 0;
                    if (isAppleWebKit) { left += wScroll; }
                    //if (document.getElementsByTagName('body')[0].style.overflow != 'hidden')
                    //wScroll -= 12;
                    //alert(eWidth + ' - ' + wScroll + ' - ' + wWidth);
                    if ((left + eWidth - wScroll) > wWidth)
                        left += wWidth - (left + eWidth - wScroll + 2);
                }
                //Перестройка элемента под сафари
                if (!isNaN(top) && isAppleWebKit) {
                    var hScroll = parseInt(document.getElementsByTagName('html')[0].scrollTop);
                    if (isNaN(hScroll)) hScroll = 0;
                    hScroll += parseInt(document.getElementsByTagName('body')[0].scrollTop);
                    if (!isNaN(hScroll)) { top += hScroll; }
                }
                if (!isNaN(left))
                    a.bodyObj.style.left = left + "px";
                if (!isNaN(top))
                    a.bodyObj.style.top = top + "px";
                if (!isNaN(top) || !isNaN(left))
                    a.bodyObj.style.display = '';
            }
            //<!-- Begin включаем анимацию -->
            if (this.getCurrentType() && this.getCurrentType() == 'combo') { if (this.currentHead != a.headerObj) this.fastClose(); }
            else { this.slowClose(); }
            /*
            if (BComboManager.currentBody && (BComboManager.currentBody != a.bodyObj))                        
            slideDown(BComboManager.currentBody.id, 8, 10, -1, 'none');*/

            if (a.type == 'combo') {
                a.bodyObj.style.display = '';
            } else {
                if (this.showAnimation) {
                    slideDown(a.bodyObj.id, 8, 15, 1, '');
                }
            }
            //<!-- End включаем анимацию -->
            this.currentHead = a.headerObj;
            this.currentBody = a.bodyObj;
        }
        else {
            if (this.getCurrentType() && this.getCurrentType() == 'slide' && type == 'move')
                this.slowClose();

            if (this.getCurrentType() && this.getCurrentType() == 'combo' && type == 'click')
                this.fastClose();

            if (!this.getCurrentType())
                this.slowClose();
        }

        return flag;
    }
    
    this.getCurrentType = function(){
        if (BComboManager.currentBody && BComboManager.currentBody != null)
            return BComboManager.bodyHArray[BComboManager.currentBody.id].type;
        return null;
    }

    /*document events*/

    this.onmousedown = function(event) {
        event = event ? event : window.event;
        if (!BComboManager.close) {
            BComboManager.resize = BComboManager.enableResize(event);
            if (BComboManager.resize) { return false; }
        }
    }

    this.onmouseup = function(event) {
        event = event ? event : window.event;
        if (BComboManager.resize) {
            BComboManager.doResize(event);
            BComboManager.resize = BComboManager.disableResize();
            BComboManager.close = true;
            return false;
        }
    }

    this.onclick = function(event) {
		event = event ? event : window.event;
        var elem = srcElem(event);

        if (document.onClickEvent) {
            if (typeof document.onClickEvent == 'function') {
                document.onClickEvent(event);
            }
        }

        if (BComboManager.resize) { return false; }

        if (BComboManager.close) {
            BComboManager.close = false;
            return;
        }

        event = event ? event : window.event;
        var elem = srcElem(event);
        try {
            if (BComboManager.currentHead && BComboManager.currentHead != null) {
                var item = BComboManager.headerHArray[BComboManager.currentHead.id];
                if (elemContains(BComboManager.currentHead, elem) && elem != item.searchImg && elem != BComboManager.searchElem[item.bodyObj.id]) {
                    if (BComboManager.headerHArray[BComboManager.currentHead.id].type == 'combo') {
                        BComboManager.fastClose();
                        BComboManager.close = true;
                        return;
                    }
                    else return;
                }
            }

            if (BComboManager.currentBody && BComboManager.currentBody != null) {
                if (!elemContains(BComboManager.currentBody, elem)) { BComboManager.showBodyByElem(elem, 'click'); }
                else {
                    if (BComboManager.attrElem != null) {
                        var a = getElemByAttribute(BComboManager.currentBody, elem, BComboManager.attrElem);
                        if (a && a != null) BComboManager.select(a);
                    }
                }
            }
            else { BComboManager.showBodyByElem(elem, 'click'); }

            if (BComboManager.currentHead && BComboManager.currentHead != null) {
                var item = BComboManager.headerHArray[BComboManager.currentHead.id];
                if (elem == item.searchImg) {
                    if (item.searchImg.state == item.searchImg.openedImgSrc) {
                        BComboManager.hideSearch();
                    }
                    else {
                        item.searchImg.state = item.searchImg.openedImgSrc;
                        var a = BComboManager.captionElem[item.bodyObj.id];
                        if (a) { a.style.display = 'none'; }
                        a = BComboManager.searchElem[item.bodyObj.id];
                        if (a) { a.style.display = ''; }
                        item.searchImg.src = item.searchImg.openedImgSrc;
                        if (BComboManager.searchElem[item.bodyObj.id]) { BComboManager.searchElem[item.bodyObj.id].focus(); }
                        clearTimeout(window.searchTimeout);
                        if (BComboManager.searchElem[item.bodyObj.id].value != '') {
                            window.searchTimeout = setTimeout('BComboManager.searchText("' + BComboManager.searchElem[item.bodyObj.id].value + '");', 0);
                        }
                    }
                }
            }
        }
        catch (e) {
            BComboManager.fastClose();
        }
        return;
    }

    this.onmousemove = function(event) {
        event = event ? event : window.event;
        if (BComboManager.resize) {
            BComboManager.doResize(event);
            return false;
        }

        if (BComboManager.close) {
            BComboManager.close = false;
            return false;
        }
        if (BComboManager.currentBody) {
            //window.status = BComboManager.currentBody.id;
            if (BComboManager.overed[BComboManager.currentBody.id]) {
                BComboManager.out(BComboManager.overed[BComboManager.currentBody.id]);
            }
        }

        var elem = srcElem(event);

        if (elem.tagName == 'OBJECT') {
            if (BComboManager.currentBody) {
                if (BComboManager.bodyHArray[BComboManager.currentBody.id].type != 'combo')
                    BComboManager.slowClose();
            }
            return;
        }

        try {
            if (BComboManager.currentHead && BComboManager.currentHead != null)
                if (elemContains(BComboManager.currentHead, elem))
                return;

            if (BComboManager.currentBody && BComboManager.currentBody != null) {
                if (!elemContains(BComboManager.currentBody, elem)) { BComboManager.showBodyByElem(elem, 'move'); }
                else {
                    if (BComboManager.attrElem != null && BComboManager.getCurrentType() == 'combo') {
                        var a = getElemByAttribute(BComboManager.currentBody, elem, BComboManager.attrElem);
                        if (a && a != null) { BComboManager.over(a); }
                    }
                }
            }
            else
                BComboManager.showBodyByElem(elem, 'move');
        }
        catch (e) {
            BComboManager.fastClose();
        }
    }

    this.slowClose = function() {
        BComboManager.close = true;
        if (BComboManager.currentBody && BComboManager.showAnimation) {
            //<!-- Begin включаем анимацию -->
            slideDown(BComboManager.currentBody.id, 8, 15, -1, 'none');
            //<!-- End включаем анимацию -->
        }
        BComboManager.hideSearch();
        BComboManager.currentBody = null;
        BComboManager.currentHead = null;
    }

    this.fastClose = function() {
        BComboManager.close = true;
        if (BComboManager.currentBody) {
            BComboManager.currentBody.style.display = 'none';
            if (BComboManager.bodyHArray[BComboManager.currentBody.id].type != 'combo') { BComboManager.currentBody.style.height = 1; }
        }
        BComboManager.hideSearch();
        BComboManager.currentBody = null;
        BComboManager.currentHead = null;
        //BComboManager.close = false;
    }
    
    if (isMSIE){
        document.attachEvent('onclick', this.onclick);
        document.attachEvent('onmousemove', this.onmousemove);
        document.attachEvent('onmousedown', this.onmousedown);
        document.attachEvent('onmouseup', this.onmouseup);
        /*for (var i = 0; i < iframes.length; i++)
            iframes[i].contentDocument.attachEvent('onmousemove', this.onmousemove);*/
    }
    else{
        document.documentElement.onclick = this.onclick;
        document.documentElement.onmousemove = this.onmousemove;
        document.documentElement.onmousedown = this.onmousedown;
        document.documentElement.onmouseup = this.onmouseup;
        /*for (var i = 0; i < iframes.length; i++)
            iframes[i].contentDocument.documentElement.onmousemove = this.onmousemove;*/
    }

    if (this.initKeyDown) { this.initKeyDown(); }
    
    this.showAnimation = true;
    this.resize = false;
}
