/*
 * Twitter Search 1.0
 *
 * Created by Stephen Hallgren (aka Teevio)
 * http://teevio.com
 * 
 * Quality control by JSLint
 * http://www.jslint.com/
 * 
 */

function TwitterSearch(jsonArgs)
{
	twitterSearchObj = this;

	this.scripTag       = '';
	this.refreshTimeout = '';
	this.currentSearchTerm = '';
	
	// Defaults
	this.args = {
		"limit":"10",
		"baseApiUrl":"http://search.twitter.com/search.json?",
		"lang":"en"
		// "keyword":"teevio"
		// "fromUser":"teevio"		
	};
	
	this.callKey = 0;
	
	// Assign passed args to object
	for (var key in jsonArgs)
	{
		if (typeof jsonArgs[key] !== 'function')
		{
				this.args[key] = jsonArgs[key];
		}
	}
	
	this.search();
}

// search
TwitterSearch.prototype.search = function (keyword)
{
	if (!this.args.calls[this.callKey])
	{
		return false;
	}                
	
	this.currentSearchTerm = this.args.calls[this.callKey].keyword;
	
	this.queuCount = 0;
	limit          = this.args.limit;
	keyword        = '';
	fromUser       = '';
			
	if (!this.args.calls[this.callKey].keyword && !this.args.calls[this.callKey].fromUser)
	{
		// alert('TwitterSearch: You need to pass a either a keyword or a fromUser username');
		return false;
	}
	
	if (this.args.calls[this.callKey].keyword)
	{
		keyword = 'q='+this.args.calls[this.callKey].keyword+'&';
	}
    else if (this.args.calls[this.callKey].fromUser)
	{
		keyword = 'q=from%3A'+this.args.calls[this.callKey].fromUser+'&';
	}

	url = this.args.baseApiUrl + keyword.replace(/#/g,'%23') + 'rpp=' + limit+'&lang=' + this.args.lang + '&callback=twitterSearchObj.search_cb';

	this.addScript(url);

	this.search_cb = function (result)
	{	
		this.removeScript();
		this.buildHTML(result.results);
	};		
};

TwitterSearch.prototype.buildHTML = function (results)
{
	tweet = results[0];

		dateArray = tweet.created_at.split(' ');
		timeArray = dateArray[4].split(':');
	
		month    = dateArray[2];
		day      = dateArray[1];
		year     = dateArray[3];
		hours    = timeArray[0];
		minutes  = timeArray[1];
		seconds  = timeArray[2];
		meridian = 'am';
		adjustedHours = hours;
		
		if (hours > 11)
		{
			adjustedHours = hours - 11;
			meridian      = 'pm';
		}
	
		time = adjustedHours  + ':' + minutes;
	
		dateString = month + ' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
	
		var tweetTime = new Date(dateString);
	        
		timeAgo = this.getTimeAgo(tweetTime);
	
	output = '<h4>'+this.addLinks(tweet.text)+'</h4> <p><a href="http://twitter.com/'+tweet.from_user+'/statuses/'+tweet.id+'">'+timeAgo+'</a> by <a href="http://www.twitter.com/'+tweet.from_user+'">'+tweet.from_user+'</a> on <a href="http://www.twitter.com">Twitter</a></p>';
	
	document.getElementById(this.args.calls[this.callKey].id).innerHTML = output;
	
	this.callKey++;
	this.search();
};              

TwitterSearch.prototype.getTimeAgo = function (tweetTime)
{
  	var now   = new Date();
	
	millisecondOffset = now.getTime() - tweetTime.getTime();

	if (millisecondOffset <= 0)
	{
		timeAgo = 'Just now';
	}
	else
	{
		secondOffset = millisecondOffset/1000;
		minuteOffset = secondOffset/60;
		hourOffset   = minuteOffset/60;
		
		if (secondOffset < 60)
		{
			timeAgo = Math.round(secondOffset);
			timeAgo += ' second';

			if (Math.round(secondOffset) != 1)
			{
				timeAgo += 's';					
			}

			timeAgo += ' ago';
		}
		else if (minuteOffset < 60)
		{
			timeAgo = Math.round(minuteOffset);
			timeAgo += ' minute';

			if (Math.round(secondOffset) != 1)
			{
				timeAgo += 's';					
			}

			timeAgo += ' ago';
		}
		else if (hourOffset < 24)
		{
			timeAgo = Math.round(hourOffset);
			timeAgo += ' hour';

			if (Math.round(secondOffset) != 1)
			{
				timeAgo += 's';					
			}

			timeAgo += ' ago';
		}
		else
		{
			timeAgo = time + ' ' + meridian + ' ' + month + ' ' + day;   
		}
	}
	
	return timeAgo;  
};

TwitterSearch.prototype.entityDecode = function (str)
{
	var textarea = document.createElement('textarea');
	textarea.innerHTML = str;
	decoded = textarea.value;
		
	return decoded;
};  

TwitterSearch.prototype.removeScript = function()
{
  	scriptTags = document.getElementsByTagName("script");
	
	for (var i = 0; i< scriptTags.length; i++)
	{
		if (scriptTags[i].src.search(this.args.baseApiUrl) > -1)
		{
			scriptTags[i].parentNode.removeChild(scriptTags[i]);
		}
	}  
};

TwitterSearch.prototype.addLinks = function(string)
{
	atPattern = /(@[a-zA-z0-9]+)/g;

	matches = string.match(atPattern);

	if (matches)
	{
		for (var i = 0; i < matches.length; i++)
		{
			match = matches[i];

			string = string.replace(match, '<a href="http://twitter.com/' + match.substr(1, match.length) + '" target="_blank">' + match + '</a>');
		}		
	}
	
	string = string.replace(/([^">\/=]|^)((http:\/\/|www\.)[A-z\/~#&;=%,\?\-\.0-9]+)/gi, '$1<a href="$2" target="_blank">$2</a>');
	string = string.replace('href="www', 'href="http://www');
    
	return string;
};

// Dynamically add script tag to make JSON call
TwitterSearch.prototype.addScript = function (url)
{
	this.headTag    = document.getElementsByTagName("head")[0];
	this.scriptTag  = document.createElement('script');
	this.scriptTag.type = 'text/javascript';
	this.scriptTag.src  = url;	

    if (!this.headTag)
    {
        this.headTag = document.body.parentNode.appendChild(document.createElement("head"));
    }

    this.headTag.appendChild(this.scriptTag);
};
