
var validator = false;

$(document).ready(function() {  
	/// Twitter ///
	
	var tweet = 'Why not follow us on twitter? <a href="http://twitter.com/#!/flowinteractive">@flowinteractive</a>';
	var tweetID = 0;
	var tweetStatus = 0;
	var latestTweetID = -1;
	var username='flowinteractive'; // set user name
	var format='json';
	var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.'+format; // make the url

	// load memory - tweet ID last seen
	var id = amplify.store.sessionStorage(TWMEM); // latest seen
	if (id != undefined) {
		tweetID = id;
	}
	
	// Write the twitter stuff into the header
	$(".masthead").append('<section><img src="/assets/img/header-bird.gif" width="26" height="44" /><p id="tweet"><a href="http://twitter.com/#!/flowinteractive">'+tweet+'</a><span><img src="/assets/img/backgrounds/bg-twitter-close.png" width="9" height="9" alt="Twitter bird, click here to see our latest tweet." /></span></p></section>');
	$("#tweet").hide();
	
	// initial check + show
	getLatestTweet();
	
	// then only show if different
	setInterval(function() {
		  getLatestTweet();
	},75000);	
	
	// Clicking birdy shows and hides
	$('.masthead img').click(function(){
		if (tweetStatus == 0) {
			showTweet(true);
			tweetStatus = 1;
		} else {
			hideTweet();
			tweetStatus = 0;
		}
		return false;
	});
	
	// check for new tweet
	function getLatestTweet() {
		var req = $.ajax({
			url: url,
			dataType: 'jsonp',
			timeout: 20000,
			success: function(data,status,obj) {
				// get the tweets
				if (data[0] && !(data['error'])) {
					processTweetData(data[0].id, data[0].text);
				}
			},
			error: function(obj,status,error) {
				// show default - once
				processTweetData(-2, tweet);
			}
		});
	}
	
	function processTweetData(id,tweetTxt) {
		// set content
		tweet = tweetTxt;
		latestTweetID = id; // get the first tweet in the response and place it inside the div
		$('#tweet').html('<a href="http://twitter.com/#!/flowinteractive">'+tweet+'</a><span><img src="/assets/img/backgrounds/bg-twitter-close.png" width="9" height="9" /></span>');
		$('#tweet span').click(function(){
			hideTweet();
			tweetStatus = 0;
			return false;
		});
		
		// if they haven't seen it, show it.
		if (latestTweetID != tweetID) {
			tweetID = latestTweetID;
			
			// remember that they have now seen it
			amplify.store.sessionStorage(TWMEM,tweetID);

			// show
			showTweet();
		} else {
			hideTweet();
		}
	}
	
	// show
	function showTweet(clicked){
		if (clicked) {
			$('#tweet').fadeIn('slow');
		} else {
			$('#tweet').fadeIn('slow');
			setTimeout(function() { $('#tweet').fadeOut('fadeout'); }, 15000);
		}
	}
	// hide
	function hideTweet(){
		$('#tweet').fadeOut('slow');
	}

	/// Overlay remember ///
	
	// set up a manual history
	var history = amplify.store.sessionStorage(HSMEM);
	if (!history) {
		history = [];
	}
	
	// add this page
	history.unshift(window.location.toString());
	
	// keep it at 5 or so
	if (history.length > 5) {
		history.splice(5,(history.length-5));
	}
	
	// re-stash 
	amplify.store.sessionStorage(HSMEM, history);
	
	$('a[data-type="project"]').click(function() {
		amplify.store.sessionStorage(OVMEM,true);
	});
	
	if ($('#clientList').length > 0) {
		// get OVMEM 
		var link = amplify.store.sessionStorage(OVMEM);
		
		// nuke it
		amplify.store.sessionStorage(OVMEM,false);
		
		if (link && history) {
			// check history
			var patt = /\/projects\/(.+?)/;
			if (patt.test(history[1])) {
				// fire overlay
				$('#clientList').overlay({mask:'#3C4242', effect: 'apple', load: true});
			}
		}
	}
	
	/// Google maps - Contact page ///
	
	$('#directions').hide();
	
	var map = false;
	var marker = false;
	var dirDisp = false;
	var dirServ = new google.maps.DirectionsService();
	var FLOW = [51.523574,-0.098764];
	
	// init map
	if ($('#mapContainer').length > 0) {
		initMap();
	}
	
	// click handlers for other stuff
	$('a[rel="directions"]').click(function(){
		var self = $(this);
		var start = $(this).attr('data-place');
		if (start) {
			calcRoute(start, google.maps.DirectionsTravelMode.WALKING);
		}
	});
	
	// submit handler for custom address
	$('#frm_directions').submit(function(){
		var value = $('#frm_town').val();
		if(value) {
			calcRoute(value, google.maps.DirectionsTravelMode.DRIVING);
		}
		return false;
	});	
	
	// calc route and update map
	function calcRoute(start, mode) {
		var request = {
			origin: start,
			destination: FLOW[0]+','+FLOW[1],
			travelMode: mode
		};
		
		dirServ.route(request, function(resp,status){
			if (status == google.maps.DirectionsStatus.OK) {
				dirDisp.setDirections(resp);
				var output = '';
				for (var a in resp.routes[0].legs) {
					for (var b in resp.routes[0].legs[a].steps) {
						output += '<div>'+resp.routes[0].legs[a].steps[b].instructions+'</div>';
					}
				}
				$('.mapControls').fadeOut(2000, function(){
					$('#directions div.wrap').html(output)
					$('#directions').append('<a href="/contact" id="mapBack" style="display:block;">Back</a>').fadeIn();
				});
				
			}
		});
	}
	
	$('#mapBack').click(function(e){
		$('#directions').fadeOut();
		$('.mapControls').fadeIn();
		e.preventDefault();
	});
	// init the map
	function initMap() {
		var latlng = new google.maps.LatLng(FLOW[0],FLOW[1]);
		var myOptions = {
		  zoom: 15,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		// map
		map = new google.maps.Map(document.getElementById("mapContainer"), myOptions);
		
		// add marker
		office = new google.maps.Marker({map: map,position: latlng,visible: true});
		
		// disp
		dirDisp = new google.maps.DirectionsRenderer();
		dirDisp.setMap(map);
	}
	
	/// THINKING JS ///
	
	// prefill the filter form
	$('#frm_filter').each(function(){
		var form = $(this);
		var url = window.location.toString();
		var segments = url.split("/");
		segments = segments.slice(3, (segments.length));

		if (segments[1] == 'filter') {
			if (segments[2] != '') {
				$('#frm_who').val(segments[2]);
			}
			if (segments[3] != '') {
				$('#frm_topic').val(segments[3]);
			}
		}
	});

	// show filter form?
	$('#frm_filter').show();	
	
	// capture and handle the filter form
	$('#frm_filter').submit(function() {
		var who = $('#frm_who').val();
		var cat = $('#frm_topic').val();
		var url = '/thinking/thoughts-index/filter/'+who+'/'+cat;
		
		// load
		thnkAjax(url);	
		
		return false;
	});
	
	// capture and handle pagination links
	captPagi();
	
	/// AJax Comments ///
	validator = $("#comment_form").validator();
	$('#comment_form').submit(function() {
		if (validator && validator.data("validator").checkValidity()) {
			// disable submit
			$('input[type=submit]', this).attr('disabled','disabled');
			$(this).ajaxSubmit({
				success: commentSent 
			});	
		}
		
		return false;
	});
	
	
});

function commentSent(responseText, statusText, xhr, form) {
	// enable submit again
	$('#comment_form input[type=submit]').removeAttr('disabled');
	// LAUNCH Overlay
	$('#thankYouOverlay').overlay({mask:'#3C4242', effect: 'apple', load: true});
}

function captPagi() {
	$('.thinkingPag a').each(function(){
		var self = this;
		$(self).click(function(){
			var link = $(this);
			var url = link.attr('href');
			
			// munge the url
			var parts = url.split('/');
			parts = parts.splice(3); // strip out http, blank and domain
			
			var start = 1;
			if (parts[1] == 'thoughts-index') {
				start = 2;
			}
			parts = parts.splice(start);

			
			url = '/thinking/thoughts-index/'+parts.join('/');
			
			// do ajax
			thnkAjax(url);
			
			return false;
		})
	});
}

function thnkAjax(url) {
	$('body').css('cursor','wait');
	$.ajax({
		url: url,
		dataType: 'html',
		success: function(data,status,obj) {
			$('#thoughts').html(data);

			// re-capture pagination
			captPagi();

			$('body').css('cursor','');
		},
		error: function(obj,status,error) {
			$('body').css('cursor','');
		}
	});
}

