/**
 * NOTES:
 *
 * - This file must be loaded AFTER prototype.js loads.
 */

//EDITABLE VARIABLES
var num_tweets = 3;

//NON-EDITABLE VARIABLES
var url = "http://twitter.com/status/user_timeline/exxonmobil.json?count=" + num_tweets + "&callback=renderTweets";

//getTweets();

/** 
 * add twitter JSON URL to HEAD element
 */
function getTweets(){
    var head;
    var script;
    head = $$('head')[0];
    if (head){
	script = new Element('script', { type: 'text/javascript', src: url });
	head.appendChild(script);
    }
}

/**
 * Determine if DOM is loaded.  If so, render tweets, otherwise keep checking for page load until ready.
 */
function renderTweets(json){
    new PeriodicalExecuter(function(pe) {
	    if(json.error){
		pe.stop();
	    }
	    if($('tweets')){
		doRenderTweets(json);
		pe.stop();
	    }
    }, 1);
}

/**
 * Iterate through JSON and render each tweet.  For error correction, this only runs if we actually have tweets.
 */
function doRenderTweets(json){
    json.each(function(record){
	    var tweet = record.text;
	    //create links from URLs
	    text = tweet.parseURLs();
	    //create links from usernames
	    text = text.parseUsernames();
	    //create links from hashtags
	    text = text.parseHashtags();
	    //make a human-readable date
	    var thedate = parseDate(record.created_at);
	    //append 
	    var li = new Element('li');
	    li.update(text + ' <a href="http://twitter.com/exxonmobil/status/' + record.id + '" target="_blank">(' + thedate + ')</a>');
	    $('tweets').insert({bottom: li});
	});
    //show twitter div
    $('twitterintegration').setStyle({display: 'block'});
}

/**
 * Take date string from twitter and change format
 */
function parseDate(date_str){
    //fix date
    var fixed_date = date_str.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC");
    var date_tweet = new Date(fixed_date);
    var date_now   = new Date();
    var date_diff  = date_now - date_tweet;
    var hours      = Math.round(date_diff/(1000*60*60));

    if(hours <= 23){
	return hours + " hours ago";
    } else {
	var date = fixed_date.substr(0, 21);
	var hour = date.substr(12, 2);
	var ampm = hour<12 ? ' AM' : ' PM';
	if (hour > 12){
	    hour -= 12;
	}
	if (hour==0){
	    hour = 12;
	}
	return hour + date.substr(14, 3) + ampm + " " + date.substr(0, 6) + ordi(date.substr(6, 1));
    }
}

/**
 * Parse string for URLs and return HTML links
 */
String.prototype.parseURLs = function(){
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
	    return url.link(url);
	});
};

/**
 * Parse string for Twitter usernames and return HTML links to their Twitter pages
 */
String.prototype.parseUsernames = function(){
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u){
	    var username = u.replace("@","")
	    return u.link("http://twitter.com/"+username);
	});
};

/**
 * Parse string for hashtags and return HTML links to Twitter search
 */
String.prototype.parseHashtags = function(){
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t){
	    var tag = t.replace("#","%23")
	    return t.link("http://search.twitter.com/search?q="+tag);
	});
};

/**
 * Return ordinal based on argument
 */
function ordi(n){
    var s='th';
    if(n===1) s='st';
    if(n===2) s='nd';
    if(n===3) s='rd';
    return s;
}
