/*
* jTwitter 1.1.1 - Twitter API abstraction plugin for jQuery
*
* Copyright (c) 2009 jQuery Howto
*
* Licensed under the GPL license:
*   http://www.gnu.org/licenses/gpl.html
*
* URL:
*   http://jquery-howto.blogspot.com
*
* Author URL:
*   http://jquery-howto.blogspot.com
*
*/

var _counter = 0;
var _maxCount = 20;
var _requestedNumPosts;
var _numPosts;
var _fnk;
var _username;

(function ($) {
    $.extend({
        jTwitter: function (username, numPosts, fnk) {
            var info = {};

            // If no arguments are sent or only username is set
            if (username == 'undefined' || numPosts == 'undefined') {
                return;
            } else if ($.isFunction(numPosts)) {
                // If only username and callback function is set
                fnk = numPosts;
                numPosts = 5;
            }

            _fnk = fnk;
            _username = username;
            _requestedNumPosts = numPosts;
            _numPosts = numPosts;

            var url = "http://twitter.com/status/user_timeline/"
				+ _username + ".json?count=" + _numPosts + "&callback=?";

            checkCount(url,this);

        }
    });
})(jQuery);

function checkCount(url,ref) {
    $.getJSON(url, function (data) {
        if (data.length < _requestedNumPosts) {
            if(_counter <= _maxCount)
            {
                _counter++;
                _numPosts++;
                var url = "http://twitter.com/status/user_timeline/"
			    	+ _username + ".json?count=" + _numPosts + "&callback=?";
                checkCount(url,ref);
            }
            return;
        }
        else
        {
            var url = "http://twitter.com/status/user_timeline/"
		    	+ _username + ".json?count=" + _numPosts + "&callback=?";
            $.getJSON(url, function (data) {
                if ($.isFunction(_fnk)) {
                    _fnk.call(ref, data);
                }
            });

        }
    });


}
