/**********************************************************************************************
* ~License~ This portion should accompany the Script for Legal usage and Proper Credits       *
* author: Swashata                                                                            *
* email: admin@intechgrity.com                                                                *
* ProjectPage: http://code.google.com/p/ajax-based-twitter-status-loader/                     *  
* Blog: http://www.inTechgrity.com                                                            *  
*                                                                                             *  
* Copyright, 2009 inTechgrity                                                                 *
* Licensed under the GNU General Public License v3                                            *
*     This program 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.                                                      *
*                                                                                             *
*     This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.                   *  
* ~End of License | Now enjoy~                                                                *  
**********************************************************************************************/
function recentTwitterLoader(userOptions) {
    //Set default options
    var op = {
        'TwitName':'swashata',
        'TwitCount':10,
        'ulClass':'twitter-ul',
        'containerID':'',
        'onLoad':false
    };
    
    //Now extend it using jQuery
    op = $.extend({}, op, userOptions);
    
    //If container exists then append it there! or make a new one
    if(!op.containerID) {
        op.containerID = '#twitter-loader';
        document.write('<div id="twitter-loader"></div>');
    }
    
    //Or even if containerID is mentioned but not included in the HTML then also we write it at the script call
    if(!$(op.containerID).length){
        document.write('<div id="'+op.containerID.replace(/\#/, '')+'"></div>');
    }
    
    //Use a variable for the jQuery selector
    var twitDiv = $(op.containerID);
    
    //Store the content of the 
    var loaderHTML = twitDiv.html();
    
    //Main Twitter Loader Function
    var twitLoader = function(twitterData) {
        for(i=0;i<twitterData.length;i++){
            var twitUserName = twitterData[i].user.screen_name;
            
            //Get the status
            var status = twitterData[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>';
            });
            
            //Now append the status in form of a <li> to the twitUL
            var twitLiInsider = '<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+twitUserName+'/statuses/'+twitterData[i].id+'">'+relative_time(twitterData[i].created_at)+'</a></li>';
            twitUL.append(twitLiInsider);
            
            //Now remove the loader div if all the twits have been loaded
            if(i==twitterData.length-1) $('#itg-twitter').remove();
        }
    }
    
    var relative_time = function(time_value) {
        var values = time_value.split(" ");
        time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
        var parsed_date = Date.parse(time_value);
        var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
        var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
        delta = delta + (relative_to.getTimezoneOffset() * 60);
      
        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';
        }
    }
    
    var twitLoaderinit = function() {
        //First Remove the inner contents of the twitter div
        twitDiv.html('');
        
        //Now append the loader HTML inside the twit loader div wrapped in another div
        $('<div id="itg-twitter">'+loaderHTML+'</div>').appendTo(twitDiv);
        
        //Append the Twitter UL to the loader div
        twitUL = $('<ul'+(op.ulClass?' class="'+op.ulClass+'"':'')+'/>').appendTo(twitDiv);
        
        //Now call the twitLoader function using AJAX
            $.ajax({
            url:'http://twitter.com/statuses/user_timeline/'+op.TwitName+'.json',
            data:{'count':op.TwitCount},
            dataType:'jsonp',
            success:twitLoader,
            cache:true
        });
    }
    
    
    //Now call the twitLoader initiator!
    if(op.onLoad) $(window).load(twitLoaderinit);
    else $(document).ready(twitLoaderinit);

}
