ItvJs.Twitter = {

    _oTweetUsers: [],

    /*
    * Store usernames ready for loading
    */
    Register: function(oOptions) {
        if (oOptions.dispaly !== undefined) {
            oOptions.display = oOptions.dispaly;
        }
        ItvJs.Twitter._oTweetUsers.push(oOptions);
    },

    /*
    * Start fetching twitter feeds
    */
    Init: function() {
        var aUsers = ItvJs.Twitter._oTweetUsers;
        for (var i = 0; i < aUsers.length; i++) {
            if (aUsers[i].cache !== undefined && $.cookie('twitter_' + aUsers[i].user + '_' + aUsers[i].target))
            {
                document.getElementById(aUsers[i].target).innerHTML = $.cookie('twitter_' + aUsers[i].user + '_' + aUsers[i].target);
            }
            else {
                $('#' + aUsers[i].target).addClass('loading');
                ItvJs.Twitter._FetchFeed(aUsers[i].user, aUsers[i].results, function(oFeedData, oOptions) {

                    if ( oFeedData.results.length > 0 )
                    {
                        var sFeedHTML = ItvJs.Twitter._RenderFeed( oFeedData, oOptions );
                    }
                    else
                    {
                        var sFeedHTML = '';
                    }

                    if (oOptions.cache !== undefined) {
                        $.cookie('twitter_' + oOptions.user + '_' + oOptions.target, sFeedHTML, { expires: oOptions.cache, path: '/' });
                    }

                    document.getElementById(oOptions.target).innerHTML = sFeedHTML

                }, aUsers[i]);
            }
        }
    },

    _getFriendlyTime: function(iTime) {
        var dDateNow = new Date(), sDayPlural = '';

        iOffset = dDateNow.getTime() - iTime;

        if (iOffset > (24 * 60 * 60 * 1000)) {
            if (Math.round(iOffset / 24 / 60 / 60 / 1000) > 1) {
                sDayPlural = 's';
            }

            sOffsetOut = 'About ' + Math.round(iOffset / 24 / 60 / 60 / 1000) + ' day' + sDayPlural + ' ago';

        }
        else if (iOffset > (60 * 60 * 1000)) {
            sOffsetOut = 'About ' + Math.round(iOffset / 60 / 60 / 1000) + ' hours ago';

        }
        else {
            sOffsetOut = 'About ' + Math.round(iOffset / 60 / 1000) + ' minutes ago';
        }

        return sOffsetOut;
    },

    /*
    * Parse tweet, add HTML links
    */
    makeTweetHTML: function(sTweet) {
        sTweet = ItvJs.Twitter._linkUrl(sTweet);
        sTweet = ItvJs.Twitter._linkUser(sTweet);

        return ItvJs.Twitter._linkHash(sTweet);
    },
    _linkUrl: function(sTweet) {
        return sTweet.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, " <a href=\"$1\" target=\"_blank\">$1</a> ");
    },
    _linkUser: function(sTweet) {
        return sTweet.replace(/^[\@]+([A-Za-z0-9-_]+)| [\@]+([A-Za-z0-9-_]+)/gi, " <a href=\"http://twitter.com/$1$2\" target=\"_blank\">@$1$2</a> ");
    },
    _linkHash: function(sTweet) {
        return sTweet.replace(/[\#]+([A-Za-z0-9-_]+)/gi, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all" target="_blank">#$1</a> ');
    },

    /*
    * Render XHTML with feed data
    */
    _RenderFeed: function(oFeedData, oOptions) {
        var aTwitterHTML = [], iResultCount = 0, iCurrentResult = 0, iFinalResultCount = 0, bRowOdd = true; ;

        if (!oFeedData) { return; }
        if (oOptions.html !== false) { aTwitterHTML.push('<ul>'); }


		
		if (oOptions.icon === true && oFeedData.results[0].profile_image_url) {
			aTwitterHTML.push('<div class="tweetImg"><a href="http://twitter.com/' + oOptions.user + '" target="_blank"><img src="' + oFeedData.results[0].profile_image_url + '"/></a>');
			
			if (oOptions.title !== undefined) {
				aTwitterHTML.push('<h2><a href="http://twitter.com/' + oOptions.user + '" target="_blank">' + oOptions.title + '</a></h2>');
			}
			
			aTwitterHTML.push('</div>');
        }

        if (oFeedData.results.length) {
            // First, Count the number of results we will be displaying
            for (i = 0; i < oFeedData.results.length; i++) {
                if ((oOptions.reply !== false || !oFeedData.results[i].text.match(/^@/)) && (oOptions.display === undefined || i < oOptions.display)) {
                    iResultCount++
                }
            }

            for (i = 0; i < oFeedData.results.length; i++) {
                if ((oOptions.reply !== false || !oFeedData.results[i].text.match(/^@/) || (oOptions.display !== undefined && iResultCount < oOptions.display)) && (oOptions.display === undefined || i < oOptions.display)) {
                    iFinalResultCount++;
                }
            }


            for (i = 0; i < oFeedData.results.length; i++) {
                if ((oOptions.reply !== false || !oFeedData.results[i].text.match(/^@/) || (oOptions.display !== undefined && iResultCount < oOptions.display)) && (oOptions.display === undefined || i < oOptions.display)) {
                    if (oOptions.html === false) {
                        aTwitterHTML.push(ItvJs.Twitter.makeTweetHTML(oFeedData.results[i].text));
                    }
                    else {
                        aTwitterHTML.push('<li class="' + (bRowOdd ? 'aqua-tweetOdd' : 'aqua-tweetEven') + ' ' + ((iResultCount - 1) === iCurrentResult ? 'aqua-tweetLast' : '') + ' ' + (iCurrentResult === 0 ? 'tweetFirst' : '') + '">');
                        if (bRowOdd) { bRowOdd = false; } else { bRowOdd = true; }

//                        if (oOptions.icon === true && oFeedData.results[i].profile_image_url && iCurrentResult === 0) {
//                            aTwitterHTML.push('<div class="aqua-tweetImg"><a href="http://twitter.com/' + oOptions.user + '" target="_blank"><img src="' + oFeedData.results[i].profile_image_url + '"/></a></div>');
//                        }

                        aTwitterHTML.push('<p class="aqua-tweetText">' + ItvJs.Twitter.makeTweetHTML(oFeedData.results[i].text) + '</p>');

                        if ((i + 1) === iFinalResultCount && oOptions.follow === true) {
                            if (oOptions.name === undefined) { oOptions.name = '' }
                            aTwitterHTML.push('<p class="aqua-tweetDate">' + ItvJs.Twitter._getFriendlyTime(Date.parse(oFeedData.results[i].created_at)) + ' from Twitter <a href="http://twitter.com/' + oOptions.user + '" target="_blank">Follow ' + oOptions.name + '</a></p>');
                        }
                        else {
                            aTwitterHTML.push('<p class="aqua-tweetDate">' + ItvJs.Twitter._getFriendlyTime(Date.parse(oFeedData.results[i].created_at)) + ' from Twitter</p>');
                        }

                        iCurrentResult++;

                        aTwitterHTML.push('</li>');
                    }

                    if (oOptions.iTime === undefined) {
                        oOptions.iTime = Date.parse(oFeedData.results[i].created_at);
                    }
                }
            }
        }

        if (oOptions.html !== false) {
            aTwitterHTML.push('</ul>');
        }

        return aTwitterHTML.join('');
    },


    /*
    * Fetch Tweet Data and fire callback
    */
    _FetchFeed: function(sUserName, iTweetCount, fCallback, oOptions) {
        var screenFeedURL = '';

        if (sUserName === undefined) { sUserName = 'twitter'; }
        if (fCallback === undefined) { fCallback = function() { }; }
        if (iTweetCount === undefined) { iTweetCount = 5; }

        if (oOptions.feed !== undefined) {
            screenFeedURL = oOptions.feed;
        }
        else {
            screenFeedURL = 'http://search.twitter.com/search.json?&q=from:' + sUserName + '&rpp=' + iTweetCount + '&callback=?';
        }

        $.getJSON(screenFeedURL, function(oFeedData) {
            if (typeof oOptions.onload === 'function') {
                oOptions.onload(oFeedData, oOptions);
            }
            else {
                fCallback(oFeedData, oOptions);
            }
        });
    }
};

// Attache onload event to create tweet boxes 
$(window).ready(function()
{
	if (ItvJs && ItvJs.Twitter) 
	{
		ItvJs.Twitter.Init();
	}
});
