/**
 * Multi login for Tumblr
 * cho45 <cho45@lowreal.net>
 * 2007-09-24
 *
 * License:
 * Creative Commons by
 * http://creativecommons.org/licenses/by/3.0/
 *
 * Using information in your password manager,
 * you have to logged in tumblr previously.
 */


if (typeof MultiUserOnTumblrService != "function") {
	var MultiUserOnTumblrService = function () {
		if (arguments.callee.instance) {
			// some complex process for reloading
			for (let prop in arguments.callee.prototype) {
				if (arguments.callee.prototype.hasOwnProperty(prop)) {
					arguments.callee.instance[prop] = arguments.callee.prototype[prop];
				}
			}
			return arguments.callee.instance;
		} else {
			this.initialize.apply(this, arguments);
			arguments.callee.instance = this;
		}
	};
}
MultiUserOnTumblrService.prototype = {
	ID : "status-bar-multi-user-tumblr-uc",

	initialize : function () {
		var self = this;
		this.manager    = Components.classes["@mozilla.org/passwordmanager;1"]
		                            .getService(Components.interfaces.nsIPasswordManager);
		this.manageri   = Components.classes["@mozilla.org/passwordmanager;1"]
		                            .getService(Components.interfaces.nsIPasswordManagerInternal);
		this.cookies    = Components.classes["@mozilla.org/cookieService;1"]
		                            .getService(Components.interfaces.nsICookieService);
		this.IOService  = Components.classes["@mozilla.org/network/io-service;1"]
		                            .getService(Components.interfaces.nsIIOService);


		var statusbar = document.getElementById("status-bar");
		this.panel     = document.createElementNS(kXULNS, "statusbarpanel");

		this.img = document.createElementNS(kXULNS, "image");
		this.iconimg   = <><![CDATA[
			data:image/gif;base64,
			R0lGODlhDgAOAKIBAEx/GP///6PWcIe6VHyuSoG0To/CXP7+/iH5BAEAAAEA
			LAAAAAAOAA4AAAM7GLoMsC5KIR6gOBdCnBhgGHLeIEVkcBUPo1pr6wbmNStX
			XcmQ0KmUk6dzMRgyGFJRVNhwfgCQMALhzRIAOw==
		]]></>.replace(/\s+/g, "");
		this.img.setAttribute("src", this.iconimg);
		this.panel.appendChild(this.img);

		this.lbl = document.createElementNS(kXULNS, "label");
		this.panel.appendChild(this.lbl);

		this.menu = document.createElementNS(kXULNS, "menupopup");

		this.panel.appendChild(this.menu);
		this.panel.addEventListener("click", function () {
			self.onPanelClick.apply(self, arguments);
		}, false);

		var t = document.getElementById(this.ID)
		if (t) t.parentNode.removeChild(t);
		this.panel.id = this.ID;
		statusbar.appendChild(this.panel);


		this.setStatus("Not logged in");
	},

	onPanelClick : function (e) {
//		var foundHost = {value:""}, foundUser = {value:""}, foundPass = {value:""};
//		this.manageri.findPasswordEntry("http://www.tumblr.com", null, null, foundHost, foundUser, foundPass);
//		alert([foundUser.value, foundPass.value]);

		var matched = [];
		var passwords = this.manager.enumerator;
		var pass;
		while (passwords.hasMoreElements()) {
			var pass = passwords.getNext().QueryInterface(Components.interfaces.nsIPassword);
			if (pass.host == "http://www.tumblr.com") matched.push(pass);
		}
		while (this.menu.firstChild) this.menu.removeChild(this.menu.firstChild);
		matched.forEach(function (e) {
			var mi = document.createElementNS(kXULNS, "menuitem");
			mi.setAttribute("label", e.user);
			var self = this;
			mi.addEventListener("command", function () { self.switchUser(e) } , false);
			this.menu.appendChild(mi);
		}, this);
		this.menu.showPopup(this.panel, -1, -1, "popup", "bottomleft", "topleft");

	},

	switchUser : function (password) {
		var self = this;
		this.sessions = this.sessions || {};

//		var cookie = this.cookies.getCookieString(this.IOService.newURI("http://www.tumblr.com", null, null), null)
		self.setStatus("Logging in...");
		var req = new XMLHttpRequest;
		req.open("POST", "http://www.tumblr.com/login", true);
		req.onload = function (e) { try {
			if (req.responseText.match(/Logging in/)) {
				self.setStatus(password.user);
				content.location = "javascript:var d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://www.tumblr.com/share',l=d.location,e=encodeURIComponent,p='?v=3&u='+e(l.href) +'&t='+e(d.title) +'&s='+e(s),u=f+p;try{if(!/^(.*\\.)?tumblr[^.]*$/.test(l.host))throw(0);tstbklt();}catch(z){a =function(){if(!w.open(u,'t','toolbar=0,resizable=0,status=1,width=450,height=430'))l.href=u;};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else a();}void(0)";
			} else {
				self.setStatus("Failed");
			}
		} catch (e) { alert(e) } };
		req.onerror = function (e) {
			alert(e);
		};
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send([
			"email=", encodeURIComponent(password.user),
			"&password=", encodeURIComponent(password.password),
		].join(""));

		this.currentUser = password;
	},

	setStatus : function (msg) {
		// this.lbl.setAttribute("value", msg);
		this.panel.setAttribute("tooltiptext", msg);
	},
};

new MultiUserOnTumblrService();

