






/*
 * Page is needed for JavaScript files where XmlHttpRequest object is needed. This file should be included in these
 * pages by jsp:include action.
 */


/*------------------------------------------------- CONSTANTS -------------------------------------------------*/

/*
 * Request ready statuses.
 */
var UNINITIALIZED = 0;
var LOADING       = 1;
var LOADED        = 2;
var INTERACTIVE   = 3;
var COMPLETED     = 4;

/*
 * Request status codes.
 */
var OK_STATUS = 200;
var BAD_REQUEST_STATUS = 400;
var HTTP_VERSION_NOT_SUPPORTED_STATUS = 505;

/*
 * Request method constants.
 */
var GET_REQUEST  = "GET";
var POST_REQUEST = "POST";

/*------------------------------------------------- FUNCTIONS -------------------------------------------------*/
/*-------------------------------------------------  PUBLIC  -------------------------------------------------*/

/*
 * Creates XMLHttpRequest object.
 * Returns created object or null, if XMLHttpRequest is not supported.
 */
function createRequestObject() {
    var request = null;

    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request = new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request = new XMLHttpRequest();
    } catch (e){}

    return request;
}

/*------------------------------------------------- CONSTANTS -------------------------------------------------*/


/*
 * Browser request timeout (in ms).
 */
var BROWSER_TIMEOUT = 120000;

/*
 * Timeout (in ms) between requests to get challenge (if request.status was not OK_STATUS).
 */
var CALLS_TIMEOUT = 10000; // 10 seconds

/*
 * Cursor styles constants.
 */
var CURSOR_STYLE_WAIT = "progress";
var CURSOR_STYLE_AUTO = "auto";

/*------------------------------------------------- VARIABLES -------------------------------------------------*/

/*
 * Variable to keep id of timeout executing doGetChallenge() function.
 */
var doGetChallengeTimeOutId = null;

/*
 * Flag variable for Opera to prevent login after BROWSER_TIMEOUT expiration if network becomes available.
 * Without this variable user log in using Opera when network becomes available even if BROWSER_TIMEOUT has expired.  
 */
var toLogin = true;

/*
 * Keeps typed by user password because appropriate field is cleaned when user clicks "Login Now" button.
 */
var userPassword = null;

/*------------------------------------------------- FUNCTIONS -------------------------------------------------*/
/*-------------------------------------------------  PUBLIC  -------------------------------------------------*/

/*
 * Gets challenge from server and posts form when chalenge is got. Also sets timer to interrupt login if browser timeout
 * has been exceed.
 */
function login(form) {
    rememberPassword(form);
    prepareForLogin();
    doGetChallenge(form);
    window.setTimeout('clrTimeout(showTimeoutMessage);', BROWSER_TIMEOUT)
}

/*
 * Disables form autocompletion and focuses username field.
 */
function initKeys()
{
    document.forms[0].autocompletion = "off";
    document.forms[0]['username'].focus();
}

/*------------------------------------------------- PRIVATE -------------------------------------------------*/

/*
 * Do GET-request to get challenge with CALLING_TIMEOUT interval anf if challenge has been got calls doLogin() function.
 */
function doGetChallenge(form) {
    var request = createRequestObject();

    if (request != null) {
        setCursorStyle(CURSOR_STYLE_WAIT);
        try {
            request.open(GET_REQUEST, '/actitime/getChallenge;jsessionid=8065E714F20F1047EFBBE41F67C87AB1', true);

            request.onreadystatechange = function (aEvt) {
                if (request.readyState == COMPLETED) {
                    try {
                        if (request.status == OK_STATUS) {
                            if (toLogin) {
                                setCursorStyle(CURSOR_STYLE_AUTO);

                                var responseDataArray = request.responseText.split("-");
                                doLogin(form, responseDataArray[0], responseDataArray[1]);
                            }
                        } else {
                            var func = function() { doGetChallenge(form); };
                            doGetChallengeTimeOutId = window.setTimeout(func, CALLS_TIMEOUT);
                        }
                    } catch (e) {
                        // Can be throw when server is not available, in this case statement request.status throws exception (was observed in Firefox).
                        clrTimeout(showErrorMessage);
                    }
                }
            };

            request.send(null);
        } catch (e) {
            // Can be thrown when user works offline and XMLHttpRequest object attempts to send request.
            clrTimeout(showErrorMessage);
        }
    }
}

/*
 * Sets cursor style (see corresponding constants).
 */
function setCursorStyle(cursorStyle) {
    document.body.style.cursor = cursorStyle;
}

/*
 * Clears timeout repeating calling of doGetChallenge() function and shows timeout message if error messages is not shown.
 */
function clrTimeout(showMessageFunction) {
    setCursorStyle(CURSOR_STYLE_AUTO);
    toLogin = false;

    if (doGetChallengeTimeOutId != null) {
        window.clearTimeout(doGetChallengeTimeOutId);
    }

    stopLoad();

    if (!ClientSideErrors.errorMessageWasShown &&
        showMessageFunction != null &&
        typeof showMessageFunction != typeof undefined) {

        showMessageFunction();
    }
}

/*
 * Stops page loading (login action).
 */
function stopLoad() {
    try {
        window.stop();
    } catch (e) {
        // Can be thrown in IE because of window.stop(); statement.
        window.document.execCommand('Stop');
    }
}

/*
 * Shows message informing about login failure.
 */
function showErrorMessage() {
    hideServerSideMessages();

    document.getElementById("errorSpan").innerHTML = "Failed to login due to an error. Please try again later.";
    ClientSideErrors.showClientSideErrorMessage();
}

/*
 * Shows message informing about timeout exceeding.
 */
function showTimeoutMessage() {
    hideServerSideMessages();

    document.getElementById("errorSpan").innerHTML = "Cannot login for 2 minutes. Please try again later.";
    ClientSideErrors.showClientSideErrorMessage();
}

/*
 * Posts form to login.
 */
function doLogin(form, challenge, newSessionId)
{
    form.elements['submitted'].value = 1;
    form.elements['password'].value  = MD5(MD5(userPassword) + challenge + trim(form.elements['username'].value).toLowerCase());

    rewriteJsessionidIfNeeded(form, newSessionId);

    form.submit();
}

/*
 * Rewrites URL jsessionid parameter if URL rewriting is used to keep session. It is needed when session has expired on
 * the server and to login form action should contain right jsessionid parameter. 
 */
function rewriteJsessionidIfNeeded(form, newSessionId) {
    var jsessionidPos = form.action.indexOf("jsessionid");
    if (jsessionidPos >= 0) {
        var formAction = form.action;
        var currentSessionId = formAction.substring(formAction.indexOf("=", jsessionidPos) + 1);

        form.action = formAction.replace(currentSessionId, newSessionId);
    }
}

/*
 * Remembers typed by user password and cleans appropriate field.
 */
function rememberPassword(form) {
    userPassword = form.elements['pwd'].value;
    form.elements['pwd'].value = "";
}

/*
 * Do some initializations and functions callings to prepare for login.
 */
function prepareForLogin() {
    toLogin = true;
    ClientSideErrors.hideClientSideErrorMessage();
    ClientSideErrors.errorMessageWasShown = false;
}

/*
 * Hides server side messages. Called before client side messages showing.
 */
function hideServerSideMessages()
{
    var serverSideMessages      = document.getElementById("MessagesTable");
    var serverSideErrorMessages = document.getElementById("ErrorsTable");

    if (serverSideMessages != null) {
        serverSideMessages.style.display = "none";
    }
    if (serverSideErrorMessages != null) {
        serverSideErrorMessages.style.display = "none";
    }
}