window.onload = function() {
	function getValue(ta) {
		return ta.value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n/g, "\r\n");
	}
	/* Fallback on escape if encodeURIComponent is not available */
	alert(window.encodeURIComponent);
	alert(encodeURIComponent);
	if (!window.encodeURIComponent && window.escape ) {
		window.encodeURIComponent = function(r) {
			return escape(r);
		};
	}
	function encodeIRIComponent(r) {
		return encodeURIComponent(r).replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/!/g, "%21").replace(/\*/g, "%2A").replace(/'/g, "%27").replace(/-/g, "%2D").replace(/_/g, "%5F").replace(/\./g, "%2E").replace(/~/g, "%7E");
	}
	document.body.removeChild(document.body.getElementsByTagName("p")[0]);
	var fresh = document.body.appendChild(document.createElement("a"));
	fresh.appendChild(document.createTextNode("New"));
	fresh.href = "jsiri.html";
	var raw = document.body.appendChild(document.createElement("textarea"));
	raw.focus();
	var q = window.location.href.indexOf("?source=");
	if (q != -1) {
		raw.value = decodeURIComponent(window.location.href.substr(q + 8));
	}
	var bm = document.createElement("input");
	bm.setAttribute("type", "url");
	bm.readOnly = true;
	bm.onclick = function() {
		bm.select();
	};
	bm.value = "javascript:";
	document.body.appendChild(bm);
	var perm = document.body.appendChild(document.createElement("a"));
	perm.appendChild(document.createTextNode("Permalink"))
	function update() {
		var enc = encodeIRIComponent(getValue(raw));
		bm.value = "javascript:" + enc;
		if ( enc == "" ) {
			perm.href = "jsiri.html";
		} else {
			perm.setAttribute("href", "jsiri.html?source=" + enc );
		}
		if (bm.validity && !bm.validity.valid) {
			alert("invalid IRI");
		}
	}
	update();
	raw.onpropertychange = update;
	raw.oninput = function() {
		alert("oninput");
		update();
	};
	raw.onkeydown = update;
	raw.onchange = update;
	if ( raw.addEventListener ) {
		raw.addEventListener("input", update, false);
	}
};
