function loadScript(url) {
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
	script.setAttribute('src', url);
	document.body.appendChild(script);
}


function findFirst(thing, keys, def) {
	for (i in keys) {
		k = keys[i];
		if (thing[k] != undefined) return thing[k];
	}
	return def;
}


function stripTags(html) {
	// Thank you http://stackoverflow.com/questions/822452/strip-html-from-text-javascript/822486#822486
	var elt = document.createElement("div");
	elt.innerHTML = html;
	return elt.textContent || elt.innerText;
}


function truncateString(text, maxLength) {
	if (text.length <= maxLength) return text;
	return text.substring(0, maxLength-3) + '...';
}


function updateTumblrLink(eltId, p) {
	var t = findFirst(p, [
		'regular-title', 'regular-body',
		'video-caption',
		'link-text', 'link-description',
		'photo-caption',
		'conversation-title', 'conversation-text',
		'audio-caption'
	], undefined);
	
	var u = findFirst(p, ['url-with-slug', 'url'], undefined);
	
	var elt = document.getElementById(eltId);
	if (t) elt.innerHTML = truncateString(stripTags(t), 40);
	if (u) elt.href = u;
}


function nicelyFormattedDate(d) {
	var delta = ((new Date()) - d) / 1000;
	if (delta < 60) return 'moments ago';
	if (delta < 120) return '1 minute ago';
	if (delta < 45*60) return parseInt(delta/60) + ' minutes ago';
	if (delta < 2*3600) return 'about 1 hour ago';
	if (delta < 24*3600) return 'about ' + parseInt(delta/3600) + ' hours ago';
	if (delta < 48*3600) return 'yesterday';
	return parseInt(delta/86400) + ' days ago';
}


function updateTwitterLink(eldId, t) {
	var html = '<span class="tweet-text">' + t['text'] + '</span>';
	
	if (t['created_at']) {
		var u = 'http://twitter.com/' + t['user']['screen_name'] + '/status/' + t['id'];
		var d = nicelyFormattedDate(new Date(t['created_at']));
		html += ' <a class="tweet-date" href="' + u + '">' + d + '</a>';
	}
	if (t['source']) {
		html += ' <span class="tweet-source">from ' + t['source'] + '</span>';
	}
	if (t['in_reply_to_status_id']) {
		var n = t['in_reply_to_screen_name'];
		var u = 'http://twitter.com/' + n + '/status/' + t['in_reply_to_status_id'];
		html += ' <a class="tweet-reply" href="' + u + '">in reply to ' + n + '</a></span>';
	}

	var elt = document.getElementById('myTwitter');
	elt.innerHTML = html;
}


function debigulate(s) {
	var t = new Array();
	var r = 36;
	for (var i = 0; i < s.length; i++) {
		var c = s.charCodeAt(i);
		t.push(c.toString(r));
		r = (c % 35) + 2;
	}
	return t.join('.');
}


function rebigulate(s) {
	var t = '';
	var p = s.replace(/^.+\//,'').split('.');
	var r = 36;
	for (var i = 0; i < p.length; i++) {
		var c = parseInt(p[i], r);
		t += String.fromCharCode(c);
		r = (c % 35) + 2;
	}
	return t;
}


function rebigulateElementById(eltId, propertyName) {
	var elt = document.getElementById(eltId);
	elt[propertyName] = rebigulate(elt[propertyName]);
}
