function rand_chars(){
	var keylist="abcdefghijklmnopqrstuvwxyz"
		var temp=''
		var plength=5;
	for (var i=0;i<plength;i++){
		temp+=keylist.charAt(Math.floor(Math.random()*keylist.length))
	}
	return temp;
}

APE.Twitter = new Class({

	Extends: APE.Client,

	Implements: Options,

	options: {
		container: document.body
	},

	initialize: function(options){
		this.setOptions(options);
		this.els = {};
		this.trends = new $H;
		this.twittAnimSpeed = 500;
		this.twittHeight = 10;
		this.twitt_text = [];
		this.trendResize = false;
		this.trendFx = new $H;
		this.tQueue = [];

		this.addEvent('load', this.initPlayground);
//		this.addEvent('multiPipeCreate', this.pipeCreate);
		
		this.onRaw('trends', this.rawTrends);
		this.onRaw('twitter', this.twitter);
		this.onRaw('trendupdate', this.updateTrend);


		for (var i = 0; i < 10; i++) {
			this.tQueue[i] = [];
		}

		this.colors = ['bc5353', 'dec46a', '8bde6a', '6aded7', '1c3fb0', '9d1cb0', 'f5fbb6', '085822', '70bdff', '5f5f5f'];
	},

	initPlayground: function(){
		this.core.start({"name":rand_chars()});
		this.els.container = new Element('div', {'id': 'twitter_container'}).inject(this.options.container);	
		this.els.twitter_container = new Element('div',{'id': 'twitter_containers_twitts'}).inject(this.els.container);
		this.els.name_container = new Element('div', {'id': 'trend_name_container'}).inject(this.els.container);
		this.twittPoll.delay(this.getRandom(400, 700), this);
	},

	rawTrends: function(raw) {
				for(var i = 0; i < 10; i++) {
					this.newTrend(raw.data[i], i);
				}
/*				var trendHistory = JSON.decode(decodeURIComponent(pipe.pipe.properties.trend_history));
				for (var k in trendHistory) {
					var trend = this.trends.get(k.toLowerCase());
					if (trend) {
						for (var i = 0; i < trendHistory[k].length; i++) {
							this.tQueue[trend.index].push([trend, trendHistory[k][i]]);
						}
					 }
				}*/
	},

	twittPoll: function() {
		var idx = [];
		var i = 0;
		var args;
		var stop = false;
		for (var i = 0; i < 10; i++) {
			args = this.tQueue[i].shift();
			if (args) {
				this.addTwitt.delay(this.getRandom(0, 350), this, args );
			}
		}

		this.twittPoll.delay(this.getRandom(500, 900), this);
	},

	updateTrend: function(data) {
		var trendDiff = data.data;
		
		var oldIndex = new Array();

		for (var i = 0; i < trendDiff.toDel.length; i++) {
			if (this.trends.get(trendDiff.toDel[i].toLowerCase())) {
				oldIndex.push(this.delTrend(trendDiff.toDel[i]));
			}
		}
		var l = oldIndex.length;
		for (var i = 0; i < l; i++) {
			this.newTrend(trendDiff.toAdd[i], oldIndex.shift());
		}

	},

	delTrend: function(trend) {
		var tmp = this.trends.get(trend.toLowerCase());
		var index = tmp.index;
		tmp.els.t_container.destroy();
		tmp.els.name.destroy();
		
		this.trends.erase(trend);

		return index;
	},

	newTrend: function(trend, index){
			var t_container = new Element('div',{'class':'trend trend_'+index}).inject(this.els.twitter_container);
			var t = new Element('div').inject(t_container, 'top');
			var top = new Element('div', {
					'class': 'trend_top', 
					'styles': {
						'margin-top':'363px',
						'background-color':'#' + this.colors[index]
					}
				}).inject(t_container);

			var top_over = new Element('div', {
					'class': 'trend_top_over',
					'styles':{
						'opacity': 0
					}
			}).inject(top,'after');

			var container = new Element('div', {
					'class': 'trend_container',
					'styles': {
						'background-color':'#' + this.colors[index]
					}
				}).inject(t_container);

			var container_over = new Element('div', {
						'class': 'trend_container_over',
						'styles':{
							'opacity': 0
						}
					}).inject(container,'after');
			var trendName = trend;
			if (trend.length>10) trendName = trendName.substring(0,10)+'...';
			var name =  new Element('div', {
						'class': 'trend_name',
						'text': unescape(trendName).replace(/\+/g,' ')
					}).inject(this.els.name_container);
			this.trends.set(trend.toLowerCase(),{
					'els': {
						't_container': t_container, 
						'container': container, 
						'top': top,
						'container_over': container_over,
						'top_over': top_over,
						't':t,
						'name': name
					},
					'index': index,
					'topPos': 363
				});
	},

	resetTrendSize: function() {
		this.trendResize = true;
		this.trends.each(function(trend) {
			if (trend.fx) {
				trend.fx.cancel();
			}
			$$('.twitter_container').destroy();
			var fx = new Fx.Morph(trend.els.top, {duration:200});
			trend.topPos = 363;
			fx.start({
				'margin-top': 363
			});
		}.bind(this));
		(function(){ this.trendResize = false}).delay(220,this);
	},

	addTwitt: function(trend, twitt){
		if (trend.topPos <= 25) {
			this.resetTrendSize();
			return null;
		}

		if (!this.trendResize) {
			var tmp = new Element('div', {'class': 'twitter_container'}).inject(trend.els.t,'top');
			new Element('div', {'styles':{'background-color':'#' + this.colors[trend.index]}, 'class': 'twitt'}).inject(tmp);
			var twitt_el = new Element('div', {'class': 'twitt_over', 'styles':{'opacity':0}} ).inject(tmp);
			var first_fx = new Fx.Morph(tmp, {'duration': this.twittAnimSpeed});

			(function(el) { //flash the falling element
				var fx = new Fx.Morph(el, {'duration':100});
				fx.start({'opacity':1});
			}).delay(this.twittAnimSpeed-340, this, twitt_el);
			
			//Make the falling element fall
			first_fx.start({
					'margin-top': [0, trend.topPos-15]
				});

			//destroy the falling element
			//make the trend grow
			//Flash  the trend
			first_fx.addEvent('complete', function(trend, twitt, el){
					el.destroy();
					if (!this.trendResize) {
						var fx = new Fx.Morph(trend.els.top,{'duration':550, transition: Fx.Transitions.Elastic.easeOut});
						var old_top = trend.els.top.getStyle('margin-top').toInt();

						trend.fx = fx;

						fx.start({
							'margin-top': old_top-this.twittHeight
						});


						var fxc1 = new Fx.Morph(trend.els.container_over, {'duration':'50'});
						var fxc2 = new Fx.Morph(trend.els.container_over, {'duration':'250'});

						var fxt1 = new Fx.Morph(trend.els.top_over, {'duration':'50'});
						var fxt2 = new Fx.Morph(trend.els.top_over, {'duration':'250'});

						fxc1.start({'opacity':1});

						fxc1.addEvent('complete', function(fx2) { 
							fx2.start({'opacity':0})
						}.bind(this, fxc2));

						fxt1.start({'opacity':1});

						fxt1.addEvent('complete', function(fx2) { 
							fx2.start({'opacity':0})
						}.bind(this, fxt2));
					}
				}.bind(this, [trend, twitt, tmp]));

			//Add the twitt text
			first_fx.addEvent('complete', function(trend, twitt, el){
					if (this.twitt_text.length >= 9) {
						var el = this.twitt_text.shift();
						el.destroy();
					}
					twitt=  unescape(twitt).replace(/\+/g,' ');
					if (twitt> 70) twitt= twitt.substring(0, 70)+ '...';
					var tmp = new Element('div', {
						'html': twitt,
						'class': 'twitt_txt twitt_' + trend.index,
						'styles': {
							'color': '#'+this.colors[trend.index]
						}
					}).inject(this.els.name_container, 'after');

					this.twitt_text.push(tmp);


			}.bind(this, [trend, twitt, tmp]));

			trend.topPos -= this.twittHeight;
		}
	},

	twitter: function(data){
		var twitts = data.data;
		var trend = this.trends.get(twitts.trend.toLowerCase());
		if (!trend && this.trends.getLength() < 10 ) {
			this.newTrend(twitts.trend.toLowerCase(), this.trends.getLength());
			trend = this.trends.get(twitts.trend.toLowerCase());
		}
		if (trend) {
			this.tQueue[trend.index].push([trend, twitts.text]);
		} 
	},

	getRandom: function(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}

});
