(function($){

	$.fn.jTwitter = function(input) {
		$.each(this, function(i, item){
			new $.fn.jTwitter.instance($(this), input);	
		});
	};
	
	$.fn.jTwitter.instance = function(container, input) {
		this.container = container; 											//Het dom element waaraan deze instance wordt gekoppeld
		this.settings = $.extend({}, $.fn.jTwitter.defaults, input);			//Overschrijf default settings met gegeven settings
		this.init();
	};
	
	
	$.extend($.fn.jTwitter.instance.prototype, {
		
		init: function(){
			var that = this;
			this.since_id = 0;
			
			this.container.append($('<div id="api_top"></div>'));
			
			this.settings = $.extend(true, {}, this.settings);					//Clone
			
			//optional auto reload
			if(this.settings.interval > 0){
				window.setInterval(function(){that.handler()},that.settings.interval);
				that.handler();
			}
			else{
				that.handler();
			}
		},
		
		handler: function(){
			this.items = [];
			switch(this.settings.api_type){
				case "search": this.getDataSearch(); break;
				case "user_timeline": this.getDataUserTimeline(); break;
				case "user_list": this.getDataUserList(); break;
				default: this.getDataSearch();
			}
		},
		
		getDataSearch: function(){
			var that = this;
			var lang = "";
			if(this.settings.lang){
				lang = "&lang="+this.settings.lang_code;
			}
			
			var since = "";
			if(this.since_id !== 0){
				since = "&since_id="+this.since_id;
			}
			this.url = "http://search.twitter.com/search.json?q="+escape(this.settings.query)+"&rpp="+this.settings.count+"&page="+this.settings.page+lang+since+"&callback=?";
			$.getJSON(this.url, function(data){
				$.each(data.results, function(i, item){
					if(i == 0){
						that.since_id = item.id_str;
					}
					
					var output = {};
					output.id = item.id_str;
					output.text = that.string2hash(that.string2user(that.string2url(item.text, that.settings.prefix_class), that.settings.prefix_class), that.settings.prefix_class);
					output.text_alt = '';
					output.text_url = '';
					output.image = item.profile_image_url;
					output.image_alt = item.from_user;
					output.image_url = "http://www.twitter.com/" + item.from_user;//"http://www.twitter.com/" + item.from_user + "/status/" + item.id;
					output.user = item.from_user;
					output.user_name = item.from_user;
					output.user_url = "http://www.twitter.com/" + item.from_user;
					output.date = that.formatDate(item.created_at, 1, that.settings.format_date);
					output.i = i;
					
					that.items[that.items.length] = output;	
				});
				
				that.outputHandler();
			});
		},
		
		getDataUserTimeline: function(){
			var that = this;
			this.url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+this.settings.user+"&count="+this.settings.count+"&page="+this.settings.page+"&callback=?";
			
			$.getJSON(this.url, function(data){
				$.each(data, function(i, item){
					if(i == 0){
						that.since_id = item.id_str;
					}	
				});
				
				that.outputHandler();
			});
		},
		
		getDataUserList: function(){
			var that = this;
			
			var since = "";
			if(this.since_id !== 0){
				since = "&since_id="+this.since_id;
			}
			
			this.url = "http://api.twitter.com/1/"+this.settings.user+"/lists/"+this.settings.list+"/statuses.json?per_page="+this.settings.count+"&page="+this.settings.page+since+"&callback=?";
			
			$.getJSON(this.url, function(data){
				var len = data.length;
				$.each(data, function(i, item){
					if(i == 0){
						that.since_id = item.id_str;
					}
					
					var output = {};
					output.id = item.id_str;
					output.text = that.string2hash(that.string2user(that.string2url(item.text, that.settings.prefix_class), that.settings.prefix_class), that.settings.prefix_class);
					output.text_alt = '';
					output.text_url = '';
					output.image = item.user.profile_image_url;
					output.image_alt = item.user.screen_name;
					output.image_url = "http://www.twitter.com/" + item.user.screen_name;//"http://www.twitter.com/" + item.from_user + "/status/" + item.id;
					output.user = item.user.screen_name;
					output.user_name = item.user.name.toLowerCase();
					output.user_url = "http://www.twitter.com/" + item.user.screen_name;
					output.date = that.formatDate(item.created_at, 2, that.settings.format_date);
					output.i = i;
					
					that.items[that.items.length] = output;
				});
				
				that.outputHandler();
			});
		},
		
		outputHandler: function(){	
			var that = this;
			
			var c = (this.items.length-1);
			while(c >= 0){
				that.beforeRender(that.items[c]);
				c--;
			}
			
			//empty bottom
			$.each($('.api_item'), function(i, item){
				if(i > that.settings.count){
					$(item).remove();
				}
			});
		},
		
		beforeRender: function(output){

			//image
			var image = "";
			if(this.settings.show_image){
				if(this.settings.show_image_link){
					image += "<a href=\""+output.image_url+"\" title=\""+output.image_alt+"\" target=\"_blank\">";
				}
				image += "<img src=\"" + output.image + "\" alt=\""+output.image_alt+"\" class=\""+this.settings.prefix_class+"_image\" />";
				if(this.settings.show_image_link){
					image += "</a>";
				}
			}
			
			//user
			var user = "";
			if(this.settings.show_user){
				if(this.settings.show_user_link){
					user += "<a href=\""+output.user_url+"\" title=\""+output.user+"\" target=\"_blank\">";
				}
				user += output.user_name;
				if(this.settings.show_user_link){
					user += "</a>";
				}
				user += ": ";
			}
			
			//text
			var text = "";
			if(this.settings.show_text_link){
				text += "<a href=\""+output.text_url+"\" title=\""+output.text_alt+"\" target=\"_blank\">";
			}
			text += output.text;
			if(this.settings.show_text_link){
				text += "</a>";
			}
			
			//date
			var date = "";
			if(this.settings.show_date){
				date += output.date;
			}
			
			//put into output object
			var template_data = {};
			template_data.id = output.id;
			template_data.tab = output.tab;
			template_data.image = image;
			template_data.user = user;
			template_data.text = text;
			template_data.date = date;
			
			this.render(template_data);
		},
		
		render: function(output){
			var tweet = '<div id="tweet_'+output.id+'" class="api_item">';
    		tweet += '<div style="float: left; width: 55px;"><span class="api_image_span">'+output.image+'</span></div>';
			tweet += '<div style="float: left; width: 350px;"><span class="api_user">'+output.user+'</span>';
			tweet += '<span class="api_text">'+output.text+'</span>';
         	tweet += '<span class="api_date">'+output.date+'</span></div>';
        	tweet += '<div class="api_clear"></div>';
    		tweet += '</div>';
			
			$('#api_top').after($(tweet).hide().fadeIn());	
		},
		
		string2hash: function(str, prefix_class){
			var regexp = /[\#]+([A-Za-z0-9-_]+)/gi;
			str = str.replace(regexp, ' <a class=\"'+prefix_class+'_link\" target="_blank" href="http://search.twitter.com/search?q=&tag=$1&lang=all">#$1</a>');
			return str;	
		},
		
		string2user: function(str, prefix_class){
			var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
			str = str.replace(regexp, " <a class=\""+prefix_class+"_link\" target=\"_blank\" href=\"http://twitter.com/$1\">@$1</a>");
			return str;		
		},
		
		string2url: function(str, prefix_class){
			var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
			str = str.replace(regexp, " <a class=\""+prefix_class+"_link\" target=\"_blank\" href=\"$1\">$1</a>");
			return str;	
		},	
		
		formatDate: function(date, formatFrom, formatTo){
			//format 1 = Sat, 22 Jan 2011 15:50:25 +0000  //Fri, 24 Dec 2010 13:57:48 -0800
			//format 2 = Sat Jan 22 19:21:39 +0000 2011		
			
			var month = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'};
			
			if(formatFrom == 1){
				var temp = date.split(" ");
				var n_date = temp[1];
				var n_month = month[temp[2]];
				var n_year = temp[3];
				var n_hour = temp[4].split(":")[0] + 2;
				var n_minute = temp[4].split(":")[1];
			}
			if(formatFrom == 2){
				var temp = date.split(" ");
				var n_date = temp[2];
				var n_month = month[temp[1]];
				var n_year = temp[5];
				var n_hour = parseInt(temp[3].split(":")[0],10)+2;
				var n_minute = temp[3].split(":")[1];
			}
				
			if(formatTo == 'd-m-Y H:i'){
				date = n_date+"-"+n_month+"-"+n_year+" "+n_hour+":"+n_minute;
			}
			
			return date;
		}
		
	});
	
	
	//Default settings
	$.fn.jTwitter.defaults = {
		api_type: 'search', 			// twitter api type: search or user_timeline
		query: 'techno', 				// search: search string (see extended search parameters search.twitter.com)
		user: '_jerog',					// username (in case of user_timeline)
		list: 'detroittechno',			// list name
		count: 10, 						// count tweets
		page: 1, 						// page of tweets
		lang: false, 					// only language tweets (search only)
		lang_code: 'nl', 				// specific language
		loader: 'loading...', 			// loading html
		show_user: true, 				// show user in string
		show_user_link: true, 			// enable link for user
		show_image: true, 				// show image (avatar)
		show_image_link: true, 			// enable link for avatar
		show_text_link: false, 			// enable text links
		show_date: true, 				// show date
		interval: 30000, 				// interval of refresh (0 = no interval)
		format_date: 'd-m-Y H:i',		// format date
		prefix_class: 'api', 			// class output div
		template: '#twitter_template'	// twitter template identifier
	};

})(jQuery);
