/*
	@author: Benjamin Auer
	@email: benjaminauer@googlemail.com
	@url: http://jetpacks.benji-banned.ch
	@update: http://jetpacks.benji-banned.ch/googlereader.js
	@title: Jetpack Google Reader Checker
	@description: Jetpack Google Reader Checker, checks for unread items in Googles RSS Reader Application
	@version: 0.1b
*/



function GoogleReader() {
	//jetpack is awesome
}

GoogleReader.prototype = {

	openReader: function() {
		var tab = this.findReader();
		if(tab < 0) {
			jetpack.tabs.open("http://reader.google.com");
			jetpack.tabs[jetpack.tabs.length-1 ].focus();
		} else {
			jetpack.tabs[tab].focus()
		}
	},

	findReader: function() {
		var readertab = -1;
		for(var i=0;i<jetpack.tabs.length;i++) {
			if(jetpack.tabs[i].url.indexOf("www.google.com/reader")>=0) {
				readertab = i;
			}
		}
		return readertab;
	},

	notify: function(msg) {
		jetpack.notifications.show({
			title: "Google Reader",
			body: msg,
			icon: "http://www.google.com/reader/ui/favicon.ico"
		});
	},

	update: function(doc) {
			doc = $(doc); self = this;
			var count = 0;


			$.ajax({
				type: "GET",
				url: self.url,
				dataType: "xml",
				async: false,
				success: function(xml) {
					html = $(xml).get(0);
					regexpstr = new RegExp("^.*google\/reading-list$");

					jQuery.each($(xml).find("list").find("object"), function() {
						
						if(regexpstr.test($(this).find("string").get(0).textContent)) {
							count = parseInt($(this).find("[name=count]").get(0).textContent);
						}
					});
					$(doc).find("#count").text(count);

					if(count>self.count) self.notify('New Items! ('+(count-self.count)+')');
					
					self.count = count;
				},

				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$(doc).find("#count").text(textStatus);
				}

			});
		},

	count: 0,
	url: "http://www.google.com/reader/api/0/unread-count?all=true"
}

jetpack.statusBar.append({
	html: <>
		<center style="margin-top:2px">
			<img src="http://www.google.com/reader/ui/favicon.ico" style="opacity:0.5"/>
		</center>
		<span id="count" style="text-align:center;display:block;position:absolute;top:6px;left:0px;font-family:verdana;font-weight:bold;font-size:10px;width:30px"></span>
		</>,
	width: 30,

	onReady: function (doc) {
		var greader = new GoogleReader(doc);

		$(doc).find("*").css({cursor:"pointer"});

		$(doc).click(function() { greader.openReader() });

		greader.update(doc);
		
		setInterval( function() { greader.update(doc); }, 60*1000 );

	}

});
