var InboxUpdater = {
	working: false,
	balloon: null,
	notificationSound: "notify.mp3",

	init: function(lbl, new_msg, msg_total, theme) {
		var me = this;
		lbl = $(lbl);
		var orig_new_msg = new_msg;
		new PeriodicalExecuter(function(pe) {
			if (me.working) return;
			me.working = true;
			new Ajax.Request("user/whoami.json.php", {
				method: "get",
				onSuccess: function(transport) {
					me.working = false;
					var status = transport.responseText.evalJSON();
					if (!status.id) return;
					if (status.new_msg < orig_new_msg) orig_new_msg = status.new_msg;
					if (status.new_msg != new_msg && status.new_msg > 0) {
						lbl.update(status.new_msg + " ongelezen bericht" + (status.new_msg == 1 ? "" : "en")).addClassName("new_messages");
						if (status.new_msg > orig_new_msg) {
							me.newMessageNotification(status.new_msg - orig_new_msg, status.new_msg, status.msg_total, lbl, theme);
						} else if (me.balloon) {
							me.balloon.remove();
							me.balloon = null;
						}
					} else if (status.msg_total != msg_total || (status.new_msg != new_msg && status.new_msg == 0)) {
						lbl.update(status.msg_total + " berichten").removeClassName("new_messages");
						if (me.balloon) {
							me.balloon.remove();
							me.balloon = null;
						}
					}
					new_msg = status.new_msg;
					msg_total = status.msg_total;
				},
				onFailure: function() {
					me.working = false;
				}
			});
		}, 5);
		this.preCacheSound(theme, this.notificationSound);
	},
	
	newMessageNotification: function(newMessages, unreadMessages, totalMessages, lbl, theme) {
		var msg = "<b>" + newMessages + (newMessages == 1 ? " nieuw bericht!" : " nieuwe berichten!") + "</b><br /><span class=\"small\">Ongelezen: " + unreadMessages + " bericht" + (unreadMessages == 1 ? "" : "en") + "<br />Totaal: " + totalMessages + " bericht" + (totalMessages == 1 ? "" : "en") + "</span>";
		PopupNotification.create(lbl, msg, lbl.href, "themes/" + theme + "/images/icons/cross.png");
		this.playSound(theme, this.notificationSound);
	},
	
	playSound: function(theme, sound) {
		var objSound = $("messageNotificationSound");
		if (objSound) objSound.remove();
		objSound = $(document.createElement("embed")).setStyle({position: "absolute", left: 0, top: 0, width: "1px", height: "1px", visibility: "hidden"});
		objSound.setAttribute("id", "messageNotificationSound");
		objSound.setAttribute("src", "themes/" + theme + "/sounds/" + sound);
		objSound.setAttribute("hidden", true);
		objSound.setAttribute("loop", false);
		objSound.setAttribute("autostart", true);
		document.body.appendChild(objSound);
	},
	
	preCacheSound: function(theme, sound) {
		// Download file asynchronously so that it is already in browser cache, preventing a download delay.
		new Ajax.Request("themes/" + theme + "/sounds/" + sound, {
			method: "get"
		});
	}
};

