/* :::::::: Fashion Tabs ::::::::::::::: */
// by zeniko
// http://forums.mozillazine.org/viewtopic.php?p=2592073#2592073

// Modified for Firefox 3.0 compatibility

({
	init: function()
	{
		Array.forEach(getBrowser().mTabs, function(aTab) {
			aTab.linkedBrowser.addProgressListener(this);
			this.colorizeTab(aTab);
		}, this);
		
		gBrowser.addEventListener("TabOpen", this, false);
		gBrowser.addEventListener("TabSelect", this, false);
		gBrowser.addEventListener("TabMove", this, false);
		gBrowser.addEventListener("TabClose", this, false);
	},

	handleEvent: function(aEvent)
	{
		var tab = aEvent.originalTarget;
		
		switch (aEvent.type)
		{
		case "TabOpen":
			tab.linkedBrowser.addProgressListener(this);
			break;
		case "TabMove":
		case "TabSelect":
			this.colorizeTab(tab);
			break;
		case "TabClose":
			tab.linkedBrowser.removeProgressListener(this);
			break;
		}
	},

	onLocationChange: function(aProgress, aRequest, aURI) {
		var doc = aProgress.DOMWindow.document;
		var tab = gBrowser.mTabs[gBrowser.getBrowserIndexForDocument(doc)];
		
		this.colorizeTab(tab);
	},

	onStateChange: function() { },
	onProgressChange: function() { },
	onStatusChange: function() { },
	onSecurityChange: function() { },
	onLinkIconAvailable: function() { },

	colorizeTab: function(aTab)
	{
		function djb2hash(aString)
		{
			var hashvalue = 5381;
			for (var i = 0; i < aString.length; i++)
			{
				hashvalue = ((hashvalue << 5) + hashvalue) + aString.charCodeAt(i);
			}
			return hashvalue;
		}
		
		try
		{
			var host = aTab.linkedBrowser.currentURI.host;
		}
		catch (ex) { }
		
		if (host && host != "about:blank")
		{
			var hue = djb2hash(host.replace(/^www\.(?=.+\..)/, "")) % 360;
		}
		var color = (hue)?"hsl(" + hue + ", 50%, 50%)":null;

		aTab.style.backgroundColor = color;

		if (gBrowser.selectedTab == aTab)
		{
			var anonId = ["tabs-bottom", "close-button tabs-closebutton"];
			var node;
			for (var i in anonId)
			{
				node = aTab.ownerDocument.getAnonymousElementByAttribute(aTab.parentNode, "class", anonId[i]);
				if (color)
					node.setAttribute("style", "background-color: " + color + " !important");
				else
					node.removeAttribute("style");
			}
		}
	},

	QueryInterface: function(aIID) {
		var Ci = Components.interfaces;
		if (![Ci.nsIDOMEventListener, Ci.nsIWebProgressListener, Ci.nsISupportsWeakReference, Ci.nsISupports].some(aIID.equals))
		{
			throw Components.results.NS_NOINTERFACE;
		}
		return this;
	}
}).init();
