function $(id) {
	return $.cache[id] || ($.cache[id] = document.getElementById(id));
}
$.cache = {};


String.escapeRule = {
	'<' : '&lt;', '>' : '&gt;', '&' : '&amp;', '"' : '&quot;'
};
String.escapeFunc = function(r) { return String.escapeRule[r]; };
String.prototype.escapeHTML = function() {
	return this.replace(/[<>&"]/g, String.escapeFunc);
};

String.encodeRule = {
	'%' : '%25', '<' : '%3c', '>' : '%3e', '&' : '%26', '"' : '%22', ' ' : '%20'
};
String.encodeFunc = function(r) { return String.encodeRule[r]; };
String.prototype.urlEncode = function() {
	return this.replace(/[%<>&" ]/g, String.encodeFunc);
};


function queryToJSON() {
	var res   = {};
	var pairs = location.search.replace(/^[?&]*/, '').split('&');
	for (var i = 0, len = pairs.length; i < len; i++) {
		var pair = pairs[i].split('=');
		var key  = pair[0];
		if (key) res[decodeURIComponent(key)] = decodeURIComponent(pair[1] || '');
	}
	return res;
}

function trimText(str) {
	var buf = str.replace(/(^|\r\n?|\n)[ \t]*/g, '').split('"');
	var reg = /[ \t]*([,|&>+])[ \t]*/g;
	for (var i = 0, len = buf.length; i < len; i += 2)
		buf[i] = buf[i].replace(reg, "$1");
	return buf.join('"');
}

function generateButton() {
	var action = $('action').value;
	var label  = $('label').value;
	var anchor = $('identifier');
	if (/^[ \t]*opera:\/button\//.test(action)) {
		anchor.href = 'obe.htm?action=' + encodeURIComponent(action) + '&label=' + encodeURIComponent(label);
		action = trimText(action).urlEncode();
		label  = label.escapeHTML() || 'button';
		anchor.innerHTML      = label + ' (generated at ' + new Date().toLocaleString() + ')';
		$('result').innerHTML =
		$('htmlcode').value   = '<a href="' + action + '" title="' + label + '">' + label + '</a>';
	} else {
		anchor.href = 'obe.htm?action=opera%3A%2Fbutton%2F&label=button';
		anchor.innerHTML      = 'ボタン生成時の編集内容を再現する';
		$('result').innerHTML = '必ず「opera:/button/～」で始めてください！';
		$('htmlcode').value   = '生成したボタンのHTMLコード';
	}
}


document.forms[0][0].onclick = function() {
	var action = $('action');
	action.value = decodeURIComponent(action.value);
};

new function() {
	var opts = queryToJSON();
	if ('action' in opts) {
		$('action').value = opts.action;
		if ('label' in opts) $('label').value = opts.label;
		generateButton();
	}
};