/*
	@author: James Nisbet
	@url: http://www.bandit.co.nz
	@update: http://lab.bandit.co.nz/scripts/jetpacks/bandit-gmail.js
	@title: Jetpack Gmail Checker
	@description: Jetpack Gmail checker, adapted from Mozilla's example script
	@version: 0.1
*/

function GmailNotifier(doc){
	$(doc).click( this.goToInbox );
}

GmailNotifier.prototype = {
	goToInbox: function() {
		jetpack.tabs.open("http://mail.google.com");
		jetpack.tabs[ jetpack.tabs.length-1 ].focus();
	},

	update: function(doc) {
		doc = $(doc); self = this; // juggling name spaces
		$.get( self.url, function(xml) {
			var el = $(xml).find("fullcount"); // unread message count
			
			if( el ){
				var newcount = parseInt(el.get(0).textContent);
				if(newcount>self.count) {
					var sender = $(xml).find("name").get(0).textContent;
					self.notify("New message from "+sender);
				}
				self.count = newcount;
				doc.find("#count").text( self.count );
			}
			else {
				doc.find("#count").text( "Login" );
				self.notify("Please login to Gmail");
			}
		});
	},
	
	notify: function(msg) {
		jetpack.notifications.show({
			title: "Gmail",
			body: msg,
			icon: "http://mail.google.com/mail/images/favicon.ico"
		});
	},
	
	count: 0,
	url: "http://mail.google.com/mail/feed/atom"
}

jetpack.statusBar.append({
	html: <>
		<img src="http://mail.google.com/mail/images/favicon.ico"/>
		<span id="count"></span>
		</>,
	onReady: function(doc) {
		var gmail = new GmailNotifier(doc);
		$("#count", doc).css({
			position: "absolute",
			fontFamily: "Tahoma, Arial, sans-serif",
			left: 0, top: 8,
			width: 20,
			display: "block",
			textAlign: "center",
			fontSize: "10px",
			cursor: "pointer",
			backgroundColor: "rgba(255,255,255,.5)"
		});
		gmail.update(doc);
		setInterval( function() { gmail.update(doc) }, 60*1000 );
	},
	width: 20
});