/****************************************************************************
 *	Authentication Functions
 ****************************************************************************/

function login (event) {
	if ( event.target )
	{
		var username = GetFormValue( event.target, "email"    );
		var password = GetFormValue( event.target, "password" );
		
		pagecentric.api.login( username, password, login_handler );
	}
	else
	{
		alert( "Could not retrieve credentials from form!" );
	}
}

function login_handler (responseText) {
	if ( "" != responseText ) {
		var obj = JSON.parse( responseText );
		if ( obj && obj.idtype ) {
			//just incase, remove cookie, and then set it.
			$.removeCookie('iCuroUser');
			$.cookie("iCuroUser", JSON.stringify(obj));
			//redirect to correct dashboard
			Redirect(obj.idtype);
		}
		else {
			if (obj["error"] == "INVALID_CREDENTIALS") {
				var errorText = "Invalid username or password.";
			} else {
				var errorText = "Error logging in, please try again.";
			}
			var loginErrorDiv = document.getElementById('login-error');
			loginErrorDiv.innerHTML = "";
			loginErrorDiv.innerHTML = errorText;
		}
	}
}

function session( event )
{
	if ( event.target )
	{
		var username = GetFormValue( event.target, "email"    );
		var password = GetFormValue( event.target, "password" );
		
		pagecentric.api.login( username, password, null );
	}
	else
	{
		alert( "Could not retrieve credentials from form!" );
	}
}

function logout( event ) {
	pagecentric.api.logout( logout_handler );
}

function logout_handler ( responseText ) {
	location.pathname = "/login";
}
