// tb.js
// TweetBackRedux 0.2 JS code
// Copyright (c) 2009 Jeremy Hilton < @jeremyhilton >
// This file is part of TweetBackRedux.
//
//    TweetBackRedux is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    TweetBackRedux is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with TweetBackRedux.  If not, see <http://www.gnu.org/licenses/>.

$(document).ready(function() {

	$.getJSON("/tb_shorten_lib.php?url="+document.location.href, function(data){


		search_string = '';
		var urls = new Array;
		u_count = 0;
	
		$.each(data.urls, function(i,item){
			urls[u_count] = item;
			u_count++;

			search_string += item + '+';

		});

		// remove the trailing + sign
		search_string = search_string.substr(0, (search_string.length - 1));

		$.getJSON('http://search.twitter.com/search.json?rpp=100&q=&ors=' + search_string + '&callback=?',
		function(twitter_data)
		{
			tweet_backs = '';
			tweet_back_list = '';
			t_count = 0;
			valid_tweetback = false;

			$.each(twitter_data.results, function(i,item){
		
				for (x in urls)
				{
					// see if the URL returned matches one of the URLS we searched for. The Twitter search API is not case sensitive, URL shorteners are. This causes invalid tweetbacks to be returned.
					if(item.text.match(urls[x].replace(/\//g, "\\/")))
					{
						valid_tweetback = true;

					}
		
				}

				if(valid_tweetback)
				{
					tweet_back_list += "<li style='display: block; background-image: url("+item.profile_image_url+"); background-repeat:no-repeat; padding-left:50px; height: 50px; padding-bottom: 10px;'><b>"+item.from_user+":</b> "+item.text+" "+item.created_at+"</li>";
					t_count++;

				}

				valid_tweetback = false;
		
			});

			tweet_backs = "<b>"+t_count+" Total TweetBacks:</b>";
			tweet_backs += "<ul>";
			tweet_backs += tweet_back_list;
			tweet_backs += "</ul>";	

			$("#tweetbacks").html(tweet_backs);

		});

	});

});
