var SUPPORT_TEMPLATE = "";
var LOAD_LISTENER;
var MAP;
var MAP_LATLNG = new google.maps.LatLng(37.83673,-94.34145);
var MAP_ZOOM = 5        
var IS_NEW_VISIT
// var MAP_LATLNG = new google.maps.LatLng(-41.28551602,174.77675198);
// var MAP_ZOOM = 11

var POINTS;
var CURRENT_POST;
var MAP_TYPE = "day";
var PAGES = ["welcome", "sponsors", "follow-us"];
var RECENT_UPDATES_PAGE = 0;
var LAST_RECENT_LOAD_COUNT;
var KEEP_LOADING_RECENT = true;
var CLOSEST_INDEX;         
var BIOS_LOADED = false

var MARKERS = [];
var CHECKPOINT_MARKERS = [];
var CHECKPOINT_ZOOM_VISIBILITY = 6;
var MARKER_CLUSTERER;          
var NEW_POST_COUNT

function _init(){    
	log.info("_init")

	if($.browser.webkit){
		$("body").addClass("css3")
		$("body").addClass("webkit")				
	}else if($.browser.mozilla){
		$("body").addClass("css3")
		$("body").addClass("mozilla")		
	}else if($.browser.msie){
		$("body").addClass("ie")
	}
	
	_initMap();		
	_showLocation();	
	_getRecentUpdates();	
	_getSupport();
	_getMessagesFromHQ()
	
	//Wire up events
	$("#contentTip div.close").click(_closeTip);
	$("#contentTip div.left").click(_previousPost);
	$("#contentTip div.right").click(_nextPost);
	$("#vitals div.close").click(_hideTeam)
	$("#follow-us div.close").click(_hideTeam)
	$("#products div.close").click(_hideTeam)
	$("#teamIcebreaker div.close").click(_hideTeam)	
	$("#nextCluster, #previousCluster").click(_navigateClusters)
	$("#show-team").click(_showTeam)
	
	//Wire up nav
	$("div.page div.close").click(function(){
		window.location = "#/"
	})
	var A = SWFAddress.getPathNames();
	
	if(A.length <= 0){
		$("#welcome").removeClass("hide")
		$("#welcome .close").click(function(){
			$(this).parent().addClass("hide")
		})
	}
}                        

setInterval(_showTime, 1000)

function _showLocation(){
	$("#currentLocation span.value").text(CURRENT_LOCATION["location_name"]);
	$("#kmTravelled span.value").text(Math.round(CURRENT_LOCATION["distance_travelled"])+"km");
	var distance_to_go = Math.round(CURRENT_LOCATION["distance_to_go"])
	var dtg = ""+distance_to_go
	if(distance_to_go > 1000){
		var A = dtg.split("")
		dtg = A[0]+","+A[1]+A[2]+A[3]
	}
	$("#distanceToGo span").text(dtg+" km")
	CLOSEST_INDEX = CURRENT_LOCATION["closest_point"];
}

function _initMap() {                                             
	log.info("_initMap")	
	
	if(IS_NEW_VISIT){
		MAP_ZOOM = 9 		
		// MAP_LATLNG = new google.maps.LatLng(ALL_POSTS[0]["lat"], ALL_POSTS[0]["lng"])
		MAP_LATLNG = new google.maps.LatLng(33.25088, -117.29996)
	}else{                               
		MAP_ZOOM = 9		
		var lastPost = _constrainNumber(ALL_POSTS.length-NEW_POST_COUNT, 0, ALL_POSTS.length-1);
		MAP_LATLNG = new google.maps.LatLng(ALL_POSTS[lastPost]["lat"], ALL_POSTS[lastPost]["lng"])
	}
	
	var myOptions = {
		zoom: MAP_ZOOM,
		center: MAP_LATLNG,
		// mapTypeId: google.maps.MapTypeId.SATELLITE,
		// disableDefaultUI:true,
		backgroundColor:"#303030",
		mapTypeControl: false,
		navigationControl: false,
		// navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		// mapTypeId: google.maps.MapTypeId.ROADMAP
		mapTypeId: google.maps.MapTypeId.SATELLITE
	};
	MAP = new google.maps.Map(document.getElementById("map"), myOptions);     

	LOAD_LISTENER = google.maps.event.addListener(MAP, 'tilesloaded', _tilesLoaded) 
}

function _tilesLoaded(){    
	log.info("_tilesLoaded")	    
	google.maps.event.removeListener(LOAD_LISTENER);	
	$("#map div").each(function(){  
		if($(this).text().indexOf("Terms of Use") >= 0){
			if($(this).children("div").length == 1){
				$(this).attr("id", "copyrightText")
			}
		}
	});	
	$("#copyrightText span").each(function(){
		if($(this).text() == " - "){
			$(this).remove()
		}
	})
	
	var linePoints = [];	
	for (i = 0; i < summaryData.length; i++) {
		linePoints.push(
			new google.maps.LatLng(summaryData[i][0], summaryData[i][1])	
		);	
	}	
	
	var line = new google.maps.Polyline({
		map: MAP,
		path: linePoints,
		strokeColor: "#FFF",
		strokeOpacity: 1,
		strokeWeight: 4
	});                      
	
	var line = new google.maps.Polyline({
		map: MAP,
		path: linePoints.slice(0, CLOSEST_INDEX),
		strokeColor: "#B9413D",
		strokeOpacity: 1,
		strokeWeight: 4
	});

	POINTS = ALL_POSTS;
	_addMarkers();

	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, _handleHashChange);	
	
	$("#zoomInMap").click(function(){
		if(MAP.getZoom() <= 15){
			MAP.setZoom(MAP.getZoom()+1)
		}
		return false
	})                 
	
	$("#zoomOutMap").click(function(){ 
		log.info(MAP.getZoom())
		if(MAP.getZoom() > 2){
			MAP.setZoom(MAP.getZoom()-1)			
		}		
		return false
	})       
	
	$("#toggleMap").click(_toggleMap)
}


function _getSupport(){
	log.info("getSupport")
	_makeSupportTemplate();
	$.each(SUPPORT_MESSAGES, function(i, o) {
		var date = Date.parse(o["created_at"]);
		$("div#supportStream div.content").append(SUPPORT_TEMPLATE, {
			date:date.toString("hh:mmtt MMMM d"),
			status:o["text"].linkify_tweet(),
			user:o["from_user"],
			statusID:o["id"]
		});
	});
	
	$("#supportStream .content .loading").remove();
	$("#supportStream .content").addClass("hide");
	$("#showSupport").removeClass("hide");	
	$(".supportItem:even").addClass("even");
	$("#supportStream .content").animate({
		opacity:0
	}, 0);
	$("#supportStream .content").animate({
		opacity:1
	}, 500);
	$("#supportStream .content").removeClass("hide");
}

function _makeSupportTemplate(){
	T = ""
	T += "<div class=\"supportItem\" id=\"supportItem\">"
	T += "<p class=\"date\">${date} via <a href=\"http://www.twitter.com/${user}/statuses/${statusID}\" target=\"_blank\">${user}</a></p>"
	T += "<p class=\"status\">${status}</p>"
	T += "</div>" //.supportItem
	SUPPORT_TEMPLATE = $.template(T);
}

String.prototype.fixCaption = function(){
	var S = this;
	S = S.replace("Hamish Allen", "Hamish Allan")
	S = S.replace("hamish allen", "hamish allan")
	return S;
}         

String.prototype.linkify_tweet = function() {
	var tweet = this
	tweet = tweet.replace(/\b(https?:\/\/[^\s+\"\<\>]+)/igm, "<a href=\"$1\">$1</a>");
	tweet = tweet.replace(/(^|\s)@(\w+)/g, "$1<a href=\"http://www.twitter.com/$2\">@$2</a>");
	return tweet.replace(/(^|\s)#(\w+)/g, "$1<a href=\"http://search.twitter.com/search?q=%23$2\">#$2</a>");
};
          
function _getMessagesFromHQ(){     
	log.info("getMessagesFromHQ")	
	$.getJSON("http://raam-icebreaker.tumblr.com/api/read/json?tagged=channel1&callback=?", function(D){
		$("#icebreakerHQ .content .loading").remove()
		var o = D["posts"][0]
		$("#channel1").html(""+o["regular-body"]+"")
		$("#channel1").append({}, "<p class=\"meta\">"+Date.parse(o["date"]).toString("hh:MM MMMM d")+" via <a href=\"http://raam-icebreaker.tumblr.com/post/"+o["id"]+"\">tumblr</a></p>")
		$("#channel1").animate({
			opacity:0
		}, 0)
		$("#channel1").removeClass("hide")
		$("#channel1").animate({
			opacity:1
		}, 500)
		$.getJSON("http://raam-icebreaker.tumblr.com/api/read/json?tagged=channel2&callback=?", function(D){
			var o = D["posts"][0]
			$("#channel2").html(""+o["regular-body"]+"")
			$("#channel2").append({}, "<p class=\"meta\">"+Date.parse(o["date"]).toString("hh:MM MMMM d")+" via <a href=\"http://raam-icebreaker.tumblr.com\">tumblr</a></p>")
			$("#channel2").animate({
				opacity:0
			}, 0)
			$("#channel2").removeClass("hide")
			$("#channel2").animate({
				opacity:1
			}, 500)
		})
	})
}

function _addMarkers(){
	log.info("_addMarkers()")
	
	var image = new google.maps.MarkerImage('/static/images/map.marker.black.bg.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(22, 36),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(0, 36));
                            
		var shape = {
		      coord: [0, 0, 0, 36, 36, 20, 36, 0],
		      type: 'poly'
		  };       
		
	for(var i=0; i<POINTS.length; i++){      
		
		var o = POINTS[i]
		                             
		var id = o["id"]
		var type;
		if(id.indexOf("twt_") >= 0){
			type = "twitter"
		}else if(id.indexOf("tmb_") >= 0){
			type = "tumblr"
		}             
		id = id.replace("twt_", "").replace("tmb_", "")
		
		var latlng = new google.maps.LatLng(Number(o["lat"]), Number(o["lng"]))
		// log.info(latlng)
		var marker = new google.maps.Marker({
			position: latlng,
			// map: MAP,
			icon: image,   
			shape: shape,
			id:id,       
			type:type,
			zIndex:7
		});
		
		POINTS[i].marker = marker;
		marker.post = POINTS[i]
		marker.index = i
		MARKERS.push(marker)
	
		google.maps.event.addListener(marker, "click", function(){
			window.location = "#/"+this.type+"/"+this.id
		})
	}                     
	
	MARKER_CLUSTERER = new MarkerClusterer(MAP, MARKERS, {
		maxZoom: 13,
	  	gridSize: 34,
		zoomOnClick: false,
		styles: [{
			url: '/static/images/map.cluster.bg.png',
			height: 36,
			width: 23,
			opt_anchor:[5, 4],
			opt_textColor: '#FFF'
		},{
			url: '/static/images/map.cluster.bg.png',
			height: 36,
			width: 23,
			opt_anchor:[5, 4],
			opt_textColor: '#FFF'
		},{
			url: '/static/images/map.cluster.bg.png',
			height: 36,
			width: 23,
			opt_anchor:[5, 4],
			opt_textColor: '#FFF'
		}]
	});

	MARKER_CLUSTERER.zoomOnClick_ = false;    
	
	google.maps.event.addListener(MARKER_CLUSTERER, "clusterclick", function(cluster) {
		var m = cluster[0].markers_[0]
		window.location = "#/"+m.type+"/"+m.id 
	})
	
	_addCheckpoints();
	
	setTimeout(function(){
		$("#mapPreloader").animate({
			opacity:0
		}, 300, function(){
			$(this).remove()
			var A = SWFAddress.getPathNames();
			if(A.length > 0){
				_handleHashChange()
			}       
		})    
	}, 0)

	google.maps.event.addListener(MAP, "zoom_changed", function(a){
		_closeTip();
		_setCheckpointMarkerVisibility(
			MAP.getZoom() > CHECKPOINT_ZOOM_VISIBILITY
		);
	});
	google.maps.event.addListener(MAP, "dragstart", function(a){
		_closeTip();
	});	
	
}          

function _hideTeam(){              
	/*
	
	var A = SWFAddress.getPathNames(); 	
	
	if(A[0] == "team"){
		window.location = "#/team/"
	} 
	 
	*/                      
	$("#teamIcebreaker").addClass("hide")
	$("#products").addClass("hide")
	$("#vitals").addClass("hide")
	$("#recentUpdates").removeClass("hide")
	$("#icebreakerHQ").removeClass("hide")
	$("#supportStream").removeClass("hide")
}                      

function _handleHashChange(){    
	log.info("_handleHashChange()")
	
	var A = SWFAddress.getPathNames();  
	// google analytics event tracking... 	
	if(A.length <= 1){
		_gaq.push(['_trackEvent', A[0], "/"]);  		
	}else{
		_gaq.push(['_trackEvent', A[0], A[1]]);  		
	}
	   
	for(var i = 0; i<PAGES.length; i++){
		var page = PAGES[i]
		if(!$("#"+page).hasClass("hide")){
			$("#"+page).addClass("hide")
		} 
	}            
	/*          
	$("#teamIcebreaker").addClass("hide")
	$("#vitals").addClass("hide")
	$("#recentUpdates").removeClass("hide")
	$("#supportStream").removeClass("hide")
	*/
	var doCloseTip = false;
	var tip = $("#contentTip")  
	
	switch(A[0]){
		case "sponsors":
		// closeTip = true;
		$("#sponsors").removeClass("hide")
		break  
		case "follow-us":
		case "followus":                 
		$("#follow-us").removeClass("hide")
		break  
		case "team":
		case "team-bios":
		_showTeam();
		break
	}               
	$("div.clusterButton").addClass("hide")
	if(A.length <= 0 || doCloseTip){
		tip.attr("class", "hide")
	}else{            
		if(A[0] == "tumblr" || A[0] == "twitter"){  
			$("div.clusterButton").removeClass("hide")			
			_showTipContent(A[0], A[1])         
			if(tip.hasClass("hide")){
				tip.attr("class", "hide")			
				tip.animate({
					opacity:0,
					top:"51%"
				}, 0)
				tip.removeClass("hide")					
				tip.animate({
					opacity:1,
					top:"50%"
				}, 200)
			}
		}
	}    
}

function _closeTip(){
	window.location = "#"
	return false
}

function getPointFromId(id){
	for(var i=0;i<POINTS.length; i++){
		var o = POINTS[i];
		if(o["id"] == id){
			return i;
		}
	}
	return -1;
}

function _showTipContent(type, id, wait_for_map){
	// log.info("_showTipContent("+type+","+id+","+wait_for_map+")")
	if(wait_for_map == undefined){
		wait_for_map = false
	}
	var tip = $("#contentTip")    
	tip.attr("class", "hi")
	tip.find("div.content").html("<div class=\"loading\"></div>")
	var key;
	if(type == "tumblr"){
		key = "tmb_"+id;
	}else if(type == "twitter"){
		key = "twt_"+id;
	}
	n = getPointFromId(key);   
	// log.info("n: "+n)
	
	CURRENT_POST = n;	     
	
	$("#contentTip div.right").removeClass("last")	
	$("#contentTip div.left").removeClass("hide")	
	
	if(n >= POINTS.length-1){
		$("#nextCluster").addClass("hide")
		$("#contentTip div.right").addClass("last")
	}                      
	
	if(n == 0){
		$("#previousCluster").addClass("hide") 		
		$("#contentTip div.left").addClass("hide")
	}
	
	var post = 	POINTS[n]; 
	// log.info(POINTS[n])   
	
	if (post.marker.cluster) {
		var latlng = post.marker.cluster.center_;
	} else {
		var latlng = post.marker.position;
	}                         
	
	// log.info("latlng: "+latlng)
	
	if(!wait_for_map){
		MAP.panTo(latlng);
		MAP.panBy(305, -170)  	  
	}                
	
	 $("#contentTip div.right span").text("") 	
	                                                    
	// log.info("post.marker: "+post.marker)
	// log.info("post.marker.cluster: "+post.marker.cluster)
	// log.info("post.marker.cluster.markers_: "+post.marker.cluster.markers_)
	
	if(post.marker.cluster && post.marker.cluster.markers_){
		var cluster = post.marker.cluster
		/*
		for(var i in cluster){
			log.info(i+" = "+cluster[i])
		} 
		*/
		var cluster_index = -1;
		for(var i = 0; i<cluster.markers_.length; i++){
			var m2 = cluster.markers_[i];
			if(m2 == post.marker){
				cluster_index = i;
				break
			}
		}
		if(cluster_index >= 0){
			// log.info("cluster_index: "+cluster_index)
			$("#contentTip div.right span").text(cluster_index+1+"/"+cluster.markers_.length)
		}
		// var cluster_index = cluster.markers_.indexOf(post.marker)
	}else{
		setTimeout(function(){
			_showTipContent(type, id, true)
		}, 1000)
		return
	}              

	
	$.getJSON("/api/get_post/"+key+"/?callback=?", function(D){
		switch(D["post_type"]){
			case "photo":
			_showTweet(D)
			break
			case "tumblr":
			_showTumblr(D);
			break    
			case "video":
			_showTweet(D)
			break       
			case "tweet_text":
			_showTweet(D)
			break
		} 
		// log.info(D["post_type"])
	})
}         

function _showTweet(o){
	var json = o["json"]
	var c = $("#contentTip .content")
	c.html("<div class=\"loading\"></div>")
	if($("body").hasClass("night") || o["post_type"] != "video"){
		$("body").removeClass("night")
	}
	// log.info(o["post_type"])
	switch(o["post_type"]){
		case "video": 
			// twitvid    
			$("body").addClass("night")			
			var embedCode = o["embedly_json"]["html"]
			var wR = /width="[0-9]*"/g;
			embedCode = embedCode.replace(wR, "width=\""+376+"\"")
			var hR = /height="[0-9]*"/g
			embedCode = embedCode.replace(hR, "height=\""+269+"\"")	
			c.append(_getTemplate("twitvid"), {
				videoEmbed:embedCode,
				time:Date.parse(o["post_date"]).toString("dd.MM.yy hh:mmtt"),
				status:o["json"]["text"].linkify_tweet().fixCaption(),
				permalink:"http://twitter.com/"+o["json"]["user"]["screen_name"]+"/statuses/"+o["json"]["id"]+"/"
			})      
		break
		case "photo":
			c.append(_getTemplate("twitpic"), {
				img:o["embedly_json"]["url"],
				time:Date.parse(o["post_date"]).toString("dd.MM.yy hh:mmtt"),
				status:o["json"]["text"].linkify_tweet().fixCaption(),
				permalink:"http://twitter.com/"+o["json"]["user"]["screen_name"]+"/statuses/"+o["json"]["id"]+"/"
			})
		break
		case "tweet_text":
			var status = o["json"]["text"]
			var source = ""
			if(status.indexOf("|") > 0){
				source = status.substring(status.indexOf("|"), status.length).replace("| ", "").replace("|", "")
				status = status.substring(0, status.indexOf("|"))
			}
			c.append(_getTemplate("tumblr-quote"), {
				time:Date.parse(o["post_date"]).toString("dd.MM.yy hh:mmtt"),
				quote:status.linkify_tweet(),
				source:source.fixCaption(),
				permalink:"http://twitter.com/"+o["json"]["user"]["screen_name"]+"/statuses/"+o["json"]["id"]+"/"
			})
		break
	}                               
	c.find(".text a").each(function(){
		var url = $(this).attr("href")
		if(url.indexOf("twitpic.com") > 0 || url.indexOf("twitvid.com") > 0){
			$(this).remove()
		}
	})
	c.find("div.loading").remove()
	
	var D = Date.parse(o["post_date"]);
	var hours = D.getHours()
	if(hours > 5 || hours < 19){
		// $("body").removeClass("night")
		// $("body").addClass("day")   
		if(MAP_TYPE != "day"){
			_setMap("day")
		}
	}else{
		// $("body").removeClass("day")
		// $("body").addClass("night")
		if(MAP_TYPE != "night"){
			_setMap("night")
		}
	}
}

function _showTumblr(O){   
	// $("#contentTip").removeClass("twitter")              
	// $("#contentTip").addClass("tumblr")              
	var c = $("#contentTip div.content")	
	var js = O["json"]   
	
	for(var i=0; i<js["tags"].length; i++){
		var tag = js["tags"][i];
		switch(tag){
			case "update":
			$("#contentTip").addClass(tag)
			break
		}
	}
	var D = Date.parse(O["post_date"]).toString("dd.MM.yy hh:mmtt")
	
	if($("body").hasClass("night") || js["type"] != "video"){
		$("body").removeClass("night")
	}
	
	c.html("")
	
	switch(js["type"]){
		case "regular":    
			c.append(_getTemplate("tumblr-regular"), {
				title:js["regular-title"],
				caption:js["regular-body"].fixCaption(),
				time:D,
				permalink:js["url-with-slug"]
			})
		break  
		case "photo":
			c.append(_getTemplate("tumblr-photo"), {
				img:js["photo-url-500"],
				time:D,
				permalink:js["url-with-slug"],
				caption:js["photo-caption"].fixCaption()
			})                   
			c.find("div.loading").remove()		
		break      
		case "video":    
			$("body").addClass("night")		 
			var embedCode = js["video-player"]
			var wR = /width="[0-9]*"/g;
			embedCode = embedCode.replace(wR, "width=\""+376+"\"")
			var hR = /height="[0-9]*"/g
			embedCode = embedCode.replace(hR, "height=\""+269+"\"")	
			c.append(_getTemplate("tumblr-video"), {
				videoEmbed:embedCode,
				time:D,
				permalink:js["url-with-slug"],
				caption:js["video-caption"].fixCaption()			
			})                   
			c.find("div.loading").remove()		
		break    
		case "quote":
			c.append(_getTemplate("tumblr-quote"), {
				time:D,
				permalink:js["url-with-slug"],
				quote:js["quote-text"],
				source:js["quote-source"].fixCaption()
			})                   
			c.find("div.loading").remove()		
		break
	}
}                     

String.prototype._removeLinkToContent = function() {
	var S = this
	S = S.replace(/http:\/\/(.*twitvid\.com\/.*|.*twitpic\.com\/.*)/i, "");
	return S
};


function _getTemplate(type){      
	var T = "<div class=\"post "+type+"\">";
	switch(type){
		case "twitpic":
		T += "<div class=\"image\"><img src=\"${img}\" /></div>"
		T += "<div class=\"text\"><p>${status}</p></div>"
		break
		case "tumblr-regular":
		T+= "<div class=\"text\">"
		T+= "<h3>${title}</h3>"
		T+= "${caption}"
		T+= "</div>"
		break
		case "tumblr-photo":   
		T+= "<div class=\"image\"><img src=\"${img}\" /></div>"
		T+= "<div class=\"text\">${caption}</div>"
		break  
		case "tumblr-video":
		T+= "<div class=\"video\">${videoEmbed}</div>"
		T+= "<div class=\"text\">${caption}</div>"
		break       
		case "twitvid":
		T += "<div class=\"video\">${videoEmbed}</div>"    
		T += "<div class=\"text\"><p>${status}</p></div>"    		
		break    
		case "tumblr-quote":
		T += "<div class=\"text\">"
		T += "<p class=\"quote\">${quote}</p>"
		T += "<p class=\"source\">${source}</p>"
		T += "</div>"
		break
	}                  
 	T += "<div class=\"clear_left\"></div>"
   	T += "<div class=\"time\"><a href=\"${permalink}\" target=\"_blank\">${time}</a></div>"
	T += "</div>" //.post
	return $.template(T);
}

function _nextPost(){  
	_gaq.push(['_trackEvent', "navigation", "next-post"]);  						
	if(CURRENT_POST < POINTS.length-1){
		var N = CURRENT_POST + 1;
		var newID = POINTS[N]["id"]
		var type
		if(newID.indexOf("twt_") >= 0){
			type = "twitter"
		}else if(newID.indexOf("tmb_") >= 0){
			type = "tumblr"
		}
		newID = newID.replace("twt_", "").replace("tmb_", "");
		window.location = "#/"+type+"/"+newID;
	}
}

function _previousPost(){
	_gaq.push(['_trackEvent', "navigation", "previous-post"]);  							
	if(CURRENT_POST > 0){
		var N = CURRENT_POST - 1;
		var newID = POINTS[N]["id"]
		var type
		if(newID.indexOf("twt_") >= 0){
			type = "twitter"
		}else if(newID.indexOf("tmb_") >= 0){
			type = "tumblr"
		}
		newID = newID.replace("twt_", "").replace("tmb_", "");
		window.location = "#/"+type+"/"+newID;
	}
}

function _getRecentUpdates(){     
	log.info("_getRecentUpdates()")
	$("#recentUpdates .loading").removeClass("hide");
	_processRecentUpdates(RECENT_UPDATES);
	var down = $("#recentUpdates .arrow.down")
	down.fadeTo(0, 0)
	down.removeClass("hide")
	down.animate({
		opacity:1
	}, 300)
	$("#recentUpdates .arrow.down").click(function(){
		_getRecentUpdatesPage(RECENT_UPDATES_PAGE+1, function(){
			var Y = $("#recentUpdates .content").scrollTop()+154;			
			$("#recentUpdates .content").animate({
				'scrollTop':Y
			}, 200, _onRecentScrollComplete)
		})         
	})
	$("#recentUpdates .arrow.up").click(function(){
		var Y = $("#recentUpdates .content").scrollTop()-154;
		$("#recentUpdates .content").animate({
			'scrollTop':Y
		}, 200, _onRecentScrollComplete)
	})
}   
             
function _onRecentScrollComplete(){
	var Y = $("#recentUpdates .content").scrollTop();
	var H = $("#recentUpdates .content .inner").height()
	$("#recentUpdates .arrow.up").removeClass("hide")
	$("#recentUpdates .arrow.down").removeClass("hide")
	
	if(Y <= 0){
		$("#recentUpdates .arrow.up").addClass("hide")
	}               
	if(Y >= H-160){
		$("#recentUpdates .arrow.down").addClass("hide")
	}
	
}

function _getRecentUpdatesPage(page, onComplete){
	RECENT_UPDATES_PAGE = page;
	$("#recentUpdates .loading").removeClass("hide");
	$.getJSON("/api/get_recent_posts?page="+page+"&total=13&callback=?", function(o){
		if(o.length <= 0 || !KEEP_LOADING_RECENT) {
			$("#recentUpdates .loading").addClass("hide");
			if(onComplete){
				onComplete(); 				
			}
			KEEP_LOADING_RECENT = false;
			return;
		}
		_processRecentUpdates(o);
		if(onComplete){
			onComplete(); 				
		}
	})
}

function _processRecentUpdates(o) {
	$("#recentUpdates .content .inner .clear_left").remove()
	for(var i = 0; i<o.length; i++){
		var id = o[i]["id"];
		var type = _getTypeFromId(id);	
		id = id.replace("twt_", "").replace("tmb_", "");
		var img = o[i]["thumbnail_url"];
		$("#recentUpdates .content .inner").append("<a class=\"update\" href=\"#/"+type+"/"+id+"\" style=\"background-image:url('"+img+"')\"><img src=\""+img+"\"></a>")
	}           
	$("#recentUpdates .loading").addClass("hide")    
	$("#recentUpdates .content .inner").append("<div class=\"clear_left\"></div>")	
}

function _getTypeFromId(id){
	if(id.indexOf("twt_") >= 0){
		return "twitter"
	}else if(id.indexOf("tmb_") >= 0){
		return "tumblr"
	}
}        

function _setMap(type){
	switch(type){
		case "day":  
		MAP.setMapTypeId(google.maps.MapTypeId.SATELLITE)		
		break
		case "night":
		var styledMapOptions = {
			map: MAP,
			name: "Hip-Hop"
		}
		var nightMapType =  new google.maps.StyledMapType(NIGHT_MAP_STYLE,styledMapOptions);
		MAP.mapTypes.set('evening', nightMapType);
		MAP.setMapTypeId('evening');
		break
	}
	MAP_TYPE = type
}

function _toggleMap(){    
	_gaq.push(['_trackEvent', "map", "toggle"]);  					
	switch(MAP_TYPE){
		case "day":
		_setMap("night")
		break
		case "night":
		_setMap("day")
		break
	}
}                

function _addCheckpoints(){     
	log.info("_addCheckpoints()")
  	var image = new google.maps.MarkerImage('/static/images/map.marker.checkpoint.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(22, 35),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(0, 32));

		var shape = {
		      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
		      type: 'poly'
		  };       

	for(var i = 0; i<timeStations.length; i++){
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(timeStations[i][0], timeStations[i][1]),
			map: MAP,
			icon: image,   
			shape: shape,
			visible: false,
			clickable:false,
			zIndex:4
		});
		// marker.setClickable(false)
		CHECKPOINT_MARKERS.push(marker);
	}
}

function _setCheckpointMarkerVisibility(visibility) {
	$.each(CHECKPOINT_MARKERS, function(i, marker) {
		marker.setVisible(visibility);
	});
}


var NIGHT_MAP_STYLE = [
  {
    featureType: "all",
    elementType: "all",
    stylers: [
      { invert_lightness: true }
    ]
  },{
    featureType: "road.highway",
    elementType: "geometry",
    stylers: [
      { visibility: "simplified" }
    ]
  },{
    featureType: "road.arterial",
    elementType: "geometry",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "road.local",
    elementType: "geometry",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "administrative.country",
    elementType: "labels",
    stylers: [
      { visibility: "simplified" }
    ]
  },{
    featureType: "administrative.province",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "administrative.land_parcel",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "administrative.land_parcel",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "administrative.neighbourhood",
    elementType: "labels",
    stylers: [
      { visibility: "on" }
    ]
  },{
    featureType: "road.highway",
    elementType: "labels",
    stylers: [
      { visibility: "simplified" }
    ]
  },{
    featureType: "road.arterial",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "road.local",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "landscape",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "poi",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "transit",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "water",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  }
]
//var DAY_MAP_STYLE = [ { featureType: "administrative.locality", elementType: "labels", stylers: [ { hue: "#ffaa00" }, { lightness: 58 }, { gamma: 1.29 }, { saturation: 10 }, { visibility: "on" } ] },{ featureType: "landscape.man_made", elementType: "all", stylers: [ { hue: "#fff700" }, { saturation: -8 }, { gamma: 3.24 }, { lightness: 10 }, { visibility: "simplified" } ] },{ featureType: "road.arterial", elementType: "all", stylers: [ { visibility: "simplified" }, { hue: "#ffaa00" }, { saturation: -100 }, { lightness: 53 }, { gamma: 0.5 } ] },{ featureType: "water", elementType: "all", stylers: [ { hue: "#00fff7" }, { lightness: 48 } ] },{ featureType: "poi.park", elementType: "all", stylers: [ { visibility: "on" }, { hue: "#99ff00" }, { gamma: 0.84 }, { saturation: -34 }, { lightness: 58 } ] },{ featureType: "road.highway", elementType: "all", stylers: [ { visibility: "on" }, { lightness: 36 }, { hue: "#ffaa00" } ] },{ featureType: "all", elementType: "all", stylers: [  ] } ]       

function _showTime(){
	var D = new Date();
	var localTime = D.getTime()      
	var localOffset = D.getTimezoneOffset() * 60000;     
	var utc = localTime + localOffset;
	var offset = -7;   
	var thyme = utc + (3600000*offset);	
	var nd = new Date(thyme);        
	$("#currentTime span.value").text(nd.toString("H:mm"))
}

function _getBios(){
	if(BIOS_LOADED){
		return
	}                  
	$("#teamIcebreaker div.loading").remove()
	$("#teamIcebreaker div.content div.inner").load("/static/bios.html #thumbs", function(){
		BIOS_LOADED = true;
		$("#teamIcebreaker .thumb").click(function(){
			//window.location = "#/team/"+
			_showBio($(this).attr("id").replace("thumb_", ""))
		})         
		_showBio("rob")
	})
}         

function _showBio(who){    
	_gaq.push(['_trackEvent', "team", who]);  				
	log.info("_showBio("+who+")")
	$("#vitals .content").html("<div class=\"loading\"></div>")
	$("#vitals .close").addClass("hide")
	$("#vitals .content").load("/static/bios.html #"+who, function(){
		$("#teamIcebreaker div.thumb").each(function(){
			if($(this).attr("id") == "thumb_"+who){
				$(this).addClass("selected")
			}else{
				$(this).removeClass("selected")
			}
		})
		$("#vitals .close").removeClass("hide")		
		$("#vitals .content").fadeTo(0, 0)
		$("#vitals .content").animate({
			opacity:1
		}, 300)
	})
}

function _navigateClusters(){
	var dir = ""
	switch($(this).attr("id")){
		case "nextCluster":
		dir = "next"
		break
		case "previousCluster":
		dir = "previous"
		break                                                           
	}               
	_gaq.push(['_trackEvent', "navigation", "cluster-"+dir]);  							
	
	var A = SWFAddress.getPathNames();
	var id = "" 
	
	if(A[0] == "tumblr"){
		id = "tmb_"+A[1]
	}else if(A[0] == "twitter"){
		id = "twt_"+A[1]
	}
	
	var N = getPointFromId(id)
	var post = POINTS[N]
	
	if (post.marker.cluster) {
		
		var cluster = post.marker.cluster    
		// log.info("cluster.markers_.length: "+cluster.markers_.length)
		
		if(cluster.markers_.length == 1 && dir == "next"){
			_nextPost()
			return
		} else {
			if(dir == "next"){
				CURRENT_POST = cluster.markers_[cluster.markers_.length-1].index
				_nextPost()
				return;
			} else if(dir == "previous") {
				//Get the first post in the current cluster								
				CURRENT_POST = cluster.markers_[0].index
				
				//Now get the previous post (which should be in the previous cluster)
				post = POINTS[CURRENT_POST - 1]
				
				//Get this previous cluster				
				var new_cluster = post.marker.cluster
				if (!new_cluster) {
					CURRENT_POST = CURRENT_POST - 1
				//If this previous cluster only has one point...	
				} else if (new_cluster.markers_.length == 1) {
					//Set the CURRENT_POST to the next post
					CURRENT_POST = new_cluster.markers_[0].index + 1
				} else {
					//Else, set the CURRENT_POST to the second post in the previous cluster
					CURRENT_POST = new_cluster.markers_[1].index				
				}
				//Navigate back one to get where we want
				_previousPost()
			}
		}
	} else {                       
		// this never seems to be false 
		log.info("post.marker.cluster = false!")
	}
	return false
}                                                              

function _constrainNumber(value, min, max){
	if(value < min){
		return min
	}else if(value > max){
		return max
	}else{
		return value
	}
}

function _showTeam(){   
	_gaq.push(['_trackEvent', "team", "/"]);  			
 	
	$("#teamIcebreaker").removeClass("hide")
	$("#vitals").removeClass("hide")
	$("#recentUpdates").addClass("hide")
	$("#supportStream").addClass("hide")    
	$("#icebreakerHQ").addClass("hide")
	$("#products").removeClass("hide")
	if(!BIOS_LOADED){
		_getBios()
	}
	/*
	if(A[1] != undefined && A[1] != "" && A[1] != null){
		_showBio(A[1])
	} 
	*/  
	return false;
}
