$(document).ready(function() {
	
	t.load();
	t.loadPosts();
	
	$(window).bind('scroll', function () {
		t.observer();
	});
	
});

var t = {
	offset: 	0,   // items offset (start with)
	items: 		5,   // items limit
	extraWidth: 300, // px - starts loading next bunch of data when user reach Npx to the end of the page
	loadingBox: false,
	types: 		['video', 'photo', 'audio', 'link'],
	
	observer: function() {
		// keeping eye on the horizontal scrolling
		xScroll = $(window).scrollLeft() + t.getWindowWidth() - $('#right-wrapper').offset().left;
		if (xScroll + this.extraWidth >= parseInt($('#right-wrapper').css('width').replace('px', ''))) {
			this.load()
		}
		//console.debug(xScroll);
	},
	loadPosts: function() {
		var uri = 'http://pr0jects.tumblr.com/api/read/json?type=text&num=15';
		$.getScript(uri, function() {
			t.build(tumblr_api_read.posts);
		});
	},
	load: function() {
		if (this.loadingBox) {
			return;
		}
		
		this.showLoadingBox();
		for (var i = 0; i < this.types.length; i++) {
			var uri = 'http://pr0jects.tumblr.com/api/read/json?start=' + this.offset + '&num=' + this.items + '&type=' + this.types[i];
			$.getScript(uri, function() {
				t.build(tumblr_api_read.posts);
			});
		}
		
		this.offset += this.items;
	},
	build: function(data) {
		this.hideLoadingBox();
		
		if (data.length < this.item) {
			window.unbind('scroll');
		}
		
		$.each(data, function(i, e) {
			if (e.type == 'photo') {
				var li = $('<li class="photo-post" />').appendTo('#photos');
				
				var a = $('<a rel="prettyPhoto" />').appendTo(li).attr('href', e['photo-url-500']);
				var img = $('<img alt="preview" class="preview" />').appendTo(a).attr('src', e['photo-url-250']);
				
				var right = $('<div class="photo-right" />').appendTo(li);
				$('<p class="photo-posted" />').appendTo(right).html(t.getDateTime(e));
				
				/*	
				var reblog = $('<div class="photo-reblog" />').appendTo(right);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img width="35" height="12" alt="reblog" src="http://c0170141.cdn.cloudfiles.rackspacecloud.com/pictures-reblog.png" />').appendTo(a);
				
				var like = $('<div class="photo-like" />').appendTo(right);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="like" src="http://assets.tumblr.com/images/like.png" />').appendTo(a);
				*/
			
				$('<div class="photo-caption" />').appendTo(right).html(e['photo-caption']);
			} else if (e.type == 'video') {	
				var li = $('<li class="video-post" />').appendTo('#videos');
				var caption = $('<div class="video-caption" />').appendTo(li).html(e['video-caption']);
				var video = $('<div class="video" />').appendTo(li);
				
				// hack.. no?
				var embed = e['video-player'];
				// vimeo
				embed = embed.split('width="400"').join('width="250"');
				embed = embed.split('height="300"').join('height="187"');
				// youtube
				embed = embed.split('width="250"').join('width="250"');
				embed = embed.split('height="336"').join('height="187"');
				video.html(embed);
				
				var p = $('<p class="video-posted" />').appendTo(li).html(t.getDateTime(e));
				
				/*
				var reblog = $('<div class="video-reblog" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="reblog" src="http://c0170141.cdn.cloudfiles.rackspacecloud.com/video-reblog.png" />').appendTo(a);
				
				var like = $('<div class="video-like" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="like" src="http://assets.tumblr.com/images/like.png" />').appendTo(a);
				*/
			} else if (e.type == 'audio') {
				var li = $('<li class="audioposts-post" />').appendTo('#audios');
				var audio = $('<div class="audioplayer" />').appendTo(li).html(e['audio-player']);
				var caption = $('<p class="audio-caption" />').appendTo(li).html(e['audio-caption']);
			} else if (e.type == 'link') {
				var li = $('<li class="links-post" />').appendTo('#links');
				var link = $('<a class="link" target="_blank" />').appendTo(li).attr('href', e['link-url']).html(e['link-text']);
				var descr = $('<div class="link-description" />').appendTo(li).html(e['link-description']);
				
				/*
				var like = $('<div class="links-like" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="like" src="http://assets.tumblr.com/images/like.png" />').appendTo(a);
				
				var reblog = $('<div class="links-reblog" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="reblog" src="http://c0170141.cdn.cloudfiles.rackspacecloud.com/links-reblog.png" />').appendTo(a);
				*/
			} else if (e.type == 'regular') {
				var li = $('<li />').appendTo('#posts');
				var title = $('<h3 />').html(e['regular-title']).appendTo(li);
				var date = $('<p class="post-posted" />').appendTo(li).html(t.getDateTime(e));
				var text = $('<p />').appendTo(li).html(e['regular-body']);
				
				/*
				var like = $('<div class="posts-like" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="like" src="http://assets.tumblr.com/images/like.png" />').appendTo(a);
				
				var reblog = $('<div class="posts-reblog" />').appendTo(li);
				var a = $('<a />').appendTo(li).attr('href', '#');
				var img = $('<img alt="reblog" src="http://c0170141.cdn.cloudfiles.rackspacecloud.com/post-reblog.png" />').appendTo(a);
				*/
			} else {}
		});
		
		//huh?
		$("a[rel^='prettyPhoto']").prettyPhoto({
						animationSpeed: 'fast', /* fast/slow/normal */
						padding: 40, /* padding for each side of the picture */
						opacity: 0.50, /* Value betwee 0 and 1 */
						showTitle: true, /* true/false */
						allowresize: true, /* true/false */
						counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
						theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
						callback: function(){}
					});
		
		
		
		this.adjustContentBoxWidth();
	},
	getWindowWidth: function() {
		var windowWidth;

		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth) {
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
		}	
		
		return windowWidth;
	},
	adjustContentBoxWidth: function() {
		var widths = [];
		
		$.each($('#right-wrapper ul'), function (j, ul) {
			var width = 0;
			$.each($(ul).find('li'), function(i, li) {
				width += parseInt($(li).css('width').replace('px', ''));
				width += parseInt($(li).css('marginRight').replace('px', ''));
				width += parseInt($(li).css('marginLeft').replace('px', ''));
				width += 2; // border?
			});
			// 30px is value that should cover all possible width additions to the content box such as borders etc.
			widths[widths.length] = width + 30;
			//console.debug('width: ' + (width + 30));
		});
		
		var maxWidth = 0;
		
		for (var i = 0; i <= widths.length; i++) {
			if (maxWidth < widths[i]) {
				maxWidth = widths[i];
			}
		}
		//console.debug('max width: ' + maxWidth);
		$('#right-wrapper').css('width', maxWidth);
		
		$('#videos, #links, #audios, #photos').css('width', maxWidth - 30);
	},
	showLoadingBox: function() {
		this.loadingBox = $('<li />').appendTo('.photo');
		$('<p />').html('LOADING...').appendTo(this.loadingBox);
		this.adjustContentBoxWidth();
	},
	hideLoadingBox: function() {
		//this.loadingBox.delete();
		this.loadingBox = false;
	},
	getDateTime: function(e) {
		var date = new Date();
		date.setTime(parseInt(e['unix-timestamp']) * 1000);
		//{DayOfWeek}, {DayOfMonth}{DayOfMonthSuffix} of {ShortMonth} {ShortYear} | {TimeAgo}
		return date.format('l, jS') + ' of ' + date.format('M y') + ' | ' + prettyDate(date);
	}
}




Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(origDate){
	/* var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")), */
	var date = origDate,
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
