/**
* TweetMore is a plugin written by and for Church Plant Media specifically for jQuery that allows for searching and filtering tweets
*
*
*
*
* Project Home - http://www.chuchplantmedia.com
* Copyright (c) 2010 Church Plant Media
* @author Lauren Smith
* @version 0.5
* 
*
*/
( function($) {
	
	$.fn.tweetmore  = function( users, options ) {
		
		// Twitter API URL; appended .json since that's the type of data we want
		var API_URL = 'http://search.twitter.com/search.json?callback=?';
		
		// Global HTML Variables
		var tweetBox			= '<div id="tweet-box" style="display:none;" />',
			filterContainer		= '<div id="filter" />',
			filterBlock			= '<div class="filter-block" />',
			tweetHead			= '<div id="tweet-head">',
			tweetBody			= '<div id="tweet-body" />',
			tweetHeader			= '<h1>Latest Tweets</h1>',
			filterButton		= '<a href="#" id="filter-btn">Filter</a>',
			filterInput			= '<input type="radio" name="group_twt" />',
			filterLabel			= '<label />',
			tweetsContainer		= '<div class="twitter-container" />',
			tweetContainer		= '<div class="tweet" />',
			resultsButton		= '<a href="#" id="results">Show Results</a>';
				
		settings = jQuery.extend({
			
			// Defaults; All can be overridden
			tweets	: 3, // Number of tweets to be returned per user
			width	: 250,
			height	: 350,
			showAll	: false,
			tweetSpacing : 20,
			colors	: {
				background		: '#eee',
				text			: '#555',
				links			: '#f00',
				date			: '#aaa',
				border			: '#ccc',
				headerBg		: '#cdcdcc',
				headerText		: '#545454',
				filterBg		: '#c8c8c7',
				filterHov		: '#4b4b4b',
				filterLabels	: '#eee',
				filterText		: '#545454',
				filterHovText	: '#fff',
				filterBorder	: '#b4b4b4',
				filterBtnBg		: '#eee',
				filterBtnText	: '#333',
				filterBtnHovBg	: '#333',
				filterBtnHovText: '#eee'
			}
			
		}, options );
		
		return this.each( function() {
			
			var i, request, style,
				sep			= '+OR+',
				sendData	= '&rpp=100&q=';
			
			// Adding the HTML to the DOM
			$(this).append( tweetBox ); // Create container; Hidden until we're done loading
			$('#tweet-box').append( tweetHead, filterContainer, tweetBody );
			$('#tweet-head').append( tweetHeader, filterButton );
			
			// Setting some ajax settings that don't need to be changed				
			$.ajaxSetup({
				dataType	: 'json',
				global		: false,
				type		: 'GET'
			})
						
			for( i = 0; i < users.length; i++ ) {
				
				var attributes = {
					'value'	: users[i].twitter,
					'id'	: users[i].twitter
				}
				
				// Builds the entire filter box
				$('#filter').append( $(filterBlock).append( $(filterInput).attr(attributes), $(filterLabel).attr({ 'for' : users[i].twitter }).html( users[i].name )  ) )
				// Builds the containers to hold individual tweets
				$('#tweet-body').append( $(tweetsContainer).addClass( users[i].twitter ) );
				
				if ( i >= 0 ) { $('.' + users[i].twitter ).css('display','none'); } // Only show the first user
				if ( i === ( users.length - 1 ) ) { sendData += users[i].twitter; } else { sendData += users[i].twitter + sep; } // Creating the query string
				if ( i === ( users.length - 1 ) ) {
					
					// If showAll is set to true show the all option in the filter tab
					if ( settings.showAll ) {

						$('#filter').append( $(filterBlock).append( $(filterInput).attr({'value':'all','id':'all'}), $(filterLabel).attr({ 'for' : 'all' }).html( 'All' )  ) );
						$('#tweet-body').append( $(tweetsContainer).addClass( 'all' ) );

					}
					
					$('#filter').append( resultsButton );		
					_bindButtons();
					
				}

			}
			
			// Finally we are ready to call twitter and ask for the data; it will be returned as a JSON object
			$.ajax({ url : API_URL, data : sendData, success : function( data ) {
			
				_build(data);
				_setStyles(); // Not ideal but we don't want to have to carry around a separate stylesheet with us for this purpose
				
			}});
			
		});
		
		function _build( data ) {
			
			// Function called after data has been received from twitter
			
			var r, html, user,
				counters = {};
				
			for( i = 0; i < data.results.length; i++ ) {
				
				r						= data.results[i];
				user					= r.from_user;
				counters[user]			= counters[user] || {}; // If the object hasn't been created then create it
				counters[user].count	= ( counters[user].count === undefined ) ? 0 : counters[user].count + 1; // Setup the counter or increase by 1

				if ( settings.showAll ) {
					if ( i < settings.tweets ) {
						$('#tweet-box .all').append( $(tweetContainer).html( _parseTweets(r.text) + '<span>Tweeted on ' + r.created_at.substr(0,12) + ' by <a href="http://www.twitter.com/' + user + '" target="_blank">' + user + '</a></span>' ) );
					}
				}
				
				if ( counters[user].count < settings.tweets ) {
					$('#tweet-box .' + user).append( $(tweetContainer).html( _parseTweets(r.text) + '<span>Tweeted on ' + r.created_at.substr(0,12) + ' by <a href="http://www.twitter.com/' + user + '" target="_blank">' + user + '</a></span>' ) );							
				}
				
			}
			
		}
		
		function _parseTweets( str ) {
			
			// Parses for links
			str = str.replace( /[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
				return url.link(url);
			});
			
			// Parses for @twitter_users
			str = str.replace( /[@]+[A-Za-z0-9-_]+/, function(u) {
				var username = u.replace('@','');
				return u.link('http://www.twitter.com/' + username);
			});
			
			// Parses for hashtags
			str = str.replace( /[#]+[A-Za-z0-9-_]+/, function(t) {
				var tag = t.replace('#','%23');
				return t.link('http://search.twitter.com/search?q=' + tag);
			});
			
			return str;
			
		}
		
		function _bindButtons() {
			
			var fNode = $('#filter'),
				rNode = $('#results');
			
			$(rNode).click( function(e) {
				
				fNode.toggle();
				
				$('#filter-btn').css({
					'background'		: settings.colors.filterBg,
					'color'				: settings.colors.filterText
				});
				
				fNode.removeClass('open');
				
				$('.twitter-container').each( function() {
					$(this).css('display','none');
				})
				
				$('.' + $('#filter input:checked').val()).css('display','block');
				$('#tweet-head a').removeClass('filter-current');
						
				e.preventDefault();
				
			})
			
			$('#filter-btn').click( function(e) {
								
				fNode.toggle();
				
				if ( fNode.hasClass('open') ) {
					$('#tweet-head a').removeClass('filter-current');
					fNode.removeClass('open');
					$('#filter-btn').html('Filter');
				} else {
					fNode.addClass('open')
					$('#filter-btn').html('Filter');
				}
				
				e.preventDefault();
				
			})
			
			$('#filter-btn').mouseover( function() {
				$(this).css({
					'background'		: settings.colors.filterHov,
					'color'				: settings.colors.filterHovText
				});
			})
			
			$('#filter-btn').mouseout( function() {
				if ( ! fNode.hasClass('open') ) {
					
					$(this).css({
						'background'		: settings.colors.filterBg,
						'color'				: settings.colors.filterText
					});
					
				}
			})
			
			$('#results').mouseover( function() {
				$(this).css({
					'background'		: settings.colors.filterBtnHovBg,
					'color'				: settings.colors.filterBtnHovText
				});
			})
			
			$('#results').mouseout( function() {
				$(this).css({
					'background'		: settings.colors.filterBtnBg,
					'color'				: settings.colors.filterBtnText
				});
			})
			
		}
		
		function _setStyles() {
			
			/* Resetting the styles; this is required because the site may not be using a reset stylesheet */			
			$('#tweet-box *').css({
				'margin'					: '0',
				'padding'					: '0',
				'text-indent'				: '0px'
			})
			
			$('#tweet-box').css({
				'width'						: ( settings.width - 15 ) + 'px',
				'height'					: ( settings.height - 15 ) + 'px',
				'background'				: settings.colors.background,
				'display'					: 'block',
				'overflow'					: 'hidden',
				'padding'					: '55px 15px 15px 15px'
			})
			
			$('#tweet-box #tweet-head').css({
				'overflow'					: 'hidden',
				'position'					: 'relative',
				'background'				: settings.colors.headerBg,
				'width'						: ( settings.width + 15 ) + 'px',
				'height'					: '35px',
				'position'					: 'absolute',
				'top'						: '0px',
				'left'						: '0px'
			})
			
			$('#tweet-box #tweet-head h1').css({
				'float'						: 'left',
				'font'						: 'bold 14px Arial, sans-serif',
				'color'						: settings.colors.headerText,
				'letter-spacing'			: '-1px',
				'position'					: 'relative',
				'top'						: '10px',
				'left'						: '10px'
			})
			
			$('#tweet-box #tweet-head a').css({
				'display'					: 'block',
				'position'					: 'absolute',
				'top'						: '0px',
				'right'						: '0px',
				'padding'					: '10px 10px 0',
				'text-decoration'			: 'none',
				'width'						: '40px',
				'height'					: '30px',
				'font'						: 'bold 12px Arial, sans-serif',
				'background'				: settings.colors.filterBg,
				'color'						: settings.colors.filterText,
				'border-left'				: '1px solid ' + settings.colors.filterBorder
			})
			
			$('#tweet-box #tweet-head a:hover').css({
				'background'				: settings.colors.filterHov,
				'color'						: settings.colors.filterHovText
			});
			
			$('#tweet-box #tweet-head span').css({
				'padding-left'				: '10px'
			})
			
			$('#tweet-box #filter').css({
				'display'					: 'none',
				'position'					: 'absolute',
				'top'						: '35px',
				'left'						: '0px',
				'padding'					: '20px',
				'background'				: settings.colors.filterHov,
				'width'						: ( settings.width - 25 ) + 'px'
			})
						
			$('#tweet-box .tweet').css({
				'margin-bottom'				: settings.tweetSpacing + 'px',
				'font'						: '12px Arial, sans-serif',
				'padding'					: '0 10px ' + settings.tweetSpacing + 'px 10px',
				'border-bottom'				: '1px dotted ' + settings.colors.border,
				'color'						: settings.colors.text
			})
			
			$('#tweet-box .tweet span').css({
				'display'					: 'block',
				'font-size'					: '10px',
				'color'						: settings.colors.date,
				'margin-top'				: '4px'
			})
			
			$('#tweet-box .filter-block').css({
				'margin'					: '10px 0',
				'overflow'					: 'hidden'
			})
			
			$('#tweet-box label').css({
				'display'					: 'block',
				'padding-left'				: '10px',
				'font'						: '12px Arial, sans-serif',
				'color'						: settings.colors.filterLabels,
				'float'						: 'left'
			})
			
			$('#tweet-box input').css({
				'float'						: 'left'
			})
			
			$('#tweet-box #results').css({
				'display'					: 'block',
				'font'						: 'bold 11px Arial, sans-serif',
				'background'				: settings.colors.filterBtnBg,
				'width'						: ( settings.width - 55 ) + 'px',
				'height'					: '9px',
				'padding'					: '8px 0 10px',
				'text-align'				: 'center',
				'margin-top'				: '15px',
				'text-decoration'			: 'none',
				'color'						: settings.colors.filterBtnText,
				'-moz-border-radius'		: '5px',
				'-webkit-border-radius'		: '5px'
			})

		}
				
	};
	
})(jQuery);
