/* Utilities */
var input = document.getElementById('input');
var output = document.getElementById("output");
var iframe = document.getElementsByTagName("iframe")[0];
var permalink = document.getElementById("permalink");

function w(text) {
	output.innerHTML += text + '<br>';
}

function clearLog() {
	output.innerHTML = "";
}

function loadContent(data) {
	if (data == '') {
		iframe.src = "about:blank";
	} else {
		iframe.src = "http://html5.lachy.id.au/output?type=text/html&data=" + encodeURIComponent(data);
	}
}

function updatePermalink(data) {
	permalink.href = '?' + encodeURIComponent(data);
}

function update() {
	w(sniff(input.value));
	loadContent(input.value);
	updatePermalink(input.value);
}

/* Content Sniffing */

var s = '';
var pos = 0;

function sniff(input) {
	var type = null;
	pos = 0;
	s = input.slice(0, 512);
	while (s.charAt(pos) && !type) {
		switch (s.charAt(pos)) {
		case '\t':
		case ' ':
		case '\n':
		case '\r':
			pos++;
			break;
		case '<':
			pos++;
			if (findComment() || findMarkedSection() || findPI()) break; // Steps 6 to 8
			if (isAtom()) { // Step 9
				type = "application/atom+xml";
			} else if (isRSS() || isRDF()) {
				type = "application/rss+xml"
			} else {
				type = "text/html";
			}
			break;
		default:
			type = "text/html";
			break;
		}
	}
	return type || "text/html";
}

function isAtom() {
	return (s.substr(pos, 4) == "feed");
}

function isRSS() {
	return (s.substr(pos, 3) == "rss");
}

function isRDF() {
	// This is not yet fully implemented because it's not fully specced yet!
	return (s.substr(pos, 7) == "rdf:RDF");
}

function findComment() {
	if (s.substr(pos, 3) == "!--") { // 6
		pos += 3; // 6.1
		while (s.charAt(pos)) {
			if (s.substr(pos, 3) == "-->") { // 6.2
				pos += 3;
				break;
			}
			pos++; // 6.3
		} // 6.4
		return true;
	}
	return false;
}

function findMarkedSection() {
	if (s.charAt(pos) == '!') {
		pos++;
		while (s.charAt(pos) && s.charAt(pos++) != '>');
		return true;
	}
	return false;
}

function findPI() {
	if (s.charAt(pos) == '?') {
		pos++;
		while (s.charAt(pos)) {
			if (s.substr(pos, 2) == "?>") {
				pos += 2;
				break;
			}
			pos++;
		}
		return true;
	}
	return false;
}

window.onload = update;