//// ADS
window.announce_url = '';

window.speedfactor = 2000;
adthresh = 40;
nextAdColumn = 0;
ads = [];
ad1 = {title:'Clicky Web Analytics',description:'Clicky Web Analytics is simply the best way to monitor, analyze, and react to your blog or web site\'s traffic in real time.',img:'http://monitter.com/ads/but_clicky.png',link:'http://getclicky.com/32179',linktext:'Try Clicky FREE!'}; 

ad2 = {title:'Advertise with Monitter',description:'We get over half a million impressions a month! All of them are social media junkies and internet gurus! Tap into that pool!',img:'http://monitter.com/ads/but_monitter_advertise_here.gif',link:'mailto:ads@monitter.com?subject=I want to advertise on monitter.com',linktext:'Advertise with Monitter'};

ad3 = {title:'Save $$$ on your Cell Phone Bill',description:'Tired of being overcharged on your cell phone bill? Over 65% of consumers over pay their carrier! Signup for our Affiliate Program and make extra $$$.',img:'http://monitter.com/ads/but_onlinebillreview.png',link:'http://www.onlinebillreview.com',linktext:'Get your FREE Online Bill Review Now!'};

// LIVE ON June 5 - 30 days.
//ad5 = {title:'Fix Your Enterprise&nbsp;Spam!',description:'port25 solutions provide advanced email software for ESPs and Enterprises.',img:'http://monitter.com/ads/ad_port25.gif',link:'http://www.port25.com',linktext:'Evalutate Now!'};


// LIVE ON 
ad6 = {title:'Hot Deal Alert! - Click Here',description:'See the newest freebies, deals, and coupons from all your favorite stores, brands, and restaurants.',img:'http://monitter.com/ads/ad_spoofee.png',link:'http://www.spoofee.com/index.php?ref=monitter',linktext:'View Here'}

ad4 = {title:'<form  target="_blank" class="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_s-xclick"><input type="hidden" name="hosted_button_id" value="5091474"><input class="img"  type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"></form>Keep Monitter Alive!',description:'Monitter is a free service.. however it costs us money to maintain. If you like it - consider donating via paypal :) It\'s good for your karma AND you\'ll help us&nbsp;eat!',img:false,link:false,linktext:'Donate via Paypal'};

ad7 = {title:'Is pot the new pilates?',description:'Find out what the smartest moms on Twitter think about pot. Join the discussion at Twittermoms.com.',img:'http://monitter.com/ads/but_twittermoms.jpg',link:'http://www.twittermoms.com/forum/topics/mothers-little-helper-pot?utm_source=monitter&utm_medium=Injected%2BFeed%20Advert&utm_term=Pot&utm_content=See%2Bwhat%20the%20TwitterMoms%20think&utm_campaign=Testmon1',linktext:'Join the discussion!'};

// END DATE:  April 11 2010
ad8 = {title:'Search Your Way',description:'Web, Youtube, RealTime, News results all on 1 page. Plus toggle between search engines YOU want and you skin the background with your Favorite pic.',img:'http://monitter.com/ads/favitt.png',link:'http://favitt.com/',linktext:'Join Now it\'s free!'};
 
ads.push(ad1);
//ads.push(ad8);
//ads.push(ad7);
//ads.push(ad6);
//ads.push(ad5);
ads.push(ad2);
//ads.push(ad3);
ads.push(ad4);

current_ad = 0;
function getNextAd()
{
	current_ad++;
	if(current_ad >= ads.length)
		current_ad = 0;
		
	return(ads[current_ad]);
}

window.trend_terms = [];
window.nextterm = 'obama';
cookie_expires = { expires: 30 }
function setActiveStyleSheet(title) 
{
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) 
   {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) 
     {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
   $.cookie('monitter_style',title, cookie_expires);
}

// Twitter stream js:
jQuery.fn.reverse = Array.prototype.reverse;
String.prototype.linkify = function() 
{
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) 
  {
  	m = m.link(m);
  	m = m.replace('href="','target="_blank" href="');
  	return m;
  });
};



String.prototype.linkuser = function() 
{
  return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(us) 
  {
    var username = us.replace("@","");
    
    us = us.link("http://twitter.com/"+username);
  	us = us.replace('href="','target="_blank" onclick="loadProfile(\''+username+'\');return(false);"  href="');
    return us;
  });
};

String.prototype.linktag = function() 
{
  return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) 
  {
    var tag = t.replace("#","%23");
    t = t.link("http://summize.com/search?q="+tag);
  	t = t.replace('href="','target="_blank" href="');
  	return t;
  });

}; 
window.tweetcount = 0;
window.locationurl = '';
window.locationstr = [];

window.ignorelist = [];;
window.searchers = [];
window.geocoding = [];
window.inputtimeout = [];

window.geocodes= {};

window.locations = [];
window.twitter = {};


window.tweetstack = []

function logTweetCount()
{
		try
		{
			var clicky_pause_timer = 200;
			clicky.log('#TWEETCOUNT','TWEETS:'+window.tweetcount);
			var clicky_pause_timer = 500;
			
		} catch(e){}
			
}

function fetch_as_many_as_possible(x)
{
	//alert('fetchas'+x);
	// Gather the location information:

	if(window.tweetstack[x].length > 10)
	{
		clearTimeout(window.searchers[x]);
		window.searchers[x] = setTimeout('fetch_as_many_as_possible('+x+')', 30000);
		//alert('delaying reget because our queue is big!');
		return(false);
	}
	// get the search:
	var searchstring = $('#col'+x+'input').val();
	//window.twitter['text'+x] = searchstring;
	$.cookie('box'+x,searchstring,cookie_expires);
	
	var searchurl = '';
	if(searchstring != '')
		searchurl = 'q='+searchstring.replace('#','%23');
		
	var langstr = '';
	if($('#language').val())
		langstr = "&lang="+$('#language').val();
	
	var since = window.twitter['last_id'+x];
	var rpp = '';
	if(since == 0)
	{
		rpp = '&rpp=10';
	}
	else
	{
		rpp = '&rpp=100';
	}
	since = since +rpp;
	
	// LOCATION SUPPORT:
	var locationstr = $('input#location').val();
	var locationurl = '';
	if(window.geocodes[locationstr] != 'loading' && window.geocodes[locationstr] != undefined)
	{
		point = window.geocodes[locationstr];
		window.locationurl = '&geocode='+point.lat()+','+point.lng()+','+$('#locationradius').val()+$('#locationunits').val();		
	//	alert(point+' is the geo');
	//	alert(window.geocodes[locationstr]);
	}
	
	// Let's add support for ignoring users!
	$(window.ignorelist).each(function(i,item)
	{
		searchurl += ' -from:'+item;
	});
	var url = "http://search.twitter.com/search.json?"+searchurl+window.locationurl+langstr+"&since_id="+since+"&callback=?";
	//alert(url);
	//alert(url);

	$.getJSON(url, function(json)
	{
		$(json.results).reverse().each(function() {
			if(!window.tweetstack[x])
				window.tweetstack[x] = [];
			window.tweetstack[x].push(this);
		});
		
		// OK, now requeue this for another 30 seconds:
		clearTimeout(window.searchers[x]);
		window.searchers[x] = setTimeout('fetch_as_many_as_possible('+x+')', 30000);		
	});
}

function showAd()
{
	var colcount = $('div#tweeters div.column').length;

	nextAdColumn++;
	if(nextAdColumn >= colcount)
		nextAdColumn = 0;
		
	
	var ad = getNextAd();
	var imgstr = '';
	if (ad.img != false)
		imgstr = '<a target="_blank" onclick="clicky.log(\'LINKOUT: '+ad.link+'\');" href="'+ad.link+'"><img src="'+ad.img+'" /></a>';
	
	var linkstr = '';
	if(ad.link != false)
		linkstr = '<a target="_blank" href="'+ad.link+'">'+ad.linktext+'</a>';
	
	var titlestr = ad.title;
	if(ad.link != false)
		titlestr = '<a href="'+ad.link+'" target="_blank">'+ad.title+'</a>'
	
	var adstring = '<div class="ad">'+imgstr+'<h3>'+titlestr+'</h3><p>'+ad.description+'<br />'+linkstr+'</p></div>';


	$('#col'+nextAdColumn+' div.ad').remove();
	$('#col'+nextAdColumn+' .tweets').prepend(adstring);
	clicky.log('AD: '+ad.title,ad.link);
	
	//setTimeout(function(){$('#col'+nextAdColumn+' div.ad').fadeOut();}, 1000*45);
}

function addTweet(tweet,x)
{
	//console.log('adding'+x);
	if($('#col'+x+' .tweets #tw'+tweet.id).length == 0)
	{
		$('#col'+x+' .loader').hide();
		var locationstr = $('input#location').val();
		var thedate = new Date(Date.parse(tweet.created_at));
		var hourstr = thedate.getHours();
		var minustr = new String(thedate.getMinutes());
		if(minustr.length<=1)
			minustr = '0'+minustr;
		var thedatestr = hourstr+':'+minustr;
		
		if(tweet.location)
			var locstr = '('+tweet.location+')';
		else
			var locstr = '';
		
		if(locstr.match(/^\(iPhone.*/))
			locstr = '(iPhone: '+locationstr+')';
														
								
		var divstr = '<div id="tw'+tweet.id+'" class="tweet"><a class="profile_button" title="'+tweet.from_user+'"><img class="profile" width="48" height="48" src="'+tweet.profile_image_url+'" ></a><p class="text">'+tweet.text.linkify().linkuser().linkuser().linktag().linktag().linktag()+'</p><div class="buttons"><a class="miniicon retweetbutton"  target="_blank"><img  src="img/but_retweet.png" /></a><a class="replybutton miniicon" target="_blank"><img src="img/but_reply.png" /></a></div><b><a class="profile_button" title="'+tweet.from_user+'">'+tweet.from_user+'</a></b>&nbsp;&nbsp;<b><a href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'" target="_blank">'+thedatestr+'</a></b><div style="display:none" class="rawtweettext">'+tweet.text+'</div></div>';
		
		window.tweetcount++;
	
		window.twitter['last_id'+x]=tweet.id;
		$('#col'+x+' .tweets').prepend(divstr);
		$('#col'+x+' .tweets #tw'+tweet.id+' a.profile_button').click(function(event){loadProfile($(this).attr('title'));event.stopPropagation();});
		$('#col'+x+' .tweets #tw'+tweet.id).hide();
		$('#col'+x+' .tweets #tw'+tweet.id+' img.profile').hide();
		$('#col'+x+' .tweets #tw'+tweet.id+' img.profile').fadeIn(4000);
		$('#col'+x+' .tweets #tw'+tweet.id).fadeIn('slow');		
		// Retweet
		
		$('#tw'+tweet.id+' a.retweetbutton').click(function(event){
			event.stopPropagation();
			var usr = $('.profile_button',$(this).parent().parent()).attr('title');
			var twt = $('.rawtweettext',$(this).parent().parent()).html();
			retweet(usr,twt);			
			
			return(false);
		});
		// Reply support
		$('#tw'+tweet.id+' a.replybutton').click(function(event){
			event.stopPropagation();

			reply_to($('.profile_button',$(this).parent().parent()).attr('title'));			
			
			return(false);
		});
		
	//	$('#col'+x+' .tweets #tw'+tweet.id+' a').longurl();
		
		// Ad thresholder:
		if((window.tweetcount+15)%adthresh == 0)
		{
			showAd();
		}
		
	}
}

function updateDisplaysAndSearches(x)
{

	var locationstr = $('input#location').val();
	$('#col'+x+' .tweets h2+h2').fadeOut('fast',function(){$(this).remove();});
	var locationradius 	= $('#locationradius').val();
	var locationunits 	= $('#locationunits').val();		// clean up old ones:
	$('#col'+x+' div.tweet:gt(20)').each(function(){$(this).fadeOut('fast',function(){$(this).remove();})});
				
	// FIRST WE NEED TO CHECK IF THEY CHANGED THE SEARCH:
	var searchstring = $('#col'+x+'input').val();
	// debug: alert('"'+searchstring+'" vs "'+window.twitter['text'+x]+'"');
	if(searchstring != window.twitter['text'+x] || locationstr != window.locations[x])
	{
		// Store it.
		window.locations[x] = locationstr;
		window.twitter['text'+x] = searchstring;
		window.twitter['last_id'+x] = 0;
		
		//$('h2#heading'+x+window.twitter['last_id'+x]).fadeOut(80000,function(){
		clearTimeout(window.inputtimeout[x]);
		window.inputtimeout[x] = setTimeout('reStack('+x+')',200);
		
		// Clear the timeout and start checking now:
		clearTimeout(window.searchers[x]);
		update_location_display(x);
	
		window.searchers[x]=setTimeout('fetch_as_many_as_possible('+x+')',10);
	
		return(true);	
	}
	return(false);
}

function showTweets()
{	
	if(window.geocodes[locationstr] != 'loading' && window.geocodes[locationstr] != undefined)
	{
		point = window.geocodes[locationstr];
		
		var locationurl = '&geocode='+point.lat()+','+point.lng()+','+$('#locationradius').val()+$('#locationunits').val();
		window.locationurl = locationurl;
		if(locationurl != window.locationurl)
		{
			update_location_display(x);
			reStack(x);
		}
		
	}
	var locationstr = $('input#location').val();
	if(locationstr != window.locations[1])
	{
		update_location_displays();

		setTimeout('checkLocation()',3000);
	}

	if(!window.paused)
	{
		$(window.tweetstack).each(function(x,stack)
		{
			$('#col'+x+' .tweets h2+h2').fadeOut('fast',function(){$(this).remove();});
			var locationradius 	= $('#locationradius').val();
			var locationunits 	= $('#locationunits').val();		// clean up old ones:
			$('#col'+x+' div.tweet:gt(20)').each(function(){$(this).fadeOut('fast',function(){$(this).remove();})});
		
			
					
			// FIRST WE NEED TO CHECK IF THEY CHANGED THE SEARCH:
			var searchstring = $('#col'+x+'input').val();
			// debug: alert('"'+searchstring+'" vs "'+window.twitter['text'+x]+'"');
			if(!updateDisplaysAndSearches(x))
			{
				// SHIFT OFF THE NEXT TWEET:
				var currentTweet = stack.shift();
				if(currentTweet)
				{
					//alert(currentTweet.text);
					addTweet(currentTweet,x);
				}
			}
			
		});
	}
	
	var sum = 0;
	for(var f = 0; f < window.tweetstack.length; f++)
		sum += window.tweetstack[f].length;
	var len = (sum)/3;
	var timeout = (30/len)*window.speedfactor;
	clearTimeout(window.tweettimer);
	window.tweettimer = setTimeout('showTweets()',timeout);
}
function reStack(x)
{
	window.tweetstack[x] = [];		
	var searchstring = $('#col'+x+'input').val()
	var locationstr = $('input#location').val();
	var locationradius 	= $('#locationradius').val();
	var locationunits 	= $('#locationunits').val();
	
//	window.twitter['last_id'+x] = 0;

	var langstr = '';
	if($('#language').val())
		langstr = "&lang="+$('#language').val();
	
	var lochtml = ' anywhere';
	if(locationstr != '')
	{
		lochtml = ' <small>within '+locationradius+locationunits+' of '+locationstr+'</small>';
	}
	var searchurl = searchstring;
	$(window.ignorelist).each(function(i,item)
	{
		searchurl += ' -from:'+item;
	});
	
		try
		{
			var clicky_pause_timer = 200;
			clicky.log('#SEARCH','TERM||'+searchstring+'||'+x);
			var clicky_pause_timer = 500;
		} catch(e){}
	
	$('#col'+x+' .loader').remove();
	$('#col'+x+' .tweets').prepend('<div class="loader"></div><h2 >&uarr;&nbsp;"'+searchstring+'"'+lochtml+'&nbsp;&uarr;&nbsp;<small><a href="http://search.twitter.com/search.atom?q='+searchurl+langstr+window.locationurl+'" target="_blank"><img src="feed.png" width="12" height="12" align="absmiddle" border="0" /></a></small></h2>');
	
	update_location_display(x);
	
	// empty the stack
	window.twitter['text'+x]  = searchstring;

	//fetch_as_many_as_possible(x);
}

function checkLocation()
{
	if (GBrowserIsCompatible()) 
	{	
		var locationstr 	= $('input#location').val();
		var locationradius 	= $('#locationradius').val();
		var locationunits 	= $('#locationunits').val();
		
		$.cookie('locationinput',locationstr,cookie_expires);
		$.cookie('locationradius',locationradius,cookie_expires);
		$.cookie('locationunits',locationunits,cookie_expires);
		if(locationstr != '' && window.geocodes[locationstr] != 'loading' && !window.geocodes[locationstr])
		{
			window.geocodes[locationstr] = 'loading';
			//alert('geocoding!');
			window.geocoder.getLatLng(locationstr,function(point)
			{
				var locationstr = $('input#location').val();
				if (point) 
				{
					window.geocodes[locationstr] = point;
					update_location_displays();
				}
				else
				{
					window.locationfail = 'YES';
					
				}
			});
		}
		else
		{
			$(window.tweetstack).each(function(x,stack)
			{	
				var locationstr = $('input#location').val();
				var locationradius 	= $('#locationradius').val();
				var locationunits 	= $('#locationunits').val();
				if(locationstr != window.locations[x])
				{
					window.locations[x] = locationstr;
					if(locationstr=='')
						locationstr = 'Any Location';
					
					update_location_display(x);
					reStack(x);
				}
			});
		}
	}
}
function update_location_displays()
{
	$('div#tweeters div.column').each(function(x,col){
		update_location_display(x);
	});
}
function update_location_display(elem)
{
	elem = $(elem);
	var searchstring = $('input',elem).val()
	var locationstr 	= $('input#location').val();
	var locationradius 	= $('#locationradius').val();
	var locationunits 	= $('#locationunits').val();

	var langstr = '';
	if($('#language').val())
		langstr = "&lang="+$('#language').val();
		
	if(locationstr == '')
	{
		//$('#col'+x+' h2.locationdisplay ').slideUp('fast');
		window.locationurl = '';
		$('h2.locationdisplay ',elem).html('&darr;&nbsp;anywhere&nbsp;&darr;&nbsp;<small><a href="http://search.twitter.com/search.atom?q='+searchstring+langstr+window.locationurl+'" target="_blank"><img src="feed.png" width="12" height="12" align="absmiddle" border="0" /></a></small>');
		$('h2.locationdisplay ',elem).slideDown('fast');

	}
	else
	{
		$(' h2.locationdisplay ',elem).html('&darr;&nbsp;within '+locationradius+locationunits+' of '+locationstr+'&nbsp;&darr;&nbsp;<small><a href="http://search.twitter.com/search.atom?q='+searchstring+langstr+window.locationurl+'" target="_blank"><img src="feed.png" width="12" height="12" align="absmiddle" border="0" /></a></small>');
		$('h2.locationdisplay ',elem).slideDown('fast');
		
	}
}

function start_fetching()
{
	$('#tweeters div.column').each(function(x,col){
		fetch_as_many_as_possible(x);
	});
}
function toggle_pause()
{
	if($('#pause_button').text() == 'Pause')
	{
		window.paused = true;
		$('#pause_button').text('Play');
	}
	else
	{
		window.paused = false;
		$('#pause_button').text('Pause');
	}
}
function add_column()
{
	var colcount = $('div#tweeters div.column').length;
	var search = $.cookie('box'+colcount);
/*	if(!search) 
	{
		search=window.nextterm;
		if( window.nextterm == 'obama')
			window.nextterm = 'inauguration';
		else if(window.nextterm == 'inauguration')
			window.nextterm = 'inaug09';
	}*/
	$('div#tweeters').append('<div id="col'+colcount+'" class="column">'+
			'<div class="padder">'+
			'<input type="text" id="col'+colcount+'input" value="'+search+'"  tabindex="1" />'+
			'<h2 class="locationdisplay"> </h2>'+
			'</div><div class="tweets"> </div>'+
		'</div>');

	window.locationstr[colcount] = '';
	window.searchers[colcount] = false;
	window.geocoding[colcount] = false;
	window.inputtimeout[colcount] = false;
	
	window.locations[colcount] = '';
	window.twitter['text'+colcount] = '-BOO-BOO-';
	window.tweetstack[colcount] = [];

	window.twitter['last_id'+colcount] = '0&rpp=10';

	var elem = $('div#tweeters div#col'+colcount);
	update_location_display(elem);
	fetch_as_many_as_possible(colcount);
	
	colcount++;
	update_widths();
}
function rem_column()
{
	var colcount = $('div#tweeters div.column').length-1;
	$('div#tweeters div#col'+colcount).remove();
	
	$.cookie('box'+colcount,null,cookie_expires);
	update_widths();
}
function update_widths()
{
	var colcount = $('div#tweeters div.column').length;

	var width = Math.round(100/colcount);
	$('div#tweeters div.column').css('width',width+'%');
	var minwidth = colcount*300;
	$('div#tweeters').css('min-width',minwidth+'px');
}
function load_trends()
{
	var url = "http://search.twitter.com/trends.json?callback=?";
	var purchased = []; //['twittermoms'];
	
	
	$.getJSON(url, function(json)
	{
		var colcount = $('div#tweeters div.column').length;
		
		for (var x = 0; x < colcount; x++)
		{
			if(x < purchased.length)
			{
				window.trend_terms.push(purchased[x]);
			}
			else
			{
				window.trend_terms.push(json.trends[x].name);			
			}
			$.cookie('box'+x,window.trend_terms[x],cookie_expires);
			$('#col'+x+'input').val(window.trend_terms[x]);
			reStack(x);
		}
	});
}
// Loads up the various functions we are going to use
$(document).ready(function(){


	//window.locationstr = $.cookie('location');

	window.geocoder =  new GClientGeocoder();

	 $('input#location').val($.cookie('locationinput'));
	 $('input#locationradius').val($.cookie('locationradius'));
	 $('input#locationunits').val($.cookie('locationunits'));
	
	if($.cookie('locationurl'))
		window.locationurl = $.cookie('locationurl');
	
	// Let's check here if they have passed in bookmark ones:
	var loaded_from_url = 0;
	var i = 0;
	if(window.location.href.indexOf('?') > 0)
	{
		// we just want to overwrite the cookied boxes with the new ones...
		var parts = window.location.href.split('?',2);
		if(parts[1].indexOf('&'))
		{
			var searches = parts[1].split('&');
			if(searches.length > 0)
			{
				loaded_from_url = 1;
				for(i in searches)
				{
					var search = searches[i];	
					search = search.replace('%20',' ');
					search = search.replace('%20',' ');
					search = search.replace('%20',' ');
					search = search.replace('%20',' ');
					search = search.replace('%23','#');							
					add_column();
					$('#col'+i+'input').val(search);
				}
			}
		}
	}
	// Let's check and retrieve their cookied searches:
	if(loaded_from_url == 0)
	{
		while(search = $.cookie('box'+i))
		{
			add_column();
			$('#col'+i+'input').val($.cookie('box'+i));
			reStack(i);
			i++;
		}
	}
	// if there are none.. then let's load 3 empty ones:
	if(i == 0)
	{	
		add_column();
		add_column();
		add_column();

		load_trends();
	}

	if($.cookie('monitter_panel') != 'closed')
		$('#slidebox').slideDown(1000);
	else
	{
		$('#header a.hider').text(window.monitter['hider_show']);
	}
		
	if($.cookie('monitter_style'))
	{
		setActiveStyleSheet($.cookie('monitter_style'));
		
		if($.cookie('monitter_style') == 'Light')
		{
			$('#header a.themer').text(window.monitter['darktheme']);		
		}
		else if($.cookie('monitter_style') == 'Dark')
		{	
			$('#header a.themer').text(window.monitter['lighttheme']);
		}
	}
	
	$('div#tweeters div.column input').keyup(function(e)
	{
		if(e.keyCode == 13)
		{
			var x = $(this).attr('id').replace('col','').replace('input','')
			updateDisplaysAndSearches(x);
		}
	});
		
	$('a#remove_column').click(rem_column);
	$('a#add_column').click(add_column);
	$('a#pause_button').click(toggle_pause);
	$('a#trends').click(load_trends);
	//fetch_tweets('1');
	//fetch_tweets('2');
	//fetch_tweets('3');
	
	window.twitter['last_id0'] = '0&rpp=10';
	update_location_displays();
	$('h2.locationdisplay ').slideDown('fast');
	checkLocation();	
	start_fetching();	

	
	setTimeout('logTweetCount()',120000);	
	setTimeout('showTweets()',1000);
	
	$('input').focus(function(){$(this).select();});
	
	$('a.hider').click(function(){
		$('#slidebox').slideToggle(1000,function(){
			if($('#header a.hider').text() == window.monitter['hider_show'])
			{
				$('#header a.hider').text(window.monitter['hider_hide']);
				$.cookie('monitter_panel','open',cookie_expires);
			}
			else
			{
				$('#header a.hider').text(window.monitter['hider_show']);
				$.cookie('monitter_panel','closed',cookie_expires);
			}
		});
	});
	
	$('a.themer').click(function()
	{
		if($('#header a.themer').text() == window.monitter['lighttheme'])
		{
			setActiveStyleSheet('Light');
			$('#header a.themer').text(window.monitter['darktheme']);
		}
		else
		{
			setActiveStyleSheet('Dark');
			$('#header a.themer').text(window.monitter['lighttheme']);
		}
	});
	$('a.help').click(function()
	{
			$('#help').fadeIn('slow');
	});
	$('#help a.closer').click(function()
	{
		$('#help').fadeOut('slow');
	});
	
	$('#tweet_button').click(function(){
		tweet();
	});
	$('#twitter_status').keyup(update_char_count);
	$('#cancel_button').click(function(){$('#tweetbox').fadeOut();$('#twitter_status').val('');})
	$('#announce_button').click(function(e){announce_monitter();e.stopPropagation();return(false);})
	$('#login-change').click(function(){
		$('#login-change').hide();
		$('#twitter_username').val('')
		$('#twitter_password').val('')
		$('#login-hider').slideDown();
	});

});

function loadProfile(username)
{
	var url = "http://twitter.com/status/user_timeline/"+username+".json?count=1&callback=?";
    var info = {};
    $.getJSON(url, function(data)
    {
		var user = data[0].user;
		//console.log(data);
		// Profile Template:
		template = 	'<div class="inner"><span class="closer">X</span>'+
					'<img class="avatar" src="'+user.profile_image_url+'" />'+
					'<div class="info">'+
					'<div class="name">'+user.name+' <small>('+user.screen_name+')</small></div>';
		if(user.location != null) template 		+= '<div class="location">'+user.location+'</div>';
		if(user.url != null) template 			+= '<div class="url"><a target="_blank" href="'+user.url+'">'+user.url+'</a></div>';
		if(user.description != null) template 	+= '<div class="description">'+user.description+'</div>';
		
		template += '<div class="updates">Updates: '+user.statuses_count+'</div>';
		template += '<div class="followers">Followers: '+user.followers_count+'</div>';
		template += '<div class="favourites">Favourites: '+user.favourites_count+'</div>';
		template += '<p style="margin-top: 4px;"><a style="color:#0BA3EC" href="http://twitter.com/'+user.screen_name+'" target="_blank">View complete profile on Twitter &raquo;</a></p>';
		template 	+= '</div></div>';
		
		$('#profile').html(template);
		$('#profile span.closer').click(function(e){$('#profile').fadeOut(); e.stopPropagation();});
		$('#profile').fadeIn();

    });
			
}

///// PROFILE CODE:
(function($){
  $.extend({
    getTwitterProfile : function(username, fnk){
      var url = "http://twitter.com/status/user_timeline/"+username+".json?count=1&callback=?";
      var info = {};
      $.getJSON(url, function(data){
      //console.log(data);
        if(typeof fnk == 'function') fnk.call(this, data[0].user);
      });
    }
  });
})(jQuery);
function retweet(username,status)
{
	$('#twitter_status').val('RT @'+username+' '+status);
	show_tweet_window();
	$('#twitter_status').focus();
}
function reply_to(username)
{
	$('#twitter_status').val('@'+username+' ');
	show_tweet_window();
	$('#twitter_status').focus();
}
function show_tweet_window()
{
	update_char_count();
	$('#tweetbox').fadeIn();
}

function do_announce(data)
{
    var first_result;
    // Results are keyed by longUrl, so we need to grab the first one.
    for     (var r in data.results) {
            first_result = data.results[r]; break;
    }
    //console.log(first_result);
    var url = first_result.shortUrl;

	$('#twitter_status').val($('#twitter_status').val()+' - '+url);
	update_char_count();
	$('#tweetbox').fadeIn()	
}
function announce_monitter()
{
	var colcount = $('div#tweeters div.column').length;	var searchstring = '';
	var searches = [];
	for(var x = 0; x < colcount; x++)
		searches.push($('#col'+x+'input').val());
	
	searchstring = 'using @monitter to watch twitter: '+searches.join(',');
	$('#twitter_status').val(searchstring);
	var urlstring = 'http://monitter.com/?'+searches.join('&');

	BitlyClient.call('shorten', {'longUrl': urlstring}, 'do_announce');	
}
function update_char_count(){
		var len = $('#twitter_status').val().length
		if (len > 140)
			len = '<b style="color:red">'+len+'</b>';
		$('#charcount').html('Chars: '+len);
	}
	
function is_logged_in()
{

	var usr = $('#twitter_username').val();
	var pwd = $('#twitter_password').val();
	
	if(usr != '' && pwd != '')
	{
		return(true);
	}
	return(false);
}
// How we tweet a message thru to twitter

function tweet()
{
	var usr = $('#twitter_username').val();
	var pwd = $('#twitter_password').val();
	
	if(usr != '' && pwd != '')
	{
		$('#tweetbox h2').html('Send a tweet as: '+usr);
		$('#login-hider').slideUp();
		$('#login-change').slideDown();
		$('#twitter_status').disabled = true;
	}
	
	var stat = $('#twitter_status').val();	
	var url = '/api/tweet'; 
	//http://twitter.com/account/verify_credentials.json?callback=?';
	$.ajax({
		type: "POST",
		url: url,
		dataType: 'json',
		data: {username:usr,password:pwd,status:stat},
		success: function(data)
		{
			//console.log(data);
			if(data == 1)
			{
				$('#success-message').html('Tweet posted successfully.');
				$('#success-message').fadeIn();
				setTimeout(function(){
					$('#success-message').hide();
					$('#tweetbox').fadeOut();
				},1000);
				$('#twitter_status').val('');					
			}
			else if(data == -1)
			{				
				$('#error-message').html('Login incorrect.. try again.');
				$('#error-message').fadeIn();
				
				$('#tweetbox h2').html('Send a tweet');
				$('#login-hider').slideDown();
				$('#login-change').slideUp();
				
				setTimeout(function(){$('#error-message').fadeOut()},3000);
				//$('#twitter_status').val('');
			}
			else
			{
				$('#error-message').html('Tweet posting failed.');
				$('#error-message').fadeIn();
				setTimeout(function(){$('#error-message').fadeOut()},3000);
				//$('#twitter_status').val('');
			
			}
		},
		error:function(data)
		{
			$('#error-message').html('Tweet posting failed.');
			$('#error-message').fadeIn();
			setTimeout(function(){$('#error-message').fadeOut()},5000);
			$('#twitter_status').val('');
		}
	});
	return(false);
}


