// ==UserScript==  
// @name           Bookma Entry
// @namespace      http://www.bookma.org/
// @description    Bookmaに投稿するスクリプト、サイトを開いてCtrl+Shift+Enterだよ♪
// @include        *
// @version        0.2
// ==/UserScript==


(function (){

	var useComment = true

	var w = window, d = document;
	if (typeof unsafeWindow != 'undefined') { w = unsafeWindow }
	function debug(arguments) { try{ w.console.log(arguments)   } catch(e) {} }
	function error(arguments) { try{ w.console.error(arguments) } catch(e) {} }

	var Browsing = function() { this.init.apply(this, arguments) }

	Browsing.prototype = {

		init : function(url) {
			var comment = '';
			while (useComment) {
				comment = prompt('[bookma.org] 投稿して良ければ一言コメントを下さい！(20文字以内)', '');
				if (comment == null) {
					alert('[bookma.org] サーセン!!');
					return ;
				}
				if (comment.length <= 20) {
					useComment = false;
				} else {
					alert('[bookma.org] ' + comment.length + '文字ってことは・・・20文字超えてるぉ...');
				}
			}
			this.post(url, comment);
		},

		post : function(url, comment) {
			
			GM_xmlhttpRequest({
				method : 'post',
				url    : 'http://www.bookma.org/',
				headers: {
					'Content-type': 'application/x-www-form-urlencoded',
				},
				data   : 'api=1&body=' + encodeURIComponent(url) + '&recomment=' + encodeURIComponent(comment),
				onload : function(res) {
					if (res.responseText == 'ok') {
						alert('[bookma.org] うほ♪いいサイト！');
					} else if (res.responseText == 'double') {
						alert('[bookma.org] ごりっ？ もうすでに登録済みのURLでしたうほっ＞＜');
					} else {
						alert('[bookma.org] 投稿失敗、原因不明: ' + res.responseText);
					}
				},
				onerror: function(res) {
					alert('[bookma.org] 投稿失敗、サーバーエラーだお');
				},
			});
		},
	}

	addEventListener('keypress', function(e) {
		var c = (e.ctrlKey), s = (e.shiftKey), v = (e.keyCode == 13);
		if (c && s && v) {
			var loc      = d.location.href,
			    callback = function(url) { new Browsing(url) },
			    error    = function(res) { new Browsing(loc) },
			    func     = callback;

			func(loc, callback, error);
		}
	}, true);

})()
