/**
************************************
* Google Account Interaction
************************************
*
* Google Account Authentication
*
* @copyright	Copyright (C) 2006, Jack Chapple
* @author	Jack Chapple <jack@jcxp.net>
*/

function jcGoogle()
{
	this.gmailUrl   = "http://mail.google.com/mail";
	this.feedUrl    = "/feed/atom";
	this.inboxUrl   = "/?search=inbox&auth=";
	this.searchUrl  = "/?search=query&view=tl&start=0&init=1&fs=1&q=";
	this.messageUrl = "/?fs=1&tf=1&view=cv&search=all&th=";
	this.composeUrl = "/?view=cm&tf=0&auth=";
	this.authUrl    = "https://www.google.com/accounts/ClientAuth";
	this.tokenUrl   = "https://www.google.com/accounts/IssueAuthToken";

	this.authenticate = function( account, password, onFinish )
	{
		var me = this;
		var request = new XMLHttpRequest();
		request.open( "POST", this.authUrl );
		request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
		request.setRequestHeader( "Cache-Control", "no-cache" );

		request.onreadystatechange = function()
		{
			if ( request.readyState == 4 )
			{
				if ( request.status && request.status != 200 )
				{
					if ( request.status == 403 )
					{
						authError( 'Invalid Username or Password!' );
					}
					else
					{
						authError( 'Could not connect to Gmail ' + request.status );
					}

					return false;
				}

				if ( request.responseText.indexOf( 'Error=badauth' ) > -1 )
				{
					authError( 'Invalid Username or Password!' );
					return false;
				}

				var sl   = request.responseText.split('\n');
				var sid  = sl[0];
				var lsid = sl[1];

				me.getAuthToken( sid, lsid, onFinish );
			}
		}

		var params = "Email=" + encodeURI(account) + "&Passwd=" + encodeURI(password);

		try
		{
			request.send(params);
		}
		catch(e){}
	}

	this.getAuthToken = function( sid, lsid, onFinish )
	{
		var request = new XMLHttpRequest();
		request.open( "POST", this.tokenUrl );
		request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
		request.setRequestHeader( "Cache-Control", "no-cache" );
		request.onreadystatechange = function()
		{
			if ( request.readyState == 4 )
			{
				if ( typeof(onFinish) == 'function' ) onFinish( request.responseText );
			}
		}

		var params = sid + "&" + lsid + "&service=mail";

		request.send(params);
	}
}

jc.Google = new jcGoogle();