// ==UserScript==
// @name          LDR Ipatsu Delicious
// @namespace     http://www.ohmiyapatriots.com/blog/
// @description   post the entry to del.icio.us with pushing one key
// @include       http://reader.livedoor.com/reader/*
// ==/UserScript==
// @version   1.0.0.0
// @license   http://creativecommons.org/licenses/by-sa/2.1/jp/
//            original: http://d.hatena.ne.jp/antipop/20060427/1146067330
//                      by: kentaro
//                      license: cc by-sa

(function() {
	// settings
	var shortcutKey = "d";
	var libraries = [
		"http://reader.livedoor.com/js/wsse.js"
	];

	var w       = unsafeWindow;
	var _onload = w.onload;

	function REST() {}
	REST.prototype = {

		makeURI : function(baseURI, queries) {
			var query = "";
			for (var q in queries)
				query += "&" + q + "=" + encodeURIComponent(queries[q]);

			return baseURI + query.substr(1);
		},

		post : function(method, baseURI, queries,oncallback) {
			GM_xmlhttpRequest({
				method : method,
				url    : this.makeURI(baseURI, queries),
				onload : oncallback
			});
		}

	};

	var onload = function() {
		for (var i = 0; i < libraries.length; i++)
		{
			var script = document.createElement('script');
			document.getElementsByTagName('head')[0].appendChild(script);
			script.type = 'text/javascript';
			script.src  = libraries[i];
		}
		var rest = new REST();
		w.Keybind.add(shortcutKey, function() {
			var item = w.get_active_item(true);
			if (!item) return;
			
			w.message("post del.icio.us: " + item.title);
			
			// del.icio.us
			
			var tags = [], notes = "";
			var queries = {
				url         : item.link,
				description : item.title,
				tags        : '\u3042\u3068\u3067\u8AAD\u3080',
				dt          : (function() {
					var date = new Date();
					return date.getW3CDTF();
				})()
			};
			
			var itemid = item.item_id;
			w.document.getElementById("clip_icon_"+itemid).src = "/img/icon/clipped.gif";
			rest.post("get", "https://api.del.icio.us/v1/posts/add?", queries,function(response){
				var msg = 'del.icio.us \u3078\u306E\u767B\u9332\u306B\u5931\u6557\u3057\u307E\u3057\u305F';
				if(response.status == '200'){
					msg = 'del.icio.us \u306B\u767B\u9332\u3057\u307E\u3057\u305F';
				}else{
					w.document.getElementById("clip_icon_"+itemid).src = "/img/icon/clip.gif";
				}
				w.message(msg);
			});
		});
	};

	w.onload = function() {
		_onload();
		onload();
	};


	function complementDate(s)
	{
		return (s < 10) ? '0' + s : s;
	}

	Date.prototype.getW3CDTF = function()
	{
		var Y = this.getFullYear();
		var m = complementDate(this.getUTCMonth() + 1);
		var d = complementDate(this.getUTCDate());
		var H = complementDate(this.getUTCHours());
		var i = complementDate(this.getUTCMinutes());
		var s = complementDate(this.getUTCSeconds());

		return Y + "-" + m + "-" + d + "T" + H + ":" + i + ":" + s + "Z";
	}
})();
