/**
 * Jetpack Sample KBText
 * http://blog.xlune.com/
 */
var KBText = KBText || {};
KBText.Config = {
	yUrl: "http://jlp.yahooapis.jp/MAService/V1/parse",
	yParam: {
		appid: "rvNw382xg656tyPRhdp1t6_qfwWeQ1SWU_XEm.xaq8U8AIVo5bUDEgzeTlDqDr2TkZE-",
		results: "ma",
		sentence: ""
	},
	boxName: "KBTextBox"
};
KBText.init = function(){
	var mes = "文字を選択してね！";
	var selectStr = jetpack.tabs.focused.contentDocument.getSelection() || '';
	if(selectStr)
	{
		mes = "変換開始！";
		var param = KBText.Config.yParam;
		param.sentence = selectStr;
		$.post(
			KBText.Config.yUrl,
			param,
			KBText.onComplete
		);
		
	}
	jetpack.notifications.show(
		{
			title: 'KBText',
			body: mes,
			icon: 'http://blog.xlune.com/favicon.ico'
		}
	);
};
KBText.onComplete = function(xml)
{
	var arr = [];
	$(xml)
		.find("reading")
			.each(function(num){
				if(!$(this).text().match(/[ 　]+/))
				{
					arr.push($(this).text());
				}
			});
	jetpack.notifications.show(
		{
			title: 'KBText',
			body: "変換完了。。。右上に表示されてるよ！",
			icon: 'http://blog.xlune.com/favicon.ico'
		}
	);
	KBText.showBox(arr.join(' ').cmabrigde());
};

KBText.makeBox = function()
{
	return $("<div>")
		.html('<p class="sj-text"></p><p class="sj-close"><a href="#">close</a></p>')
		.css({
				"position": "fixed",
				"right": "5px",
				"top": "5px",
				"padding": "5px 10px",
				"background-color": "#000000",
				"color": "#FFFFFF",
				"z-index": "1000",
				"line-height": "1.5em",
				"width": "40%",
				"-moz-border-radius": "5px",
				"-moz-opacity": "0.7",
				"font-size": "14px"
		})
		.attr('id', KBText.Config.boxName)
		.find('p.sj-close a')
			.click(function(){
				$(jetpack.tabs.focused.contentDocument.documentElement)
					.find('#'+KBText.Config.boxName)
					.remove();
				return false;
			})
			.css({
				"display": "block",
				"text-align": "right",
				"color": "#FFFFFF"
			})
			.end();
};
KBText.showBox = function(str)
{
	KBText.removeBox();
	$(jetpack.tabs.focused.contentDocument.documentElement)
		.append(KBText.makeBox())
		.find('p.sj-text').html(str);
};
KBText.removeBox = function()
{
	$(jetpack.tabs.focused.contentDocument.documentElement)
		.find('#'+KBText.Config.boxName)
		.remove();
};

/**
 * writed by "amachang"
 * from: http://d.hatena.ne.jp/amachang/20090518/1242656425
 */
String.prototype.cmabrigde = function() {
	return this.split(' ').map(function(w) {
		var ws = w.split('');
		var l = ws.pop();
		return (ws.shift() || '') + (ws.length ? ws.sort(Math.random).join('') : '') + l;
	}).join(' ');
};

/**
 * jetpack init
 */
jetpack.statusBar.append({
	html: '<img src="http://blog.xlune.com/favicon.ico" />',
	width: 16,
	onReady: function(doc) {
		$(doc).find("img").click(function() {
			KBText.init();
		});
	}
});
