/*

Copyright (c) 2011 FIELD Co., Ltd.

 * tweetTicker.js - require jQuery latest
 * Copyright 2011 FIELD Co., Ltd.
 *
 * Created on: 2011.10.21
 * @ Field Inoue

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/


// Settings how to....
/***********************************************
*
BoxWidth: 610,				// Width of ticker 
BoxHeight: 48,				// Height of the ticker
TweetWidth: 610,			// Width of each tweet
TweetHeight: 30,			// Height of each tweet
tweetPadding: 0 0 0 0,	// Up Right Bottom Left
tweetMargin: 35,		// Right Only...
tweetColor: '#333333'	// Color of Tweet text
backGround: '#ffffff',	// Background color...
hashTag: '',			// Twitter hash !! MANDATORY !!
txtAlign: 'left',		// Text-align
anchorColor: 'green',	// Link Color
hashColor: 'green',		// Link Color of hash
ATcolor: 'green',		// Link Color of @
dateColor: 'green',		// Text Color of the date
userColor: 'red',		// Text Color of the user
tweetTxtWhtSp: 'nowrap',// Tweet text white space
tweetImgSize: 48,		// Size of twitter User Image
txtBoxWidth: 250,		// Box Size of text area
lang: 'ja',				// Language...
duration: 1000,			// Animate duration
stay: 5000,				// staying duration
easing: 'leaner' 		// easing .. require jQuery easing,
lastEffect: 'loop' 		// effect of the last frame 'loop' or 'rewind'
*
**********************************************/
/** This script make the elements like below .... 

	<div id="tweetTicker-tweetContainer-wrap">
		<ul id="tweetTicker-tweetContainer">
			<li>
				<div>
					<div>
						<a target="_blank" href="#"><img  /></a>
					</div>
					<div>
						<p><a href="#">@USERNAME</a> <span>2011.01.23 12:34</span></p>
						<p>Tweet TEXT...<a target="_blank" href="#">URL</a> <a target="_blank" href="http://twitter.com/search?q=#">#hash_tag</a></p>
					</div>
					<div style="clear:both;"><hr style="display:none;"></div>
				</div>
			</li>	
		</ul>
	</div>

**/

(function($) {

    $.fn.tweetTicker = function(options) {

        var opt = $.extend({}, $.fn.tweetTicker.defaults, options);
		var Container = $(this);
		Container.append('<ul id="tweetTicker-tweetContainer" style="background:'+opt.backGround+'; list-style-type:none; margin:0; padding:0; position:relative;"></ul>');
		var TweetContainer = $("#tweetTicker-tweetContainer");
		
		var tweetExist = 0;
		
		var adjustDigits = function(num){
			num += "";
			if (num.length === 1) {
				num = "0" + num;
			}
			return num;     
		};
		
		return this.each(function(){
			
			
			
			// Search and Get Tweets !!!
			$.getJSON('http://search.twitter.com/search.json?callback=?&q=from%3A'+encodeURIComponent(opt.hashTag)+'&lang='+opt.lang, function(json){
				// Insert tweets to the container element.
				$.each(json.results, function(i, tweet){
					tweetCount = 0;
					tweetExist = 1;
					tweetCount = tweet.text.length;
					if(tweetCount > 34 ) tweet.text = tweet.text.substring(0 ,34) + '...';
					tweet.text = tweet.text.replace(/#/g, '%23'); // convert # to %23 for this instans...
					tweet.text = tweet.text.replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1" target="_blank" style="color:'+opt.anchorColor+'">$1</a>'); // Get URL and set anchor tag...
					tweet.text = tweet.text.replace(/%23(\w+)/g, '<a href="http://twitter.com/search?q=%23$1" target="_blank" style="color:'+opt.hashColor+'">#$1</a>'); // Link to hash...
					tweet.text = tweet.text.replace(/%23/g, '#'); // Convert back reak %23 to hash...
					tweet.text = tweet.text.replace(/@(\w+)/g, '<a href="http://twitter.com/$1" target="_blank" style="color:'+opt.ATcolor+'">@$1</a>'); // Link to @...
					
					
					var date = new Date(tweet.created_at); // encode time
					
					TweetContainer.append(
						'<li style="width:'+opt.TweetWidth+'px; height:'+opt.TweetHeight+'px; border:0; color:'+opt.tweetColor+'; float:left; list-style-type:none; padding:'+ opt.tweetPadding +'; overflow:hidden; margin:0 '+ opt.tweetMargin +' 0 0;">'
							+'<div style="background:'+opt.backGround+'; border:none; margin:0;">'
								+'<div style="width:'+opt.txtBoxWidth+'px; float:right; border:none;padding:0;white-space:'+opt.tweetTxtWhtSp+'; overflow: hidden;">'
									+'<p style="font-weight:normal;line-height:1.3;margin:0 0 6px 0;padding:0;text-align:left;"><span style="font-size:85%; color:'+opt.dateColor+';">'+date.getFullYear()+"."+adjustDigits(date.getMonth()+1)+"."+adjustDigits(date.getDate())+" "+adjustDigits(date.getHours())+":"+adjustDigits(date.getMinutes())+'</span></p>'
									+'<p style="font-size:93%;font-weight:normal;line-height:1.3;margin:0 0 4px 0;padding:0;text-align:left;">'+tweet.text+'</p>'
								+'</div>'
								+'<div style="clear:both;"><hr style="display:none;" /></div>'
							+'</div>'
						+'</li>'
					);
				});
				
				
				// get width of tweets
				var tweetWidth = 1;
				var tweetHeight = opt.TweetHeight;
				$('li', TweetContainer).each(function(i){
					var thisWidth = $(this).outerWidth({margin: true});
					var thisHeight = $(this).outerHeight({margin: true});
					tweetHeight = (thisHeight > tweetHeight) ? thisHeight: tweetHeight;
					tweetWidth += thisWidth;
				});
				TweetContainer.width(tweetWidth + 100);//100は余白
				
				
				//Making wrapper element
				var txtAlign = 'margin:0 auto';
				if (opt.txtAlign == 'left')  txtAlign = 'margin:0 auto 0 0';
				if (opt.txtAlign == 'right') txtAlign = 'margin:0 0 0 auto';
				var tweetBoxContainer = TweetContainer.wrap('<div id="tweetTicker-tweetContainer-wrap" style="width:'+opt.BoxWidth +'px; height:'+opt.BoxHeight+'px; overflow:hidden;position:relative;'+txtAlign+';padding:0;"></div>');
				
				//ticker
				function ticker(i){
					var stay = opt.stay;
					var left = 0;
					var duration = opt.duration;
					var containerChildren = 0;
					
					if (i == null) i = 1;
					containerChildren = $('li', TweetContainer).size();
					
					if (i <= containerChildren){
						if (i == containerChildren){
							if(opt.lastEffect == 'loop'){
								left = -1 * TweetContainer.outerWidth({margin: true});
							}else{
								left = 0; 
							}
						}
						else{
							left = -1 * $('li', TweetContainer).eq(i).position().left;
						}
					}else{
						// start over
						TweetContainer.css({ left: TweetContainer.outerWidth(true) + 'px' });
						left = 0;
						stay = 0;
						duration = 0;
						i = 0;
					}
					
					TweetContainer.delay(stay).animate({
						left: left + 'px'
					}, duration, opt.easing, function(){
						ticker(++i)
					});
					
				}
				
				// Excute the ticker
				if(tweetExist)	ticker();
				
				//alert(tweetExist);
				if(!tweetExist){
					TweetContainer.append(
						'<li style="width:'+opt.TweetWidth+'px; height:'+opt.TweetHeight+'px; line-height:'+opt.TweetHeight+'px; border:0; color:'+opt.tweetColor+'; float:left; list-style-type:none; padding:'+ opt.tweetPadding +'; overflow:hidden; margin:0 '+ opt.tweetMargin +' 0 0;">'
							+'ツイートを検索できませんでした。'+opt.hashTag+'が存在しない可能性があります。'
						+'</li>'
					);
				}
			});
			
		});
				
	};
	
    $.fn.tweetTicker.defaults = {
        BoxWidth: 610,
		BoxHeight: 30,
		TweetWidth: 610,
		TweetHeight: 30,
		tweetPadding: '10px 0 0 0',
		tweetMargin: '35px',
		backGround: 'none',
		hashTag: '',
		txtAlign: 'left',
		tweetColor: '#333333',
		anchorColor: 'green',
		hashColor: 'green',		
		ATcolor: 'green',
		dateColor: 'greemn',
		userColor: 'red',
		tweetTxtWhtSp: 'nowrap',
		tweetImgSize: 48,
		txtBoxWidth: 250,
		lang: 'ja',
		duration: 1000,
		stay: 5000,
		easing: 'leaner' ,
		lastEffect: 'loop'
    };

})(jQuery);




