// get Twitter posts
$(function() {
	$.get('/twitter.json', {}, function(twits) {
		Array.prototype.in_array = function(el) {
			for(var i in this) {
				if (this.hasOwnProperty(i) && this[i] == el) {
					return true;
				}
			}

			return false;
		}

		Number.prototype.numericEndingsRussian = function(one, several, many) {
			count = this.toString();

			lastLetter       = count.substr(-1);
			secondLastLetter = count.length > 1 ? count.substr(-2, 1) : '0';

			if(secondLastLetter != 1) {
				if(lastLetter == '1') {
					return one;
				}

				if(['2', '3', '4'].in_array(lastLetter)) {
					return several;
				}
			}

			return many;
		}

		function diffString(diff, one, several, many) {
			return diff + ' ' + diff.numericEndingsRussian(one, several, many) + ' назад';
		}

		function timeDiffToString(time) {
			var diff =  Math.ceil((now - time.getTime()) / 1000);

			if(diff < 60) {
				return diffString(diff, 'секунду', 'секунды', 'секунд');

			} else if(diff < 3600)  {
				return diffString(Math.ceil(diff/60), 'минуту', 'минуты', 'минут');

			} else if (diff < 86400) {
				return diffString(Math.ceil(diff/3600), 'час', 'часа', 'часов');

			} else {
				return [
					time.getDate(),

					[
						'января',
						'февраля',
						'марта',
						'апреля',
						'мая',
						'июня',
						'июля',
						'августа',
						'сентября',
						'октября',
						'ноября',
						'декабря'
					][time.getMonth()],

					time.getFullYear()

				].join(' ');
			}
		}

		function matchLinks(text) {
			var matches = [];

			while((m = urlRe.exec(text)) != null) {
				matches.push(m);
				text = text.replace(m[0], '__URL' + matches.length + '__');
			}

			for(var i =0; i < matches.length; i++) {
				text = text.replace('__URL' + (i + 1) + '__', '<a href="' + matches[i] + '" target="_blank">' + matches[i] + '</a>');
			}

			return text;
		}

		var urlRe = new RegExp("http://[^\\s]+", 'g');

		var list  = $('<ul class="twitter-posts"></ul>');
		var now   = (new Date()).getTime();

		$.each(twits, function(i, twit) {
			var time = timeDiffToString(new Date(twit.created_at));

			list.append('<li>' + matchLinks(twit.text) + ' <span class="time">' + time + '</span></li>');
		});

		var hide = null;

		$('#twitter').append(list);

	}, 'json');
})