/**
*	Custom Javascript functions
*
*/

$(function($){
	
	// Hide the address bar on iPhone
	setTimeout(function(){
		window.scrollTo(0, 1);
	}, 100);
	
	
	// Make a new grid overlay. See js/jquery.hashgrid.js for additional options
	var grid = new hashgrid();
	
	$(".post footer a:not(.post footer .aligncenter a)").truncate({limit: 20});
	
	// Set up smooth scrolling to text anchors
	//$("a").smoothScroll();	
	
	
	// Get latest Twitter update:
	var settings = {
		username: "emwebe",
		url: "http://twitter.com" + this.username,
		urlJSON: "http://api.twitter.com/statuses/user_timeline/"
	},
		url = settings.urlJSON + settings.username + ".json?count=1&callback=?";
	
	$.ajaxSetup({ cache: true });
	
	$.getJSON(url, function(tweets){
		if(tweets){
			var tweet = tweets[0],
				status = tweet.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
			                        return '<a href="'+url+'">'+url+'</a>';
			                    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
			                        return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
			                    });
			
			$("<p />", {
				"id": "latest-tweet",
				html: "<small>Senaste tweet från <a href='http://twitter.com/emwebe'>@emwebe</a></small><span class='tweet-content'>" + status + "</span>" + "<a class='tweet-link' href='http://twitter.com/statuses/"+ tweet.id + "'>" + time_ago(tweet.created_at) + "</a>"
			}).appendTo("aside#countdown").hide().fadeIn("slow");
		}
	});
	
	
	
});


function hobbit(){
	var countdown = $("#countdown"),
		hobbit = new Date(2012, 12-1, 19, 00, 00, 00),
		today = new Date(),
	
		expiry_text = '<strong id="complete">"The Hobbit" har släppts. See ya in the cinema ...</strong>';
	
	if(hobbit.getTime() >= today.getTime() ){
	
		countdown.find("#data").countdown({
			until: hobbit,
			layout: '{dn} dagar och {hn} timmar',
			onExpiry: function(){
				setTimeout(function(){
					countdown.fadeOut("fast", function(){
						setTimeout(function(){
							countdown.html(expiry_text).fadeIn("slow");
						}, 1000);
					});
				}, 1000);
				countdown.countdown("destroy");
				$("#countdownscript").remove();
			}
		});
	}else{
		countdown.html(expiry_text);
	}
}


function time_ago(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'mindre än en minut sedan';
    } else if(delta < 120) {
        return 'ungefär en minut sedan';
    } else if(delta < (60*60)) {
        return (parseInt(delta / 60)).toString() + ' minuter sedan';
    } else if(delta < (120*60)) {
        return 'ungefär en timme sedan';
    } else if(delta < (24*60*60)) {
        return 'ungefär ' + (parseInt(delta / 3600)).toString() + ' timmar sedan';
    } else if(delta < (48*60*60)) {
        return 'för 1 dag sedan';
    } else {
        return (parseInt(delta / 86400)).toString() + ' dagar sedan';
    }
}


(function($) {
	
	/**
	*	A simple jQuery I wrote to truncate long links (in the post footers, amongst others).
	*
	*	Usage:
	*	$("a.long-links").truncate( [ {limit: 40, truncationText: "..."} ] );
	*
	*/

	$.fn.truncate = function(options) {
		
		var settings = {
			limit: 40,
			truncationText: "..."
		};
		
		
		return this.each(function(){
			
			var chars,
				i,
				$this = $(this),
				str = $this.text();
			
			if(options){
				$.extend(settings, options);
			}
			
			chars = str.split('');
			
			if (chars.length > settings.limit) {
				for (i = chars.length - 1; i > -1; --i) {
					if (i > settings.limit) {
						chars.length = i;
					}
					else if (' ' === chars[i]) {
						chars.length = i;
						break;
					}
				}
				chars.push(' '+settings.truncationText);
			}
			
			$this.text(chars.join(''));
			
		});
		
	
	};
	
}) (jQuery);
