$(document).ready(function(){
    
    var twIsLoading = false;
    var twPage      = $("input[name='twPage']").length ? $("input[name='twPage']").val() : 1;
    
// -------------------------------------------------------------------------------------
        
    $("#tweets").scroll(function() {
        
        var elem        = $(this);
        var twCount     = $('input[name="twCount"]').val() || 0;
        var twUsername  = $('input[name="twUsername"]').val() || 0;
        var twQuery     = $('input[name="twQuery"]').val() || 0;
        var twClass     = $('input[name="twClass"]').val() || 0;
        var twRel       = $('input[name="twRel"]').val() || 0;
        var twTarget    = $('input[name="twTarget"]').val() || 0;
        var twSlug      = $('input[name="twSlug"]').val() || 0;
        var twMethod    = $('input[name="twMethod"]').val() || 0;
        
        if (elem[0].scrollHeight - elem.scrollTop() == elem.height() && twIsLoading === false) 
        {
            twPage++;
            twIsLoading = true;
            
            // Only allow the feed to reload 5 times
            // so we don't overuse our rate for the API
            if(twPage <= 5) 
            {
            	// Show the loading graphic while the request is loading
                $(this).append('<img id="loading_tweet" src="/global/images/loader_large.gif" alt="Loading More Tweets" />');
            	
            	// Position the loading indicator
            	var parent  = elem.parent();
            	var loader  = $("#loading_tweet");
            	
            	// Force the parent element to be relative position
            	parent.css("position", "relative");
            	
            	// Position the loading graphic
            	$("#loading_tweet")
            	    .css("padding", "20px")
            	    .css("position", "absolute")
            	    .css("top", (elem.outerHeight() / 2) - (loader.outerHeight() / 2) + elem.position().top + "px")
            	    .css("left", (elem.outerWidth() / 2) - (loader.outerWidth() / 2) + "px")
            	    .css("border", "1px solid #CCC")
            	    .css("background", "#FFF")
            	    .css("z-index", "100");
                
            	// Make the request to the Twitter API    
        	    $.ajax({
                    type:       "POST",
                    async:      true,
                    url:        "/section/cci?template=TwitterAjax&count="+twCount+
                                    "&page="+twPage+
                                    "&twUsername="+twUsername+
                                    "&twQuery="+twQuery+
                                    "&twMethod="+twMethod+
                                    "&twSlug="+twSlug+
                                    "&TwitterClass="+twClass+
                                    "&TwitterRel="+twRel+
                                    "&TwitterTarget="+twTarget,
                    dataType:   "html",
                    success:    function(response) {
                                    
                                    // Add the response to the bottom of the list
                                    elem.append(response);
                                    
                                    // Update the time tweeted for each item
                                    twGetTimeTweeted(); 
                                    
                                    // Remove the loading graphic and reset status
                                    loader.remove();
                                    twIsLoading = false;                         
                                }
                });
            }    
        }
    });
    
// -------------------------------------------------------------------------------------
    
    // Update the time tweeted for each item on page load
    if($("p.tweeted_ago").length){
        twGetTimeTweeted();
    }
    
// -------------------------------------------------------------------------------------
    
    // Changes Twitter's Ruby time into "posted ago" time
    // and writes it to an element on the page.
    function twGetTimeTweeted()
    {
        // Determines if the browser is IE
        var browser = function() {
          var ua = navigator.userAgent;
          return {
            ie: ua.match(/MSIE\s([^;]*)/)
          };
        }();
        
        // Loop through all of the elements
        $("p.tweeted_ago").each(function(){
                     
            var displayDate = function()
                {
                    var dateString = $(this).attr("title");
                    var rightNow = new Date();
                    var then = new Date(dateString);
                    
                    if (browser.ie) {
                        // IE can't parse these crazy Ruby dates
                        then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
                    }
                    
                    var diff = rightNow - then;
                    
                    var second = 1000,
                        minute = second * 60,
                        hour = minute * 60,
                        day = hour * 24,
                        week = day * 7;
              
                    if (isNaN(diff) || diff < 0) { return "" }
                    if (diff < second * 2) { return "right now" }
                    if (diff < minute) { return Math.floor(diff / second) + " seconds ago" }
                    if (diff < minute * 2) { return "about 1 minute ago" }
                    if (diff < hour) { return Math.floor(diff / minute) + " minutes ago" }
                    if (diff < hour * 2) { return "about 1 hour ago" }
                    if (diff < day) { return  Math.floor(diff / hour) + " hours ago" }          
                    if (diff > day && diff < day * 2) { return "yesterday" }
                    if (diff < day * 365) { return Math.floor(diff / day) + " days ago" } 
                    else { return "over a year ago" }
                    
                }    
            
            // Write the results to the tag and replace the rollover attribute with a readable date
            $(this).html(displayDate).removeClass("tweeted_ago").attr("title", $(this).attr("title").toLocaleString());
                        
        });
    }
    
// -------------------------------------------------------------------------------------
      
});
