//var map, icon;
var follow = false;
var latest = '';
var tweets = new Array();
var log = new Array();
var addthis_brand = "adienceitservices.com";
var addthis_share = { templates: { twitter: '{{url}}' } };
var panelFade = 150;



function showAbout() {
	showPanel('#about');
}

function showHelp() {
	showPanel('#help');
}

function showTerms() {
	if ($('#terms .content').html().length < 50) {
		$("#terms .content").load("/terms.html");
	}
	showPanel('#terms');
}

function showPrivacy() {
	if ($('#privacy .content').html().length < 50) {
		$("#privacy .content").load("/privacy.html");
	}
	showPanel('#privacy');
}

function showPanel(selector) {
	panel = $(selector);
	var l = ($(window).width() - panel.width()) / 2;
	var t = ($(window).height() - panel.height()) / 2;	
	if ($('.panel:visible').length > 0) {
		$('.panel:visible').fadeOut(panelFade, function() {
			panel.css('left', l).css('top', t).fadeIn(panelFade);
		});
	}
	else {
		panel.css('left', l).css('top', t).fadeIn(panelFade);
	}
}

function hidePanels() {
	 $('.panel').fadeOut(panelFade);
}

function toggleFollow() {
	follow = !follow;
	if (follow) {
		followTweets();
		$('#map').everyTime('10s', 'follow', followTweets);
	} else {
		$('#map').stopTime('follow');
	}
	$('#follow').html(follow ? 'Follow: On' : 'Follow: Off');
}

function followTweets() {
	if (!follow) return;
	var marker = tweets.shift();
	if (marker) {
		map.setCenter(marker.getPoint(), 10);		
		GEvent.trigger(marker, 'click');
	}
}

function logTweet() {
	var item = log.shift();
	if (item) {
		var lt = $("#tweets").prepend('<li>'+item+'</li>').children('li:first');
		var lh = lt.outerHeight();
		lt.hide();
		$("#tweets").animate({'marginTop': lh}, 500, function() {
			$(this).css('margin-top', '0px');
			lt.fadeIn(400);
		});
	}
}

function toggleLeft() {
	var lv = ($('#left').css('left') == '0px');
	var lx = lv ? '-240px' : '0px';
	var ltx = lv ? '0px' : '240px';
	var ltt = lv ? 'Show info' : 'Hide info';
	var cx = lv ? '10px' : '250px';
	var mly = lv ? '0px' : '-50px';
	$('#left').animate({'left': lx}, 1000);
	$('#left-tab').animate({'left': ltx}, 1000).fadeOut(100, function() { $(this).text(ltt); }).fadeIn(100);
	$('#lmc3d').animate({'left': cx}, 1000);
	$('#logocontrol').animate({'left': cx}, 1000);
	$('#mini-logo').animate({'top': mly}, 1000);
}

function toggleRight() {
	var rv = ($('#right').css('right') == '0px');
	var rx = rv ? '-250px' : '0px';
	var rtx = rv ? '0px' : '250px';
	var rtt = rv ? 'Show tweets' : 'Hide tweets';
	var cx = rv ? '10px' : '260px';
	$('#right').animate({'right': rx}, 1000);
	$('#right-tab').animate({'right': rtx}, 1000).fadeOut(100, function() { $(this).text(rtt); }).fadeIn(100);
	$('#copyright').animate({'right': cx}, 1000);
}




	
	
function gmapsLoaded() {
	$('#logocontrol').css('left', $('#left').width() + 10);
	$('#copyright').css('right', $('#right').width() + 10);
}

function sortTweets(x, y) {
	return x.status_id - y.status_id;
}

function getTweets() {
	$('#status').html('Updating...').animate({'top': '0px'}, 1000);
	$.getJSON('/app/json.php?method=latest&since='+latest, function(data) {
		if (data.tweets) {
			data.tweets = data.tweets.sort(sortTweets);														   
			$.each(data.tweets, function(i, tweet) {
				var distance = 0;
				var home_location, home_marker, destination_location, destination_marker;
				
				var twitpic = tweet.text.match('(?:http://twitpic.com/)[0-9a-z]{5}');
				
				var urls = tweet.text.match(/http\S+/ig);
				if (urls) {
					for (u = 0; u < urls.length; u++) {
	 					var url = urls[u];
						var atext = (url.length > 30) ? url.substr(0, 27)+'...' : url;
						var a = '<a href="'+url+'" target="_blank">'+atext+'</a>';
						tweet.text = tweet.text.replace(url, a);
					}
				}
				
				if (!tweet.profile_image_url) tweet.profile_image_url = 'http://static.twitter.com/images/default_profile_normal.png';
				
				var popUpHtml = '<div class="popup"><a href="http://twitter.com/'+tweet.username+'" target="_blank"><img class="profilepic" height="48" src="'+tweet.profile_image_url+'" width="48" /></a><div><h3><a href="http://twitter.com/'+tweet.username+'" target="_blank">'+tweet.username+'</a></h3>'+tweet.text;
				if (twitpic) {
					var thumbUrl = 'http://twitpic.com/show/thumb/'+twitpic[0].substr(19);
					popUpHtml = popUpHtml + '<br/><br/><a href="'+twitpic+'" target="_blank"><img class="twitpic" src="'+thumbUrl+'" height="150" width="150" /></a>';
				}
				
				var logHtml = '<a href="http://twitter.com/'+tweet.username+'" target="_blank"><img class="profile-pic" src="'+tweet.profile_image_url+'" alt="'+tweet.username+'" /></a><div class="tweet"><h3><a href="http://twitter.com/'+tweet.username+'" target="_blank">'+tweet.username+'</a></h3>'+tweet.text+'</div>';
				
				if (tweet.home_located > 0) {
					home_location = new GLatLng(tweet.home_latitude, tweet.home_longitude);
					home_marker = new GMarker(home_location, { icon: icon });					
				}
				
				if (tweet.destination_located > 0) {
					destination_location = new GLatLng(tweet.destination_latitude, tweet.destination_longitude);
					destination_marker = new GMarker(destination_location, { icon: icon });
				}				
								
				if (home_location && destination_location) {
					var line = new GPolyline([home_location, destination_location], "#ffffff", 3);
					map.addOverlay(line);
					
					distance = home_location.distanceFrom(destination_location, 3963.192).toFixed(0); // miles
				}				
				
				if (distance) {
					popUpHtml = popUpHtml + '<div class="info">Travelling '+distance+' miles</div>';
					logHtml = logHtml + '<div class="info">Travelling '+distance+' miles</div>';
				}
				
				popUpHtml = popUpHtml + '</div></div>';
				
				if (home_marker) {
					GEvent.addListener(home_marker, "click", function() {
						home_marker.openInfoWindowHtml(popUpHtml);
					});
					map.addOverlay(home_marker);
					tweets.push(home_marker);
				}
				
				if (destination_marker) {
					GEvent.addListener(destination_marker, "click", function() {
						destination_marker.openInfoWindowHtml(popUpHtml);
					});
					map.addOverlay(destination_marker);
				}
				
				log.push(logHtml);	
			});
			
			setStatus(data.tweets.length + ' new tweet' + ((data.tweets.length == 1) ? '' : 's'), 10);
		}
		else {
			setStatus('No new tweets', 2);
		}
		latest = data.statusId;
	});
}

function setStatus(text, hold) {
	if (text) {
		$('#status').html(text);
	}
	if (hold) {	
		$('#status').oneTime(hold+'s', function() { hideStatus(); });	
	} else {
		hideStatus();
	}
}

function hideStatus() {
	$('#status').animate({'top': '-30px'}, 1000); 
}

function getDestinations() {
	$.getJSON('/app/json.php?method=destinations', function(data) {
		if (data.destinations) {
			$('#destinations li').fadeOut(500, function() {						   
				$.each(data.destinations, function(i, destination) {
					var item = '<span>'+(i+1)+'.</span> <a href="#" title="Show '+destination.name+' on the map">'+destination.name+'</a> ('+destination.n+')';
					$('#destinations li:eq('+i+')').html(item).fadeIn(Math.random()*2000).click(function() {
						map.setCenter(new GLatLng(destination.latitude, destination.longitude), 10);	
					});
				});
			});
		}
	});
}
