$(function(){

	var maxId = 0, liveInterval;
	var ids = null;
	initQueries();	

	function initQueries() {
		var queries = $('#queries .selected .query');
		var queriesLength = queries.length;
		if (queriesLength) {
			var random = Math.floor(Math.random() * queriesLength);
			loadTweets(queries.eq(random));
			
			queries.click(function(e){
				loadTweets($(this));

				e.preventDefault();
				e.stopPropagation();
			});
		}
	}

	function loadTweets(query) {
		ids = new Array();
		clearInterval(liveInterval);

		$('.query.selected').removeClass('selected');
		query.addClass('selected');

		var q = query.attr('data-query'), ul = $('#timeline ul');
		
		ul.html('<li id="ajax-loader"></li>');
		$.get('http://search.twitter.com/search.json', {'q': q, 'rpp': '30'}, function(data){
			
			var html = '';
			var added = 0;
			for (var i in data.results) {
				if (added == 10) {
					break;
				}
				var tweet = data.results[i];
				var content = getHtml(q, tweet);
				if (content !== false) {
					added++;
					ids.push(tweet.id);					
					html += content;
				}
			}
			maxId = data.max_id;
			ul.html(html).find('li').live('mouseover', function(){
				var obj = $(this);
				if (obj.attr('id') == 'ajax-loader') {
					return;
				}

				var id = obj.attr('data-id'),
						popup = $('#popup')
				;
				if (popup.attr('data-id') == id) {
					return;
				}
				popup.find('#p-sub-sub').html(obj.html());
				popup.attr('data-id', id);
			});
			$('#p-sub-sub').html(ul.find('li:first').html());
			$('#popup').show();
			
			liveInterval = setInterval(function(){
				if (q != $('.query.selected').attr('data-query')) {
					//console.log('reset happened');
					clearInterval(liveInterval);					
					return;
				}
				$.get('http://search.twitter.com/search.json', {'q': q, 'rpp': '3', 'since_id': maxId}, function(data){					
					//console.log(maxId);
					//console.log(ids);
					var html = '';
					for (var i in data.results) {
						var tweet = data.results[i];
						var content = getHtml(q, tweet, true);
						//console.log(tweet.id);
						
						//console.log(!$.inArray(tweet.id, ids));
						//console.log(content !== false);
						
						if (content !== false && $.inArray(tweet.id, ids) == -1 ) {
							maxId = tweet.id;
							ids.push(maxId);							
							html += content;
							break;
						}						
					}
					
					if (html != '') {
						ul.find('li').last().slideDown(600, function(){
							$(this).remove();
						});
						
						ids.shift();
						
						ul.find('li.new').removeClass('new');
						ul.prepend(html);

						var hidden = ul.find('.hidden');
						hidden.addClass('new');												
						$('#p-sub-sub').html(hidden.html());

						ul.find('.hidden').slideDown(600, function(){
							$(this).removeClass('hidden');
						});
					}
				}, 'jsonp');
			}, 15000);
		}, 'jsonp');
	}

	function getHtml(q, tweet, isHidden) {
		if (tweet.text.match(/fuck|asshole|cunt|cock|cocksucker|queer|fag|faggot|gay bash|homophob|lesbian|motherfucker|blowjob|fellatio|cunnil|dicking|tits|vagina|pussy/gi)) {
			return false;
		}
		var html = '';
		html += '<li data-id="' + tweet.id + '" class="' + (isHidden ? 'hidden ' : '') + '">';
		html += '<div class="t-image">';
		html += '<a href="http://twitter.com/' + tweet.from_user + '"><img src="' + tweet.profile_image_url + '" alt="' + tweet.from_user + '" width="48" height="48" /></a>';
		html += '</div>';
		html += '<div class="t-content">';
		html += '<a href="http://twitter.com/' + tweet.from_user + '" class="t-user">' + tweet.from_user + '</a> ';
		var text = tweet.text
								.replace(/(^|[\s()\[\]_:~+@*"'><])((?:https?|ftp|irc):\/\/)((?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:(?:[a-z\d]|[a-z\d][a-z\d-]*[a-z\d])\.)+[a-z]{2,6})(:\d+)?(\/(?:[-\w.!~*'()%:@&=+$,;\/]*[\w~*%@&=+$\/])?(?:\?(?:[-\w;\/?:@&=+$,.!~*'()%\[\]|]*[\w\/@&=+$~*%])?)?(?:#(?:[-\w;\/?:@&=+$,.!~*'()%]*[\w\/@&=+$~*%])?)?|\b)/ig, '$1<a href="$2$3$4$5">$2$3$4$5</a>')
								.replace(/@(\w+)\b/g, '<a href="http://twitter.com/$1">@$1</a>')
								.replace(/#(\w+)\b/g, '<a href="http://twitter.com/search?q=%23$1">#$1</a>')
		;
		text = doHighlight(text, q);
		html += '<span class="t-text">' + text + '</span>';
		html += '<div class="t-meta">';
		var createdAt = prettyDate(tweet.created_at);
		var source = tweet.source
									.replace(/&lt;/g, '<')
									.replace(/&gt;/g, '>')
									.replace(/&quot;/g, '"')
		;
		if (source.indexOf('href="http://') == -1 && source.indexOf('href="https://') == -1) {
			source = source.replace(/(href=")/, '$1http://twitter.com');
		}
		html += '<a href="http://twitter.com/' + tweet.from_user + '/status/' + tweet.id + '">about ' + createdAt + '</a> via ' + source;
		html += '</div>';
		html += '</div>';
		html += '</li>';
		return html;
	}

});

/*
 * http://ejohn.org/blog/javascript-pretty-date/
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Modified by splurov@gmail.com, 2010
 * Licensed under the MIT license.
 */
function prettyDate(time){
	var date = new Date(time),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return 'more than one month ago';

	return day_diff == 0 && (
			diff < 2 && "1 second ago" ||
			diff < 60 && Math.floor( diff ) + " seconds ago" ||
			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";
}

/*
 * (c) http://www.nsftools.com/misc/SearchAndHighlight.htm
 * Modified by splurov@gmail.com, 2010
 */
function doHighlight(bodyText, searchTerm) {
  // the highlightStartTag and highlightEndTag parameters are optional
	var highlightStartTag = "<strong>";
	var highlightEndTag = "</strong>";

  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();

  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }

  return newText;
}
