/*

TwitteringJS - jQuery Plugin

Description:

TwitteringJS allows you to publish news on your website via a twitter account.

@require: jQuery 1.7+
@author: EmaWebDesign
@version: 1.0
@website: www.emawebdesign.com/twitteringjs
@license: MIT and GPL licenses http://jquery.org/license
    
Usage: 

$(element).twitteringjs(options);
    
Options:

Twitter username: Your Twitter username
Hashtag: hashtag to be used to fetch the tweets
maxNumber: max number of tweets to be displayed

*/


(function($) {


  $.fn.twitteringjs = function(options) {
  
    var config = {
      username: 'emawebdesign',
	  hashtag: '#emanews',
      maxNumber: 10
     };
	 
	 var me = this;
	
     var options = $.extend(config, options);  
      

     var TwitteringJS = new function() {
		
		
		  this.replaceURL = function(val) {
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			return val.replace(exp,"<a href='$1' rel='nofollow' target='_blank'>$1</a>"); 
		  }
		  
		  
		  this.replaceMentions = function(val) {
			return val.replace(/([^\w])\@([\w\-]+)/gm,'$1<a href="http://twitter.com/$2" target="_blank" rel="nofollow">@$2</a>');
		  }
		  
		
		  this.run = function() {
		     
			  $.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + options.username + "&count=50&callback=?", function(data) {
	
			  var cont = 0;
		  
			  $.each(data, function(i, item) {
		  
				  var txt = item.text;
				  
				  if ((txt.indexOf(String(options.hashtag))>0 || txt.indexOf(String(options.hashtag))==0) && cont<parseInt(options.maxNumber)) {
				  
				  txt = TwitteringJS.replaceURL(txt);
				  txt = TwitteringJS.replaceMentions(txt);
				  txt = txt.replace(String(options.hashtag),"");
		  
				  me.append('<li>' + txt + '</li>');

				  
				  cont++;
				  
				  }
				  
		  
			  });
			  
				
		  
			  });
	
			 
		  }
		  
		  
		  
		
	};
	
	
	return me.each(function() {
    
       TwitteringJS.run();          
          
    });           
  
  
  };



})(jQuery);
