var google = null;

var fml = new Class({
	Extends: APE.Client, 
	Implements: Options,
	
	options:{
		container: null,
		logs_limit: 10,
		container: document.body
	},
	
	filter: false,
	pause: false,
	elements: [],
	format: '%B %d%o, %Y at %X',

	initialize: function(options, history) {
		this.mapKey = 'ABQIAAAA6KUuwMXyv847hB4epiS4IRQvqivbCs1yi-G2XlWaNOYs7uae4RQQ5oPzmfv6hlwrFT0YyHReoA5Grw';
		
		this.setOptions(options);
		this.currentPipe = null;
		this.logging = true;
		this.addEvent('load', this.start);
		this.onRaw('fml', this.rawFML);
		this.onRaw('counter', this.rawCounter);
		this.onError('004', this.reset);

		this.filter = false;

		if (window.location.hash == '#null') window.location.hash = '';

		if (window.location.hash != '#map') {
			this.filter =  window.location.hash.replace('#', '');
			if (this.filter == '') this.filterNav(false);
			else this.filterNav();
			
			this.initText();
		} else {
			$('btn').set('class', 'btext');
			this.initMap();
		}

		document.addEvent('keyup', function(ev) {
		   if (ev.code == 32) this.pauseStream();
		}.bind(this));

		$('btn').addEvent('click', function(ev) {
			if ($('btn').get('class') == 'bmap') {
				$('btn').set('class', 'btext');
				window.location.hash = 'map';
				$('fuck_content').empty();
				this.initMap();
				new Fx.Tween($('fuck_content'), {'duration': 2500}).start('opacity', 0, 1);
			} else {
				$('btn').set('class', 'bmap');
				$('fuck_content').empty();
				$('nav').setStyle('display', 'block');
				window.location.hash = '';
				this.filter =  window.location.hash.replace('#', '');
				this.filterNav(false);
				this.initText();
				history();
			}
		}.bind(this));
	},
	
	initText: function() {
		$$('.filter a').addEvent('click', function(ev) {
			var el 	 = $(ev.target).getParent();
			var elID = el.get('id');
			this.filterContent(elID);
			ev.stop();
		}.bind(this));
	},
	
	initMap: function() {
		$('nav').setStyle('display', 'none');
		new Element('div', {
			'id':    'map_canvas',
			'width': '100%',
			'style': 'height:'+($('fuck_content').getSize().y+50)+'px; border: 1px solid #AAA;'
		}).inject($('fuck_content'), 'top');

		google = new GMap2(document.getElementById("map_canvas"));
		google.setCenter(new GLatLng(37.2947, -96.0008), 3);
		google.setUIToDefault();
		google.setMapType(G_PHYSICAL_MAP);
	},

	start: function() {
		this.core.start();
	},

	rawFML: function(raw) {
		try {
			if ($defined(raw.data.user.avatar)) {
				this.create(raw.data.id, decodeURIComponent(raw.data.content), decodeURIComponent(raw.data.date), [raw.data.user.nickname, raw.data.user.avatar], 'tweet', raw.data.user.options.location);
			} else {
				this.create(raw.data.id, decodeURIComponent(raw.data.content), raw.data.time, raw.data.user, raw.data.tag, [raw.data.country[0], raw.data.region[0]]);
			}
		} catch(er) {}
	},
	
	rawCounter: function(raw) {
		var i = raw.data.count.toInt();
		var s = ' ';

		if (i > 1) s = 's ';
		$('counter').set('text', i + ' user'+ s +'online');
	},
	
	reset: function(){
		this.core.clearSession();
		this.core.initialize(this.core.options);
	},

	filterNav: function(execpt) {
		$$('.filter').removeClass('select');
		if ($defined(execpt) == false) {
			$(this.filter).addClass('select');	
			$('fml').setStyle('left', ($(this.filter).getPosition().x)+'px');
		} else {
			$('all').addClass('select');
			$('fml').setStyle('left', 'auto');
		}
	},

	pauseStream: function() {
		if (this.pause == true) {
			this.pause = false;
			$('play_button').set('style', 'background-position: 0 0');	
		} else {
			this.pause = true;
			$('play_button').set('style', 'background-position: 0 -29px');
		}
		this.bigPause();
	},
	
	bigPause: function() {
		if (this.pause) $('big_pause').set('html', '<img src="http://static.weelya.com/fuckmylive/template/imgs/pauseBig.png" style="width: 100%; height: 100%" alt="Pause"/>');
		else $('big_pause').set('html', '<img src="http://static.weelya.com/fuckmylive/template/imgs/playBig.png" style="width: 100%; height: 100%" alt="Play"/>');
		
		new Fx.Morph($('big_pause'), {duration: 500}).start({
			'opacity': [1, 0],
			'display': ['none', 'block'],
			'width': ['200px', '300px'],
			'height': ['200px', '300px'],
			'margin-left': ['-100px', '-150px'],
			'margin-top': ['-100px', '-150px']
		}).addEvent('complete', function() {
			$('big_pause').set('style', 'display: none')
		});
	},

	filterContent: function(id) {
		if (id == 'all') {
			this.filter = false;
			this.filterNav(false);
			window.location.hash = null;
		} else {
			this.filter = id;
			this.filterNav();
			window.location.hash = id;
		}

		new Fx.Tween($('fuck_content')).start('opacity', 1, 0).addEvent('complete', function() {
			if (id == 'all') {
				$$('.msg').setStyle('display', 'block');
			} else {
				$$('.msg').setStyle('display', 'none');
				$$('.'+id).setStyle('display', 'block');
			}	
			new Fx.Tween($('fuck_content')).start('opacity', 0, 1);
		}.bind(this));
	},

	create: function(id, txt, time, user, tag, loc) {
		if (this.pause == false) {
			if (window.location.hash != '#map') {
				var msg = new Element('div', {
					'class': 'msg '+tag, 
					'id': 	 'msg_'+id,
					'style': 'opacity: 0'
				});

				if (this.filter != false && tag != this.filter) {
					msg.setStyles({'display': 'none', 'opacity': 0});
				}
		
				var msgTxt = new Element('p', {
					'class': 'txt'
				});
			
				var txt = this.parseText(txt);
			
				txt.each(function(el) {
					if ($type(el) == 'element') {
						msgTxt.grab(el);
					} else {
						msgTxt.grab(new Element('span', {'html':el}))
					}
				});
		
				var theDate = new Date().format(this.format);

				var msgMeta = new Element('p', {
					'text':  '#'+id+' - ' + theDate,
					'class': 'meta'
				});
		
				var userName = null;
	
				if (user.length == 2) {			
					var twitterMin = new Element('img', {
						'src': 'http://static.weelya.com/fuckmylive/template/imgs/twitter.png',
						'alt': 'Twitter',
						'class': 'twitter_min'
					}).inject(new Element('a', {
						'href': 'http://twitter.com/'+user[0],
						'target': '_blank'
					}).inject(msgTxt, 'top'));
			
					var twitterAvatar = new Element('img', {
						'src': 'http://static.weelya.com/fuckmylive/template/imgs/stroke.png',
						'alt': user[0],
						'class': 'avatar',
						'style': 'opacity:0; background-image: url("'+user[1]+'");',
						'events': {
							'load': function() {
								new Fx.Tween(this, {'duration': 400}).start('opacity', 0, 1);
							}
						}
					}).inject(msgTxt, 'top');
			
					new Element('a', {
						'href': 'http://twitter.com/'+user[0],
						'text': user[0],
						'target': '_blank'
					}).injectInside(new Element('span', {
						'text': ' - '
					}).inject(msgMeta, 'bottom'));
				} else {

					new Element('img', {
						'src': 'http://a1.twimg.com/profile_images/107103218/fml_twitter_bigger.png',
						'alt': user[0],
						'class': 'avatar fml_av'
					}).inject(msgTxt, 'top');
				}

				msgTxt.injectInside(msg);
				msgMeta.injectInside(msg);
		
				msg.inject($('fuck_content'), 'top');
		
				msg.setStyle('margin-top', '-'+msg.getSize().y+'px');
				new Fx.Morph(msg, {duration: 300}).start({
					'opacity': [0, 1],
					'margin-top': ['-'+msg.getSize().y+'px', '0px']
				});
		
				if ($defined(this.elements[tag]) == false) {
					this.elements[tag] = [];
				}
		
				this.elements[tag].push(msg);
				if (this.elements[tag].length > 20) {
					var msg = this.elements[tag].shift();
					msg.dispose();
				}
			} else {
				var msgTxt = new Element('p', {
					'class': 'txt'
				});
			
				var txt = this.parseText(txt);

				var msgTxt = new Element('p', {
					'class': 'txt'
				});
			
				txt.each(function(el) {
					if ($type(el) == 'element') {
						msgTxt.grab(el);
					} else {
						msgTxt.grab(new Element('span', {'html':el}))
					}
				});
			
				txt = msgTxt.get('html');
		
				if (loc != null) {
					if (loc.length == 2) {
						var theLoc = loc[0];
						if ($defined(loc[1])) {
							theLoc += ','+loc[1];
						}
					} else {
						loc = loc.replace('iPhone%3A%20', '');
						loc = loc.replace('%C3%9CT%3A%20', '');

						var theLoc = loc;
					}
					if (theLoc != 'null' && $defined(theLoc)) {
						new Request({method: 'get', url: '/map.php'}).send('q='+encodeURIComponent(theLoc)).addEvent('complete', function(result) {
							if (result != null) {
								result    = JSON.decode(result);
								if ($defined(result.Placemark[0].Point)) {
									var point = new GLatLng(result.Placemark[0].Point.coordinates[1], result.Placemark[0].Point.coordinates[0]);
					
									// Set Marker;
									var fmlIcon      = new GIcon();
									fmlIcon.image	 = "http://live.fmylife.com/template/imgs/pin.gif";
									fmlIcon.iconSize  = new GSize(39, 19);
									fmlIcon.iconAnchor = new GPoint(20, 0);
									fmlIcon.infoWindowAnchor = new GPoint(5, 1);

									markerOptions = { icon:fmlIcon };

									if (loc.length == 2) {
										if (loc[1] != 'undefined' && loc[0] != 'undefined') {
											var marker = new GMarker(point, markerOptions);
											google.addOverlay(marker);
											GEvent.addListener(marker, "click", function() {
												this.openInfoWindowHtml('<div style="line-height: 18px; font-size: 11px;"><img src="http://static.weelya.com/fuckmylive/template/imgs/stroke.png" alt="FML" style="background-image: url(http://a1.twimg.com/profile_images/107103218/fml_twitter_normal.png);" class="avatar" /><strong>'+user+'</strong>'+': '+txt+'</div>');
											});
				
											GEvent.trigger(marker, "click");	
											google.panTo(point);
										}
									} else {
										if (loc != 'undefined') {
											var marker = new GMarker(point, markerOptions);
											google.addOverlay(marker);
											GEvent.addListener(marker, "click", function() {
												this.openInfoWindowHtml('<div style="line-height: 18px;"><img src="http://static.weelya.com/fuckmylive/template/imgs/stroke.png" alt="'+user[0]+'" style="background-image: url('+user[1]+');" class="avatar" /> <img src="http://static.weelya.com/fuckmylive/template/imgs/twitter.png" alt="Twitter" style="vertical-align: middle;" /> <a href="http://twitter.com/'+user[0]+'"><strong>'+user[0]+'</strong></a>'+'<br /> '+txt+'</div>');
											});
				
											GEvent.trigger(marker, "click");	
											google.panTo(point);
										}
									}
								}
							}	
						}.bind(this));
					}
				}
			}
		}
	},
	
	parseText: function(txt) {
		txt = txt.replace('\03', '');

		txt = txt.replace(/\02/g, '"');
		txt = txt.replace(/([a-z]{2,6}:\/\/[a-z0-9\-_#\/*+%.~,?&=]+)/gi, '\03$1\04$1\03');
		txt = txt.replace(/([^a-z0-9\-_.\/]|^)((?:[a-z0-9\-_]\.?)*[a-z0-9\-_]\.(?:com|arpa|asia|pro|tel|travel|jobs|edu|gov|int|mill|net|org|biz|arpa|info|name|pro|aero|coop|museum|mobi|[a-z]{2})(?:\/[a-z0-9\-_#\/*+%.~,?&=]*)?)([^a-z]|$)/gi, '$1\03http://$2\04$2\03 ');
		txt = txt.replace(/\@([a-zA-Z0-9_]+)/ig, '\03http://twitter.com/$1\04@$1\03');
		//Contains URLs
		if(txt.contains('\03')){
			var tmp = new Array();
			txt = txt.split('\03');
			txt.each(function(item){
				if (!item.contains('\04')){
				    tmp.push(item);
				} else {

				    var link = item.split('\04');

				    tmp.push(new Element('a', {
				        'href': link[0],
				        'text': link[1],
				        'target': '_blank'
				    }));

				}
			});
			return tmp;
		}
		return [txt];
	}
});

function setSize() {
	$('fuck_content').setStyle('height', (window.getSize().y-170-70)+'px');
	if (window.location.hash == "#map") {
		if ($defined($('map_canvas'))) {
			$('map_canvas').setStyle('height', (window.getSize().y-120)+'px');
			google.setCenter(new GLatLng(37.2947, -96.0008), 4);
		}
	}
}
window.addEvent('resize', function() {
	setSize();
});
document.addEvent('domready', function() {
	setSize();

});
