var jvb = (function(jvb){
	var exports = jvb || {};


	/**
	*	Linkify URLs, @mentions and #hashtags
	*/
	exports.linkify = function(a){
		return a.replace(/[@#]\w+/g, function(b,c){
			c="twitter.com/";
			return b.link("//"+(b[a="search"]("#")?c:a+"."+c+a+"?q=")+b)
		})
		.replace(/((https?|s?ftp|ssh|www)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(d, e){
			return d.link(e);
		});
	};

	/**
	*	'Time ago'
	*/
	exports.relative_date = function(a,b,c){
		for(b=[1e3,60,60,24], a = new Date - a, c = 0; a > 2*b[c]; a /= b[c++]);
	
		return~~a+" "+"m0second0minute0hour0day".split(0)[c]+"s ago";
	}



	/**
	*	Micro templating. Godsend. (http://mir.aculo.us/2011/03/09/little-helpers-a-tweet-sized-javascript-templating-engine/)
	*/
	exports.t = function(string, d){
		for(var p in d)
			string = string.replace(new RegExp('{'+p+'}','g'), d[p]);
		return string;
	};
	
	return exports;

})(jvb);

(function(d, w){
	
	/* Prevent iPhone and iPad to autoscale the page when rotated (http://adactio.com/journal/4470/) */
	function preventAutoscale(){
		var viewportmeta = d.querySelector('meta[name="viewport"]');
		  if (viewportmeta) {
		    viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0';
		    d.body.addEventListener('gesturestart', function() {
		      viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
		    }, false);
		  }
	}
	
	/* Hide the address bar on iPhone */
	function hideAddressBar(){
		setTimeout(function(){
			w.scrollTo(0, 1);
		}, 100);
	}

	
	if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
		preventAutoscale();
		hideAddressBar();
	}
	
})(document, window);


$(function(){
	$(".post-nav a").addClass("button");
	
	var url = "https://api.twitter.com/1/statuses/user_timeline/johanbrook.json?count=1&callback=?",
		template = $("#twitter-template").html();
	$.getJSON(url, function(json){
		if(!json.error){
			var items = [];
			
			$.each(json, function(i, item){
				item.status = jvb.linkify(item.text);
				item.time_ago_in_words = jvb.relative_date(new Date(item.created_at));
				items.push(jvb.t(template, item));
			});
			
			$("#tweets ul").html(items.join(""));
		}
	});
	
	
	/* 	CLONE THE MAIN NAV AND CREATE SELECT ELEMENT

		To show for small screens.
		From: http://css-tricks.com/13303-convert-menu-to-dropdown/
	*/

	// Create the dropdown base
	var $nav = $("nav[role='navigation']"),
		$select = $nav.append("<select />").find("select");

	// Create default option "Go to..."
	$("<option />", {
	   "selected": "selected",
	   "value"   : "",
	   "text"    : "Go to .."
	}).appendTo($select);

	// Populate dropdown with menu items
	$("a", $nav).each(function() {
		var el = $(this);

		$("<option />", {
			"value"   : el.attr("href"),
			"text"    : el.text()
		}).appendTo($select);
	});

	$select.change(function() {
		window.location = $(this).find("option:selected").val();
	});
});
