/* 
 * This file allows an MVx client to interact with Pearson's SSO system.
 *
 * It will also define a set of features allowing the results to be
 * stored on an application specific server (via sessions).
 *
 * @author Brian Roy
 * @date 02/07/2011
 *
 */

/*
 * Constructor
 *
 *
 */
function ajaxSSO() {
    this.GETLOGINURL = "http://" + window.location.host + "/api/auth/v1/";
    this.GETAUTHSTATURL = "http://" + window.location.host + "/api/auth/v1/";
    this.DOLOGOUT = "http://" + window.location.host + "/api/auth/v1/";
    this.loginState = false;
    this.siteId = 0;

    this.statusCallback = "";
    this.errorCallback = "";

    // Error Handler
    tErr = new mvcErrorHandler;
    tErr.setObject("ajaxSSO");
}

/*
 * Method setSiteId sets the current Site ID
 *
 * @param siteId int The current applicaiton's SSO Site ID
 *
 */
ajaxSSO.prototype.setSiteId = function(siteId) {
    this.siteId = siteId;
}

/*
 * This method fetches the current auth status for this
 * application. If we are NOT auth'd for this app we will re-direct
 * to the SSO Check Login Page.
 *
 */
ajaxSSO.prototype.getAuthStatus = function(callBack, errorCallback) {
    var reqData = "status=true";
    this.statusCallback = callBack;
    this.errorCallback = errorCallback;
    this.getServerData(this.GETAUTHSTATURL, this.authStatus, this.ssoAjaxError, 'json', 'GET', reqData);
}

/*
 * This method gets the response for the getAuthStatus method.
 *
 * @param json object The returned JSON object.
 *
 */

ajaxSSO.prototype.authStatus = function(json) {

    this.statusCallback(json);
    
}

/*
 * Method getServerData is generic and allows for the fetching of any
 * data from a server side using the JQuery ajax method.
 *
 * @param URL string The URL for the server side API.
 * @param SuccessFunc string The name of the function to call when the result is returned.
 * @param ErrorFunc strinf The name of the function to call when the result is an error.
 * @param DataType string The kind of data interaction (xml, json, etc).
 * @param Method string HTTP method (get, post, put, etc).
 * @param reqData string The request data.
 * 
 *
 */

ajaxSSO.prototype.getServerData = function(URL, SuccessFunc, ErrorFunc, DataType, Method, reqData) {

    /*
     * Set default values if optional are empty.
     */
    DataType = typeof(DataType) != 'undefined' ? DataType : "xml";
    Method = typeof(Method) != 'undefined' ? Method : 'GET';
    reqData = typeof(reqData) != 'undefined' ? reqData : "";


    $.ajax({
            url: URL,
            type: Method,
            dataType: DataType,
            data: reqData,
            success: function(xml) {
                    SuccessFunc(xml);
            },
            error: function(a,b,c) {
                var msg = ('error', a.status + " message: " + a.statusText + " response text: " + a.responseText);
                tErr.throwError(msg, tErr.SEVERE, tErr.IGNORE, "");
                ErrorFunc(a, b, c);
            }

    });

}

/*
 * Method ssoLogin takes the username and password and fetches the SSO login URL info.
 *
 * We will then re-direct to the SSO Login URL.
 *
 * @param username string The provided (and checked) username.
 * @param password string The provided (and checked) password.
 * @param errorCallback function Callback function to handle errors.
 *
 * @return boolean Returns false on failure.
 */

ajaxSSO.prototype.ssoLogin = function(username, password, errorCallback) {
    tErr.setMethod("ssoLogin");
    this.errorCallback = errorCallback;
    /*
     * Set default values if optional are empty.
     */
    if(typeof(username) == 'undefined') {
        return false;
    }
    if(typeof(password) == 'undefined') {
        return false;
    }

    // Get the SSO Login URL.

    var reqData = "loginurl=true&uname=" + username + "&pwd=" + password + "&siteid=" + this.siteId;
    this.getServerData(this.GETLOGINURL, this.ssoLoginUrlResult, this.ssoAjaxError, "json", "GET", reqData);
    
    return true;

}

/*
 * Method ssoLogout logs the user out of this application and
 * will return an SSO Logout url the user should be re-directed to.
 *
 * @param logoutErrorCallback function Callback function.
 *
 */

ajaxSSO.prototype.ssoLogout = function(logoutErrorCallback) {
    tErr.setMethod("ssoLogout");
    var reqData = "logout=true";

    this.errorCallback = logoutErrorCallback;

    this.getServerData(this.DOLOGOUT, this.ssoLogoutRedir, this.ssoAjaxError, "json", "POST", reqData);
}

ajaxSSO.prototype.ssoLogoutRedir = function(json) {
    if(json.result == 200) {
        window.location = json.sso_logout_url;
    }
}

/*
 * This Method is called as a result of a AJAX fetch of the SSO Login
 * result.
 *
 * @param json object object result.
 * 
 */
ajaxSSO.prototype.ssoLoginUrlResult = function(json) {
    tErr.setMethod("ssoLoginUrlResult");
    if(json.result == 200) {
        // Good response

        var gotoURL = json.loginUrl;

        window.location = gotoURL;
        
    } else {
        var msg = ('error', a.status + " message: " + a.statusText + " response text: " + a.responseText);
        tErr.throwError(msg, tErr.SEVERE, tErr.MESSAGEBOX, "There was an error while attempting to log you in. Please try again.");

    }

}

/*
 * This method handles errors (non 200 responses) for AJAX requests.
 *
 * NOTE: Non-200 responses are not always "errors" - most RESTful APIs use
 * 400 & 500 series for normal operational errors/responses.
 *
 * @param a XMLHTTPRequest Object
 * @param b String Error Message
 * @param c int Error Number
 *
 */

ajaxSSO.prototype.ssoAjaxError = function(a, b, c) {
    var msg = ('error', a.status + " message: " + a.statusText + " response text: " + a.responseText);
    tErr.throwError(msg, tErr.SEVERE, tErr.MESSAGEBOX, "An authentication error occurred. Please try again.");

    this.errorCallback(a);
}
