// ==UserScript==
// @name           Hatebu with Twitter + google
// @namespace      http://www.otchy.com&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 += "(withT+GoogleBookmark)";
	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;
		var msg = '[B!]' + comment + ' ' + bkurl + ' "' + title + '"';
		var status = encodeURIComponent(msg);
		var url = 'http://twitter.com/statuses/update.json';
		GM_xmlhttpRequest({
			method : 'POST',
			url : url,
			data: 'status=' + status,
			headers: {
				'Content-Type':'application/x-www-form-urlencoded',
				'X-Twitter-Client': 'Hatebu with Twitter',
				'X-Twitter-Client-Version': '1.0.2'
			}
		});
				
		//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);
	}
})();
