/*
	Script: af_auth.js
	Desc:	This JS file is a wrapper to access AFAuth library
*/

/* !*** HIGH-LEVEL FUNCTIONS *** */

// From page where email was taken, user can click on button to login. This presets login form
function auth_loginPrompt(user)
{
	clearAllWarnings();
	setTimeout( "$('#login_pane').slideDown(600);" , 680);
	setTimeout( "$('#u').val('" + user + "'); $('#p').focus();" , 1290);
} // auth_loginPrompt


// Attempt to log user in using Appsire Sign-In procedure
// Caller should pass a callback function to continue upon success. If login fails, function returns "0"
function loginUserPass_triggered(callback)
{
	// var params	= "'" + $("#u").val() + "','" + $("#p").val() + "'";
	// var params	= $("#u").val() + "," + $("#p").val();
	// var success	= parseInt ( queryAuth("logInUserWithCredentials", params ) ); // need user and pass
	
	AFLogin($("#u").val(),$("#p").val(),callback);
	
	/*
	if (success)
	{
		if (callback)
		{
			callback( true );
		} else {
			return true;
		}
	} else {
		if (callback)
		{
			callback( false );
		} else {
			return false;
		}
	}
	*/
	
} // loginUserPass_triggered

/**
 * Appsfire login method
 * @param string user
 * @param string password
 * @param string callback function
 * @param bool remember
 * 
 */
function AFLogin(user,pass,callback,remember)
{
	var params	= user + "," + pass + ",0,"  + remember;
	var success	= parseInt ( queryAuth("logInUserWithCredentials", params ) ); // need user and pass
	if (success)
	{
		if (callback)
		{
			callback( true );
		} else {
			return true;
		}
	} else {
		if (callback)
		{
			callback( false );
		} else {
			return false;
		}
	}
} // AFLogin

// Logs user out and calls callback() if provided
function AFLogout( callback )
{
	
	var success = queryAuth("logUserOutWithID");
	if ( callback )
	{
		callback( success );
	} else {
		return success;
	}
	
} // AFLogout


// Attempt to log user in using Facebook Connect
// Caller should pass a callback function to continue upon success. If login fails, function returns false
function loginFBConnect_triggered(callback)
{
	loginFB(callback);
} // 

function loginFBConnect_triggered_part2()
{

} // loginFBConnect_triggered_part2


/* !*** LOW-LEVEL FUNCTIONS *** */

// Token used for all API calls
var AFToken = null;
// Passes command to AFAuth in order to retrieve a result
function queryAuth( func, params, async, callback )
{
	if (AFToken == null)
	{
		queryToken();
	}

	var dtype = "json";
	var ret   = "";
	
	if (typeof params == "undefined")
		params = "";
	
	if (typeof async == "undefined")
	{
		asyncVal = false;
	}else{
		if (typeof async == "boolean")
		{
			asyncVal = async;
		}else{
			asyncVal = false;
		}
	}
	
	var dataSet = dataSet = "t=" + AFToken;
	
	// Calculate data value
	if (params instanceof Array)
	{
		// Array was sent
		for(var k in params)
		{
			dataSet += "&" + k + "=" + params[k];
		}
		// dataSet = dataSet.substring(0,dataSet.length-1);
	} else {
		dataSet += "&p=" + params + "&f=" + func;
	}
	
	// alert(dataSet);
	
	$.ajax({
		async	: asyncVal,
		url		: document.location.protocol + "//" + window.location.hostname + "/lib/auth/AFAuth_GK.php",
		cache 	: false,
		data	: dataSet,
		// dataType: dtype,
		type	: "POST",
		success	: function(response) {
			// alert("Response = " + response);
			if (!checkTokenValidity(response))
			{
				resetQueryToken();
				return queryAuth( func, params );
			}
			ret = response;
			
			if ( callback )
			{
				callback(ret);
			} else {
				if ( isInt(ret) )
					ret = parseInt(ret);
				return ret;
			}
		}
	});
	
	if (asyncVal === false)
		return ret;
	
	if ( isInt(ret) )
		ret = parseInt(ret);
	
	return ret;
	
	
} // queryAuth

// Checks if a token is valid
function checkTokenValidity(res)
{
	if (res == "ACCESS DISABLED")
	{
		return false;
	} else {
		return true;
	}
} // checkTokenValidity

function queryToken()
{
	$.ajax({
		async	: false,
		url		: document.location.protocol + "//" + window.location.hostname + "/lib/auth/AFAuth_Token.php",
		data	: "z=n",
		cache	: false,
		type	: "POST",
		success	: function(response) {
			AFToken = response;
			// queryAuth( func, params );
		}
	});
	
	// Reset token in 10 minutes
	setTimeout( "resetQueryToken()", 600000 );
}

function resetQueryToken()
{
	AFToken = null;
}

function isInt(x)
{
	var y=parseInt(x);
	if (isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
}

// Resets user password by using email as key. This returns the entire HTML of the view
// that is generated by index.php/login/lost_send. No coherent value hence. The
// assumption made is that you have alread confirmed that the email is valid and in the DB
function resetPasswordByEmail(email)
{
	var res = queryAuth( "resendUserCredentialsForUserWithEmail", email);
	return res;
} // resetPasswordByEmail

// Returns true if a username is valid (not in the sense
// that it exists but in the sense that the characters are allowed
function isUserNameValid(username)
{
	if (/^[a-zA-Z0-9_]{6,}$/.test(username))
	{
		return true;
	} else {
		return false;
	}
} // isUserNameValid

// Serialize an element into an object - super useful!
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
