$(document).ready(function(){
   	 
	/* a counter outside the context of setCountdown() */
	var timeleft = 0;

	var maxResults = 100;
	var keyword = ""; //default word
	var counter = 4; //keeps a count of the total number of tweets
	var tweetIndex = 0; //position of the index to pop
	var index = 0;
	var selectedIndex = 0;
	var i = 0;	
	
  	var urirex = /(https?):\/\/+([\w\d:#@%\/;$()~_?\+-=\\\.&]*)/g;
  	var hashrex = /\#+([\w\d:#@%/;$()~_?\+-=\\\.&]*)/g;
  	var thashuri = "http://search.twitter.com/search?q=%";
  			
	var $paneTarget = $('#pane-target'); //Declare the containing div of the scrolling elements
	$('ul.keywords a').click(function() {
    	var id = $(this).attr('id');
    	selectedIndex = id.replace('keyword','');
    	//keyword = '"'+$(this).text()+'"';  
      	keyword = $(this).text();  	 	
 		var target = $('#litwitter-container');
		$.scrollTo(target, 800);   	
	});
	
	//returns a case insenstive regex string for search and replacing.
	function preg_quote(str) {
    	return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
	}
	
	var array = new Array('');
	
	var offset = 0;
	$('ul.keywords li').each(function(index) {    	
    	/* set everything up */
  		var url="http://search.twitter.com/search.json?rpp="+maxResults+"&lang=en&callback=?&q=";
  		var query = escape($(this).text());
  		var display = '<div class="tweetDisplayContainer error"></div>';

  		var tweets = new Array();
  		
  		//$("#twitterresults").html('');

    	// go get the data, then parse it
    	$.getJSON(url+query,function(json){	
			if(json) {
				$.each(json.results,function(p,tweet){
					tweets[p] = tweet.text;
	    		});
			}
			array[index] = tweets;
    		$("#twitterresults").before(display);
    	});
    	i++;
  	});
	
	//update the timer display - if timer has reached then pop form array and scroll.
	var setCountdown = function() {
		timeleft--;
		
		//update keyword 
		keyword = $('#keyword'+selectedIndex).text();
		if(timeleft > 0) {
			//$("#countdown").html("scrolling in = " + timeleft + " & keyword = " + keyword + " & selectedIndex = " + selectedIndex);
		} else {
			//$("#countdown").html("scrolling in = " + timeleft + " & keyword = " + keyword + " & selectedIndex = " + selectedIndex);
			timeleft = 4;
			var color = ($('#keyword'+selectedIndex).css("color"));

				//if JSON object is not empty then
				if (array[selectedIndex][tweetIndex] != null){	
					//1. pop from the selected JSON object into the list of tweets
					var startpos = array[selectedIndex][tweetIndex].search(new RegExp(keyword, "ig"));
						//this replaces any http links in the tweet
						array[selectedIndex][tweetIndex] = array[selectedIndex][tweetIndex].replace(urirex, '<a href="$1://$2" title="" target="_blank">$2</a>');
						array[selectedIndex][tweetIndex] = array[selectedIndex][tweetIndex].replace(
						//search the tweet for a case insenstive match which it will replace 
						new RegExp(preg_quote(keyword), 'ig' ), 
						//replace the match with an anchor tag plus...
						'<a class="color" title="tweet" style="color: '+color+'">'+
						//plus the word as it was tweeted i.e not case sensitive
						array[selectedIndex][tweetIndex].substring(startpos, startpos+keyword.length)+
						//finally close the anchor tag
						'</a>'
					);
					
					//this replaces hash words
					//ttext = ttext.replace(hashrex, '<a href="' + thashuri  + '$1" title="">#$1</a>');
					
					count = counter+1;
					display =	
					'<div class="tweets" id="tweet'+count+'">'+
						'<p>' +
							array[selectedIndex][tweetIndex] +	
						'</p>' +
					'</div>';			
					
					$("#tweet"+counter).after(display);
					
					// select the next one in the list.
					var target = $('#tweet'+count);
					
					$paneTarget.stop().scrollTo(target, 800);
					counter ++;
					tweetIndex ++;
				}else{
				
					if (selectedIndex < $(".keywords li").size() -1){
						//alert('else yes');
						selectedIndex++;
						tweetIndex = 0;
					}else{
						//alert('else no');
						selectedIndex = 0;
						tweetIndex = 0;
					}
					//stop delaying the next tweet
					timeleft = 0;
					
				}
			
		}
	}

//getTweet();
setInterval(setCountdown, 1000);			

});
