/**
 *	This function must be located out of the HTML/PHP page to hide implementation from possible intruders.
 */
var eLoginImages = {
    '1': 'warning',
    '2': 'error',
    '3': 'error',
    '4': 'error'
}

//This piece of code checks if the hex_md5 function has already been included by the page.
if (typeof hex_md5 == 'undefined') 
    throw ("Login requires md5.js library");

/**
 * Detects the "agent type" and returns an object containing the information about browser's family and version
 * This code is extracted from jQuery (jQuery.browser), but since it has been deprecated, it is replicated here to
 * ensure the functionality will be present although future jQuery versions will be installed in the application.
 */
function browserDetection(){
    var userAgent = navigator.userAgent.toLowerCase();
    
	var version = (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1];
    return '{"version":"' + version + '"' +
	    ',"safari":' +  /webkit/.test(userAgent) +	
	    ',"opera":' +  /opera/.test(userAgent) + 
        ',"msie":' +  (/msie/.test(userAgent) && !/opera/.test(userAgent)) + 
        ',"mozilla":' + (/mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)) + 
		'}';
};

/**
 * This function does the actual login procedure.
 * @param ai_key The unique key obtained from server to authenticate the client univocally.
 * @return The server response (i.e. username and password are valid and match)
 */
function login(){
    user = $('#username').val();
    password = $('#password').val();
	operator = $('#operator').val();
    digest = hex_md5(password);
    authenticate(user, operator, digest, browserDetection());
}

/**
 * This function performs the actual error displaying when the login form is in use.
 * @param errorCode
 * @param message
 */
function showAuthenticationError(errorCode, message){
    $('#login-loader').hide();
    $('#errorMessage').html(message);
    $('#login-error').fadeIn('slow');
    $('#login-form-container').fadeIn('fast');
}

/**
 * This function is the client side of the "authenticate" method in LoginAjaxConnector, using the
 * marshalling mechanism.
 * @param username 	The username entered in form.
 * @param operator  The operator entered in form. If empty, it is not considered in server side.
 * @param password	The password entered in form digested using the proper md5 key returned by server.
 * @param browser   Browser object info as returned by browserDetection.
 */
function authenticate(username, operator, password, browser){
    authenticate.invoke("Login");
    $('#login-error').hide();
}

/**
 * Response function when no marshalling error happened.
 */
function authenticateOK(json){
    if (0 == json.errorCode) {
        if (json.data.change_pass == '0000-00-00 00:00:00' && json.data.impersonator==json.data.username) {
            $('#login-loader').hide('fast');
            $('#errorMessage').html("DEBE CAMBIAR SU CONTRASEÑA");
            $('#login-error').fadeIn('slow');
            $('#login-form-container').fadeOut('fast', showPasswordChange);
        }
        else {
            showLoaderAndSetupSession();
        }
    }
    else {
        if (json.data == 'PASSWORD_RESET') {
            $('#login-error').hide();
            $('#login-form-container').fadeOut('slow', showPasswordResetLoader);
            return;
        }
        showAuthenticationError(json.errorCode, json.data);
    }
}

/**
 * Response function called when marshalling error happens.
 */
function authenticateError(xhr, desc, exception){
    showAuthenticationError(4, desc);
}


/**
 * This function performs the actual error displaying when the password modification form is in use
 * @param errorCode
 * @param message
 * @return
 */
function showPasswordError(errorCode, message){
    $('#login-loader').hide();
    $('#errorMessage').html(message);
    $('#login-error').fadeIn('slow');
    $('#login-form-pass-change').fadeIn('fast');
}

/**
 * This function does the actual login procedure.
 * @param ai_key The unique key obtained from server to authenticate the client univocally.
 * @return The server response (i.e. username and password are valid and match)
 */
function changePassword(){
    user = $('#username').val();
    pass1 = $('#pass1').val();
    pass2 = $('#pass2').val();
    $('#login-error').hide();
    
    if (pass1 != pass2) {
        showPasswordError(1, "Las contraseñas no coinciden");
        return;
    }
    
    digest = hex_md5(pass1);
    modifyPassword(user, digest);
}


/**
 * This function is the client side of the "modifyPassword" method in LoginAjaxConnector, using the
 * marshalling mechanism.
 * @param username 	The username entered in form.
 * @param password	The password entered in form digested using the proper md5 key returned by server.
 */
function modifyPassword(username, password){
    modifyPassword.invoke("Login");
    $('#login-error').hide();
}

/**
 * Response function when no marshalling error happened.
 */
function modifyPasswordOK(json){
    if (0 == json.errorCode) {
        showLoaderAndSetupSession();
    }
    else {
        showPasswordError(json.errorCode, json.data);
    }
}

/**
 * Response function called when marshalling error happens.
 */
function modifyPasswordError(xhr, desc, exception){
    showPasswordError(4, desc);
}

/**
 * Shows the proper elements ins screen and invokes the setupSession method.
 */
function showLoaderAndSetupSession(){
    $('#login-error').hide();
    $('#login-form-container').fadeOut('fast', function(){
		$('#login-form-pass-change').fadeOut('fast', function(){
			$('#login-loader').fadeIn('fast',function(){setupSession();});
		});	
	});
}


/**
 * Shows the password reset page.
 */
function showPasswordResetLoader(){
    $('#login-loader').fadeIn('fast', function(){
        document.location = "password_reset.php";
    });
}

/**
 * Shows the form for password change.
 */
function showPasswordChange(){
    $('#login-form-pass-change').fadeIn('slow',function(){$('#pass1').focus();});
}


/**
 * Sets up the session in server (gets infro fro the current user).
 */
function setupSession(){
    setupSession.invoke("Login");
}

/**
 * The OK callback for setupSession marshall function.
 */
function setupSessionOK(json){
    if (0 == json.errorCode) {
        document.location = "../index.php";
    }
    else {
        showAuthenticationError(json.errorCode, json.data);
    }
}

/**
 * The Error callback for setupSession marshall function.
 */
function setupSessionError(xhr, desc, exception){
    showAuthenticationError(4, desc);
}


/**
 * AJAX function to send the password to the user set in the username box
 */
function sendPassword(){
    sendPassword.invoke("Login");
}

/**
 * The OK callback for sendPassword marshall function.
 */
function sendPasswordOK(json){
    // Nothing to do
}

/**
 * The Error callback for sendPassword marshall function.
 */
function sendPasswordError(xhr, desc, exception){
    // Nothing to do
}

/**
 * Shows the operator field in login form.
 */
function openOperatorField(){
	$('#login-form-container').fadeOut('fast',function(){$('#operatorRow').show();$('#login-form-container').fadeIn('fast');});
}

