
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

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 ------------------------------------------------

//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";
};

function goTab( 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();
    //currentLittleTabIndex = 0;
    return false;
};

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 );
    }
    
    currentLittleTabIndex = 0;
    wantLoadNewData = false;
    if( newCurrentCell != null &&  typeof( newCurrentCell ) != 'undefined' ) {
        //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 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.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.cursor = "default";
    }
};

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);
};

