var f = document.getElementById("f");
var sample = document.getElementById("sample");

f.pre.onclick = function() {
	var code = f.area2.value;
	code = ['<div id="targetEl">', code, '</div>'].join("\n");
	code = code.replace(/<table /i,'<table id="orgTable" ');
	sample.innerHTML = code;
	document.getElementById('sort').style.display = 'inline';
//	document.getElementById('pre').style.display = 'none';
//	window.scrollTo(0, sort.offsetTop);
};

f.update.onclick = function() {
	var moto = sample.innerHTML;
	moto =	moto.replace(/<div id="?targetEl"?>/gi,'');
	moto =	moto.replace(/<\/div>/gi,'');
	moto =	moto.replace(/ id="?orgTable"?/gi,'');
	moto =	moto.replace(/ style="?cursor: move;?"? id="?yui-gen\d*"?/gi,'');
	moto =	moto.replace(/<tbody>/gi,'');
	moto =	moto.replace(/<\/tbody>/gi,'');
	moto =	moto.replace(/\n\n/gm,'\n');
	f.area2.value = moto;
	window.scrollTo(0, f.run.offsetTop);
};

f.run.onclick = function()
{
	function sortObj(obj){
		var ary = new Array();
		for(var i in obj){
			ary.push({key:obj[i][1], kazu:i, value:obj[i][0]});
		}
		ary = ary.sort(sortFunc);

		var ret = new Array();
		for(var i = 0; i < ary.length; i++){
			ret[i] = ary[i].value;
		}
		return ret;

		function sortFunc(left, right){
			var kv = "key";
			var a = left[kv], b = right[kv];

			a = Number(a);
			b = Number(b);
			var isDesc = false;
		    if(isDesc){
		      return a > b ? -1 : a < b ? 1 : 0;
		    }else{
		      return a < b ? -1 : a > b ? 1 : 0;
		    }
		}
	}

	var tx = f.area1.value;
	if (!tx) return false;
	if (f.lfcd.checked == true) {
		tx += "\n";
	}
	tx = tx.replace(/\r\n|\r|\n/g,"<br \/>");
	var stot = tx.split(/]<br \/>+/);
	var stot_len = stot.length;
	
	var per = [];
	var per_len = 0;
	var per_id = "";
	var per_tx = "";
	var link = "";
	var tag = "";
	var ary = new Array(stot_len);

	var matchs = [];
	var haba = f.haba.value;
	if ( haba != "" ) {
		haba = [' width="'+haba+'"'].join("");
	}
	var twitter_haba = f.haba.value - 40;

	if (f.like.checked == true) {
		var matome = [];
		for ( var i=0; i < stot_len; i++ ){
			matchs = stot[i].match(/^([^:]+):(.*)$/);
			
			if ( matchs != null ) {
				
				per_id = String(matchs[1]);
				per_tx = String(matchs[2]);

				number = per_tx.match(/statuse?s?\/(.*)$/);
				per_number = String(number[1]);

				a = per_tx.split("[h");
				b = a[1].split("]<br />");
				a[0] =	a[0].replace(/(https?:\/\/[-_\.!~a-zA-Z0-9;/?:@&=+$,%#]+)\s/g,'<a href="$1" target="_blank">$1</a> ');
				c =	a[0].replace(/@(\w{2,})\b/g,'@<a href="http://twitter.com/$1">$1</a> ');
				a =	c.replace(/(\s+)#(\w+)/g,' <a href="http://twitter.com/#search?q=%23$2">#$2</a> ');

				matome[i] = '<div class="matome-tweet" style="border-top:1px solid #f5f5f5;min-height:34px;padding-top:2px;clear:both;">\n';
				matome[i] += '<div class="matome-icon" style="float:left;margin-right:8px;">\n';
				matome[i] += '<a href="http://twitter.com/' + per_id + '"><img src="http://usericons.relucks.org/twitter/' + per_id + '" height="32" width="32" style="vertical-align:text-top;border-style:none;"></a>\n';
				matome[i] += "</div>\n";
				matome[i] += '<span class="matome-status-body" style="display:block;width:' + twitter_haba + 'px;overflow:hidden;margin-left:40px;">\n';
				matome[i] += '<div class="matome-status-content" style="font-size:0.9em;"><div class="entry-content">\n';
				matome[i] += '<strong><a href="http://twitter.com/' + per_id + '" class="screen-name" style="font-size:1.2em;color:#0099cc;text-decoration: none;">' + per_id + '</a></strong><br />';
				matome[i] += a;
				matome[i] += '\n</div></div>\n';
				matome[i] += '<div class="matome-status-data" style="font-size:small;">\n';
				matome[i] += '<div class="matome-published timestamp" style="line-height:120%;">\n';
				matome[i] += '<a class="matome-entry-date" href="h' + b[0] + '" style="color:#a9a9a9;float:right;">発言ページへ</a>';
				matome[i] += "\n</div></div>\n";
				matome[i] += "</span>\n";
				matome[i] += "</div>\n";
				
				ary[i] = [matome[i], per_number];
				ary[i][1] -= 0;

				if (tag.indexOf(per_id) == -1) {
					tag = [tag, "[", per_id, "]"].join("");
				}
			} else {
				matome[i] = "";
			}
		}
	}else{
		for ( var i=0; i < stot_len; i++ ){
			matchs = stot[i].match(/^([^:]+):(.*)$/);
			
			if ( matchs != null ) {
				
				per_id = String(matchs[1]);
				per_tx = String(matchs[2]);

				number = per_tx.match(/statuse?s?\/(.*)$/);
				per_number = String(number[1]);

				a = per_tx.split("[h");
				b = a[1].split("]<br />");
				a[0] =	a[0].replace(/(https?:\/\/[-_\.!~a-zA-Z0-9;/?:@&=+$,%#]+)\s/g,'<a href="$1" target="_blank">$1</a> ');
				c =	a[0].replace(/@(\w{2,})\b/g,'@<a href="http://twitter.com/$1">$1</a> ');
				a =	c.replace(/(\s+)#(\w+)/g,' <a href="http://twitter.com/#search?q=%23$2">#$2</a> ');

				stot[i] = [
					"<tr><td>",
					'<a href="http://twitter.com/', per_id, '"><img src="http://usericons.relucks.org/twitter/', per_id, '" height="32" width="32"></a></td><td>' + '<a href="http://twitter.com/', per_id, '">', per_id, '</a></td><td>',
					, a,'</td><td><a href="h' + b[0] + '">link</a></td></tr>'
				].join("");

				ary[i] = [stot[i], per_number];
				ary[i][1] -= 0;

				if (tag.indexOf(per_id) == -1) {
					tag = [tag, "[", per_id, "]"].join("");
				}
			} else {
				stot[i] = "";
			}
		}
	}

	var result = null;

	if (f.lfcd.checked == true && f.like.checked == false) {
		result = sortObj(ary);
		f.area2.value = ['<table', haba, ">\n", result.join("\n"), '\n</table>'].join("");
	} else if(f.lfcd.checked == false && f.like.checked == true) {
		f.area2.value = ['<div style="width:', f.haba.value, 'px;text-align:left;border-bottom:1px solid #f5f5f5;">\n', matome.join(""), '</div>'].join("");
	} else if(f.lfcd.checked == true && f.like.checked == true) {
		result = sortObj(ary);
		f.area2.value = ['<div style="width:', f.haba.value, 'px;text-align:left;border-bottom:1px solid #f5f5f5;">\n', result.join(""), '</div>'].join("");
	} else {
		f.area2.value = ['<table', haba, ">\n", stot.join("\n"), '</table>'].join("");
	}

	document.getElementById('pre').style.display = 'inline';
	document.getElementById('update').style.display = 'none';
	document.getElementById('sort').style.display = 'none';
	f.tag.value = tag;
	sample.innerHTML = "";
};