var gGiveawaysArr = Array();
var gGetting = false;
var gData = Object();
var gInitialShow = true; // show first grabbed items, without a fade in
var gIntervalID = 0;
var gHighlightedID = 0;
var gDoFast = true;
var gInfoTimeoutID = 0;
var gGiveawayMax = 50;
var gGiveawaysHere = Array();

var gShowingGives = false;

	$(document).ready(function(){
		
		// handle search bar
		var k_search = $("#k");
		if (k_search.val() == '')
		{
			k_search.val("Keyword Search");
			k_search.css("color","#d4d4d4");
		}
		else
		{
			k_search.css("color","#CCCCCC");
		}
		k_search.focus(function(){
								
									if (gNotSearched == true)
									{
										$("#k").val('');
										$("#k").css("color","#CCCCCC");
										gNotSearched = false;
									}
									else
									{
										$("#k")[0].select();	
									}
								});
		grab_giveaways(gKeyword, gWhich);
		startTimer();
		
	});
	function startTimer()
	{
		if (gIntervalID == 0)
		{
			gIntervalID = setInterval(function(){grab_giveaways(gKeyword,gWhich)},10000);	
		}		
	}
	function info_msg(msg)
	{
		// create the info message div
		if (gInfoTimeoutID)
		{
			// hide the current div
			var origDiv = $("#info_box");
			origDiv.fadeOut(300, function(){ $(this).remove(); });
			clearTimeout(gInfoTimeoutID);
		}
		var theDiv = $(document.createElement("div"));
		theDiv.attr("id","info_box");
		theDiv.hide();
		theDiv.html(msg);
		$("body").append(theDiv);
		
		gInfoTimeoutID = setTimeout(  "fade_info_msg()" , 1500);
		theDiv.fadeIn(500);
	
	}
	function fade_info_msg()
	{
		
		$("#info_box").fadeOut(500, function(){ $(this).remove(); });
		clearTimeout(gInfoTimeoutID);
		gInfoTimeoutID = 0;
	}
	function unhighlightDiv(id)
	{
		if (id > 0)
		{
			var oldDiv = $("#" + id);
					// get the old one and unhighlight it	
					if (oldDiv[0] != null)
					{
						oldDiv.animate({					
							  "backgroundColor" : "#FFFFFF"
							  },500,"linear");
					}
		}
		gHighlightedID = 0;
	}
	function clicked_give_away(e)
	{
			// highlight it and pause
			var theDiv = $(this);
			
			if (theDiv[0] != null)
			{
				if (gHighlightedID == theDiv.attr("id") )
				{
					// clicked on the highlighted item
					
						
					playUpdates();	
					gHighlightedID=0;
					
					info_msg("Live Updates Resumed");
					theDiv.attr("title" , "");
				}
				else
				{
					// clicked on a different highlighted item
					// highlight this	
					if (gHighlightedID > 0)
					{
						// unhighlight old one
						unhighlightDiv(gHighlightedID);
					}
					
					
					theDiv[0].oldBGColor = theDiv.css("backgroundColor");
					theDiv.animate({					
							  "backgroundColor" : "#ffff99"
							  },500,"linear");	
					
					gHighlightedID = theDiv.attr("id");
					pauseUpdates();	
					
					info_msg("Updates are paused");
					theDiv.attr("title" , "Click to Resume Updates");
					
				}
			}
			
			
	}
	function fadeInInitDivs()
	{		
		if (gGiveawaysArr.length > 0)
		{
			
			// go through each object and fade it in one after the other
			var twitter_obj = gGiveawaysArr.pop();
			
			// fade in fast
			var d = $("#" + twitter_obj.id);
			
			if (d[0] != null)
			{			
				d.fadeIn(100, fadeInInitDivs);
			}
			
		}
		else
		{
			// done with inits
			gInitialShow = false;	
		}
	}
	function doInitialShow()
	{
		
		for (var i=0; i<gGiveawaysArr.length; i++)
		{
			
			// go through each object and add it to dom
			var twitter_obj = gGiveawaysArr[i];
			
			// fade in fast
			var d = create_giveaway_div(twitter_obj);
			
			if (d[0] != null)
			{
				// prepend to top of list (NEWEST AT TOP)
				$("#give_aways").prepend(d);
			}
			
		}
		
		fadeInInitDivs();
		
		
		
		
		
	}
	function create_giveaway_div(twitter_obj)
	{
		// create the giveaway container			
			var m = $(document.createElement("div"));
			var theText = $(document.createElement("div"));
			theText.html(twitter_obj.text);
			theText.autolink();
			var retweet_link  =  "http://twitter.com/home/?status=" + escape("RT @twimme_com @" + twitter_obj.from_user + ": " + twitter_obj.text);

			m.html('<div class="twi_pic"><a href="http://www.twitter.com/' + twitter_obj.from_user + '" target="_blank"><img src="' + twitter_obj.profile_image_url + '" align="left" class="pic" height="48" width="48" /></a></div><div class="twi_right"><div class="twitter_title">' + theText.html() + '</div><div class="twitter_date">' + twitter_obj.created_at + ' <div class="retweet"><a href="' + retweet_link + '" target="_blank"><img src="graphics/rt.gif" width="21" height="17" border="0" alt="Re-Tweet" title="Re-Tweet"></a></div></div></div><div class="clear"></div>' );
			
			
			m.attr({
				   "class" : "give_away",
				   "id"	   : twitter_obj.id

				   });
			m.css("display","none");
			
			m.click(clicked_give_away);
			//m.autolink();
			
			
			
			// add to array to keep track, if we need to delete them
			gGiveawaysHere.push(twitter_obj.id);
			
			// are we over our giveaways?
			if (gGiveawaysHere.length >= gGiveawayMax )
			{
				// remove something at the bottom of the list
				// the oldest one is element [0]
				var toRemoveID = gGiveawaysHere[0];
				
				// remove it from array
				gGiveawaysHere.splice(0,1);
				
				// fade it out and delete it
				var theDiv = $("#" + toRemoveID);
				if (theDiv[0] != null)
				{
					theDiv.fadeOut(500, function(){ $(this).remove(); });
				}
			}
			return m;
		
	}
	function show_giveaway(twitter_obj, doFade)
	{
		// create the giveaway container			
			var m = create_giveaway_div(twitter_obj);
			
			if (m[0] != null)
			{
				// prepend to top of list (NEWEST AT TOP)
				$("#give_aways").prepend(m);
			
				// FADE IN
				if (doFade)
				{
					m[0].oldBGColor = m.css("backgroundColor");
					m.fadeIn(300);
					m.animate({						
							  "backgroundColor" : "#ffff99"
							  }, 
								500,
								"linear",
								function(){
									$(this).animate({ "backgroundColor" : "#FFFFFF" }, 500);
								});
					
				}
				else
				{
					m.show();
				}
			}
			
	}
	function show_giveaways_left()
	{
		if (gGiveawaysArr.length > 0)
		{
			gShowingGives = true;
			// go through each object and fade it in one after the other
			var twitter_obj = gGiveawaysArr.pop();
			
			// fade in fast
			var d = create_giveaway_div(twitter_obj);
			
			if (d[0] != null)
			{		
				
				//d.fadeIn(1000, show_giveaways_left);
				d.show();
				d.css("opacity" ,  0.0);

				$("#give_aways").prepend(d);
				
				d.animate({		
						  	   
						  	  "opacity" : 1.0 ,
							  "backgroundColor" : "#ffff99"
							  }, 
								750,
								"swing",
								function(){
									
									$(this).animate({ "backgroundColor" : "#FFFFFF" }, 500);
									show_giveaways_left();
								});
			}
			
		}
		else
		{
			gShowingGives = false;	
		}
		
	}
	function grab_giveaways(k,w)
	{
	
		// check if we have any in the queue
		if (gGiveawaysArr.length > 0 && gShowingGives == false)
		{
			//alert("popem");
			// pop one off and show it
			// show the rest of giveaways
			show_giveaways_left();
			
		}
		else if (gGetting == false)
		{
			// go fetch more from twitter
			
			get_giveaways(k,w);
		}
	}
	function get_giveaways(k, w)
	{
		gGetting = true;
		
		$.getJSON("search.json.php?since_id=" + gLatestID + "&k=" + k + "&w=" + w + "&best=" + gBest + "&callback=?", twitter_recv);
		
	}
	function twitter_recv(data)
	{
		//alert(data);
		if (data.results != null)
		{
			gData = data;
			//alert(data.results.length);
			for (var i= data.results.length-1; i >=0; i--)
			{			
				// slide content up		
				if (gInitialShow == true)
				{
					// just show them all without a fade
					
					gGiveawaysArr.push(data.results[i]);
					gDoFast = true;
				}	
				else
				{
					// queue them for later fade in slowly
					gGiveawaysArr.push(data.results[i]);
					gDoFast = false;
					
				}
				

				
				
			}
			if (data.latestID > 0)
			{
				gLatestID = data.latestID;
			}
			
			if (gInitialShow == true)
			{
				doInitialShow();			
			}
		
		}
		
			//$.scrollTo( '#' + gLatestID, 800 );
			gGetting = false;
		
		
	}
	
	function pauseUpdates()
	{
		clearInterval(gIntervalID);
		gIntervalID = 0;
		$("#play_stream").show();
		$("#pause_stream").hide();		
	}
	function playUpdates()
	{
		unhighlightDiv(gHighlightedID);
		startTimer();
		$("#play_stream").hide();
		$("#pause_stream").show();		
	}
/* addons to jQuery */
jQuery.fn.highlight = function (text, o) {
	return this.each( function(){
		var replace = o || '<span class="highlight">$1</span>';
		$(this).html( $(this).html().replace( new RegExp('('+text+'(?![\\w\\s?&.\\/;#~%"=-]*>))', "ig"), replace) );
	});
}
 
jQuery.fn.autolink = function () {
	return this.each( function(){
		var re = /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
		$(this).html( $(this).html().replace(re, '<a href="http://www.twimme.com/c.php?u=$1" target="_blank">$1</a> ') );
	});
}
 
