/*
 * index.js
 * Copyright (c) 2006 Scalix Corporation - All rights reserved
 */

gIsNS = document.getElementById && !document.all;
gIsIE = document.all;
// Needed for annoying bug 11732 where the keyup handler
// was catching the enter key everywhere on the page, not
// just on the username and password fields.
var gUsernameOrPasswordFieldHasFocus = false;

/*-------------- Useful functions --------------*/

function getEvent( evt, wnd ) {
    if ( gIsIE ) {
        if ( wnd != null )
            return wnd.event;
        else
            return window.event;
    } else if ( gIsNS ) {
        return evt;
    }
}

function getElementByID( elemID ) {
    return document.getElementById( elemID );
}

function iframeGetVariable( iframeID, variableID ) {
    var w3cFrame = getElementByID( iframeID );
    return eval( "w3cFrame.contentWindow." + variableID );
}

function iframeExecFunction( iframeID, functionID ) {
    var w3cFrame = getElementByID( iframeID );
    return eval( "w3cFrame.contentWindow." + functionID );
}

function blockDisplay( elemID ) {
    var elem = getElementByID( elemID );
    if ( elem ) elem.style.display = "block";
}

function noDisplay( elemID ) {
    var elem = getElementByID( elemID );
    if ( elem ) elem.style.display = "none";
}

function strip( str ) {
    var whitespacePattern = new RegExp("^\\s*(\\S*(\\s+\\S+)*)\\s*$");
    return whitespacePattern.exec( str )[1];
}

function getUrlParameterValue( url, paramName ) {
    paramName = strip( paramName );
    var idx = url.indexOf( "?" );
    if ( idx < 0 || idx >= url.length-1 )
        return null;
    var result = null;
    var str = url.substring( idx+1 );
    var params = str.split( "&" );
    for ( var i=0 ; i<params.length ; i++ ) {
        var param = params[i];
        idx = param.indexOf( "=" );
        if ( idx > 0 ) {
            str = param.substring( 0, idx );
            if ( str == paramName ) {
                result = param.substring( idx+1 );
                break;
            }
        }
    }
    return result;
}

/*----------------- UI handlers ----------------*/

var jsLoaded = false;
var autoLoginMode = false;

function loginHandler(evt) {
    var theEvent = getEvent(evt);
    if ( theEvent.keyCode == 13 ) {
        if ( getElementByID("loginForm").style.display == "block" && gUsernameOrPasswordFieldHasFocus )
            login();
        else if ( getElementByID("expPwdForm").style.display == "block" )
            chgExpPwd();
    }
}

function loginPageOnLoadHandler() {
    check_jsLoaded();
}

function check_jsLoaded() {
    if ( iframeGetVariable( "jsFrame", "js_done_loading" ) ) {
        setTimeout( "check_jsLoaded()", 100 );
    } else {
        jsLoaded = true;
        // Reverting back to onkeydown for #11732. bug #9790 was only FF1.5rc1,
        // Used to catch onkeyup instead of onkeydown due to bug #9790...
        document.onkeydown = loginHandler;
        if ( !autoLoginMode )
            showLoginForm();
    }
}

/*------------------ UI control ----------------*/

function showLoginForm() {
    noDisplay( "loadingMessage" );
    noDisplay( "loginSuccessful" );
    noDisplay( "waitLogin" );
    noDisplay( "expPwdForm" );
    blockDisplay( "loginForm" );

    var username = getUrlParameterValue( top.location.href, "username" );
    var username_field = getElementByID("username_field");
    if ( username != null && username != "" ) {
        //enter the username in the login screen
        if ( username_field != null )
            username_field.value = username;
    } else {
        username_field.value = "";
    }
    getElementByID("password_field").value = "";
    try {
        if ( username_field.value == "" ) {
            getElementByID( "username_field" ).focus();
        } else {
            getElementByID( "password_field" ).focus();
        }
    } catch (e) {
        ;
    }
}

function showExpPwdForm() {
    noDisplay( "loadingMessage" );
    noDisplay( "loginForm" );
    noDisplay( "loginSuccessful" );
    noDisplay( "waitLogin" );
    blockDisplay( "expPwdForm" );
    getElementByID("old_password_field").value = "";
    getElementByID("new_password_field1").value = "";
    getElementByID("new_password_field2").value = "";
    try {
        getElementByID( "old_password_field" ).focus();
    } catch (e) {
        ;
    }
}

function showWaitLogin() {
    noDisplay( "loadingMessage" );
    noDisplay( "loginForm" );
    noDisplay( "loginSuccessful" );
    noDisplay( "expPwdForm" );
    blockDisplay( "waitLogin" );
}

function showLoginSuccessful() {
    noDisplay( "loadingMessage" );
    noDisplay( "loginForm" );
    noDisplay( "expPwdForm" );
    noDisplay( "waitLogin" );
    blockDisplay( "loginSuccessful" );
}

/*--------------- Login functions --------------*/

/* 
 * Bug 15735 - Test the criteria on which we will
 * BLOCK the user from logging into the SWA. This
 * was moved here from index.jsp, and is now also
 * run after each login function, because the user
 * could be using a custom index.jsp login page
 * that doesn't include this method and we still 
 * want to verify browser criteria.
 *
 * We block on all browser engines that aren't 
 * 'gecko' or 'msie', and further on IE < v5.5,
 * Mozilla < v1.7 and Firefox < 0.10.
 */
function testBrowserReject() {
	var br = getBrowser();
	var browserID = br[0];
	var browserMajorVersion = getMajorVersion( br[1] );
	var browserMinorVersion = getMinorVersion( br[1] );
	var browserEngine = br[2];
	
	var reject = true;
	
	if ( browserEngine == "gecko" ) {
		if ( browserID == "mozsea" ) {
		  if ( browserMajorVersion > 1 ||
			   ( browserMajorVersion == 1 &&
			   versionGreaterOrEqualTo( browserMinorVersion,  '7' ) ) ) {
			 reject = false;
		  }
		}
		else if ( browserID == "firefox" )  {
		  if ( browserMajorVersion >= 1 ||
		       ( browserMajorVersion == 0 &&
        		 versionGreaterOrEqualTo( browserMinorVersion , '10' ) ) ) {
		    reject = false;
		  }		
		}
		else {
			reject = false;
		}
	}
	else if ( browserEngine == "msie" ) {
		if ( browserID == "msie" ) {
			if ( browserMajorVersion >= 6 ||
		    	   ( browserMajorVersion == 5 &&
		        	versionGreaterOrEqualTo( browserMinorVersion, '5' ) ) ) {
		    	reject = false;
		  	}
		 }
		 else {
		 	reject = false;
		 }		 		 				 
	}
	
	if ( reject )
	  location.replace( "browserReject.jsp" );
	
} 

function login() {
	testBrowserReject();
    if (!jsLoaded) {
        setTimeout( "login()", 100 );
        return;
    }
    
    showWaitLogin();
	iframeExecFunction( "jsFrame", "getAccountClass()" ).partnerLogin(
	    getElementByID("username_field").value,
	    makeFugu( getElementByID("password_field").value ) );
}

function autoLogin( username, fugu ) {
	testBrowserReject();
    if (!jsLoaded) {
        autoLoginMode = true;
        setTimeout( "autoLogin('" + username + "','" + fugu + "')", 100 );
        return;
    }
    showWaitLogin();
    iframeExecFunction( "jsFrame", "getAccountClass()" ).partnerLogin( username, fugu );
}

function urlLogin( username, fugu ) {
	testBrowserReject();
    if (!jsLoaded) {
        autoLoginMode = true;
        setTimeout( "urlLogin('" + username + "','" + fugu + "')", 100 );
        return;
    }
    showWaitLogin();
	iframeExecFunction( "jsFrame", "getAccountClass()" ).partnerLogin( username, fugu );
}

function chgExpPwd() {
    if (!jsLoaded) {
        setTimeout( "chgExpPwd()", 100 );
        return;
    }
    var passwd1 = getElementByID("new_password_field1").value;
    var passwd2 = getElementByID("new_password_field2").value;
    if ( passwd1 != passwd2 ) {
        alert( iframeGetVariable( "jsFrame", "strings.change_password_wnd_passwords_no_match" ) );
        return;
    }
    showWaitLogin();
    iframeExecFunction( "jsFrame", "getAccountClass()" ).chgExpPasswd(
        getElementByID("username_field").value,
        makeFugu( getElementByID("old_password_field").value ),
        makeFugu( getElementByID("new_password_field1").value ) );
}

