(function(jQuery){
  jQuery.fn.twitter = function (options) {
    var opts = jQuery.extend({}, jQuery.fn.twitter.defaults, options);
    var _this = this;
    var _i = -1;
    var _tweets = [];
	var _timer = null;
	var _tweet = null;

    var _wait = function() {
	  if(_timer) return;
      _timer = window.setTimeout(_rotate, opts.speed);
	};
	var _pause = function() {
      if(_timer) clearTimeout(_timer);
      _timer = null;
	};

    var _rotate = function() {
      _i++;
      _timer = null;
	  if(_i==0) {
	    _tweet = $(document.createElement("div"));
	    $(_this).empty().append(_tweet);
	  }
      if(opts.count==1) {
        _tweet.html(_tweets[_i]);
        return;
      }
	  _tweet.mouseenter(_pause);
	  _tweet.mouseleave(_wait);
      if(_i==0) {
        _tweet.html(_tweets[_i]);
        _wait();
        return;
      }
      if(_i==_tweets.length) _i=0;
      if(opts.animate) {
        _tweet.fadeOut(opts.changeSpeed,function(){
          _tweet.html(_tweets[_i]).fadeIn(opts.changeSpeed,_wait);
        });
      }
      else {
        _tweet.html(_tweets[_i]);
        _wait();
      }
    };

    var _htmlify = function (text) {
      var htmltext = text
        .replace(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/g, '<a href="$1" target="_blank"'+( (opts.linkclass)?('class="'+(opts.linkclass)+'"'):'')+'>$1</a>')
        .replace(/@([a-zA-Z0-9_]+)/g, '<a href="http://twitter.com/$1" target="_blank"'+( (opts.linkclass)?('class="'+(opts.linkclass)+'"'):'')+'">@$1</a>')
        .replace(/#([a-zA-Z0-9_]+)/g, '<a href="http://twitter.com/search?q=%23$1" target="_blank"'+( (opts.linkclass)?('class="'+(opts.linkclass)+'"'):'')+'">#$1</a>');
      return htmltext;
    };

    jQuery.ajax({
      url: (opts.location) + opts.user + '.json',
      data: {count:opts.count},
      dataType: 'jsonp',
	  jsonpCallback: 'json',
      success: function (json) {
          if(!json) return false;
          if(json.length==0) return false;
          $.each(json, function(index, value) {
            _tweets.push(_htmlify(value.text));
          });
          _rotate();
        }
      });
    return true;
  };

  jQuery.fn.twitter.defaults = {
    user: "PwC_LLP",
    count: 1,
    speed: 7000,
    changeSpeed: 500,
    linkclass: null,
    location: 'http://twitter.com/statuses/user_timeline/',
    animate: false
  };
})(jQuery);

