/**
 * CJ Twitter timeline
 *
 * Copyright (c) 2011 Creative Jar
 *
 * Version 0.1
 *
 */

(function ($) {

	jQuery.fn.cjTwitter = function (options) {
	    options = $.extend({
	    	callback: null
	    }, options || {});
	
	    return this.each(function () {
	    	var oElement = $(this), 
	    	twitterAccounts = $(this).attr("data-twitter-accounts"), 
	    	tweetCount = $(this).attr("data-tweet-count"), 
	    	tUrl = 'http://twitter.creative-jar.ru/index.php?callback=?&users=' + twitterAccounts, 
	    	loadedTweets = {};
	    	
    	    $.getJSON(tUrl, function(data){
    	        $.each(data, function(index, tweets){
    	            for (var i in tweets)
    	            {
    	                var tweet = tweets[i];
    	                loadedTweets[parseInt(tweet.id)] = {
    	                    image: tweet.image,
    	                    login: tweet.login,
    	                    name: tweet.name,
    	                    date: tweet.date,
    	                    text: tweet.text
    	                };
    	            }
    	        });
    	
    	        var statuses = new Array();
    	        $.each(loadedTweets, function(statusId, tweet){
    	            statuses.push(parseInt(statusId));
    	        });
    	        statuses = statuses.sort(rsort);
    	
    	        $(".loading", oElement).remove();
    	
    	        $.each(statuses, function(index, status) {
    	            tweet = loadedTweets[status];
    	            if(index < tweetCount) {
	    	            var html = "<article>";
	    	            html += "<header>";
	    	            html += "<img src=\"" + tweet.image + "\" alt=\"" + tweet.name + " avatar\" />";
	    	            html += "<h1>" + tweet.name + "</h1>";
	    	            html += "</header>";
	    	            html += "<p>" + tweet.text + "</p>";
	    	            html += "</article>";
	    	            $(oElement).append(innerShiv(html));
    	            }
    	            else if(index == tweetCount) {
    	            	if (typeof options.callback == "function") {
    	            		options.callback.call(this);
    	                }
    	                if ($(oElement).is("[data-scroll=true]")) {
    	                    $(oElement).cjInnerScroll({
    	                        minHeight: '350'
    	                    });
    	                }
    	            }
    	        });
    	
	  		});
	  		
	  		function rsort(a, b) {
	  		    if (a > b) return -1;
	  		    if (b > a) return 1;
	  		    return 0;
	  		}
	    });
	};
	
})(jQuery);
