var tweets_final = [];
var tweets_tmp;
var screennames_final;
var followerLimit;
var frequency;
var maxid = 0;
var minid = 0;
var reloading = true;
var firstLoad = true;
var err_msg = $('<p id="err_msg">The Twitter API is not responding. Try refreshing the page.</p>');

// The following variables are made public through the getTweets object.
var userName;
var divName;
var divTweet;
var preloader

// Return new array with duplicate values removed
Array.prototype.unique = function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
};// JavaScript Document
 
// Checks if a value exists in an array
Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		//alert(this[i]+':'+p_val);
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
};

// Checks if a function is an array
function is_array(obj) {
	if (obj) {
		if (obj.constructor.toString().indexOf("Array") == -1)
		  return false;
		else
		  return true;
	} else {
		return false;
	}
}

// A javascript function that behaves like PHP's urlencode function.
function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/urlencode    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str+'').toString();
        // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

// used for debugging
function showObject(obj) {
	str='';
	for(prop in obj) {
		/*str+=prop + ":"+ obj[prop]+"\n";*/
		if ( typeof(obj[prop]) != "object" ) {
			str+=prop + ":"+ obj[prop]+"\n";
		} else {
			str+=prop + ":"+ showObject(obj[prop])+"\n";
		}
	}
  return(str);
}


(function($) {
	/*
		jq.twitter.js v1.0
		Last updated: 10 June 2010

		Created by Maurice Wright
		based on code originated by Damien du Toit
		http://coda.co.za/blog/2008/10/26/jquery-plugin-for-twitter

		Licensed under a Creative Commons Attribution-Non-Commercial 3.0 Unported License
		http://creativecommons.org/licenses/by-nc/3.0/
	*/

	$.fn.getTweets = function(options) {
		var o = $.extend({}, $.fn.getTweets.defaults, options);
		var pl = $('<p id="'+o.preloaderId+'">'+o.loaderText+'</p>');
		preloader = pl;
		
		divName = o.divName; // This is the id name of the div containing all tweets.
		divTweet = o.divTweet;	// This is the class name of the div containing each tweet.
		userName = o.userName; // This will be used in the usersCallback function
		followerLimit = o.followerLimit; // This will also be used in the usersCallback function
		frequency = o.frequency; // This will be used to determine how frequently to ping Twitter (in seconds).
		divName_nohash = o.divName.substring(1,o.divName.length); // remove leading hash sign
	
		// only perform these initial appendages the first time when maxid hasn't been defined.
		if ( firstLoad ) {
			// hide container element
			$(this).hide();
			
			// add css to #twitter div
			var csso_twitter = {
				'border' : '0px solid #ccc',
				'margin' : '0',
				'padding' : '0px',
				'width' : '458px'
			}
			$(o.divName).css(csso_twitter);
			
						
			// add heading to container element
			if (o.showHeading) $(this).append('<div id="'+divName_nohash+'_heading">'+o.headingText+'</div>');
			if (o.showDescription) $(this).append('<div id="'+divName_nohash+'_desc" style="padding-bottom:0px;">'+o.description+'</div>');
			$(this).append('<div class="tweetlinks"><a href="http://twitter.com/home" target="_blank">Send A Tweet</a> | <a href="javascript:{}" onclick="toggleReload();" id="reloader">Stop Message Loading</a></div>');
			
			var csso_twitter_desc = {
				'clear' : 'both',
				'padding' : '10px 0 0 0'
			}
			$(o.divName+'_desc').css(csso_twitter_desc);
			
	
			// add twitter list to container element
			$(this).append('<ul id="'+divName_nohash+'_update_list"></ul>');
	
			// hide twitter list
			$("ul"+o.divName+"_update_list").hide();
	
			// add preLoader to container element
			$(this).append(pl);
	
			// add Twitter profile link to container element
			if (o.showProfileLink) {
				$(this).append('<div class="blankrow_10"></div><a id="profileLink" href="http://twitter.com/'+o.userName+'">http://twitter.com/'+o.userName+'</a>');
			}
	
			// show container element
			$(this).show();
		}
	
		// get search results
		if (reloading) {
			url_search = "http://search.twitter.com/search.json?callback=searchCallback&q="+urlencode(o.query)+"&rpp="+o.numTweets+"&since_id="+maxid;
			//alert(url_search);
			$.getScript(url_search, function() {
	
				// show twitter list
				o.slideIn ? $("ul"+o.divName+"_update_list").slideDown(1000) : $("ul"+o.divName+"_update_list").show();
		
				// give last list item a special class
				$("ul"+o.divName+"_update_list li:last").addClass("lastTweet");
			});
		}
	};

	// plugin defaults
	$.fn.getTweets.defaults = {
		divName: "#twitter",
		divTweet: ".tweet",
		userName: null,
		numTweets: 5,
		followerLimit: 5,
		frequency: 25,
		preloaderId: "preloader",
		loaderText: "Loading tweets...",
		slideIn: false,
		showHeading: true,
		headingText: "Latest Tweets",
		showProfileLink: true,
		description: "",
		showDescription: false,
		query: "#luv"
	};
})(jQuery);

function searchCallback(tweets) {
	var statusHTML = [];
	var userHTML = [];
	var screenname_long;
	var screenname;
	var userid_long = [];
	var screennames_long = [];
	var screennames = [];
	var j = 0;
	maxid = tweets.max_id;
	
//alert("maxid:"+maxid);
//$("#twitter").html("<pre>"+showObject(tweets.results)+"</pre>");
//alert(tweets.results[0].from_user);
	// Get the screennames from the search results for filtering
	for (var i=0; i<tweets.results.length; i++) {
		screenname = tweets.results[i].from_user;
		userid = tweets.results[i].from_user_id;
		screennames_long.push(screenname); // Has duplicates in the array.
		userid_long.push(userid);
	}
	screennames = screennames_long.unique(); // Remove dupes from array.
	userids = userid_long.unique();
	
	tweets_tmp = tweets;
	
//alert('searchCallback:'+screennames);
	url_users = "http://api.twitter.com/1/users/lookup.json?callback=usersCallback&screen_name="+screennames;
	// Get JSON formatted screennames from Pay4Tweet
	url_users_filtered = "http://www.pay4tweet.com/searchfilter.php?callback=usersCallback&screen_name="+userName+"&screen_names="+screennames+"&follower_limit="+followerLimit;
	
//alert(url_users_filtered);
//$.getScript(url_users_filtered));
	// There are 100 or less screennames.  Sent to Twitter for filtering using the usersCallback callback function.
	$.getScript(url_users_filtered, function() {
		//alert('Load was performed.');
		firstLoad = false;
		
		// remove preLoader from container element
		$(preloader).remove();
		
		// edit styles here
		// change ul properties
		var csso_ul = {
			'list-style-type' : 'none',
			'margin' : '0',
			'padding' : '15px 0 0 0'
		}
		$("ul"+divName+"_update_list").css(csso_ul);
		
		// change li (tweet) properties)
		var csso_li = {
			'display' : 'block',
			'list-style-type' : 'none',
			'margin-left' : '0px',
			'padding' : '10px 10px 0px 0',
			'border-top' : '1px dashed #ccc',
			'clear' : 'both',
			'font' : 'normal 10pt Trebuchet MS'
		}
		$("ul"+divName+"_update_list li").css(csso_li);
		
		// change avatar properties
		var csso_avatar = {
			'padding' : '5px 10px 30px 0',
			'float' : 'left'
		}
		$('.avatar').css(csso_avatar);
		
		// change anchor properties within tweet text
		var csso_anchor = {
			'color' : '#c33',
			'text-decoration' : 'none',
			'padding-right' : '0'
		}
		$(divTweet+' a').css(csso_anchor);
		//alert(divTweet+' a');
		
		$(divTweet).css('color','#000');
				
		// change avatar padding
		$('.avatar').css('padding-top','5px');
				
		// remove the #appendafter list item
		$('#appendafter').css('display','none');
	});
}

function usersCallback(users) {
	//alert(users);
	//alert(users+":"+users.length);
	var screenname;
	var screennames = [];
	var tweets_html = [];
	var avatar;
	var avatarsize = 28;
	var avatar_bottom_margin = "10px";
	var text;
	var existing_html = "";
	var str_tweets;
	var divTweet_nodot = divTweet.substring(1,divTweet.length); // remove leading hash sign
	
	if (is_array(users)) {
	
		// Match good screennames with search results.
		for (var i=0; i<tweets_tmp.results.length; i++) {
			screenname = tweets_tmp.results[i].from_user; //screen_name from tweet
			avatar = tweets_tmp.results[i].profile_image_url
			avatar = '<img src="'+avatar+'" width="'+avatarsize+'" height="'+avatarsize+'" alt="'+screenname+'" />';
			text = tweets_tmp.results[i].text;
			
			if (users.in_array(screenname)) { // compare screen_name from tweet to the filtered user list returned from Pay4Tweet
				//alert("screenname2="+screenname2+" : created_at="+tweets_tmp.results[i].created_at);
			//alert(avatar);
				tweets_final.push(tweets_tmp.results[i]);
				if ( text.length > 100 ) avatar_bottom_margin = "40px";
				text = tweets_tmp.results[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
				  return '<a href="'+url+'">'+url+'</a>';
				}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
				  return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
				});
				tweets_html.push('<li class="'+divTweet_nodot+'"><div class="avatar">'+avatar+'</div><div><div><a href="http://twitter.com/'+screenname+'" target="_blank" style="font-weight:bold;">@'+screenname+'</a>: '+text+'</div><div class="tweetlinks" style="padding-bottom:10px"><a href="http://twitter.com/'+screenname+'/statuses/'+tweets_tmp.results[i].id+'" style="font-weight:bold;" target="_blank">'+relTime(tweets_tmp.results[i].created_at)+'</a> | <a href="http://twitter.com/home?status=@'+screenname+'+%23luv" target="_blank">reply</a> | <a href="http://twitter.com/home?status=RT @'+screenname+': '+urlencode(getAnchorText(text))+'" target="_blank">retweet</a> | <a href="http://twitter.com/direct_messages/create/'+screenname+'" target="_blank">direct message</a> | <a href="http://twitter.com/'+screenname+'" target="_blank">follow</a></div></div></li>');
				//tweets_html.push('<li class="'+divTweet+'"><div class="avatar">'+avatar+'</div><div>'+text+'</div></li>');
			}
		}
	
		str_tweets = tweets_html.join('');
		
		// reset the "existing_html" variable
		firstLoad ? existing_html = str_tweets : existing_html = $(divName+'_update_list').html();
		
//alert("firstLoad="+firstLoad+"\nexisting_html="+existing_html);
		
		// prepend new tweets
		if ( firstLoad ) {
			// Add all of the HTML at once
			$(divName+'_update_list').html('<li id="appendafter" style="display:none;"></li>' + existing_html);
		} else {
			// Just add the new tweets
			$("#appendafter").after(str_tweets);
		}
		
		str_tweets = $(divName+'_update_list').html();
		
	} else {
		// Twitter is having problems...again
		if ( firstLoad ) {
			$(divName).append(err_msg);
		}
		// If the error occurs during the refresh sequence, the error doesn't need to be shown.
	}
	// run it again
	if (reloading) timer = setTimeout('getTweets_func()', Number(frequency)*1000);
	
//alert('after:'+$(divName+'_update_list').html());
//alert ('tweets_final:'+tweets_html.join(''));
}

function toggleReload() {
	if (reloading) {
		//alert("stop reloading");
		reloading=false;
		$('#reloader').html('Get New Messages');
	} else {
		//alert("start reloading");
		reloading=true;
		getTweets_func();
		$('#reloader').html('Stop Message Loading');
	}
}

function relTime(tweetTime) {
	tweetTime = new Date(tweetTime);
	currentTime = new Date();
	var delta = (currentTime.getTime() - tweetTime.getTime())/1000;
	//return delta;
	
	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}

// Takes a string and unwraps all anchor tags from anchor text
function getAnchorText(str) {
	var rxp1 = /<a\s+[^>]*>/g;
	var rxp2 = /<\/a>/g;
	str_new = str.replace(rxp1,'');
	str_new = str_new.replace(rxp2,'');
	return str_new;
}