// JavaScript Document
var maxLeft = $(window).width();
var maxTop = $(window).height();
var timeName = new Array();
var fMove = new Array();
var tweetArray = new Array();


// VARS instellen
	$(document).ready(function(){
	    // Tweets ophalen en plaatsen
		buildTweets();

	});

function buildTweets() {
	// Tweets ophalen en plaatsen
	// use ['username'] for array of users 
	$('#tweets').getFlyingTweets('aristotelesweb',{ 
			avatar : true,
			maximum : 6,
			divClass : 'flyingTweet',
			textClass : 'flyingText',
			duration: 15000,
			delay: 100,
			reloadAfter : 10,
			direction: 'right'
		});
}

// Random positie krijgen
function randomXToY(minVal,maxVal,floatVal){
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}


(function(jQuery){
  /** public methods **/
  jQuery.fn.getFlyingTweets = function (user, options) {
   try
   {
    var
      opts = jQuery.extend({}, jQuery.fn.getFlyingTweets.defaults, options),
      c = jQuery.isFunction(opts.callback) ? opts.callback: _build,
      url = 'http://search.twitter.com/search.json'
      params = { q : _query(user), page : opts.page, rpp : opts.maximum };

    return this.each(function(i, e) {
      jQuery.ajax({
        url: url,
        data: params,
        dataType: 'jsonp',
        success: function (o) {
          c.apply(this, [(o.results) ? o.results: o, e, opts]);
        }
      });
    });
   } catch (e){}
  };
  
  /** defaults **/
  jQuery.fn.getFlyingTweets.defaults = {
    user: null,
    callback: null,
    page : 1,
    maximum : 10,
	avatar : true,
    divClass : 'flyingTweet',
	textClass : 'flyingText',
	duration : 5000,
	delay: 100,
	reloadAfter : 5,
	direction: 'right'
  };

  /** private methods **/
  var _build = function (object, element, opts)
  {
	
	$(element).html('');
	
    for ( var i = 0; i < object.length; i++ )
    {
        var tweet = '';
		current = object[i];
		user = current.from_user;
		publish_time = current.created_at;
		text = current.text.replace(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/, function (u) {
            var shortUrl = (u.length > 30) ? u.substr(0, 30) + '...': u;
            return '<a href="' + u + '">' + shortUrl + '</a>';
		}).replace(/@([a-zA-Z0-9_]+)/g, '@<a href="http://twitter.com/$1" target="_blank">$1</a>').replace(/(?:^|\s)#([^\s\.\+:!]+)/g, function (a, u) {
            return ' <a href="http://twitter.com/search?q=' + encodeURIComponent(u) + '" target="_blank">#' + u + '</a>';
        });
        tweet += '<div class="'+ opts.divClass +'" id="tweet-'+ current.id+'" rel="'+ current.id+'"><div class="'+ opts.textClass +'" id="text-'+ current.id+'">'+( opts.avatar ? '<a href="http://twitter.com/'+user+'"><img src="'+ current.profile_image_url +'" align="left"></a>' : '')+'<strong>'+ user + '</strong> &ndash; <em>'+ publish_time.substr(5,11) + '</em><div>'+ text +'</div></div></div>' ;
    
		// Add tweet to the page
		$(element).append(tweet);
		// put it on a random place
		
		$('#tweet-'+ current.id).css({'left': 40,'top': 90});
		$('#tweet-'+ current.id).fadeIn(100, function() {});
		
		// Nu gaat we deze tweet laten bewegen
		var m = _move(current.id, opts.direction, opts);
	}
	
	
	// Alle tweets nu activeren om te gaan bewegen
	$('.'+opts.divClass).hover(function(){
	// Mouseover so we pause possible movement
		$(this).stop(true, false);
		var id = $(this).attr('rel');
		$('#text-'+id).css('background-image','url(images/twitter/tweetContainer.png)');
		$('#tweet-'+id).css('zIndex',100);
		$('#text-'+id).fadeIn(500).css({'height':100 , 'width':320});
		
		
		//$(this).css({'left':100, 'top':100});
	}, 
    function () {

		var id = $(this).attr('rel');
		$('#text-'+id).css('background-image','url()');
		$('#tweet-'+id).css('zIndex',99);
		$('#text-'+id).fadeOut(500).css({'height':0 , 'width':0});
		var directionImg = $('#tweet-'+id).css('background-image');
		
		if(directionImg.search(/right.png/i) > 1) {
			$('#tweet-'+ id).animate({'left': randomXToY(maxLeft-450,maxLeft-600),'top': randomXToY(0,maxTop)}, (opts.duration/2));
		} else {
			$('#tweet-'+ id).animate({'left': randomXToY(0,150),'top': randomXToY(0,maxTop)}, (opts.duration/2));
		}
	});

	// Reload alvast definieren
	// Reload instellen na x seconden
	var reloadTweets = function() { _reload(opts); };
	var secReload = (opts.duration + ((opts.delay)-1)) * opts.reloadAfter;
	setTimeout(reloadTweets, secReload);
	
	
  };
  
  
  
  var _move = function(id, direction, opts) {
	
		 	var newDirection = (direction == 'left')? 'right':'left';
			$('#tweet-'+id).css('background-image','url(images/twitter/twitter-bird-'+ direction +'.png)');
			
			
			var maxCSSLeft = (direction == 'right')? randomXToY(maxLeft-450,maxLeft-600) : randomXToY(0,150);
			var toTop = 	randomXToY(0,maxTop) ;		
			// Nu gaan we ze laten verplaatsen
		    $('#tweet-'+id).animate(
				{
						left: maxCSSLeft,
						top: toTop 
				},
				opts.duration,
				function() { 
					
					
				}
			 );
			
			
		
				tweetArray[id] = new Array(direction, opts.duration, maxCSSLeft,toTop);
				// timer setten om hem weer terug te laten gaan
				fMove[id] = function() { _move(id, newDirection, opts); };
				timeName[id] = setTimeout(fMove[id], (opts.delay + opts.duration));
			
				
			
				
	  
  }

  var _reload = function (opts)
  {
	  
	  
	  $('.'+opts.divClass).each(function(index){
			var id = $(this).attr('rel');
			//var directionImg = $('#tweet-'+id).css('background-image');
			//if(directionImg.search(/right.png/i) > 1) {
			//	$('#tweet-'+ id).animate({'left': randomXToY(maxLeft-450,maxLeft-600),'top': randomXToY(0,maxTop)}, opts.duration);
			//} else {
				$('#tweet-'+ id).animate({'left': 40,'top': 90}, opts.duration);
			//}
			//$('#tweet-'+id).fadeOut(1000);
			clearTimeout(timeName[id]);
	  });
	  
	  setTimeout('buildTweets()', (opts.duration)*2);
  }
  
  
  var _query = function(q)
  {
    if( typeof q == 'string' )
        return '@'+q+' OR '+q;
    else if( typeof q == 'object' )
        return '@'+q.join(' OR @');
    throw 'data type not supported';
  }
})(jQuery);

