/**
************************************
* GMail Gadget
************************************
*
* Front-end functionality
*
* @copyright	Copyright (C) 2006, Jack Chapple
* @author	Jack Chapple <jack@jcxp.net>
*/

var listScroll = new jc.Effect();
listScroll.setAttribs( 'effect:scroll;layer:inboxList;by:125;duration:0.7;' );

var fadeAttribs           = 'effect:fade;duration:0.7;max:60;';
var scrollUpFade          = new jc.Effect();
var scrollDownFade        = new jc.Effect();
scrollUpFade.setAttribs   ( fadeAttribs + "layer:scrollUp;extrafilter:DXImageTransform.Microsoft.AlphaImageLoader(src='img/scroll_up_inactive.png', sizingMethod='crop');" );
scrollDownFade.setAttribs ( fadeAttribs + "layer:scrollDown;extrafilter:DXImageTransform.Microsoft.AlphaImageLoader(src='img/scroll_down_inactive.png', sizingMethod='crop');" );

var authFlashAtt           = "effect:flash;duration:3;";
var authFlash1             = new jc.Effect();
authFlash1.setAttribs      ( authFlashAtt );
authFlash1.onAfterFinish   = clearError;
var authFlash2             = new jc.Effect();
authFlash2.setAttribs      ( authFlashAtt );
authFlash2.onAfterFinish   = clearError;

var authPassBool = false;
var goodUser     = "";
var goodPass     = "";
var isSettings   = false;
var lastCount    = 0;
var refreshTimer;

function settingsOnload()
{
	System.Gadget.onSettingsClosing = saveSettings;
	isSettings = true;

	authFlash1.layerObj = document.getElementById('username');
	authFlash2.layerObj = document.getElementById('password');

	var storUser = System.Gadget.Settings.read( 'gmailUser' );
	var storPass = System.Gadget.Settings.read( 'gmailPass' );

	if ( storUser && storPass )
	{
		document.getElementById('username').value = storUser;
		document.getElementById('password').value = storPass;
		jc.Google.authenticate( storUser, storPass, function(){ authPass(true) } );
	}
	else
	{
		noAuth();
	}
}

function settingsAuthenticate()
{
	var user = document.getElementById('username');
	var pass = document.getElementById('password');
	
	if ( !user.value || !pass.value )
	{
		authError('Please complete both fields');
		return;
	}

	var lbObj = document.getElementById('loginButton');
	lbObj.value = 'Wait...';
	lbObj.disabled = true;

	jc.Google.authenticate( user.value, pass.value, authPass );
}

function authPass( noModifyButton )
{
	if ( typeof(noModifyButton) == "string" || !noModifyButton )
	{
		var lbObj = document.getElementById('loginButton');
		lbObj.value = 'Pass';
		lbObj.disabled = true;
	}

	authPassBool = true;
	goodUser = document.getElementById('username').value;
	goodPass = document.getElementById('password').value;
	goodUser = goodUser.replace( '@gmail.com', '' );

	var statObj = document.getElementById('status');
	statObj.className = 'statusGood';
	statObj.innerHTML = "Logged in as " + goodUser;
}

function authError( errTxt )
{
	if ( !isSettings )
	{
		jc.error( errTxt );
		return;
	}

	var lbObj = document.getElementById('loginButton');
	lbObj.value = 'Login';
	lbObj.disabled = false;

	authFlash1.run();
	authFlash2.run();

	authErrObj = document.getElementById('authError');
	authErrObj.innerHTML = errTxt;
	authErrObj.style.display = '';
}

function noAuth()
{
	var statObj = document.getElementById('status');
	statObj.className = 'statusBad';
	statObj.innerHTML = "Not Logged In";
}

function clearError()
{
	var cE = new jc.Effect();
	cE.setAttribs( 'effect:fade;direction:out;layer:authError;' );
	cE.run();
}

function saveSettings()
{
	if ( authPassBool == true )
	{
		System.Gadget.Settings.write( 'gmailUser', goodUser );
		System.Gadget.Settings.write( 'gmailPass', goodPass );
	}
}

function gadgetOnload( doReset )
{
	System.Gadget.settingsUI = "settings.htm";
	System.Gadget.onSettingsClosed = function(){ gadgetOnload(true) };

	if ( doReset )
	{
		window.clearTimeout(refreshTimer);
		lastCount = 0;
	}

	var countObj = document.getElementById('emailCount');
	countObj.innerHTML = "";
	countObj.style.cursor = 'auto';
	countObj.onclick = null;

	var storUser = System.Gadget.Settings.read( 'gmailUser' );
	var storPass = System.Gadget.Settings.read( 'gmailPass' );

	if ( storUser && storPass )
	{
		document.getElementById('inboxList').innerHTML = '<p style="font-style:italic;padding:4px;margin:0;">Loading...</p>';
		jc.Google.authenticate( storUser, storPass, getInbox );
	}
	else
	{
		document.getElementById('inboxList').innerHTML = '<p style="font-size:10px;padding:4px 18px 0 3px;margin:0;">The GMail gadget doesn\'t know your account details.<br /><br />Navigate to the Settings page to login.</p>';
	}
}

function fetchArray( xml, parentElem, tagName, raw )
{
	if ( !xml || !parentElem || !tagName ) return;

	var items = xml.getElementsByTagName(parentElem);
	
	var fetchArray = Array();
	
	for ( var i = 0; i < items.length; i++ )
	{
		var result = items[i].getElementsByTagName(tagName)[0];
	
		if ( result )
		{
			if ( raw )
			{
				fetchArray[i] = result;
			}
			else
			{
				if ( result.childNodes.length > 1 )
				{
					fetchArray[i] = result.childNodes[1].nodeValue;
				}
				else if ( result.firstChild )
				{
					fetchArray[i] = result.firstChild.nodeValue;	
				}
				else
				{
					fetchArray[i] = result;
				}
			}
		}
	}
		
	if ( i == 0 )
	{
		return false;
	}
	else
	{
		return fetchArray;
	}
}
	
function fetchValue( xml, parentElem, tagName, index )
{
	var fetchItems = fetchArray( xml, parentElem, tagName );
	var fetchItem = fetchItems[index];
		
	return fetchItem;
}

function goMail( liChild )
{
	var liFade = new jc.Effect();
	liFade.setAttribs( 'effect:fade;direction:out;duration:0.3;' );
	liFade.layerObj = liChild;

	liFade.onAfterFinish = function()
	{
		System.Shell.execute( liChild.href );

		var eCountObj = document.getElementById('emailCount');
		var inboxList = document.getElementById('inboxList');
		var eCount = parseInt(eCountObj.innerHTML) - 1;
		var countText = (eCount > 0) ? eCount + " New" : "No New";
		eCountObj.innerHTML = countText;

		inboxList.removeChild( liChild );

		if ( eCount == 0 )
		{
			inboxList.innerHTML = '<p style="font-size:12px;padding:40px 18px 0 3px;margin:0;text-align:center;">No New Mail!</p>';
		}
	}

	liFade.run();
}

function getInbox( auth )
{
	if ( !auth ) return;

	refreshTimer = setTimeout( function(){ getInbox(auth) }, 30000 );

	var inboxFeedUrl = jc.fixXmlHttpUrl( jc.Google.gmailUrl + jc.Google.feedUrl + "/?auth=" + auth );
	var request = new XMLHttpRequest();
	request.open( "GET", inboxFeedUrl );
	request.setRequestHeader( "Cache-Control", "no-cache" );
	
	request.onreadystatechange = function()
	{
		if ( request.readyState == 4 )
		{
			document.getElementById('inboxList').innerHTML = "";

			var countObj       = document.getElementById('emailCount');
			var mailCount      = parseInt( fetchValue( request.responseXML, 'feed', 'fullcount', 0 ) );
			var countText      = (mailCount > 0) ? mailCount + " New" : "No New";
			countObj.innerHTML = countText;
			countObj.href      = jc.Google.gmailUrl + jc.Google.inboxUrl + auth;
			countObj.style.cursor = 'pointer';
			countObj.onclick   = function()
			{
				System.Shell.execute( this.href );
			}

			if ( mailCount == 0 )
			{
				lastCount = 0;

				if ( document.getElementById('scrollUp').style.display == '' )
				{
					scrollUpFade.setAttrib( 'direction', 'out' );
					scrollUpFade.run();
				}
				if ( document.getElementById('scrollDown').style.display == '' )
				{
					scrollDownFade.setAttrib( 'direction', 'out' );
					scrollDownFade.run();
				}

				document.getElementById('inboxList').innerHTML = '<p style="font-size:12px;padding:40px 18px 0 3px;margin:0;text-align:center;">No New Mail!</p>';
				return;
			}
			
			if ( mailCount > lastCount )
			{
				System.Sound.playSound( 'notify.wav' );
			}

			lastCount = mailCount;

			var titles   = fetchArray( request.responseXML, 'entry', 'title' );
			var links    = fetchArray( request.responseXML, 'entry', 'link' );
			var messages = fetchArray( request.responseXML, 'entry', 'summary' );
			var authors  = fetchArray( request.responseXML, 'entry', 'author', true );

			for ( var i = 0; i < titles.length; i++ )
			{
				var clsName = (i % 2 == 0) ? "li1" : "li2";
				var href = links[i].getAttribute('href');
				var re = /message_id=([a-z0-9]+?)&/i;
				
				if ( re.exec( href ) != null )
				{
					var message_id = RegExp.$1;
				}

				for ( var i2 = 0; i2 < authors[i].childNodes.length; i2++ )
				{
					if ( authors[i].childNodes[i2].nodeName == "name" )
					{
						var authorName = jc.truncate( authors[i].childNodes[i2].firstChild.nodeValue, 23 );
					}
				}

				if ( typeof( titles[i] ) != "string" ) titles[i] = "<em>(No Subject)</em>";
				if ( typeof( messages[i] ) != "string" ) messages[i] = "No Message...";

				messages[i] = messages[i].replace( /\s*&hellip;\s*/, "..." );

				var liObj = document.createElement( 'LI' );
				liObj.className = "lig " + clsName;
				liObj.innerHTML = jc.truncate( titles[i], 23 ) + "<br /><span class='author'>" + authorName + "</span>";
				liObj.title     = jc.stripHtml( titles[i] ) + "\n\n" + jc.stripHtml( messages[i] );
				liObj.href      = jc.Google.gmailUrl + jc.Google.messageUrl + message_id + "&auth=" + auth;
				liObj.onclick   = function()
				{
					goMail( this );
				}

				document.getElementById('inboxList').appendChild( liObj );
			}

			// ==========================
			// Make the list container a multiplier
			// of 125 (height of visible list)
			// so scrolling animation can fully complete
			// ==========================

			var liHeight = getLiHeight();

			var newHeight = 125 * Math.ceil( liHeight / 125 );
			var appendHeight = newHeight - liHeight;

			if ( appendHeight > 0 )
			{
				var lastObj = document.createElement('LI');
				lastObj.className = "liEnd";
				lastObj.style.height = appendHeight + 'px';
				document.getElementById('inboxList').appendChild( lastObj );
			}

			// ==========================
			// Scrolling, anyone?
			// ==========================
			
			if ( getLiCount() > 5 )
			{
				document.getElementById('scrollDown').style.display = '';
			}
		}
	}

	request.send(null);
}

function getLiHeight()
{
	var lis = document.getElementById('inboxList').getElementsByTagName('LI');
	var liHeight = 0;

	for ( var i = 0; i < lis.length; i++ )
	{
		if ( lis[i].className.indexOf('lig') > -1 ) liHeight += 25;
	}

	return liHeight;
}

function getLiCount()
{
	var lis = document.getElementById('inboxList').getElementsByTagName('LI');
	var liHeight = 0;

	for ( var i = 0; i < lis.length; i++ )
	{
		if ( lis[i].className.indexOf('lig') > -1 ) liHeight += 1;
	}

	return liHeight;
}

function manageScrollButtons( direction )
{
	var predict    = (direction == "down") ? 125 : -125;
	var scrollTop  = parseInt(document.getElementById('inboxList').scrollTop) + predict;
	var liHeight   = getLiHeight();
	var liCount    = getLiCount();
	var totPages   = Math.ceil( liCount/5 );
	var thisPage   = ( scrollTop/125 ) + 1;

	var suObj = document.getElementById('scrollUp');
	var sdObj = document.getElementById('scrollDown');

	if ( thisPage == 1 )
	{
		if ( suObj.style.display == '' )
		{
			scrollUpFade.setAttrib( 'direction', 'out' );
			scrollUpFade.run();
		}

		if ( sdObj.style.display == 'none' )
		{
			scrollDownFade.setAttrib( 'direction', 'in' );
			scrollDownFade.run();
		}
	}
	else
	{
		if ( suObj.style.display == 'none' )
		{
			scrollUpFade.setAttrib( 'direction', 'in' );
			scrollUpFade.run();
		}

		if ( thisPage == totPages )
		{
			if ( sdObj.style.display == '' )
			{
				scrollDownFade.setAttrib( 'direction', 'out' );
				scrollDownFade.run();
			}
		}
		else
		{
			if ( sdObj.style.display == 'none' )
			{
				scrollDownFade.setAttrib( 'direction', 'in' );
				scrollDownFade.run();
			}
		}
	}
}

function scrollUp()
{
	if ( listScroll.running) return;

	listScroll.setAttrib( 'direction', 'up' );
	listScroll.onBeforeStart = function(){ manageScrollButtons( 'up' ) }
	listScroll.run();
}

function scrollDown()
{
	if ( listScroll.running) return;

	listScroll.setAttrib( 'direction', 'down' );
	listScroll.onBeforeStart = function(){ manageScrollButtons( 'down' ) }
	listScroll.run();
}
