// ==UserScript==
// @name           Hatebu with googleBookmark
// @namespace      http://blog.gifumaster.com
// @include        http://b.hatena.ne.jp/bookmarklet*
// @include        http://b.hatena.ne.jp/add?*
// @include        http://b.hatena.ne.jp/*/add.confirm?*
// ==/UserScript==

(function() {
	var d = document;
	function getElement(xpath) {
		var result = d.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return result.singleNodeValue;
	}
	function getSignature(){
		sig = GM_getValue("sig",0);
		if(!sig){
			GM_xmlhttpRequest({
				method: 'GET',
				url: 'http://www.google.com/bookmarks/lookup?output=rss&sort=',
				onload: function(r){
					sig = r.responseText.replace(/.*<smh:signature>(.*)<\/smh:signature>.*/gi,"$1");
					GM_setValue("sig",sig);
				}
			});
		}
		return 0;
	}
	getSignature();
	
	var s = getElement('//form[@id="bookmarklet-form" or @id="add-form"]//input[@type="submit"]');
	var b = s.cloneNode(false);
	b.value += "(withGB)";
	b.addEventListener('click', function (e) {
		var comment = d.getElementById('comment').value;
		// remove tag
		// comment = comment.replace(/^(\[[^\]]+\])+/, ''));
		var bkurl = getElement('//input[@name="url"]').value;
		var title = getElement('//span[@class="title"]').innerHTML;
		//google bookmark 用
		var tagdata = [];
		var arrayTag = comment.match(/\[([^\]]+)\]/gi);
		for( i in arrayTag){
			t = arrayTag[i].replace(/\[([^\]]+)\]/gi,"$1");
			tagdata.push("hatenaBookmark>" + t);
		}
		tag = tagdata.join();
		gburl = "http://www.google.com/bookmarks/mark";
		bkurl = encodeURIComponent(bkurl);
		title = encodeURIComponent(title);
		tag   = encodeURIComponent(tag);
		comment = encodeURIComponent(comment);
		sig = GM_getValue("sig",0);
		data  = 'sig='+ sig +'&bkmk='+ bkurl + '&title=' + title + '&labels=' + tag +'&annotation=' + comment + '&hl=ja&zx='+Math.floor(Math.random()*32768);
		//タグがないと登録しない。
		if(tag != "" && sig != 0){
			GM_xmlhttpRequest({
				method : 'POST',
				url: gburl,
				data: data,
				headers: {
					'Content-Type':'application/x-www-form-urlencoded'
				}
			});
		}
		//ここまで
	}, false);
	var p = s.parentNode;
	var l = d.getElementById("redirect_entry_label");
	if (l) {
		p.insertBefore(b, l);
	} else {
		p.appendChild(b);
	}
})();

