
var tabs = new Array();

var currentTabIndex = -1;
var currentSubitemIndex = -1;
var currentLittleTabIndex = -1;

var currentNewsYear = -1;
var currentNewsMonth = -1;

var tmpTabIndex = 0;

var maxColumns = 3; // should be > 0- КОЛВО КОЛОНОК В МЕНЮ 2-ГО УРОВНЯ

var wantLoadNewData = false;

var isFormationsListLinear = false;
 
var afterDocClick = false;

var imagesNormal = new Array();
var imagesHot = new Array();
var preloadArray = new Array();

var initFlag = true;

// ----------------------------------- STRING CONSTANTS ----------------------------------------

AV_CHECK_PASS = '\u0412\u0438\u0440\u0443\u0441\u043e\u0432 \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u043e';
AV_CHECK_INFECTED = '\u0417\u0430\u0440\u0430\u0436\u0451\u043d \u0432\u0438\u0440\u0443\u0441\u043e\u043c!';
AV_CHECK_PROGRESS = '\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430..';

SIG_UNSUPPORTED_FILE = '\u041f\u043e\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u044e\u0442\u0441\u044f\u0020\u0442\u043e\u043b\u044c\u043a\u043e\u0020\u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b\u0020\u0057\u006f\u0072\u0064';
SIG_UNSUPPORTED_FILE_VERSION = '';
SIG_NO_SIGNATURE_FOUND = '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0020\u043d\u0435\u0020\u043f\u043e\u0434\u043f\u0438\u0441\u0430\u043d';
SIG_SUCCESS_SIGNATURE = '\u041f\u043e\u0434\u043f\u0438\u0441\u044c\u0020\u043f\u0440\u043e\u0432\u0435\u0440\u0435\u043d\u0430';
SIG_CORRUPTED_FILE = '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0020\u043f\u043e\u0432\u0440\u0435\u0436\u0434\u0451\u043d';
SIG_SIGNATURE_IRRELEVANT = '\u0421\u0435\u0440\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u0020\u043d\u0435\u0020\u0431\u044b\u043b\u0020\u0432\u044b\u0434\u0430\u043d\u0020\u0418\u0410\u0426';
SIG_CERTIFICATE_EXPIRED = '\u0421\u0435\u0440\u0442\u0438\u0444\u0438\u043a\u0430\u0442\u0020\u043f\u0440\u043e\u0441\u0440\u043e\u0447\u0435\u043d';

// ----------------------------------- SIMPLE UTILS ----------------------------------------


function recursiveCleaner( baseNode ) {
    if( ( baseNode != null ) && ( typeof( baseNode.childNodes ) != "undefined" ) && ( baseNode.childNodes != null ) ) {
        var childs = baseNode.childNodes;
        var len = childs.length;
        var i = 0;
        for( i = 0; i < len; i++ ) {
            var node = childs[ 0 ];
            recursiveCleaner( node );
            baseNode.removeChild( node );
        }
    }
};

function destroyNode( node ) {
    recursiveCleaner( node );
    if( node.parentNode != null ) {
        node.parentNode.removeChild( node );
    }
};

function calcElementY( element ) {
    var y = 0;
    while( element != null ) {
        y += element.offsetTop;
        element = element.offsetParent;
    }
    return y;
};

function calcElementX( element ) {
    var x = 0;
    while( element != null ) {
        x += element.offsetLeft;
        element = element.offsetParent;
    }
    return x;
};



// ----------------------------------- HOT IMAGES ------------------------------------------

function appendImages( idOrClassName, normalImage, hotImage ) {
    if( (idOrClassName != null ) && ( idOrClassName != "" ) ) {
        imagesNormal[ idOrClassName ] = normalImage;
        imagesHot[ idOrClassName ] = hotImage;
        preloadArray.push( normalImage );
        preloadArray.push( hotImage );
    }
};

function initialize_images() {
    appendImages( "menuBar", "img/glass-mb.png", "img/glass-mb_hot.png" );
    appendImages( "imgLVBtn", "img/listView.png", "img/listView_hot.png" );
    appendImages( "imgTVBtn", "img/treeView.png", "img/treeView_hot.png" );
    appendImages( "imgFmsList", "img/listbox_right.png", "img/listbox_right_hot.png" );
    appendImages( "imgCollapseBtn", "img/collapse.png", "img/collapse_hot.png" );
    appendImages( "imgExpandBtn", "img/expand.png", "img/expand_hot.png" );
    
    appendImages( "yearsButtonBack", "img/glass-mb.png", "img/glass-mb_hot.png" );
    appendImages( "yearsButtonFwd", "img/glass-mb.png", "img/glass-mb_hot.png" );
    appendImages( "monthButtonBack", "img/glass-mb.png", "img/glass-mb_hot.png" );
    appendImages( "monthButtonFwd", "img/glass-mb.png", "img/glass-mb_hot.png" );
    
    
    var i;
    var m = preloadArray.length;
    var preloadBlock = $( "preloadBlock" );
    var el = null;
    
    for( i = 0; i < m; i++ ) {
        el = document.createElement( "IMG" );
        el.src = preloadArray[ i ];
        el.alt = preloadArray[ i ];
        preloadBlock.appendChild( el );
    }
    
};

function document_click() {
    hideFormations();
    afterDocClick = true;
};

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function postInit() {
//;
};

// ----------------------------------- AJAX ------------------------------------------------
function loadSuggest(id,tableName){
                var fld = document.getElementById(id);
                var clss = fld.className;
                var suggflds = document.getElementsByClassName(clss);
                var qwntOfSugFlds = suggflds.length;
                var CaretPos = document.getElementById(id).selectionEnd;
                var colNumb = id.substring(id.indexOf("ind_")+4);
                var options = {
                    script: function (input) {
                            var hid = "hidden_" + fld.id;
                            var hdnFld = document.getElementById(hid);
                            if(!fld.readOnly){hdnFld.value = "";}
                            //else {alert("\u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u043e\u0447\u0438\u0441\u0442\u0438\u0442\u044c \u043d\u0438\u0436\u043d\u0438\u0435 \u043f\u043e\u043b\u044f.");} //Сначала необходимо очистить нижние поля.
                        var alrdChsn = "";
                        for (var i=0;i<qwntOfSugFlds;i++){
                            var hsid = "hidden_"+suggflds[i].id;
                            var elya = document.getElementById(hsid);
                            if (elya.value!="") {
                                alrdChsn = alrdChsn  + elya.value+";";
                            }
                        }
                        alrdChsn = alrdChsn.substring(0, alrdChsn.length-1);
                        //alert(alrdChsn);
                        return prefix+"/MakeSuggestServlet?qwery="+input+"&ind="+colNumb+"&way="+alrdChsn;
                    } ,
                    minchars: 1,//минимальное кол-во символов
                    cache: false,
                    delay: 250,//задержка перед запросом в БД
                    timeout: 10000,//время жизни посказки при бездействии
                    json: false,
                    //shownoresults: false
                    noresults: "\u041d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u043e!" // Не найдено!
                };
                var as = new bsn.AutoSuggest(id, options, tableName); // !important do not comment line or delete
                document.getElementById(id).focus();
                document.getElementById(id).setSelectionRange(CaretPos,CaretPos);

            }



//var timerC = 0;
var loginLogout = false;
function sessionCheck() {
    if( !loginLogout ) {
        new Ajax.Request( prefix + "/SessionDoneServlet?garbage=" + Math.random() + "_" + Math.random(), {
            onComplete: function(transport) {
                if( ( transport.status != 200 ) || ( trim( transport.responseText ) != "no" ) ) {
                    window.location.reload( false );
                } else {
                    setTimeout( sessionCheck, 45000 );
                }
            },
            method : 'get',
            asynchronous: true
        });
    }
};

function sendStateToServer() {
    var url = "/StateChanged?tab=" + currentTabIndex + "&item=" + currentSubitemIndex + "&littleTabIndex=" + currentLittleTabIndex;
    new Ajax.Request( prefix + url, {
        onComplete: function(transport) {
            var fail = ( transport.status != 200 || transport.responseText == 'ERROR' );
            if( wantLoadNewData ) {
                if( !fail ) {
                    hideFormations();
                    loadLittleTabs();
                    //                    alert( 'response: \'' + transport.responseText + '\'' );
                    var o = eval( transport.responseText );
                    if( o.isTable ) {
                        tmpRefresh();
                        goTableView();
                    } else {
                        var url2 = translatePageCode( o.customPageAdress );
                        if( url2 == null ) {
                            url2 = "/DocBody.jsp?garbage=" + Math.random();
                        }
                        loadCustomDataByUrl( url2, null, o.customPageAdress );
                    }
                } else {
                    goStupidView();
                    showData( transport );
                    tmpRefresh();
                }
                //                loadCustomData();
                requestFormationState();
                
            } else if( fail == true ) {
                alert( 'status: ' + transport.status + '\ntext: ' + transport.responseText );
            }

        //            new Ajax.Request( prefix + "/GetSpecificData?isFmRequired&garbage=" + Math.random(), {
        //                onComplete: function(transport) {
        //                    if( transport.status == 200 ) {
        //                        if( trim( transport.responseText ) == "yes" ) {
        //                            unlockFormations();
        //                            new Ajax.Request( prefix + "/GetSpecificData?isMiddleFormations&garbage=" + Math.random(), {
        //                                onComplete: function(transport) {
        //                                    if( transport.status == 200 ) {
        //                                        if( trim( transport.responseText ) == "yes" ) {
        //                                            isPrevedRequired = true;
        //                                        } else {
        //                                            isPrevedRequired = false;
        //                                        }
        //                                    }
        //                                }
        //                            });
        //                        } else {
        //                            lockFormations();
        //                        }
        //                    }
        //                }
        //            });
            
        }
    });
};

function requestFormationState() {
    var rq = new Ajax.Request( prefix + "/GetSpecificData?getFormationsSettings" + "&garbage=" + Math.random(), {
        onComplete : function( transport ) {
            if( rq.success() ) {
                var o = eval( transport.responseText );
                if( o.fmRequired ) {
                    unlockFormations();
                } else {
                    lockFormations();
                }
                isPrevedRequired = o.middleAllowed;
                $('formationsListText').innerHTML = o.formationText;
            }
        },
        asynchronous: true
    });
}

function sendNewsState() {
    new Ajax.Request( prefix + "/ValueChange?newsYear=" + currentNewsYear + "&garbage=" + Math.random(), {
        onComplete: function( transport ) {
            currentNewsYear = parseInt( transport.responseText );
            visualizeNewsYear();
            new Ajax.Request( prefix + "/ValueChange?newsMonth=" + currentNewsMonth + "&garbage=" + Math.random(), {
                onComplete: function(transport) {
                    currentNewsMonth = parseInt( transport.responseText );
                    visualizeNewsMonth();
                    newsRefresh();
                }
            });
        }
    });
    
};

function loadDataFromServer() {
    hideFormations();
    new Ajax.Request( prefix + "/GetSpecificData?isTable&garbage=" + Math.random(), {    // old value: docBody.jsp
        onComplete: function(transport) {
            if( trim( transport.responseText ) == "no" ) {
                loadCustomData();
            } else {
                tmpRefresh();
                goTableView();
            }
        },
        method : 'get'
    });
    
    loadLittleTabs();
};

function loadLittleTabs() {
    new Ajax.Request( prefix + "/littleTabs.jsp?highlight=" + currentLittleTabIndex + "&garbage=" + Math.random(), {
        onComplete: function(transport) {
            showLittleTabs( transport );
        },
        asynchronous: true
    });
}

function loadCustomData() {
    var url = "/GetSpecificData?customPageAddress=1&garbage=" + Math.random();
    new Ajax.Request( prefix + url, {
        onComplete: function( transport ) {
            var url2 = null;
            if( ( transport.status == 200 ) && ( transport.responseText != "[no link]" ) ) {
                url2 = translatePageCode( transport.responseText );
            } else {
                url2 = "/DocBody.jsp?garbage=" + Math.random();
            }
            loadCustomDataByUrl( url2, null, transport.responseText );
        },
        method : 'get'
    });
};

function loadCustomDataByUrl( url, special, code ) {
    new Ajax.Request( prefix + url , {
        onComplete: function(transport) {
            showData( transport );
            goStupidView();
            new Ajax.Request( prefix + "/GetInitScript?" + code + "&garbage=" + Math.random() , {
                onComplete: function(transport) {
                    eval( transport.responseText );
                },
                method : 'get'
            });
        },
        method : 'get'
    });
};

function requestFormationsListFromServer() {
    var url = "/formationsTree";
    if( isFormationsListLinear == true ) {
        url = url + "?linear=1";
    }
    //requsetFormationTextFromServer();
    new Ajax.Request( prefix + url, {
        onComplete: function( transport ) {
            if( transport.status == 200 ) {
                var listBody = $("listBodyTD");
                if( listBody != null ) {
                    listBody.innerHTML = transport.responseText;
                    convertTrees();
                    $("formationsList").style.display = "block";
                    expandCurrentFormation();
                }
            }
        },
        method : 'get',
        asynchronous: true
    });
};

function requsetFormationTextFromServer() {
    var url = "/GetSpecificData?mftext&garbage=" + Math.random();
    new Ajax.Request( prefix + url, {
        onComplete: function( transport ) {
            if( transport.status == 200 ) {
                //alert(  transport.responseText );
                $("formationsListText").innerHTML = transport.responseText;
            }
        },
        method : 'get',
        asynchronous: true
    });
};

function sendFormationToServer( mfid ) {
    if( mfid != null ) {
        var url = "/StateChanged?mfid=" + mfid;
        new Ajax.Request( prefix + url, {
            onComplete: function( transport ) {
                if( transport.status == 200 ) {
                    requsetFormationTextFromServer();
                    loadDataFromServer();
                }
            }
        });
    }
};

function sendLogin( username, password ) {
    var url = "/LoginServlet";
    if( username != null && password != null ) {
        url = url + "?username=" + escape( username ) + "&password=" + escape( password );
    } else {
        url = url + "?logout";
    }
    
    loginLogout = true;
    new Ajax.Request( prefix + url, {
        onComplete: function( transport ) {
            try {
                if( transport.status == 200 ) {
                    if( trim( transport.responseText ) == "ok" ) {
                        window.location.reload( false );
                    } else {
                        enableLoginButtons();
                        alert( "\u043d\u0435\u0432\u0435\u0440\u043d\u043e\u0435\u0020\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0435\u0020\u0438\u043c\u044f\u0020\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f\u003a\u043f\u0430\u0440\u043e\u043b\u044c" );
                    }
                }
            } finally {
                loginLogout = false;
            }
        },
        asynchronous: true
    });
};

function windowLoad( wnd, url, onload ) {
    new Ajax.Request( prefix + url, {
        onComplete: function( transport ) {
            var client = getClientDiv( wnd );
            if( transport.status == 200 ) {
                client.innerHTML = transport.responseText;
            } else {
                client.innerHTML = "<a class=\"error\"> error loading page. status: " + transport.status + "</a>";
            }
            appendWindow( wnd );
            showWindow( wnd );
            if( onload ) {
                onload.call( wnd, wnd );
            }
        }
    });
};

function checkNewLogin( loginElToCheck, cnlcallback ) {
    new Ajax.Request( prefix + "/Check?type=login&value=" + escape( loginElToCheck.value ), {
        onComplete: function( transport ) {
            if( cnlcallback != null ) {
                cnlcallback.call( loginElToCheck, transport.responseText );
            }
        },
        asynchronous: true
    });
};

function checkAnyField( elementToCheck, type, cafcallback ) {
    new Ajax.Request( prefix + "/Check?type=" + escape( type ) + "&value=" + escape( loginElToCheck.value ), {
        onComplete: function( transport ) {
            if( cnlcallback != null ) {
                cnlcallback.call( loginElToCheck, transport.responseText );
            }
        },
        asynchronous: true
    });
};


// ----------------------------------- NAVIGATION ------------------------------------------

function goTableView() {
    $("docBodyStupid").style.display = "none";
    $("docBodyTable").style.display = "block";
};

function goStupidView() {
    $("docBodyStupid").style.display = "block";
    $("docBodyTable").style.display = "none";
};
////the is old metod of goTab( tabNumber )kozhuhov we dont use it here
//function goTabOld( tabNumber ) {
//    hideFormations();
//    var ctabid = 'menuTab' + tabNumber;
//    var ctabid_old = 'menuTab' + tmpTabIndex;
//    var menuTabTD = document.getElementById( ctabid );
//    var menuTabOldTD = document.getElementById( ctabid_old );
//    
//    if( menuTabTD ) {
//        if( menuTabOldTD ) {
//            $(ctabid_old + 'left').className = "menuTabsBarLeft";
//            $(ctabid_old + 'right').className = "menuTabsBarRight";
//            menuTabOldTD.className = "menuTabsBar";
//        //menuTabOldTD.setAttribute( 'class', 'menuTabsBar' );
//        }
//        tmpTabIndex = tabNumber;
//        menuTabTD.className = "menuTabsBarCurrent";
//        $(ctabid + 'left').className = "menuTabsBarLeftCurrent";
//        $(ctabid + 'right').className = "menuTabsBarRightCurrent";
//        //menuTabTD.setAttribute( 'class', 'menuTabsBarCurrent' );
//        
//        if( !tabs ) {
//            alert('no tabs array');
//            return false;
//        }
//        
//        /*var s = '';
//        for( var i = 0; i < tabs.length; i++ ) {
//            for( var j = 0; j < tabs[i].subItems.length; j++ ) {
//                s += tabs[i].subItems[j] + '\n';
//            }
//        }
//        alert( s );*/
//        if( tabs.length == 0 && tabNumber == 0 ) {
//        //alert( 'no such tab' );
//        // ignore
//        } else {
//            var itTab = tabs[ tabNumber ];
//            if( itTab ) {
//                var count = itTab.getLength();
//                var processed = 0;
//                var menuBar = document.getElementById( 'menuBar' );
//                
//                //alert( "count: " + count + "\nrows: " + rowsCount );
//                
//                if( menuBar ) {
//                    var m = menuBar.childNodes.length;
//                    for( var i = 0; i < m; i++ ) {
//                        menuBar.removeChild( menuBar.childNodes[ 0 ] );
//                    }
//                    var rows = new Array();
//                    var gcount = 0;
//                    for( var i = 0; processed < count; i++ ) {
//                        var row = document.createElement( 'tr' );
//                        rows.push( row );
//                        row.id = "menuRow" + i;
//                        //row.setAttribute( 'id', 'menuRow' + i );
//                        for( var j = 0; j < maxColumns; j++,processed++ ) {
//                            var cell = document.createElement( 'td' );
//                            var leftCell = document.createElement( 'td' );
//                            var rightCell = document.createElement( 'td' );
//                            
//                            cell.style.backgroundImage = "url( img/glass-mb.png )";
//                            cell.style.height = "20px";
//                            cell.myTag = gcount;
//                            cell.myLeft = leftCell;
//                            cell.myRight = rightCell;
//                            
//                            if( gcount < count ) {
//                                // data
//                                cell.className = "menuBar";
//                                
//                                /*cell.onclick = go;
//                                cell.onmouseover = highlight_menuItem;
//                                cell.onmouseout = unhighlight_menuItem;
//                                 */
//                                
//                                cell.id = "menuItem" + gcount;
//                                cell.setAttribute( 'id', cell.id );
//                                cell.style.overflow = 'hidden';
//                                cell.style.whiteSpace = 'nowrap';
//                                notcurrent_menuItem( cell );
//                                
//                                cell.setAttribute( 'valign', 'middle' );
//                                var innerA = document.createElement( 'a' );
//                                cell.appendChild( innerA );
//                                innerA.setAttribute( 'href', 'javascript:void(0);' );
//                                innerA.className = "menuBarText";
//                                var text = itTab.subItems[ gcount ];
//                                if( text ) {
//                                    innerA.innerHTML = text;
//                                }
//                                // left
//                                leftCell.style.backgroundImage = "url( img/cellCorners.png )";
//                                leftCell.style.width = "3px";
//                                leftCell.style.height = "20px";
//                                leftCell.style.minWidth = '3px';
//                                leftCell.style.overflow = 'visible';
//                                
//                                // right
//                                rightCell.style.backgroundImage = "url( img/cellCorners.png )";
//                                rightCell.style.width = "3px";
//                                rightCell.style.height = "20px";
//                                rightCell.style.minWidth = '3px';
//                                rightCell.style.overflow = 'visible';
//                                gcount++;
//                            } else {
//                                cell.className = "menuBarStatic";
//                                leftCell.style.backgroundImage = "url( img/glass-mb.png )";
//                                rightCell.style.backgroundImage = "url( img/glass-mb.png )";
//                            }
//                            
//                            row.appendChild( leftCell );
//                            row.appendChild( cell );
//                            row.appendChild( rightCell );
//                        }
//                        menuBar.appendChild( row );
//                    }
//                    
//                    if( tmpTabIndex == currentTabIndex ) {
//                        go( currentSubitemIndex );
//                    }
//                    
//                } else {
//                    alert('error. no menuBar');
//                }
//            } else {
//                alert( 'no such tab' );
//            }
//        }
//    } else {
//        if( tabs.length > 0 ) {
//            alert( ' error. no such element: ' + ctabid );
//        }
//    }
//    updateFormationLocker();
//    return false;
//}
//for vertical type of menu . we dont use it here
//function goTabVertical( tabNumber, tabCount ) {
//
//    hideFormations();
//    var ctabid       = 'menuTab' + tabNumber;
//    var ctabid_old   = 'menuTab' + tmpTabIndex;
//    var menuTabTD    = document.getElementById( ctabid );
//    var menuTabOldTD = document.getElementById( ctabid_old );
//
//    if( menuTabTD ) {
//        tmpTabIndex = tabNumber;
//
//        if( tabs == null) {
//            alert('no tabs array');
//            return false;
//        }
//
//        if( tabs.length == 0 && tabNumber == 0 ) {
//        // ignore
//        } else {
//            var itTab = tabs[ tabNumber ];
//            if( itTab ) {
//                var count = itTab.getLength();
//                var processed = 0;
//
//                var menuBar = document.getElementById( 'menuBarVertical' );
//
//                if( menuBar ) {
//                    var m = menuBar.childNodes.length;
//                    for( var i=0; i < m; i++ ) {
//                        menuBar.removeChild( menuBar.childNodes[ 0 ] );
//                    }
//
//                    //var rows = new Array();
//                    var gcount = 0;
//                    var firstSubNumber = -1;
//                    for( var i=0; processed < count; i++ ) {
//                        processed++;
//
//                        var row = document.createElement( 'tr' );
//                        //rows.push( row );
//                        row.id = "menuRow" + i;
//                        var cell = document.createElement( 'td' );
//
//                        //cell.style.height = "20px";
//                        cell.style.width = "95%";
//                        cell.myTag = gcount;
//
//                        cell.className = "menuBarVertical";
//
//                        cell.id = "menuItem" + gcount;
//                        cell.setAttribute( 'id', cell.id );
//                        cell.style.overflow = 'hidden';
//                        cell.style.whiteSpace = 'nowrap';
//                        notcurrent_menuItemVertical( cell );
//
//                        cell.setAttribute( 'valign', 'middle' );
//                        cell.setAttribute( 'width', '95%' );
//                        var innerA = document.createElement( 'a' );
//                        cell.appendChild( innerA );
//                        innerA.setAttribute( 'href', 'javascript:void(0);' );
//                        innerA.onclick = function(){setMenuCurrent(ctabid);};
//
//
//
//                        var text = itTab.subItems[ gcount ];
//
//                        if( text ) {
//                            innerA.innerHTML = text;
//                            if(i==0){
//                                var rowHeader = document.createElement( 'tr' );
//                                var cellHeader = document.createElement( 'td' );
//                                cellHeader.style.height = "20px";
//                                cellHeader.style.width = "95%";
//                                cellHeader.className = "menuBarVerticalTitle";
//                                cellHeader.setAttribute( 'width', '95%' );
//                                var innerAH = document.createElement( 'a' );
//                                innerAH.innerHTML = "&nbsp;";
//                                cellHeader.appendChild(innerAH)
//
//                                rowHeader.appendChild(cellHeader);
//                                menuBar.appendChild( rowHeader );
//                            }
//
//                            row.appendChild( cell );
//                            menuBar.appendChild( row );
//                        }
//
//                        if(i == 0){
//                            //innerA.style.fontWeight = "bold";
//                            //innerA.innerHTML = "&rarr;" + innerA.innerHTML;
//                            setMenuCurrent(ctabid);
//                            firstSubNumber = gcount;
//                        }
//
//                        gcount++;
//
//                    }
//
//
//                    if( firstSubNumber != -1 && currentSubitemIndex != -1) {
////                        alert('currentLittleTabIndex1 = '+ currentLittleTabIndex);
//                        goVertical( firstSubNumber,0);
//                    }
//
//                } else {
//                    alert('error. no menuBar');
//                }
//            } else {
//                alert( 'no such tab' );
//            }
//        }
//    } else {
//        if( tabs.length > 0 ) {
//            alert( ' error. no such element: ' + ctabid );
//        }
//    }
//    updateFormationLocker();
//    return false;
//}
//kozhuhov new method to show first tab of 3th menu level 
function goTab( tabNumber ) {
    hideFormations();
    var ctabid = 'menuTab' + tabNumber;
    var ctabid_old = 'menuTab' + tmpTabIndex;

    var menuTabTD = document.getElementById( ctabid );
    var menuTabOldTD = document.getElementById( ctabid_old );

    var subMenuTable = document.getElementById("subMenuId");

    if( menuTabTD ) {
        if( menuTabOldTD ) {
            $(ctabid_old + 'left').className = "menuTabsBarLeft";
            $(ctabid_old + 'right').className = "menuTabsBarRight";
            menuTabOldTD.className = "menuTabsBar";
        //menuTabOldTD.setAttribute( 'class', 'menuTabsBar' );
        }
        tmpTabIndex = tabNumber;
        menuTabTD.className = "menuTabsBarCurrent";
        $(ctabid + 'left').className = "menuTabsBarLeftCurrent";
        $(ctabid + 'right').className = "menuTabsBarRightCurrent";
//        menuTabTD.setAttribute( 'class', 'menuTabsBarCurrent' );

        if( !tabs ) {
            alert('no tabs array');
            return false;
        }

        /*var s = '';
        for( var i = 0; i < tabs.length; i++ ) {
            for( var j = 0; j < tabs[i].subItems.length; j++ ) {
                s += tabs[i].subItems[j] + '\n';
            }
        }
        alert( s );*/
        if( tabs.length == 0 && tabNumber == 0 ) {
        //alert( 'no such tab' );
        // ignore
        } else {
            var itTab = tabs[ tabNumber ];
            if( itTab ) {
                var count = itTab.getLength();
                var processed = 0;
                var menuBar = document.getElementById( 'menuBar' );

                //alert( "count: " + count + "\nrows: " + rowsCount );

                if( menuBar ) {
                    var m = menuBar.childNodes.length;
                    for( var i = 0; i < m; i++ ) {
                        menuBar.removeChild( menuBar.childNodes[ 0 ] );
                    }
                    var rows = new Array();
                    var gcount = 0;
                    for( var i = 0; processed < count; i++ ) {
                        var row = document.createElement( 'tr' );
                        rows.push( row );
                        row.id = "menuRow" + i;
                        //row.setAttribute( 'id', 'menuRow' + i );
                        for( var j = 0; j < maxColumns; j++,processed++ ) {
                            var cell = document.createElement( 'td' );
                            var leftCell = document.createElement( 'td' );
                            var rightCell = document.createElement( 'td' );

                            cell.style.backgroundImage = "url( img/glass-mb.png )";
                            cell.style.height = "20px";
                            cell.myTag = gcount;
                            cell.myLeft = leftCell;
                            cell.myRight = rightCell;

                            if( gcount < count ) {
                                // data
                                cell.className = "menuBar";

                                /*cell.onclick = go;
                                cell.onmouseover = highlight_menuItem;
                                cell.onmouseout = unhighlight_menuItem;
                                 */

                                cell.id = "menuItem" + gcount;
                                cell.setAttribute( 'id', cell.id );
                                cell.style.overflow = 'hidden';
                                cell.style.whiteSpace = 'nowrap';
                                notcurrent_menuItem( cell );

                                cell.setAttribute( 'valign', 'middle' );
                                var innerA = document.createElement( 'a' );
                                cell.appendChild( innerA );
                                innerA.setAttribute( 'href', 'javascript:void(0);' );
                                innerA.className = "menuBarText";
                                innerA.setAttribute('onclick', 'setMenuCurrent("'+ctabid+'")');
                                innerA.onclick = function(){setMenuCurrent(ctabid)};
                                var text = itTab.subItems[ gcount ];
                                if( text ) {
                                    innerA.innerHTML = text;
                                }
                                // left
                                leftCell.style.backgroundImage = "url( img/cellCorners.png )";
                                leftCell.style.width = "3px";
                                leftCell.style.height = "20px";
                                leftCell.style.minWidth = '3px';
                                leftCell.style.overflow = 'visible';

                                // right
                                rightCell.style.backgroundImage = "url( img/cellCorners.png )";
                                rightCell.style.width = "3px";
                                rightCell.style.height = "20px";
                                rightCell.style.minWidth = '3px';
                                rightCell.style.overflow = 'visible';

                                if(i == 0){
                                    //innerA.style.fontWeight = "bold";
                                    //innerA.innerHTML = "&rarr;" + innerA.innerHTML;
                                    setMenuCurrent(ctabid);
                                    firstSubNumber = 0//it starts from zero - 0((gcount > 0)?gcount-1:gcount)-1;
                                }
                                
                                gcount++;///kozhuhov
//                                alert("gcount = " + gcount);
                            } else {
                                cell.className = "menuBarStatic";
                                leftCell.style.backgroundImage = "url( img/glass-mb.png )";
                                rightCell.style.backgroundImage = "url( img/glass-mb.png )";
                            }

                            row.appendChild( leftCell );
                            row.appendChild( cell );
                            row.appendChild( rightCell );
                        }
                        menuBar.appendChild( row );
                    }

//                    if( tmpTabIndex == currentTabIndex ) {
//                        goVertical( currentSubitemIndex );
//                    }
                      if( firstSubNumber != -1 && currentSubitemIndex != -1) {
//                          alert('firstSubNumber = '+ firstSubNumber);
//                          alert('currentLittleTabIndex2 = '+ currentLittleTabIndex);
                          go( firstSubNumber,0);
                          
                      }

                } else {
                    alert('error. no menuBar');
                }
            } else {
                alert( 'no such tab' );
            }
        }
    } else {
        if( tabs.length > 0 ) {
            alert( ' error. no such element: ' + ctabid );
        }
    }
    updateFormationLocker();
    //currentLittleTabIndex = 0;
    return false;
};

function setMenuCurrent(menuId)
{
    var menuTabTD    = document.getElementById( menuId );

    var elems_cur = document.getElementsByClassName('menuTabsBarCurrent');
    var elems_cur_left  = document.getElementsByClassName('menuTabsBarLeftCurrent');
    var elems_cur_right = document.getElementsByClassName('menuTabsBarRightCurrent');

    for(i=0; i<elems_cur.length; i++){
        elems_cur[i].className = "menuTabsBar";
        elems_cur_left[i].className = "menuTabsBarLeft";
        elems_cur_right[i].className = "menuTabsBarRight";
    }


    menuTabTD.className = "menuTabsBarCurrent";
    $(menuId + 'left').className = "menuTabsBarLeftCurrent";
    $(menuId + 'right').className = "menuTabsBarRightCurrent";
}


function showData( req ) {
    if( req.status == 200 ) {
        $( 'docBodyStupid' ).innerHTML = req.responseText;
    } else {
        $( 'docBodyStupid' ).innerHTML = '<a class=\"error\"> Error loading data. Status: ' + req.status + '</a>';
    }
};

function showLittleTabs( req ) {
    if( req == null ) 
        alert( "PREVED is null " );
    if( req.status == 200 ) {
        //alert( req.responseText );
        //$( 'littleTabsBody' ).innerHTML = "MEDVED";
        $( 'littleTabsBody' ).innerHTML = req.responseText;
    //alert( req.responseText );
    } else {
        //alert( "2" );
        $( 'littleTabsBody' ).innerHTML = '&nbsp; <!-- error loading data for little tabs. status code: ' + req.status + '-->';
        alert( "error " + req.status + "\n" + req.responseText );
    }
    
/*var i = 0;
    var el = null;
    for( i = 0; i < 15; i++ ) {
        if( ( el = $( "littleTabTd_" + i ) ) != null ) {
            el.style.className = "littleTab";
        } else
            document.title = document.title + "e";
    }
    if( ( el = $( "littleTabTd_" + currentLittleTabIndex ) ) != null ) {
        el.style.className = "littleTabCurrent";
    } else
        document.title = document.title + "e";*/
};

function go( itemNumber ) {
    hideFormations();
    var newCurrentCell = null;
    if( typeof( itemNumber) == "number" ) {
        newCurrentCell = $( 'menuItem' + itemNumber );
    } else if( this != null  ) {
        newCurrentCell = this;
    }
    
    var newItemNumber = null;
    var currentCell = null;
    
    /*if( newCurrentCell == null ) {
        //alert( '!!!' );
        return;
    }*/
    
    if( newCurrentCell != null ) {
        newItemNumber = newCurrentCell.myTag;
        currentCell = $( 'menuItem' + currentSubitemIndex );
        notcurrent_menuItem( currentCell );
    }
//alert(currentLittleTabIndex);
    currentLittleTabIndex = 0;
    wantLoadNewData = false;
    if( newCurrentCell != null &&  typeof( newCurrentCell ) != 'undefined' ) {
        if(currentCell!=null)
            currentCell.className = "menuBarCurrent";

        current_menuItem( newCurrentCell );
        //currentCell.setAttribute( 'class', 'menuBarCurrent' );
        if( ( currentSubitemIndex != newItemNumber ) || ( currentTabIndex != tmpTabIndex ) ) {
            wantLoadNewData = true;
            $( "docBodyStupid" ).innerHTML = "\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430..."; // Загрузка...
        }
        //alert( newItemNumber );
        currentSubitemIndex = newItemNumber;
        currentTabIndex = tmpTabIndex;
    }
    
    sendStateToServer();

    return false;
};

function goVertical( itemNumber , currentLittleTab) {
    loadingShow();
    hideFormations();
    var newCurrentCell = null;
    if( typeof( itemNumber) == "number" ) {
        newCurrentCell = $( 'menuItem' + itemNumber );
    } else if( this != null  ) {
        newCurrentCell = this;
    }

    var newItemNumber = null;
    var currentCell = null;
   
    if( newCurrentCell != null ) {
        newItemNumber = newCurrentCell.myTag;
        currentCell = $( 'menuItem' + currentSubitemIndex );
        
        notcurrent_menuItemVertical( currentCell );
    }
    if(currentLittleTab == 'undefined'||currentLittleTab==null){
    currentLittleTabIndex = 0;
    }else currentLittleTabIndex = currentLittleTab;
//    alert(currentLittleTab+" : "+currentLittleTabIndex);//
    wantLoadNewData = false;
    if( newCurrentCell != null &&  typeof( newCurrentCell ) != 'undefined' ) {
        //currentCell.className = "menuBarCurrent";
        current_menuItemVertical( newCurrentCell );
        //currentCell.setAttribute( 'class', 'menuBarCurrent' );
        if( ( currentSubitemIndex != newItemNumber ) || ( currentTabIndex != tmpTabIndex ) ) {
            wantLoadNewData = true;
            $( "docBodyStupid" ).innerHTML = "\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430..."; // Загрузка...
        }
//        alert( newItemNumber );
        currentSubitemIndex = newItemNumber;
        currentTabIndex = tmpTabIndex;
    }
    
    if(document.getElementById("subMenuVertical").style.display == "none")
        hideSubMenuVertical();

    sendStateToServer();
//    currentLittleTabIndex = 0;
    return false;
};


function goLittleTab( littleTabIndex ) {
    // unselect little tabs
    
    currentLittleTabIndex = littleTabIndex;
    wantLoadNewData = true;
    sendStateToServer();
};
// ------------------------------------------- WINDOWING ---------------------------------------------

var windowLayerZorder = 1000;
var windowIds = new Array();

function createWindow( isModal, windowId, title, width, height ) {
    if( windowIds.indexOf( windowId ) >= 0 ) {
        return null;
    }
    windowIds.push( windowId );
    
    var baseDiv = null;
    
    if( isModal == true ) {
        baseDiv = document.createElement( "div" );
        baseDiv.className = "modalWindowLayer";
    }
    
    var windowDiv = document.createElement( "div" );
    windowDiv.className = "windowBar";
    windowDiv.style.position = "absolute";
    //    windowDiv.style.overflow = "hidden";
    
    if( width && height ) {
        windowDiv.style.width = width + "px";
        windowDiv.style.height = height + "px";
        windowDiv.style.left = 150 + "px";   // TODO: auto positioning
        windowDiv.style.top = 150 + "px";
    } else {
        var _1_3w = screen.width / 3;
        var _1_4h = screen.height / 4;
        windowDiv.style.width = _1_3w + "px";
        windowDiv.style.height = _1_4h + "px";
        windowDiv.style.left = _1_3w + "px";
        windowDiv.style.top = _1_4h + "px";
    }
    
    if( baseDiv == null ) {
        baseDiv = windowDiv;
    } else {
        baseDiv.appendChild( windowDiv );
    }
    
    var table = document.createElement( "table" );
    table.style.width = "100%";
    table.style.height = "100%";
    var tbody = document.createElement( "tbody" );
    table.appendChild( tbody );
    windowDiv.appendChild( table );
    
    var captionRow = document.createElement( "tr" );
    var captionCell = document.createElement( "td" );
    captionRow.appendChild( captionCell );
    tbody.appendChild( captionRow );
    
    captionCell.className = "windowCaption";
    captionCell.innerHTML = title;
    
    
    var bodyRow = document.createElement( "tr" );
    var bodyCell = document.createElement( "td" );
    bodyRow.appendChild( bodyCell );
    tbody.appendChild( bodyRow );
    
    var bodyDiv = document.createElement( "div" );
    bodyDiv.style.width = "100%";
    bodyDiv.style.height = "10%";
    bodyCell.appendChild( bodyDiv );
    bodyDiv.id = windowId + "__body";
    bodyDiv.style.overflow = 'auto';
    
    baseDiv.id = windowId;
    baseDiv.style.display = "none";
    baseDiv.style.zIndex = windowLayerZorder;
    return baseDiv;
};

function createWindowUrl( isModal, windowId, title, url, width, height, onload ) {
    var wnd = createWindow( isModal, windowId, title, width, height );
    if( wnd != null ) {
        windowLoad( wnd, url, onload );
    }
};

function showWindow( baseDiv ) {
    baseDiv.style.display = "block";
};

function hideWindow( baseDiv ) {
    baseDiv.style.display = "none";
};

function appendWindow( baseDiv ) {
    if( baseDiv != null ) {
        $("bodyDiv").appendChild( baseDiv );
    }
};

function getClientDiv( baseDiv ) {
    var windowId = baseDiv.id + "__body";
    var el = document.getElementById( windowId );
    if( el != null ) {
        return el;
    } else {
        if( baseDiv.className == "modalWindowLayer" ) {
            el = baseDiv.firstChild;
        } else {
            el = baseDiv;
        }
        // here el is window div
        
        el = el.firstChild.firstChild;
        
        // here tbody
        el = el.lastChild.firstChild;
        
        // here td
        
        el = el.firstChild;
        
        // here div
        
        return el;
        
    }
};

function destroyWindow( baseDiv ) {
    var index = windowIds.indexOf( baseDiv.id );
    if( index >= 0 ) {
        windowIds[ index ] = null;
        delete windowIds[ index ];
    }
    hideWindow( baseDiv );
    recursiveCleaner( baseDiv );
    if( baseDiv.parentNode != null ) {
        baseDiv.parentNode.removeChild( baseDiv );
    }
    
};

function destroyWindowById( windowId ) {
    destroyWindow( $( windowId ) );
};



// ------------------------------------------- LOGIN -------------------------------------------------

var loginWindow = null;

function login() {
    // alert( "login not implemented" );
    if( loginWindow != null ) {
        destroyWindow( loginWindow );
    }
    
    loginWindow = createWindow( true, "loginDiv", "\u0412\u0445\u043e\u0434" );
    
    var div = getClientDiv( loginWindow );
    
    var t = document.createElement( "span" );
    t.innerHTML = "\u0418\u043c\u044f\u0020\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f";
    t.style.width = "98%";
    div.appendChild( t );
    
    var username = document.createElement( "input" );
    username.type = "text";
    username.id = "__username";
    username.style.width = "98%";
    div.appendChild( username );
    
    t = document.createElement( "span" );
    t.innerHTML = "\u041f\u0430\u0440\u043e\u043b\u044c";
    t.style.width = "98%";
    div.appendChild( t );
    
    var password = document.createElement( "input" );
    password.type = "password";
    password.id = "__password";
    password.style.width = "98%";
    div.appendChild( password );
    
    var button = document.createElement( "button" );
    button.onclick = tryLogin;
    button.innerHTML = "\u0412\u0445\u043e\u0434";   // вход
    button.id = "loginTry";
    div.appendChild( button );
    
    button = document.createElement( "button" );
    button.onclick = cancelLogin;
    button.innerHTML = "\u041e\u0442\u043c\u0435\u043d\u0430";  // отмена
    button.id = "loginCancel";
    div.appendChild( button );
    
    appendWindow( loginWindow );
    //document.body.appendChild( loginWindow );
    showWindow( loginWindow );

    username.focus();
    password.onkeypress = function(e) {
        keynum = (window.event)? e.keyCode : e.which;
        if( keynum == 13 ) {
            tryLogin();
        }
        return true;
    };
};

function logout() {
    sendLogin();
};

function disableLoginButtons() {
    var cb = $( "loginCancel" );
    if( cb != null ) {
        cb.disabled = true;
    }
    cb = $( "loginTry" );
    if( cb != null ) {
        cb.diabled = true;
    }
};

function enableLoginButtons() {
    var cb = $( "loginCancel" );
    if( cb != null ) {
        cb.disabled = false;
    }
    cb = $( "loginTry" );
    if( cb != null ) {
        cb.diabled = false;
    }
};

function tryLogin() {
    disableLoginButtons();
    var username = $("__username").value;
    var password = $("__password").value;
    sendLogin( username, password );
};

function cancelLogin() {
    destroyWindow( loginWindow );
};

var userDetailsString = "\u041b\u0438\u0447\u043d\u044b\u0435\u0020\u0434\u0430\u043d\u043d\u044b\u0435";
function ownData() {
    createWindowUrl( true, "own_data", userDetailsString, "/userSettings.jsp" ); //, 300, 300 );
};

var registrationString = "\u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f";
var register = function() {
    createWindowUrl( false, "registerWindow", registrationString, "/register.jsp", 500, 400, function() {
        $('usernameRegister').focus();
    });
};

settings = function() {

    var wnd;
    wnd = new JSWindow();
    wnd.zOrder = 1200;
    wnd.resize(new RectangularArea(150, 50, 600, 400));
    wnd.setCaption('\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430');
    wnd.setOnHide( function() {
        mtFlush( wnd.getBody() );
        window.location.reload( false );
    });
    wnd.loadFromURL('/menu_tree.jsp?' + Math.random(), true, '/scripts/inits/menu_tree_settings.js' );
//createWindowUrl( false, 'settingsWindow', 'settings', '/menu_tree.jsp', 500, 400 );
};

checkFile = function( id, first, element, type ) {
    var req = prefix + '/VirusCheckServlet?id=' + id;
    if( first ) {
        req += '&init=1';
    }
    req += '&rnd=';
    req += Math.random();
    if( type == 'sig' ) {
        req += '&sig=yes';
    }

    recursiveCleaner(element);
    element.onclick = null;
    element.className = '';
    element.innerHTML = AV_CHECK_PROGRESS;
    var r = new Ajax.Request( req, {
        onComplete: function( t ) {
            if( t.readyState == 4 && t.status == 200 ) {
                var done = false;
                if( !first ) {
                    var resp = t.responseText;
                    if( resp == 'PASS' ) {
                        element.innerHTML = '<span style="color: green">' + AV_CHECK_PASS + '</span>';
                        done = true;
                    } else if( resp == 'PASS_BUT_OLD_BASE' ) {
                        element.innerHTML = '<span style="color: green">' + AV_CHECK_PASS + ' (note: virus-list is not fresh)</span>';
                        done = true;
                    } else if( resp == 'VIRUS_DETECTED' ) {
                        element.innerHTML = '<span style="color: red">' + AV_CHECK_INFECTED + '</span>';
                        done = true;
                    } else if( resp == 'UNKNOWN' || resp == 'INTERRUPTED' ) {
                        element.innerHTML = 'File was not checked due to error';
                        done = true;
                    } else if( resp == 'NOT_READY' ) {
                        element.innerHTML += '.';
                    } else if( resp == 'NONE' ) {
                        element.innerHTML = 'File was not checked due to error';
                        done = true;
                    } else if( resp == 'UNSUPPORTED_FILE' ) {
                        element.innerHTML = SIG_UNSUPPORTED_FILE;
                        done = true;
                    } else if( resp == 'NO_SIGNATURE_FOUND' ) {
                        element.innerHTML = SIG_NO_SIGNATURE_FOUND;
                        done = true;
                    } else if( resp == 'SUCCESS_SIGNATURE' ) {
                        element.innerHTML = SIG_SUCCESS_SIGNATURE;
                        done = true;
                    } else if( resp == 'CORRUPTED_FILE' ) {
                        element.innerHTML = SIG_CORRUPTED_FILE;
                        done = true;
                    } else if( resp == 'SIGNATURE_IRRELEVANT' ) {
                        element.innerHTML = SIG_SIGNATURE_IRRELEVANT;
                        done = true;
                    } else if( resp == 'CERTIFICATE_EXPIRED' ) {
                        element.innerHTML = SIG_CERTIFICATE_EXPIRED;
                        done = true;
                    }
                } else {
                    done = false;
                }
                if( !done ) {
                    window.setTimeout(function() {
                        checkFile( id, false, element, type );
                    }, 1000 );
                }
            } else {
                element.innerHTML = 'File checking failed due to network problem';
            }
        },
        asynchronous: true
    });
};

// ------------------------------------------- SEARCH --------------------------------------

function search() {
    document.location = 'search?q=' + encodeURIComponent( $('searchBarText').value );
};

function advancedSearch() {
    alert( "advanced search not implemented" );
};

// ----------------------------------- FORMATIONS TREE -------------------------------------

function toolbarButtonOver( event ) {
    if( !event ) {
        event = window.event;
    }
    highlightItem( this );
    if( this.tooltip != null ) {
        showTooltipEvent( event, this.tooltip );
    }
};

function toolbarButtonOut( event ) {
    if( !event ) {
        event = window.event;
    }
    unhighlightItem( this );
    hideTooltip();
};

function createToolbarButton( id, image, alt, onclick, tooltip ) {
    var btn = document.createElement( 'TD' );
    var a = document.createElement( 'A' );
    var img = document.createElement( 'IMG' );
    btn.style.width = "20px";
    a.href = onclick; //"javascript:treeViewClick();";
    img.id = id; //"imgTVBtn";
    img.onmouseover = toolbarButtonOver;
    img.onmouseout = toolbarButtonOut;
    img.tooltip = tooltip;
    img.src = image; //"img/treeView.png";
    img.alt = alt; //"T";
    img.border = "0";
    a.appendChild( img );
    btn.appendChild( a );
    return btn;
};

var formationsListDiv = null;
function createFormations() {
    var formationsDiv = document.createElement( "div" );
    var tabl = document.createElement( "table" );
    var tbody = document.createElement( "tbody" );
    var toolbar = document.createElement( "tr" );
    var listBodyRow = document.createElement( "tr" );
    
    formationsDiv.style.display = "none";
    formationsDiv.style.position = "absolute";
    formationsDiv.style.backgroundColor = "GhostWhite";
    
    formationsDiv.style.opacity = ".95";
    //formationsDiv.style.filter = "alpha(opacity=95)"; // IE7 slow and buggy...do not uncomment before paradise time comes
    
    toolbar.style.backgroundImage = "url( img/formationsListToolbar.png )";
    toolbar.style.height = "23px";
    
    //tabl.setAttribute( 'border', '1' );
    tabl.setAttribute( "cellPadding", "0" );
    tabl.setAttribute( "cellSpacing", "0" );
    tabl.setAttribute( "summary", "" );
    tabl.style.borderBottom = "1px solid black";
    tabl.style.borderLeft = "1px solid black";
    tabl.style.borderRight = "1px solid black";
    tabl.style.borderTop = "1px solid black";
    
    tabl.style.width = "100%";
    tabl.width = "100%";
    
    // tree view button
    // createToolbarButtons
    var treeViewBtn = createToolbarButton( "imgTVBtn", "img/treeView.png", "T", "javascript:treeViewClick();", "\u0412\u0020\u0432\u0438\u0434\u0435\u0020\u0434\u0435\u0440\u0435\u0432\u0430" );
    
    var listViewBtn = createToolbarButton( "imgLVBtn", "img/listView.png", "L", "javascript:listViewClick();", "\u0412\u0020\u0432\u0438\u0434\u0435\u0020\u0441\u043f\u0438\u0441\u043a\u0430" );
    
    var collapseBtn = createToolbarButton( "imgCollapseBtn", "img/collapse.png", "C", "javascript:collapseFormationsTree();", "\u0421\u0432\u0435\u0440\u043d\u0443\u0442\u044c\u0020\u0432\u0441\u0435" );
    
    var expandBtn = createToolbarButton( "imgExpandBtn", "img/expand.png", "E", "javascript:expandFormationsTree();", "\u0420\u0430\u0437\u0432\u0435\u0440\u043d\u0443\u0442\u044c\u0020\u0432\u0441\u0435" );
    
    // search bar
    var searchBar = document.createElement( "TD" );
    searchBar.innerHTML = "search";
    searchBar.style.textAlign = "right";
    searchBar.style.width = "100%";
    
    // body
    var listBody = document.createElement( "TD" );
    listBody.colSpan = "5";
    var listBodyDiv = document.createElement( "div" );
    listBodyDiv.innerHTML = "loading...";
    listBodyDiv.id = "listBodyTD";
    listBodyDiv.style.display = "block";
    listBodyDiv.style.width = "100%";
    listBodyDiv.style.height = "350px";
    listBodyDiv.style.overflowY = "scroll";
    
    listBody.appendChild( listBodyDiv );
    toolbar.appendChild( treeViewBtn );
    toolbar.appendChild( listViewBtn );
    toolbar.appendChild( collapseBtn );
    toolbar.appendChild( expandBtn );
    toolbar.appendChild( searchBar );
    listBodyRow.appendChild( listBody );
    tbody.appendChild( toolbar );
    tbody.appendChild( listBodyRow );
    tabl.appendChild( tbody );
    formationsDiv.appendChild( tabl );
    
    return formationsDiv;
};

function getFormationsList() {
    if( formationsListDiv == null ) {
        formationsListDiv = createFormations();
        $("formationsList").appendChild( formationsListDiv );
        formationsListDiv.style.width = "98%";
        requestFormationsListFromServer();
    }
    return formationsListDiv;
};

function setupFormationsList( width ) {
    if( getFormationsList() == null ) {
        alert( "error" );
    }
    return formationsListDiv;
};

var tvar = true;

function showFormations() {
    if( tvar == true ) {
        var lstParent = $("formationsList")
        var el = setupFormationsList(); // "98.5%" );   // lstParent.style.width );
        //el.show();
        el.style.display = "block";
        tvar = false;
        expandCurrentFormation();
    }
};


function hideFormations() {
    if( tvar == false ) {
        var el = getFormationsList();
        //el.hide();
        el.style.display = "none";
        tvar = true;
    }
};

var lockerDiv = null;
function lockFormations() {
    hideFormations();
    if( getFormationsList() != null ) {
        if( lockerDiv == null ) {
            lockerDiv = document.createElement( "div" );
            lockerDiv.style.width = $("fmsTr").clientWidth + "px";
            lockerDiv.style.height = $("fmsTr").clientHeight + "px";
            lockerDiv.style.left = "" + calcElementX( $("fmsTr") ) + "px";
            lockerDiv.style.top = "" + calcElementY( $("fmsTr") ) + "px";
            lockerDiv.style.zIndex = "1000";
            lockerDiv.style.display = "block";
            lockerDiv.style.position = "absolute";
            lockerDiv.style.backgroundColor = "GhostWhite";
            lockerDiv.style.opacity = ".85";
            lockerDiv.style.filter = "alpha(opacity=85)"; // IE7 slow and buggy...do not uncomment before paradise time comes
        //lockerDiv.style.border = "1px dotted black";
        }
        //document.body.appendChild( lockerDiv );
        $("formationsList").style.display = "none";
    }
};

function unlockFormations() {
    if( lockerDiv != null ) {
        lockerDiv.style.display = "none";
        //document.body.removeChild( lockerDiv );
        lockerDiv.parent = null;
        recursiveCleaner( lockerDiv );
        $("formationsList").style.display = "block";
        lockerDiv = null;
    }
};

function updateFormationLocker() {
/*if( lockerDiv != null ) {
        lockerDiv.style.width = $("fmsTr").clientWidth + "px";
        lockerDiv.style.height = $("fmsTr").clientHeight + "px";
        lockerDiv.style.left = "" + calcElementX( $("fmsTr") ) + "px";
        lockerDiv.style.top = "" + calcElementY( $("fmsTr") ) + "px";
    }*/
};

/*toggleLockFormations = function() {
    if( lockerDiv == null ) {
        lockFormations();
    } else {
        unlockFormations();
    }
};*/

function expandCurrentFormation() {
    expandToItem( "idFormationsTree", "tree_node_mo_" + currentFmId );
//$( "formationsList" ).scrollTop = $( "tree_node_mo_" + currentFmId ).offsetTop;   // TODO: ???
};

function collapseFormationsTree() {
    collapseTree( "idFormationsTree" );
};

function expandFormationsTree() {
    expandTree( "idFormationsTree" );
};


function toggleFormations() {
    if( tvar == true ) {
        showFormations();
    } else {
        hideFormations();
    }
};

function treeViewClick() {
    if( isFormationsListLinear == true ) {
        isFormationsListLinear = false;
        requestFormationsListFromServer();
    }
};

function listViewClick() {
    if( isFormationsListLinear == false ) {
        isFormationsListLinear = true;
        requestFormationsListFromServer();
    }
};


function selectFormation( fmId, deep ) {
    if( !deep ) {
        var el = $( "tree_node_mo_" + fmId );
        if( isPrevedRequired ) {
            el.className = nodeOpenClass;
        } else {
            el.className = (el.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
            return;
        }
    }
    
    sendFormationToServer( fmId );
    hideFormations();
    currentFmId = fmId;
};

// ----------------------------------- TOOLTIPS --------------------------------------------

var tooltip = null;
var tooltipTextP = null;
var ttTimer = null;
var currentTooltipOpacity = 0;

function getTooltip() {
    if( tooltip == null ) {
        tooltip = document.createElement( "DIV" );
        tooltip.style.backgroundColor = "LemonChiffon";
        tooltip.style.position = "absolute";
        tooltip.style.display = "none";
        tooltip.style.borderBottom = "1px solid black";
        tooltip.style.borderLeft = "1px solid black";
        tooltip.style.borderRight = "1px solid black";
        tooltip.style.borderTop = "1px solid black";
        tooltip.style.zIndex = "2000";
        tooltipTextP = document.createElement( "A" );
        tooltipTextP.innerHTML = "(empty)";
        tooltip.appendChild( tooltipTextP );
        document.body.appendChild( tooltip );
    }
    return tooltip;
};

setTooltipOpacity = function( op ) { // 0 <= op <= 1
    var tt = getTooltip();
    if( tt != null ) {
        if( op != null ) {
            currentTooltipOpacity = op;
        }
        tt.style.opacity = currentTooltipOpacity; //FF
        tt.style.filter = "alpha(opacity=" + ( currentTooltipOpacity * 100 ) + ")"; //IE
    }
};

function increaseOpacity() {
    if( currentTooltipOpacity >= 1 || currentTooltipOpacity < 0 ) {
        return false;
    }
    currentTooltipOpacity += 0.1;
    if( currentTooltipOpacity > 1 ) {
        currentTooltipOpacity = 1;
    }
    setTooltipOpacity();
    return true;
};

function onTimer() {
    if( increaseOpacity() == true ) {
        ttTimer = setTimeout( onTimer(), 200 );
    }
};

function showTooltip( text, x, y ) {
    if( ttTimer != null ) {
        clearTimeout( ttTimer );
        ttTimer = null;
    }
    var tt = getTooltip();
    if( tt != null ) {
        tooltipTextP.innerHTML = text;
        tt.style.left = "" + x + "px";
        tt.style.top = "" + y + "px";
        setTooltipOpacity( 0 );
        tt.style.display = "block";
        onTimer();
    }
};

function showTooltipEvent( event, text ) {
    showTooltip( text, ( event.clientX ) + 20, ( event.clientY ) + 20 );
};

function hideTooltip() {
    currentOpacity = 0;
    var tt = getTooltip();
    if( tt != null ) {
        tt.style.display = "none";
    }
    ttTimer = null;
    clearTimeout( ttTimer );
};

// ----------------------------------- HIGHLIGHTING ----------------------------------------


function highlightItem( item ) {
    if( ( typeof( imagesHot ) != 'undefined' ) && ( imagesHot != undefined ) && ( imagesHot != null ) ) {
        if( this.tagName != null )
            item = this;
        if( ( item != null ) && ( item.tagName != null ) ) {
            var img = imagesHot[ item.id ];
            if( img == null ) {
                img = imagesHot[ item.className ];
            }
            if( img != null ) {
                
                if( item.tagName == "IMG" ) {
                    item.src = img;
                } else if ( ( item.tagName == "TD" ) || ( item.tagName == "TR" ) ) {
                    item.style.backgroundImage = "url( " + img + " )";
                } else {
                    alert( "highlighting can be applied to img, td or tr tags" );
                }
                
            }
//            else {
//                alert( "some problem.\nid= " + item.id + "\nclassName=" + item.className );
//            }
        }
    }
};

function unhighlightItem( item ) {
    if( ( typeof( imagesNormal ) != 'undefined' ) && ( imagesNormal != null ) && ( imagesNormal != undefined ) ) {
        if( this.tagName != null )
            item = this;
        if( ( item != null ) && ( item.tagName != null ) ) {
            var img = imagesNormal[ item.id ];
            if( img == null ) {
                img = imagesNormal[ item.className ];
            }
            if( img != null ) {
                
                if( item.tagName == "IMG" ) {
                    item.src = img;
                } else if ( ( item.tagName == "TD" ) || ( item.tagName == "TR" ) ) {
                    item.style.backgroundImage = "url( " + img + " )";
                } else {
                    alert( "highlighting can be applied to img, td or tr tags" );
                }
                
            }
//            else {
//                alert( "some problem.\nid= " + item.id + "\nclassName=" + item.className );
//            }
        }
    }
};

function notcurrent_menuItem( item ) {
    if( item != null && item.style ) {
        item.style.backgroundImage = "url( img/glass-mb.png )";
        item.onclick = go;
        item.onmouseover = highlightItem;
        item.onmouseout = unhighlightItem;
        item.style.border = "";
        item.style.cursor = "pointer";
    }
};

function current_menuItem( item ) {
    if( item != null && item.style ) {
        item.style.backgroundImage = "url( img/glass-mb_current.png )";
        item.onclick = null;
        item.onmouseover = null;
        item.onmouseout = null;
        item.style.border = "1px dotted navy";
        item.style.cursor = "default";
    }
};

function notcurrent_menuItemVertical( item ) {
    if( item != null && item.style ) {

        item.onclick = goVertical;

        //определяем, вертикальное меню или "старое горизонтальное"
        var isVertical = (document.getElementById("subMenuVertical") != null);

        if(isVertical){
            item.style.cursor = "pointer";
            item.style.fontWeight=  "normal";
        }else{
            item.style.backgroundImage = "url( img/glass-mb.png )";
            item.style.cursor = "pointer";
            //alert(item.innerHTML);
            if(item.getElementsByTagName("a").length > 0)
                item.getElementsByTagName("a").item(0).style.color = "#000";
            item.style.fontWeight=  "normal";
        }
    }
};

function current_menuItemVertical( item ) {
    if( item != null && item.style ) {

        //определяем, вертикальное меню или "старое горизонтальное"
        var isVertical = (document.getElementById("subMenuVertical") != null);
        if(isVertical){
            item.style.cursor = "default";
            item.style.fontWeight=  "bold";
        }else{
            item.style.backgroundImage = "url( img/glass-mb_current.png )";
            item.style.cursor = "default";
            //alert(item.innerHTML);
            if(item.getElementsByTagName("a").length > 0)
                item.getElementsByTagName("a").item(0).style.color = "#fff";
            item.style.fontWeight=  "bold";
        }
    }
};

function eventTest( event ) {
    event = event;
};

// ----------------------------------- TABS ------------------------------------------------

var menuTab = new Object();
menuTab = function( text ) {
    this.caption = text;
    this.subItems = new Array();
    return this;
};

menuTab.prototype.getCaption = function() {
    return this.caption;
};

menuTab.prototype.putSubtab = function( title ) {
    this.subItems.push( title );
};

menuTab.prototype.getLength = function() {
    return this.subItems.length;
};


// ---------------------------- input values checking engine -----------------------------------

// internal methods. Do not call outside
var elementUnderReview = null;
var callback = null;
var checkersTimer = null;
var reviewTimer = null;
var oldValue = null;

function reviewTimerCallback() {
    if( elementUnderReview != null ) {
        if( elementUnderReview.value != oldValue ) {
            shakeTimer();
            oldValue = elementUnderReview.value;
        }
        startReviewTimer();
    }
};

function checkTimer() {
    if( checkersTimer != null ) {
        clearTimeout( checkersTimer );
        checkersTimer = null;
    }
    if( elementUnderReview == null ) {
    } else {
        if( callback != null ) {
            callback.call( elementUnderReview );
        }
    }
};

function startTimer() {
    checkersTimer = setTimeout( "checkTimer()", 100 );
};

function startReviewTimer() {
    reviewTimer = setTimeout( "reviewTimerCallback()", 50 );
};

function interruptTimer() {
    if( reviewTimer != null ) {
        clearTimeout( reviewTimer );
        reviewTimer = null;
    }
    if( checkersTimer != null ) {
        clearTimeout( checkersTimer );
        checkersTimer = null;
    }
};

function shakeTimer( ) {
    interruptTimer();
    if( elementUnderReview != null ) {
        startTimer();
    }
};


// public interface
function beginReview( element, call ) {
    interruptTimer();
    callback = call;
    elementUnderReview = element;
    oldValue = elementUnderReview.value;
    startTimer();
    startReviewTimer();
};

function doneReview() {
    interruptTimer();
    if( ( elementUnderReview != null ) && ( callback != null ) ) {
        callback.call( elementUnderReview );
    }
    elementUnderReview = null;
    callback = null;
};

// ---------------------------- VALUES CHECK ---------------------------------------------------

function usernameCheck() {
    checkNewLogin( this, usernameCheckProcess );
};

function usernameCheckProcess( result ) {
    if( trim( result ) == "ok" ) {
        this.className = "input_ok";
    } else {
        this.className = "input_error";
    }
};

// ----------------------- news ----------------------------------------------------------------

function newsRefresh() {
    //newsUpdate
    var newsReq = new Ajax.Request( prefix + "/StateChanged?newsUpdate&garbage="+ Math.random() + "_" + Math.random(), {
        onComplete: function( transport ) {
            if( newsReq.success() ) {
                visualizeNewsYear();
                visualizeNewsMonth();
                tmpRefresh();
                updateTable( "omsuNews" );
            } else {
                alert( "Fail to update news" );
            }
        },
        method : 'post'
    });
};

function topNewsRefresh() {//kozhuhov не используется теперь
    //topNewsUpdate
    var newsReq = new Ajax.Request( prefix + "/StateChanged?topNewsUpdate&garbage="+ Math.random() + "_" + Math.random(), {
        onComplete: function( transport ) {
            if( newsReq.success() ) {
                visualizeNewsYear();
                visualizeNewsMonth();
                tmpRefresh();
                updateTable("omsuTopNews");
            } else {
                alert( "Fail to update news" );
            }
        },
        method : 'post'
    });
};

function visualizeNewsYear() {
    if( $("year__2") != null ) {
        $("year__2").innerHTML = "<a class=\"cglink\" href=\"javascript:setYear('" + (currentNewsYear - 2) + "');\">" + (currentNewsYear - 2) + " </a>";
        $("year__1").innerHTML = "<a class=\"cglink\"  href=\"javascript:setYear('" + (currentNewsYear - 1) + "');\">" + (currentNewsYear - 1) + " </a>";
        $("currentYear").innerHTML = currentNewsYear;
        $("year_plus1").innerHTML = "<a class=\"cglink\"  href=\"javascript:setYear('" + (currentNewsYear + 1) + "');\">" + (currentNewsYear + 1) + " </a>";
        $("year_plus2").innerHTML = "<a class=\"cglink\"  href=\"javascript:setYear('" + (currentNewsYear + 2) + "');\">" + (currentNewsYear + 2) + " </a>";
    }
};

function setYear( yearStr ) {
    var year = parseInt( yearStr );
    currentNewsYear = year;
    sendNewsState();
};

function nextYear() {
    currentNewsYear++;
    sendNewsState();
};

function prevYear() {
    currentNewsYear--;
    sendNewsState();
};

function visualizeNewsMonth() {
    var i ;
    for( i = -1; i < 12; i++ ) {
        $("month_" + i).className = "month";
    }
    $("month_" + currentNewsMonth).className = "month_current";
};

function setMonth( monthStr ) {
    var month = parseInt( monthStr );
    currentNewsMonth = month;
    sendNewsState();
    visualizeNewsMonth();
};

function nextMonth() {
    currentNewsMonth++;
    sendNewsState();
};

function prevMonth() {
    currentNewsMonth--;
    sendNewsState();
};

/*function goYear( yearStr ) {
    setYear( yearStr );
    newsRefresh();
};
 
function goMonth( monthStr ) {
    setYear( monthStr );
    newsRefresh();
};*/

function tmpRefresh() {
    updateTable( "omsuTable" );
};

refreshRegisterCaptcha = function() {
    var imgSpan = $('registerImgSpan');
    if( imgSpan != null ) {
        recursiveCleaner(imgSpan);
        var img = document.createElement('IMG');
        img.src = 'CaptchaServlet?captchaName=registerCaptcha&garbage=' + Math.random();
        imgSpan.appendChild(img);
    }
    $('captchaRegister').value = '';
};

passwordCheck = function() {
    var p1 = $('passwordRegister');
    var p2 = $('password2Register');
    
    p1.className = 'input_ok';
    p2.className = 'input_ok';
    
    if( p2.value != '' && p1.value != p2.value ) {
        p2.className = 'input_error';
    }
    if( p1.value == '' ) {
        p1.className = 'input_error';
    }
};

$EV = function( id ) {
    var el = $(id);
    if( el == null ) {
        return '?';
    }
    return el.value //It was escape( el.value ) Kozhuhov 04.08.09
};

function doPermitionToRegister()
{
	var username = (document.getElementById('usernameRegister'));//пропустит только латинские символы
	var email = (document.getElementById('emailRegister'));
	var password = (document.getElementById('passwordRegister'));
    var captcha = (document.getElementById('captchaRegister'));
    var usernameCleared = escape(username.value);
	var btn = document.getElementById('btn');
	usernameCleared != '' && email.value != '' && password.value != '' && captcha.value !='' ? btn.disabled = false : btn.disabled = true;
}

doRegister = function() {// Kozhuhov added patronymic
    var req = 'username=' + $EV('usernameRegister')
    + '&password=' + $EV('passwordRegister')
    + '&email=' + $EV('emailRegister')
    + '&patronymic=' + $EV('patronymicRegister')
    + '&firstName=' + $EV('firstNameRegister')
    + '&lastName=' + $EV('lastNameRegister')
    + '&captcha=' + $EV('captchaRegister')
    + '&sexCode=' + $EV('sexRegister');
    new Ajax.Request( prefix + '/RegisterSerlvet?' + req, {
        onComplete : function(transport) {
            if( transport.responseText == 'OK' ) {
                destroyWindowById('registerWindow');
                alert( '\u0421\u043f\u0430\u0441\u0438\u0431\u043e \u0437\u0430 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044e. \u041d\u0430 \u0432\u0430\u0448 \u043f\u043e\u0447\u0442\u043e\u0432\u044b\u0439 \u044f\u0449\u0438\u043a \u0432\u044b\u0441\u043b\u0430\u043d\u043e \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u0438\u0435. \u0412\u044b \u043c\u043e\u0436\u0435\u0442\u0435 \u0432\u043e\u0439\u0442\u0438 \u043f\u043e\u0434 \u0441\u0432\u043e\u0438\u043c \u0438\u043c\u0435\u043d\u0435\u043c \u0441\u0435\u0439\u0447\u0430\u0441, \u043d\u043e \u043f\u043e\u043a\u0430 \u043d\u0435 \u043f\u043e\u0434\u0442\u0432\u0435\u0434\u0438\u0442\u0435 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044e, \u043d\u0435 \u0441\u043c\u043e\u0436\u0435\u0442\u0435 \u043f\u043e\u0434\u043f\u0438\u0441\u044b\u0432\u0430\u0442\u044c\u0441\u044f \u043d\u0430 \u0440\u0430\u0441\u0441\u044b\u043b\u043a\u0438');
            } else {
                refreshRegisterCaptcha();
                alert( transport.responseText);
            }
        },
        method: 'post'
    });
};

showNews = function( id ) {
    var wnd = new JSWindow();
    wnd.setCaption('');
    wnd.resize( new RectangularArea(50, 50, 600, 300 ) );
    wnd.loadFromURL('/ShowNewsServlet?id=' + id, true, null);
};

/**
 * функции для блока опросов
 */
var REQUEST_POLL_VALUE = "";
var REQUEST_POLL_NAME  = "poll";
var REQUEST_POLL_TIME  = "Mon, 05-Jan-2099 00:00:00 GMT";
//запрос на голосование
function doPoll(){
    
    var questions_arr =  $('pollTable').getElementsBySelector('div.poll_question');
    var old_cookie = (getCookie(REQUEST_POLL_NAME) != null)?getCookie(REQUEST_POLL_NAME):"";
    var old_coockie_arr = old_cookie.split(",");
    REQUEST_POLL_VALUE = old_cookie;
    if(REQUEST_POLL_VALUE != "")
        REQUEST_POLL_VALUE += ",";


    //собираем строчку запроса
    //собираем строчку для Coockie
    var req_str = "answer_ids=";
    var input_arr = $('pollTable').getElementsByTagName('input');
    var pred_q_id = "";
    size = input_arr.length;
    for(var i=0;i<size;i++){
        var curr_input = input_arr[i];
        if(curr_input.type == "radio" || curr_input.type == "checkbox"){
           if(curr_input.checked){
                req_str += curr_input.value + "<,>";
                var q_id = curr_input.id.replace("answer_","").split("_")[0];
                if(q_id != pred_q_id && old_coockie_arr.indexOf(q_id)==-1){
                    REQUEST_POLL_VALUE += q_id;
                    REQUEST_POLL_VALUE += ",";
                }

                pred_q_id = q_id;
            }
        }
    }

    var req_len = req_str.length;
    req_str = (req_str.toString().substr(req_len-1, 1) == ',')?req_str.toString().substr(0, req_len-1):req_str;

    var req_val_len = REQUEST_POLL_VALUE.length;
    REQUEST_POLL_VALUE = (REQUEST_POLL_VALUE.toString().substr(req_val_len-1, 1) == ',')?REQUEST_POLL_VALUE.toString().substr(0, req_val_len-1):REQUEST_POLL_VALUE;

    new Ajax.Request( prefix + '/PollServlet?act=doPoll&' + req_str, {
                      onSuccess :doPollSetCookie,
                      onFailure :doPollGeneratException,
                      onComplete:doPollUpdate,
                      method: 'post'});
}
//устанавливаем Coockie на голосование
function doPollSetCookie(){
    setCookie (REQUEST_POLL_NAME, REQUEST_POLL_VALUE, REQUEST_POLL_TIME, null, null, null);
}

function doPollGeneratException(){
    alert('Error!Request execution failed.');
}

function doPollUpdate(){
    new Ajax.Updater({success: 'poll_div'}, prefix + '/poll.jsp',
                 {method: "post"});
}

function showPollResults(flag){
    new Ajax.Request( prefix + '/PollServlet?act=showPollResults&show=' + flag, {
                      onFailure :doPollGeneratException,
                      onComplete:doPollUpdate,
                      method: 'post'});
}

//функции для работы с cookie

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
//
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
//
function deleteCookie(name) {
        if (getCookie(name)) {
                var path = null;
                var domain = null;
                document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
          }
}

/**
 *проверить статус обращения
 **/
function checkOrderTry(){
    var elem_user_fam     = document.getElementById("__user_fam");
    var elem_user_name    = document.getElementById("__user_name");
    var elem_user_otch    = document.getElementById("__user_otch");
    var elem_user_onumber = document.getElementById("__user_onumber");

    var user_fam     = (elem_user_fam != null)?elem_user_fam.value.toString().trim():"";
    var user_name    = (elem_user_name != null)?elem_user_name.value.toString().trim():"";
    var user_otch    = (elem_user_otch != null)?elem_user_otch.value.toString().trim():"";
    var user_onumber = (elem_user_onumber != null)?elem_user_onumber.value.toString().trim():"";

    var correct = (user_fam != null && user_fam != "") &&
                  (user_name != null && user_name != "") &&
                  (user_onumber != null && user_onumber != "");
    if(correct){
        user_otch    = (user_otch != null)?user_otch.toString().trim():"";

        user_fam = user_fam.toString().substr(0, 1).toUpperCase() + user_fam.toString().substr(1).toLowerCase();
        user_name = user_name.toString().substr(0, 1).toUpperCase() + user_name.toString().substr(1).toLowerCase();
        user_otch = user_otch.toString().substr(0, 1).toUpperCase() + user_otch.toString().substr(1).toLowerCase();

        elem_user_fam.value     = user_fam;         //     = document.getElementById("__user_fam");
        elem_user_name.value     = user_name;       //    = document.getElementById("__user_name");
        elem_user_otch.value    = user_otch;        //    = document.getElementById("__user_otch");
        elem_user_onumber.value = user_onumber;     // = document.getElementById("__user_onumber");

        var req_str = "?reqParams=";
        req_str    += "<-param-><-pkey->obr_f<-/pkey-><-pval->" + user_fam + "<-/pval-><-/param->";
        req_str    += "<-param-><-pkey->obr_i<-/pkey-><-pval->" + user_name + "<-/pval-><-/param->";
        req_str    += "<-param-><-pkey->obr_o<-/pkey-><-pval->" + user_otch + "<-/pval-><-/param->";
        req_str    += "<-param-><-pkey->obr_reg_num<-/pkey-><-pval->" + user_onumber + "<-/pval-><-/param->";

        $('orderTry').style.visibility = "hidden";
        $('loginCancel').style.visibility = "hidden";
        $('__user_ostatus').innerHTML = "\u041E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430...";

        new Ajax.Request( prefix + '/CheckOrderStatusServlet' + req_str, {
                          onSuccess :checkOrderStatusResult,
                          onFailure :doCheckGeneratException,
                          onComplete:doCheckOnComplete,
                          method: 'post'});
    }else{
        doCheckGeneratException("\u0414\u0430\u043D\u043D\u044B\u0435 \u0432\u0432\u0435\u0434\u0435\u043D\u044B \u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u043E");
    }
}

function doCheckOnComplete(){
        $('orderTry').style.visibility = "visible";
        $('loginCancel').style.visibility = "visible";
}

function doCheckGeneratException(str){
    if(str != null && str != "")
        $('__user_ostatus').innerHTML = str;
    else
        $('__user_ostatus').innerHTML = "\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430!";

}

function checkOrderStatusWindow(){

    if( loginWindow != null ) {
        destroyWindow( loginWindow );
    }

    loginWindow = createWindow( true, "orderStatusDiv", "\u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \u0441\u0442\u0430\u0442\u0443\u0441 \u043E\u0431\u0440\u0430\u0449\u0435\u043D\u0438\u044F",500,300 );

    var div = getClientDiv( loginWindow );

    //фамилия
    var t = document.createElement( "span" );
    t.innerHTML = "\u0424\u0430\u043C\u0438\u043B\u0438\u044F";
    t.style.width = "98%";
    div.appendChild( t );

    var user_fam = document.createElement( "input" );
    user_fam.type = "text";
    user_fam.id = "__user_fam";
    user_fam.style.width = "98%";
    user_fam.style.marginBottom = "5px";
    div.appendChild( user_fam );

    //имя
    t = document.createElement( "span" );
    t.innerHTML = "\u0418\u043C\u044F";
    t.style.width = "98%";
    div.appendChild( t );

    var user_name = document.createElement( "input" );
    user_name.type = "text";
    user_name.id = "__user_name";
    user_name.style.width = "98%";
    user_name.style.marginBottom = "5px";
    div.appendChild( user_name );

    //отчество
    t = document.createElement( "span" );
    t.innerHTML = "\u041E\u0442\u0447\u0435\u0441\u0442\u0432\u043E";
    t.style.width = "98%";
    div.appendChild( t );

    var user_otch = document.createElement( "input" );
    user_otch.type = "text";
    user_otch.id = "__user_otch";
    user_otch.style.width = "98%";
    user_otch.style.marginBottom = "5px";
    div.appendChild( user_otch );

    //номер обращения
    t = document.createElement( "span" );
    t.innerHTML = "\u041D\u043E\u043C\u0435\u0440 \u043E\u0431\u0440\u0430\u0449\u0435\u043D\u0438\u044F";
    t.style.width = "98%";
    div.appendChild( t );

    var user_onumber = document.createElement( "input" );
    user_onumber.type = "text";
    user_onumber.id = "__user_onumber";
    user_onumber.style.width = "98%";
    user_onumber.style.marginBottom = "15px";
    div.appendChild( user_onumber );

    var user_ostatus = document.createElement( "div" );
    user_ostatus.id = "__user_ostatus";
    user_ostatus.style.width = "98%";
    user_ostatus.style.fontSize = "15px";
    user_ostatus.style.fontWeight = "bold";
    user_ostatus.style.marginBottom = "15px";
    div.appendChild( user_ostatus );

    var button = document.createElement( "button" );
    button.onclick = checkOrderTry;
    button.innerHTML = "\u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C";   // проверить
    button.id = "orderTry";
    button.className = "enableButton";//kozhuhov
    button.style.marginRight = "5px";
    button.style.marginBottom = "5px";
    div.appendChild( button );

    button = document.createElement( "button" );
    button.onclick = cancelLogin;
    button.innerHTML = "\u041e\u0442\u043c\u0435\u043d\u0430";  // отмена
    button.id = "loginCancel";
    button.className = "enableButton";//kozhuhov
    button.style.marginBottom = "5px";


    div.appendChild( button );
    
    var br = document.createElement( "br" );
    div.appendChild( br );

    div.style.paddingBottom = "10px";

    appendWindow( loginWindow );
    //document.body.appendChild( loginWindow );
    showWindow( loginWindow );

    user_fam.focus();
    user_onumber.onkeypress = function(e) {
        keynum = (window.event)? e.keyCode : e.which;
        if( keynum == 13 ) {
            checkOrderTry();
        }
        return true;
    };

}

function checkOrderStatusResult(request){
    if (request.responseXML != null && request.responseXML.getElementsByTagName("root").length > 0){
         var doc = request.responseXML;
         //тут поменять на request.responseXML
         var root = doc.getElementsByTagName("root")[0];
         var value = root.getElementsByTagName("value")[0].childNodes[0].nodeValue;
         var stsstr = root.getElementsByTagName("stsstr")[0].childNodes[0].nodeValue;
         var sts = root.getElementsByTagName("sts")[0].childNodes[0].nodeValue;
         var statusHTML = "\u0421\u0442\u0430\u0442\u0443\u0441 \u043e\u0431\u0440\u0430\u0449\u0435\u043d\u0438\u044f:";
       
         if(sts == 0)
            statusHTML += value;
         else{
             if(stsstr != null)
                 statusHTML += stsstr;
             else
                 statusHTML += "Request error!";
         }
         $('__user_ostatus').innerHTML = statusHTML;
    }

}


///скрипты для лодинга
function loadingShow()
{
    var loadingId = "data_loading";
    var loading_elem = document.getElementById(loadingId);
    if(!loading_elem)
        return;

    loading_elem.className = "LoadingOn";

//    var window_width;
//    var window_height;
//
//    if( typeof( window.innerWidth ) == 'number' ) {
//        window_width = window.innerWidth;
//        window_height = window.innerHeight;
//    } else if( document.documentElement &&
//             ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//        window_width = document.documentElement.clientWidth;
//        window_height = document.documentElement.clientHeight;
//    }
//    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
//    {
//        window_width = document.body.clientWidth;
//        window_height = document.body.clientHeight;
//    }

//   var left = "0";//Math.round((window_width - 200) / 2);
//   var top  = "0";//Math.round(((window_height - 46) / 3) + 46);

   loading_elem.style.left = '0';
   loading_elem.style.top  = '0';

   var ua = navigator.userAgent.toLowerCase();
   var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
   if(!isIE)
       loading_elem.style.paddingLeft = "50%";
   else
       loading_elem.style.paddingLeft = "20%";
   /*loading_elem.innerHTML = "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430...";*/

}

function loadingHide()
{
    var loadingId = "data_loading";
    var loading_elem = document.getElementById(loadingId);
    if(!loading_elem)
        return;
    
    loading_elem.className = "LoadingOff";
    loading_elem.style.left = 0;
    loading_elem.style.top  = 0;
    /*loading_elem.innerHtml = "";*/
}


//printing form
function doPrintForm(table_id, type){
    if(type == null || type == '') return;
    
    var table_elem = document.getElementById(table_id);
    var outHTML = "<style>";
        outHTML += "a, table tr td a{color: black;text-decoration: none;font-weight: bold;}";
        outHTML += "table{border-collapse: collapse;border:1px solid #000;}";
        outHTML += "table{border:1px solid #000;}";
        outHTML += "</style>";
        outHTML += "<table border=1>";

    if(type == 'tableView'){
        //разбираем как table_view
       
        //цапаем trки только с классами, относящимися к аднным
        allowedTrClass = new Array("even", "odd", "header", "checked", "cglink");
    }else if(type =='view'){
        //разбираем как view
        //цапаем trки только с классами, относящимися к дaнным
        allowedTrClass = new Array("caption",
                                   "omsuTable_trToHide_0",
                                   "value",
                                   "table2_field_even indent_0",
                                   "table2_field_odd indent_0");
    
    }else{
        //разбираем как form_view
        //цапаем trки только с классами, относящимися к аднным
        allowedTrClass = new Array("even table2_field_odd indent_0",
                                   "even table2_field_odd indent_1",
                                   "even table2_field_odd indent_2",
                                   "even table2_field_odd indent_3",
                                   "even table2_field_odd indent_4",
                                   "even table2_field_even indent_0",
                                   "even table2_field_even indent_1",
                                   "even table2_field_even indent_2",
                                   "even table2_field_even indent_3",
                                   "even table2_field_even indent_4",
                                   "odd table2_field_odd indent_0",
                                   "odd table2_field_odd indent_1",
                                   "odd table2_field_odd indent_2",
                                   "odd table2_field_odd indent_3",
                                   "odd table2_field_odd indent_4",
                                   "odd table2_field_even indent_0",
                                   "odd table2_field_even indent_1",
                                   "odd table2_field_even indent_2",
                                   "odd table2_field_even indent_3",
                                   "odd table2_field_even indent_4",
                                   "even "
                                   );//"odd table2_field_odd indent_0
    }
    //alert(allowedTrClass);
    //бежим по DOM дерева
    var trs = table_elem.getElementsByTagName("tr");
    
    for(var i=0;i<trs.length;i++){
        var cur_tr = trs[i];
       
        if(cur_tr.className != null
           && allowedTrClass.indexOf(cur_tr.className)!= -1
           && cur_tr.innerHTML != null){
          
            //cur_html = cur_html.toString().replace("input", "input style='visibility: none'");
            var td_arr = cur_tr.getElementsByTagName("td");
//alert(td_arr);
            var cur_tr_html = "";

            var bgcolor = "background-color:#fff;";
            if(i%2 != 0)
                bgcolor = "background-color:#EFEFEF;";

            if(cur_tr.className == "header"){
                var tl_nodes  = cur_tr.childNodes;
                var tl_length = cur_tr.childNodes.length;
                
                for(var k=0;k<tl_length;k++){
                    
                    if(tl_nodes[k].tagName == "TD" /*&& tl_nodes[k].getElementsByTagName("td").length > 0*/){
                        if(tl_nodes[k].getElementsByTagName("td").length > 0){
                            cur_tr_html += "<td>" + tl_nodes[k].getElementsByTagName("td")[0].innerHTML + "</td>";
                        }else{
                            if(tl_nodes[k].innerHTML.indexOf("<input")!= -1){
                                cur_tr_html += "<td>&nbsp;</td>";
                            }else{
                                cur_tr_html += "<td>" + tl_nodes[k].innerHTML + "</td>";
                            }
                        }
                    }
                }
            }
            else{

                for(j=0;j<td_arr.length;j++){
                    var cur_td = td_arr[j];
                    var cur_html = cur_td.innerHTML;
                    var paddingLeft = "";


                    if(cur_td.className != null && cur_td.className != ""){
                        if(cur_td.className.indexOf("indent_0") != -1)
                            paddingLeft = "padding-left: 15px;font-weight:bold;";

                        else if(cur_td.className.indexOf("indent_1") != -1)
                            paddingLeft = "padding-left: 30px;font-weight:bold;";

                        else if(cur_td.className.indexOf("indent_2") != -1)
                            paddingLeft = "padding-left: 45px;";

                        else if(cur_td.className.indexOf("indent_3") != -1)
                            paddingLeft = "padding-left: 60px;";

                        else if(cur_td.className.indexOf("indent_4") != -1)
                            paddingLeft = "padding-left: 75px;";
                    }



                    if(cur_html.indexOf('<input')!=-1 || cur_html == "" || cur_html == null){
                        cur_tr_html +="<td>&nbsp;</td>";

                    }else{
                        cur_tr_html += "<td style='" + paddingLeft + bgcolor +"'>" + cur_html + "</td>";
                    }

                }
            }
            

            outHTML += "<tr>" + cur_tr_html + "</tr>";
        }
    }
    outHTML += "</table>";

  
    
    var OpenWindow = window.open('about:blank',null,"height=600,width=800,left=300,top=200,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes");

       var ua = navigator.userAgent.toLowerCase();
       var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);

       if(isIE){
            OpenWindow.document.body.innerHTML = outHTML;
             //OpenWindow.document.body.onload=
                 OpenWindow.window.print();
       }else{
           OpenWindow.document.write('<HTML>');
            OpenWindow.document.write('<HEAD>');
            OpenWindow.document.write('<TITLE>Print</TITLE>');
            OpenWindow.document.write('<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">');
            OpenWindow.document.write('</HEAD>');
            OpenWindow.document.write('<BODY>');
            OpenWindow.document.write(outHTML);
            OpenWindow.document.write('</BODY>');
            OpenWindow.document.write('</HTML>');
            OpenWindow.document.body.onload=OpenWindow.window.print();
       }

}







function hideSubMenuVertical(){
    
    var hideSubMenu    = document.getElementById("hideSubMenu");    //subMenuVertical
    var hideSubMenuImg = document.getElementById("hideSubMenuImg");
    var menuTd         = document.getElementById("subMenuVertical");
    var menuTable      = document.getElementById("subMenuVerticalTable");
    var contentTd      = document.getElementById("contentTd");
    var menuDiv        = document.getElementById("subMenuDiv");
//    var wwidth  = (window.innerWidth)?window.innerWidth:
//                  ((document.all)?document.body.clientWidth:null);

    var ua = navigator.userAgent.toLowerCase();
    var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);

    if(hideSubMenuImg.src.indexOf("/img/hideSubMenu.gif") != -1){
        menu = true;
        jQuery("#gridTable").setGridWidth(jQuery(window).width()*0.97);
        hideSubMenuImg.src = prefix + "/img/showSubMenu.gif";
        hideSubMenu.title  = "\u041E\u0442\u043E\u0431\u0440\u0430\u0437\u0438\u0442\u044C \u043C\u0435\u043D\u044E";

        menuDiv.style.width = "0";
        
        menuTd.style.width = "0";

        if(isIE)
        menuTd.style.display = "none";
        else
            menuTd.style.visibility = "hidden";
        
        contentTd.style.width = "98%";//Math.round(wwidth - 25).toString() + "px";
    }else{
        menu = false;
        jQuery("#gridTable").setGridWidth(jQuery(window).width()*0.73);
        hideSubMenuImg.src = prefix +  "/img/hideSubMenu.gif";
        hideSubMenu.title  = "\u0421\u043A\u0440\u044B\u0442\u044C \u043C\u0435\u043D\u044E";


        menuTd.style.width = "25%";

        if(isIE)
        menuTd.style.display = "block";
        else
            menuTd.style.visibility = "visible";

        menuTable.style.width = "100%";
        menuDiv.style.width = "100%";
        contentTd.style.width = "73%";

//        menuTd.style.width = menuTable.getBoundingClientRect().right + "px";

        
        
        //contentTd.style.width = Math.round(wwidth -menuTable.getBoundingClientRect().right- 25).toString() + "px";

    }
}


