// ==UserScript==
// @name           Hatena Diary Comment From livedoor Reader
// @namespace      http://tokyoenvious.xrea.jp/
// @include        http://reader.livedoor.com/reader/*
// ==/UserScript==
(function() {
	var w = unsafeWindow;

	function addBookmarkCommentForm() {
		var item = w.get_active_item(true);
		if (!item) return;

		var old = w.$('gm-hatena-comment-form');
		if (old) old.die();

		var url = item.link;
		var m = url.match(/(^.*?\/\/(?:[^\/\.]+\.g|d)\.hatena\.ne\.jp)\/([^\/]+)\/(\d+)(?:\/([^\/#]+))?/);
		var server = m[1], id = m[2], date = m[3];

		function addCommentForm(html) {
			var m = html.match(/<div class="comment">(?:.|\n|\r)*?<form method="post" action=".+?\/comment" class="comment">(?:.|\n|\r)*?<\/form>(?:.|\n|\r)*?<\/div>(?:.|\n|\r)*?<\/div>|<form method="post" action=".+?\/comment" class="comment">(?:.|\n|\r)*?<\/form>/);
			if (!m) return false;

			var div = w.document.createElement('div');
			div.id = 'gm-hatena-comment-form';
			div.innerHTML = m[0].replace(/action=".*?\/comment"/, 'action="' + server + '/' + id + '/comment"');
			div.die = function() {
				w.Control.scroll_to_px(div.parentNode.offsetTop);
				div.parentNode.removeChild(div);
			};

			var divs = div.getElementsByTagName('div');
			for (var i = 0; i < divs.length; ++i) {
				if (divs[i].className == 'caption') {
					divs[i].innerHTML = '';
					var img = w.document.createElement('img');
					img.src = 'http://reader.livedoor.com/img/icon/batu.gif';
					img.onclick = div.die;
					divs[i].appendChild(img);
					break;
				}
			}

			var form = div.getElementsByTagName('form')[0];
			function onsubmit(e) {
				if (e) w.Event.stop(e);

				GM_log(e.target + ', ' + e.target.name);
				var query = w.Form.toJson(form);
				var queryString;
				if (form.deleteMode) {
					// "コメントを削除しています..."
					w.message('\u30B3\u30E1\u30F3\u30C8\u3092\u524A\u9664\u3057\u3066\u3044\u307E\u3059...');
					queryString = w.Object.toQuery(query);
					for (var i = 0; i < form.cid.length; ++i)
						if (form.cid[i].checked)
							queryString += '&cid=' + i;
				} else {
					// "コメントを送信しています..."
					w.message('\u30B3\u30E1\u30F3\u30C8\u3092\u9001\u4FE1\u3057\u3066\u3044\u307E\u3059...');
					delete query.deletecomment;
					queryString = w.Object.toQuery(query);
				}

				GM_xmlhttpRequest({
					method: form.method,
					url: form.action,
					data: queryString,
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					onload: function() {
						// "送信しました"
						w.message('\u9001\u4FE1\u3057\u307E\u3057\u305F');
						div.die();
					},
					onerror: function() {
						// "なんかエラー"
						w.message('\u306A\u3093\u304B\u30A8\u30E9\u30FC');
						div.die();
					}
				});
			}
			form.onsubmit = form.submit = onsubmit;

			form.onclick = function(e) {
				if (e.target.name == 'deletecomment')
					form.deleteMode = true;
			}

			item.element.parentNode.parentNode.parentNode.appendChild(div);

			var textareas = form.getElementsByTagName('textarea');
			if (textareas) {
				textareas[0].focus();
				textareas[0].onkeydown = function(e) {
					if (e.keyCode == 27) {
						w.Event.stop(e);
						div.die();
					}
				}
			}

			// "読み込み完了"
			w.message('\u8AAD\u307F\u8FBC\u307F\u5B8C\u4E86');
			return true;
		}

		function fetchCommentPage(schemes, onLast) {
			if (!schemes.length) {
				onLast();
			} else {
				var s = schemes.shift();
				// "コメントフォームを取得中(" + s[1] + ")..."
				w.message('\u30B3\u30E1\u30F3\u30C8\u30D5\u30A9\u30FC\u30E0\u3092\u53D6\u5F97\u4E2D(' + s[0] + ')...');
				GM_xmlhttpRequest({
					method: 'GET',
					url: s[1],
					onload: function(details) {
						if (!addCommentForm(details.responseText))
							fetchCommentPage(schemes);
					}
				});
			}
		}

		fetchCommentPage(
			[['\u30D6\u30ED\u30B0\u30E2\u30FC\u30C9', url],	                                   // "ブログモード"
			 ['\u65E5\u8A18\u30E2\u30FC\u30C9', server + '/' + id + '/comment?date=' + date]], // "日記モード"
			w.message.curry('\u30B3\u30E1\u30F3\u30C8\u30D5\u30A9\u30FC\u30E0\u304C\u306A\u3044\u307F\u305F\u3044\u3067\u3059'));
	}

	var _onload = w.onload;
	w.onload = function() {
		_onload();

		w.Keybind.add('C', addBookmarkCommentForm);
		w.vi.hdcomment = addBookmarkCommentForm;

		GM_addStyle('#gm-hatena-comment-form, #gm-hatena-comment-form textarea { font-size: smaller; }');
	};
})();
