var fromuser = new Array;
var fromors = new Array;
var currentIds = new Array;
var lastid = 0;
var browserheight = 0;
var originalKeywords = '';


$(document).ready(function(){

	//initial resize
	var newWindowHeight = $(window).height() - 150;
	$("#tweet-container").height(newWindowHeight);
	//resize #tweet-container on window resize
	$(window).bind("resize", resizeWindow);
	function resizeWindow( e ) {
		var newWindowHeight = $(window).height() - 150;
		$("#tweet-container").height(newWindowHeight);
	}
	
	originalKeywords = jtweet_keywords;

	append_keywords();
	create_query();	
	keywordHover();
	// get our feeds
	getfeed_fromors(fromors, lastid);
	
});

function getfeed_fromors(fromors_l, lastid_l){
	
	$.ajax({
	type: "GET",
	url: "http://search.twitter.com/search.json?q=" + jtweet_keywords + "&rpp=8&callback=?",
	//url: 'http://search.twitter.com/search.json?q=wordpress+OR+"and+then"&rpp=8&callback=?',
	dataType: "json",
	success: function(json){
		/* Parse JSON objects */
		var k = 0; //counter for fromors
		$.each(json.results, function(i, item){
			
			displayId = true;
			for(var j=0;j<currentIds.length;j++) { 
				// I'm testing to see if this ID was displayed before
				if (currentIds[j] == item.id) { displayId = false; } 	
			}
			
			//if (lastid < item.id) {
			if (displayId) {
				fromors_l[k] = ['', '', '', '']
				if (item.profile_image_url != "undefined") {
					fromors_l[k][0] = item.profile_image_url;
				}
				if (item.from_user != "undefined") {
					fromors_l[k][1] = item.from_user;
				}
				if (item.text != "undefined") {
					fromors_l[k][2] = item.text;
				}
				if (item.created_at != "undefined") {
					fromors_l[k][3] = item.created_at;
				}
				k++;
			}
			
			currentIds.push(item.id) // I'm adding all of the current id's to an array
			
			
		}); //end $.each
					
		append_tweets(fromors_l);
		
		while(fromors.length>0){
			fromors.pop(); //we're emptying the json array
		}
		
		setTimeout("getfeed_fromors(fromors, lastid)", 3000);
	} //end success
	});// end fromors ajax			
	
}


function scrollToBottomOfdiv(divName) {
	var height = $(divName).top;
}

function append_tweets(tweetarray)
{
	var str ='';

	var container = $('#tweet-container');

	for(var j=tweetarray.length-1;j>-1;j--) {
		str = str + '<div class="tweet" style="display:none;">\
					<!--<div class="avatar"><a href="http://twitter.com/' + tweetarray[j][1] + '" target="_blank"><img src="' + tweetarray[j][0] + '" alt="' + tweetarray[j][1] + '" /></a></div>-->\
					<!--<div class="time">' + relativeTime(tweetarray[j][3]) +'</div>-->\
					<div class="txt">' + formatTwitString(tweetarray[j][2]) +	'</div>\
					<div class="user"><a href="http://twitter.com/' + tweetarray[j][1] + '" target="_blank">—' + tweetarray[j][1] + '</a></div>\
					</div>';
	}
	
	container.append(str);

	$('.tweet').fadeIn('slow');
	height = container[0].scrollHeight;
	container.animate({scrollTop: height}, 2000); 
}
function create_query(){
	txt = jtweet_keywords.split("+");
	
	for (i in txt) {
		   f = txt[i].search(/\w*\s\w*/)
		   if (f!=-1)
		   {
				   txt[i] = '"'+txt[i]+'"'
		   }
	}
	jtweet_keywords = txt.join("+OR+");
	//alert(jtweet_keywords);
}

function append_keywords()
{
	var container = $('#tweet-keywords');
	keywordsArr = jtweet_keywords.split("+");
	
	str = '<ul>';
	for(var j=0;j<keywordsArr.length;j++){
		str = str + '<li>' + keywordsArr[j] + '</li>';		
	}
	str = str + '</ul>';
	container.append(str);
	
}
function checkIfBanned(username){
	
	bannedUsers =jtweet_excluded_users.split("+");
	
}

function formatTwitString(str)
{
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\-\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
	return str;
}

function formate_date(pastTime)
{
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	
	var difference = parseInt((currentStamp - origStamp)/1000);
	return difference;
}

function relativeTime(pastTime)
{	
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) return false;

	if(difference <= 5)				return "Just now";
	if(difference <= 20)			return "Seconds ago";
	if(difference <= 60)			return "A minute ago";
	if(difference < 3600)			return parseInt(difference/60)+" minutes ago";
	if(difference <= 1.5*3600) 		return "One hour ago";
	if(difference < 23.5*3600)		return Math.round(difference/3600)+" hours ago";
	if(difference < 1.5*24*3600)	return "One day ago";
	
	var dateArr = pastTime.split(' ');
	return dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
}


function keywordHover(){
	var keyList = $("#tweet-keywords ul li");
	$.each(keyList, function(i, item) {
			var currentPlus = "pluskey-" + i;
			var currentMinus = "minuskey-" + i;

			var currentKeyword = $(this).html();
			
			//$(item).append('<span class="plusminus"><a href="#" name="'+ currentKeyword +'" class="" id="'+ currentPlus +'">+</a> <a href="#" name="'+ currentKeyword +'" id="'+ currentMinus +'">-</a></span>');
			$(this).append('<span class="plus">+</span><span class="minus">-</span>');
			
			$(item).attr("name", function(){
					return currentKeyword;
			});
			$(item).attr("display", function(){
					return "yes";
			});
			
			$(item).click( function () {
					if ($(this).attr("display") == "yes")
					{
						
						jtweet_keywords = originalKeywords;
						
						var txt = jtweet_keywords.split("+");
						var newtxt = new Array; 
						k = 0;
						for (i in txt) {
							if ( txt[i] != $(this).attr("name") ) {
								//alert ('eureka!');
								newtxt[k] = txt[i];
								k+=1;
							}
						}
						jtweet_keywords = newtxt.join('+');
						originalKeywords = jtweet_keywords;
						create_query();
						$(this).addClass("removedKeyword");
						$(this).children(".plus").show();
						$(this).children(".minus").hide();
						$(this).attr("display", "no");
						
					} else {
						
						jtweet_keywords = originalKeywords;
						
						var txt = jtweet_keywords.split("+");
						var donotadd = false;
						for (i in txt) {
							if ( txt[i] == $(this).attr("name") ) {
								//alert ('eureka!');
								donotadd = true;
							}
						}
						if (!donotadd) {
							var addtotxt = new Array;
							addtotxt[0] = $(this).attr("name"); 
							$.merge(txt, addtotxt);
						}
						jtweet_keywords = txt.join('+');
						originalKeywords = jtweet_keywords;
						create_query();
						$(this).removeClass("removedKeyword");
						$(this).children(".plus").hide();
						$(this).children(".minus").show();
						$(this).attr("display", "yes");
					}
			});				
	

			
	});

	$("#tweet-keywords ul li").hover(function(){ 
			$(this).addClass("hover");
			
			if ($(this).attr("display") == "yes")
			{
				$(this).children(".minus").show();
			} else {
				$(this).children(".plus").show();	
			}
	},function(){ 
		$(this).removeClass("hover");
		$(this).children(".plus").hide();
		$(this).children(".minus").hide();
	});

}


