// by Lewis Lane
// Cool Blue Brand Communications
// http://www.coolblue.co.uk/

Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;
 
  now_threshold = parseInt(now_threshold, 10);
 
  if (isNaN(now_threshold)) {
	now_threshold = 0;
  }
 
  if (delta <= now_threshold) {
	return 'Just now';
  }
 
  var units = null;
  var conversions = {
	millisecond: 1, // ms -> ms
	second: 1000, // ms -> sec
	minute: 60, // sec -> min
	hour: 60, // min -> hour
	day: 24, // hour -> day
	month: 30, // day -> month (roughly)
	year: 12 // month -> year
  };
 
  for (var key in conversions) {
	if (delta < conversions[key]) {
	  break;
	} else {
	  units = key; // keeps track of the selected key over the iteration
	  delta = delta / conversions[key];
	}
  }
 
  // pluralize a unit when the difference is greater than 1.
  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
};
 
/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

window.ify = function() {
	var entities = {
			'"' : '&quot;',
			'&' : '&amp;',
			'<' : '&lt;',
			'>' : '&gt;'
	};

	return {
		"link": function(t) {
			return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a target="_blank" rel="nofollow" href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			});
		},
		"at": function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
				return m1 + '@<a target="_blank" rel="nofollow" href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
			});
		},
		"hash": function(t) {
			return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a target="_blank" rel="nofollow" href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
			});
		},
		"clean": function(tweet) {
			return this.hash(this.at(this.link(tweet)));
		}
	};
}();

function cycleTweets() {
	$("#tweets").css({marginTop: "-72px"}).prepend($("#tweets li:last")).animate({marginTop: 0}, "slow");
};

var cycleTweetsInterval;
var cyclePhotosInterval;

var items = [];

function checkIn() {
	if (items.length > 0) {
		items.sort(function() { return Math.round(Math.random()*8) - 4;});
		items.sort(function() { return Math.round(Math.random()*8) - 4;});
		items.sort(function() { return Math.round(Math.random()*8) - 4;});
		$("#socialboxes").empty();
		for (var i = 0; i < 18; i++) {
			$("#socialboxes").prepend('<li><a href="' + items[i].url + '"><img src="' + items[i].thumb + '" alt="' + items[i].title + '" /></a></li>')
		}
	}
}

$(function() {
	if ($("#tweetswrapper")) {
		$("#tweetswrapper").prepend('<ul id="tweets"><li class="loading">Loading...</li></ul><div class="fadebottom">&nbsp;</div>');
		$.getJSON("data.php?service=twitter&rpp=10&q=@teesvalleygiant%20OR%20%23temenos%20OR%20middlehaven%20-dead",
			function(data) {
				var results = data.results;
				$("#tweets").empty();
				if (results.length > 0) {
					for (var i = 0; i < results.length; i++) {
						$("#tweets").append($("<li />").append(
							'<div><a target="_blank" rel="nofollow" href="http://twitter.com/' + results[i].from_user + '">' + results[i].from_user + '</a>: '
							+ ify.clean(results[i].text)
							+ ' <span class="time">' + new Date(results[i].created_at).toRelativeTime(10) + '</span></div>'
							)
						);
					}
					clearInterval(cycleTweetsInterval);
					cycleTweetsInterval = setInterval(cycleTweets, 7000);
					$("#tweets").hover(function() {
						clearInterval(cycleTweetsInterval);
					}, function() {
						cycleTweetsInterval = setInterval(cycleTweets, 7000);
					});
				}
			}
		);
	}
	
	if ($("#photos") && ($("#photos .photo").length > 1)) {
		$("#photos").cycle({
			sync: 0,
			timeout: 5000,
			containerResize: 0,
			pause: false,
			slideExpr: "div.photo",
			cleartype: true,
			cleartypeNoBg: true					
		})
	}
	
	if ($("#flickrcompowrapper").length > 0) {
		$("#flickrcompowrapper").prepend('<ul id="flickrgallery"><li class="loading">Loading...</li></ul>');
		$.getJSON("http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&api_key=6408fce46143909c3ece097b86923649&group_id=1445296@N22&safe_search=1&content_type=1&per_page=36&format=json&jsoncallback=?", function(data) {
			var results = data.photos.photo;
			$("#flickrgallery").empty();
			for (var i = 0; i < results.length; i++) {
				$("#flickrgallery").append($("<li />").append(
				'<a target="_blank" rel="nofollow" href="http://www.flickr.com/photos/' + results[i].owner + '/' + results[i].id + '" alt="' + results[i].title + '">'
				+ '<img src="http://farm' + results[i].farm + '.static.flickr.com/' + results[i].server + '/' + results[i].id + '_' + results[i].secret + '_s.jpg" alt="' + results[i].title + '" />'
				+ '</a>'))
			}
		});
	}
	
	if ($("#flickrwrapper").length > 0) {
		$("#flickrwrapper").prepend('<ul id="flickrgallery"><li class="loading">Loading...</li></ul>');
		$.getJSON("http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&api_key=6408fce46143909c3ece097b86923649&group_id=1365392@N21&safe_search=1&content_type=1&per_page=16&format=json&jsoncallback=?", function(data) {
			var results = data.photos.photo;
			$("#flickrgallery").empty();
			for (var i = 0; i < results.length; i++) {
				$("#flickrgallery").append($("<li />").append(
				'<a target="_blank" rel="nofollow" href="http://www.flickr.com/photos/' + results[i].owner + '/' + results[i].id + '" alt="' + results[i].title + '">'
				+ '<img src="http://farm' + results[i].farm + '.static.flickr.com/' + results[i].server + '/' + results[i].id + '_' + results[i].secret + '_s.jpg" alt="' + results[i].title + '" />'
				+ '</a>'))
			}
		});
	}
	
	if ($("#socialbox")) {
		$("#socialbox").prepend('<ul id="socialboxes"><li class="loading">Loading...</li></ul>');
		$.getJSON("http://api.flickr.com/services/rest/?method=flickr.groups.pools.getPhotos&api_key=6408fce46143909c3ece097b86923649&group_id=1365392@N21&safe_search=1&content_type=1&per_page=16&format=json&jsoncallback=?", function(data) {
			var results = data.photos.photo;
			for (var i = 0; i < results.length; i++) {
				items.push({
					url: 'http://www.flickr.com/photos/' + results[i].owner + '/' + results[i].id,
					thumb: 'http://farm' + results[i].farm + '.static.flickr.com/' + results[i].server + '/' + results[i].id + '_' + results[i].secret + '_s.jpg',
					title: results[i].title,
					type: 'flickr'
				});
			}
			checkIn();
		});
		
		$.getJSON("data.php?service=twitter&rpp=10&q=@teesvalleygiant%20OR%20%23temenos%20OR%20middlehaven%20-dead", function(data) {
			var results = data.results;
			for (var i = 0; i < results.length; i++) {
				items.push({
					url: 'http://twitter.com/' + results[i].from_user + '/status/' + results[i].id,
					thumb: results[i].profile_image_url,
					title: results[i].from_user,
					type: 'tweet'
				});
			}
			checkIn();
		});
	}
});
