$(document).ajaxSend(function(event, xhr, settings) {
	function getCookie(name) {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
	function sameOrigin(url) {
		// url could be relative or scheme relative or absolute
		var host = document.location.host; // host + port
		var protocol = document.location.protocol;
		var sr_origin = '//' + host;
		var origin = protocol + sr_origin;
		// Allow absolute or scheme relative URLs to same origin
		return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
			(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
			// or any other URL that isn't scheme relative or absolute i.e relative.
			!(/^(\/\/|http:|https:).*/.test(url));
	}
	function safeMethod(method) {
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}

	if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
		xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
	}
});

jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		attribute: "maxlength",
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}
		
$(document).ready(function(){

	// external links -> new window
	$('a[href^="http://"]').attr("target", "_blank");
	$('a[href^="https://"]').attr("target", "_blank");


	var slideSpeed = 750;
	var scrollSpeed = 750;

	// add empty space for scrolling
	$('#make-height').height($(window).height());

	// figure out where we are
	
	url = ''+document.location; 
	url = url.substr(7);
	var splits = url.split('/');
	
	if(splits.length > 0) {
		var activeSection = splits[1];
		if(splits.length > 1) var activePage = splits[2];
		if(splits.length > 2) var activeStory = splits[3];
	} else {
		activeSection = false;
	}

	if(activeSection) {
		if($('a.nav.active').offset()) {
			$(window).scrollTop($('a.nav.active').offset().top - 200);
		}
		// $('div.row a.nav.active').css('border', '1px solid red');
	}		
	

	/* PROPOSITIONS */
	
	function initPropositions() {
	
		// proposition form
		
		if( $('#proposition-form').length ) {
		
			// submission
		
			$('#proposition-form').live('submit', function(e){
				e.preventDefault();
				var form_ok = true;
				
				if ( $('#proposition-form').hasClass('submitted') ) return;
				
				$('ul.js-errors').remove();
				$('#id_name, #id_text').each(function(){
					var v = $(this).attr('value');
					if( (v == '') || (!v) ) {
						$(this).parent('p').before('<ul class="errorlist js-errors"><li>This field is required.</li></ul>');
						form_ok = false;
					}
				});
				if(!form_ok) {
					$.scrollTo('#proposition-form', {
						'offset': { left: 0, top: -10 },
						'duration': scrollSpeed
					});
				} else {
					_gaq.push(['_trackPageview', '/citizenship/constitution/submission/' ]);
					$('#proposition-form').addClass('submitted');
					$('#content').load('/citizenship/constitution/ #content', $('#proposition-form').serializeArray());
					$.scrollTo('#citizenship-title', {
						'offset': { left: 0, top: -10 },
						'duration': scrollSpeed
					});
				}
			});


			// char counter

			var $span = $('#proposition-form span.charCount');


			var onEditCallback = function(remaining){
				$span.text(remaining + ' characters left.');
				if(remaining > 0) { $span.css('color', '#999'); }
				else { $span.css('color', 'red'); }
			}
		
			var onLimitCallback = function(){ $span.css('font-weight', 'bold'); }
		
			$('#proposition-form textarea[maxlength]').limitMaxlength({
				onEdit: onEditCallback,
				onLimit: onLimitCallback
			});

		}

	
		// vote submission
		
		$('div.proposition a.like, div.proposition a.dislike').live('click',function(e) {
			$this = $(this);
			e.preventDefault();

			if($this.hasClass('active')) return;
			
			var vote = 1;
			if( $this.hasClass('dislike') ) vote = -1;
			var object_id = $this.parent('div.proposition').attr('id').split('-')[1]
			
			$.post( $this.attr('href'), { vote: vote, object_id: object_id }, function(data) {
				$this.parent('div.proposition').html( data );
			} );
			
		});
	
	
	
	
	}



	
	// DISQUS
	
	// ajax url here?
	
	// var dsq = false;
	
	window.disqus_loaded = false;
	
	function initDisqus() {
	
		// window.disqus_developer = true;
		window.disqus_shortname = 'nowhereisland';
		
		week_url = 'http://nowhereisland.org' + $('h1.thinker a').attr('href');
		if( week_url == '' || !week_url) return;
		
		disqus_url = week_url;
		disqus_title = 'Nowhereisland Resident Thinkers: ' + $('h1.thinker a').html();

		window.disqus_loaded = true;
		/* * * DON'T EDIT BELOW THIS LINE * * */
		(function() {
			var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
			dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
		})();
		
	}

	
	function init_content() {

			$('a[href^="http://"]').attr("target", "_blank");
			$('a[href^="https://"]').attr("target", "_blank");

			$('a[href^="http://nowhereisland"]').attr("target", "");
			$('a[href^="http://www.nowhereisland"]').attr("target", "");

			if( $('#map_canvas').length > 0 ) { initializeMap(); }
			if( $('#disqus_thread').length > 0 ) { initDisqus(); }
			if( $('div.proposition').length > 0 ) { initPropositions(); }

	}
	
	
	
	// close content

	function closeContent() {
		$('#content').slideUp(slideSpeed, function(){
			$('#content').remove();
			$('a.nav').removeClass('active');
			$('a.nav').removeClass('inactive');
		});
	}

	$('#close a, #close-menu').live('click', function(e){
		e.preventDefault();
		$section = $('a.nav.active');
		closeContent();
		if($section) {
			$.scrollTo($section, {
				'offset': { left: 0, top: -10 },
				'duration': scrollSpeed
			});
		}
		return false;
	});
	

	
	// load content
	
	function loadContent(theUrl) {

		parent.location.hash = '!' + theUrl;
		
		 _gaq.push(['_trackPageview', theUrl ]);

		var splits = theUrl.split('/');
		var section = splits[1]; var page = splits[2]; var story = splits[3];
		
		$('a.nav').removeClass('active');

		$('a.nav').addClass('inactive');
		$('#'+section+'-title').removeClass('inactive').addClass('active');
		
		// add dynamic content		
		$row = $('#'+section+'-title').parent('div.row');
		$row.append('<div id="content"><\/div>');
		// <div id="preload">Loading<\/div>
		// $preload = $('#preload');
		$content = $('#content');
		// hide content
		$content.hide();
		// load new page into content
		$content.load(theUrl + ' #content', function(response, status, xhr){

			if (status == "error") {
			    var msg = "<h1>Error<\/h1>";
			    $("#content").html(msg + '<p>' + xhr.status + "<br>" + xhr.statusText + "<\/p>");
			}

			// $('a[href^="http://"]').attr("target", "_blank");
			// $('a[href^="https://"]').attr("target", "_blank");
			
			$content.slideDown(slideSpeed, function(){
				init_content();
			});

			activeSection = section;
			activePage = page;
			activeStory = story;

		
			// scroll there
			$.scrollTo($row, {
				'offset': { left: 0, top: -10 },
				'duration': scrollSpeed
			});
			


		});

	}
	
	
	function clean_url(theUrl) {
		theUrl = theUrl.replace('http://nowhereisland.org','');
		theUrl = theUrl.replace('http://nowhereisland.wiedner.co.uk','');
		theUrl = theUrl.replace('../../../..','');
		return theUrl;	
	}
	
	
	$('#press-login a').each(function(){
		$(this).addClass('force-reload');
	});
	
	// click on breaking - load whatever	
	
	$('#breaking a').live('click', function(e){
		e.preventDefault();
		loadContent($(this).attr('href'));
	});
	
	// click anywhere in content area

	$('#content a').live('click', function(e){

		$this = $(this);
		
		if($this.hasClass('norefresh')) return false;
		
		
		var theUrl = clean_url($this.attr('href'));

		if(theUrl == '#') {
			e.preventDefault();
			return false;
		}

		var dl_url = '/media/uploads/files/';
		var internal_url = 'http://nowhere';
		var mailto = 'mailto';
		
		// leave disqus alone
		if( $(this).parents('#disqus_thread').length ) return true;
		
		// exernal link, return
		if( $this.hasClass('force-reload') ) return true;
		if( theUrl.substr(0,dl_url.length) == dl_url ) return true;
		if( (theUrl.substr(0,4) == 'http') && (theUrl.substr(0,internal_url.length) != internal_url) ) return true;

		if( theUrl.substr(0,mailto.length) == mailto ) return true;
		
		// stop default
		e.preventDefault();
		
		// find which section this link is in
		var splits = $this.attr('href').split('/');
		var section = splits[1];
		$row = $('#'+section+'-title');

		
		if(!activeSection || activeSection == '') {
			
			// nothing active, just load
			parent.location.hash = '!' + theUrl;
			loadContent(theUrl);
			
		} else if (activeSection == section) {
		
			parent.location.hash = '!' + theUrl;
		
			$('#content').load(theUrl + ' #content', function(){
				init_content();

				_gaq.push(['_trackPageview', theUrl ]);

				var splits = theUrl.split('/');
				var section = splits[1]; var page = splits[2]; var story = splits[3];
				activeSection = section;
				activePage = page;
				activeStory = story;
				
			});
			
			var topOffset = $('#'+section+'-title').offset().top - $(window).scrollTop();
			
			if( (topOffset < 10) || (topOffset > 100) ) {
				$.scrollTo($('#'+section+'-title'), {
					'offset': { left: 0, top: -10 },
					'duration': scrollSpeed
				});
			}
			
			

		} else {

			// other section -> close, then load

			$('#content').slideUp(slideSpeed, function(){
				$('#content').remove();
				loadContent(theUrl);
			});

		}		
		
		return false;
	
	});


	// click on big link

	$('a.nav').click(function(e){
	
		$this = $(this);
		
		theUrl = clean_url($this.attr('href'));
		
		// don't do anything for external links
		if(theUrl.substr(0,4) == 'http') return true;

		if($this.hasClass('active')) {

			// already open, just close
			closeContent();

		} else {
			
			if($('#content').length > 0) {
				// content already shown somewhere -> remove

				$('#content').slideUp(slideSpeed, function(){
					$('#content').remove();
					loadContent(theUrl);
				});

			} else {
				// no content -> just load
				loadContent(theUrl);
			}
		}
		
		return false;
	});
	

	
	// counter
	
	var count = 0; var counterlength = 5;
	var seconds = 2; var interval = 50;
	var step = Math.floor(maxcount / ( (seconds * 1000) / interval ));
	if(step < 1) step = 1;
	
	var countInterval = setInterval(function(){
		count += step;
		if(count >= maxcount) {
			count = maxcount;
			clearInterval(countInterval);
		}
		var numberString = '' + count;
		while (numberString.length < counterlength) {
        	numberString = '0' + numberString;
    	}
    	var outstr = '';
    	i = 0;
    	while(i < numberString.length) {
    		current_number = numberString.substr(i,1);
    		outstr = outstr + '<span class="nr'+current_number+'">'+current_number+'</span>';
    		i++;
    	}
    	$('#numbers').html(outstr);
	}, 50);
	
	
	// breaking news
	
	if($('#breaking p').length > 0) {
	
		$('#breaking p').hide();
		$('#breaking p:first').show().addClass('active');
		
		var breakingInterval;
		
		startBreaking = function() {
			breakingInterval = setInterval(function(){
				$next = $('#breaking p.active').next('p');
				if($next.length == 0) $next = $('#breaking p:first');
				$('#breaking p').hide().removeClass('active');
				$next.show().addClass('active');
			}, 3 * 1000);
		}
		
		pauseBreaking = function() { clearInterval(breakingInterval); }
		
		startBreaking();
	
		$('#breaking').hover(pauseBreaking, startBreaking);
		
	}
	
	// prevent accidental form submissions

	$("form input, form select").live('keypress', function(e) {
  		if (e.keyCode == 13) { return false; }
	});
	
	
	$('#signup_form').live('submit', function(e){
		e.preventDefault();

		var form_ok = true;

		$('ul.js-errors').remove();
		
		$('#signup-required input, #signup-required select').each(function(){
			var v = $(this).attr('value');
			if( (v == '') || (!v) ) {
				$(this).parent('p').before('<ul class="errorlist js-errors"><li>This field is required.</li></ul>');
				form_ok = false;
			}
		});
		
		if(!form_ok) {
			$.scrollTo('#signup_form', {
				'offset': { left: 0, top: -10 },
				'duration': scrollSpeed
			});
		} else {
			$('#content').load('/citizenship/signup/ #content', $('#signup_form').serializeArray());
			$.scrollTo('#citizenship-title', {
				'offset': { left: 0, top: -10 },
				'duration': scrollSpeed
			});
		}

	});
	
// 	$('#login-form').live('submit', function(e){
// 		e.preventDefault();
// 		$('#content').load('/login/', $('#signup_form').serializeArray());
// 	});

	init_content();	

	
	

});

/* MAP HELPER FUNCTIONS */

function USGSOverlay(location, content, url, map) {
  this.location_ = location;
  this.content_ = content;
  this.url_ = url;
  this.map_ = map;
  this.div_ = null;
  this.setMap(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();

USGSOverlay.prototype.onAdd = function() {
	var div = document.createElement('div');
	$(div).append('<div class="myMarker">'+this.content_+'</div>');
	this.getPanes().overlayLayer.appendChild(div);
	this.div_ = div;
// 	var that = this; 
// 	google.maps.event.addDomListener(this.div_, 'click', function() { google.maps.event.trigger(that, 'click'); });
}

USGSOverlay.prototype.draw = function() {
	var overlayProjection = this.getProjection();
	var sw = overlayProjection.fromLatLngToDivPixel(this.location_);
	var div = this.div_;
	div.style.position = 'absolute';
	div.style.left = sw.x + 'px';
	div.style.top = sw.y + 'px';
}

my_map_data = false;


initializeMap = function() {

	centerLatLng = new google.maps.LatLng(50.85, -3.5); // weymouth
	map_zoom = 8;
	custom_map = false;

	page_slug = $('#page_data').html();

	if(page_slug == "expedition-svalbard-high-arctic") {
		centerLatLng = new google.maps.LatLng(75.185789,18.632813); // weymouth
		map_zoom = 3;
		custom_map = true;
	} else if (page_slug == "south-west-journey") {
		centerLatLng = new google.maps.LatLng(50.85, -3.5); // weymouth
		map_zoom = 8;
		custom_map = true;
	} else if (page_slug == "the-journey") {
		centerLatLng = new google.maps.LatLng(50.92, -3.5); // weymouth
		map_zoom = 8;
		custom_map = false; // THIS IS A SPECIAL CASE, WITH MARKERS BUT CUSTOM LOCATION AND ZOOM
	}


	var myOptions = {
		zoom: map_zoom,
		center: centerLatLng,
		mapTypeId: google.maps.MapTypeId.TERRAIN
	};

	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	if(!custom_map) {	

		my_map_data = eval( '(' + $('#map_data').html() + ')' );
	
		var bounds = new google.maps.LatLngBounds();
		
		overlays = Array();
		
		i = 0;
		while(i < my_map_data.stops.length) {
			var stop_loc = new google.maps.LatLng(my_map_data.stops[i].location[0], my_map_data.stops[i].location[1])
			bounds.extend(stop_loc);
			
			if(my_map_data.stops[i].url != '') var inner = '<a href="'+my_map_data.stops[i].url+'">'+my_map_data.stops[i].name+'</a>';
			else var inner = my_map_data.stops[i].name;
			
			// overlay = new USGSOverlay(stop_loc, my_map_data.stops[i].name, my_map_data.stops[i].url, map);
			var overlay = new InfoBubble({
				  map: map,
				  content: '<div class="myMarker">'+inner+'</div>',
				  position: stop_loc,
				  shadowStyle: 0,
				  padding: 3,
				  backgroundColor: '#ff47b0',
				  borderRadius: 0,
				  arrowSize: 5,
				  borderWidth: 0,
				  // borderColor: '#2c2c2c',
				  disableAutoPan: true,
				  hideCloseButton: true,
				  arrowPosition: 50,
				  backgroundClassName: 'phoney',
				  arrowStyle: 0,
				  disableAnimation: 1
			});
			overlay.open();
			overlays[i] = overlay;

			i++;
		}
		
// 		console.log ( overlays[0] );
// 		$('overlays[0]').css('border','3px solid black');
//		overlays[0].setZIndex('1');
		
		$('div.myMarker a').live('click',function(e){ 
			e.preventDefault(); 
			loadContent( $(this).attr('href') ); 
		});
		
		if(my_map_data.stops.length > 0 && page_slug != "the-journey" && my_map_data.current_location == undefined) map.fitBounds(bounds);
		
		
		// location path
		
		if(my_map_data.locations_future != undefined) {
		
			// past path
			path_past = [];
			i=0;
			while(i < my_map_data.locations_past.length) {
				path_past[i] = new google.maps.LatLng(my_map_data.locations_past[i].latitude, my_map_data.locations_past[i].longitude);
				i++;
			}
			past_polyline = new google.maps.Polyline({path:path_past, strokeColor: "#ff6b2e", strokeOpacity: 1.0, strokeWeight: 1});
			past_polyline.setMap(map);
			map.setCenter(new google.maps.LatLng(78.92188716988343, 8.78173828125), 6);
	
			// future path
			path_future = [];
			i=0;
			while(i < my_map_data.locations_future.length) {
				path_future[i] = new google.maps.LatLng(my_map_data.locations_future[i].latitude, my_map_data.locations_future[i].longitude);
				i++;
			}
			past_polyline = new google.maps.Polyline({path:path_future, strokeColor: "#3154a4", strokeOpacity: 0.5, strokeWeight: 1});
			past_polyline.setMap(map);
			
			
			// current location
			var image = '/media/img/position-marker.png';
			var myLatLng = new google.maps.LatLng(my_map_data.current_location.latitude, my_map_data.current_location.longitude);
			var overlay = new InfoBubble({
				  map: map,
				  content: '<div style="width: 32px; height: 32px; overflow: hidden;"><img src="'+image+'"></div>',
				  position: myLatLng,
				  shadowStyle: 0,
				  padding: 0,
				  backgroundColor: 'transparent',
				  minWidth: 32,
				  maxWidth: 32,
				  borderRadius: 0,
				  arrowSize: 0,
				  borderWidth: 0,
				  // borderColor: '#2c2c2c',
				  disableAutoPan: true,
				  hideCloseButton: true,
				  arrowPosition: 50,
				  backgroundClassName: 'phoney',
				  arrowStyle: 0,
				  disableAnimation: 1,
			});
			overlay.open();

			
			map.setCenter(myLatLng);
			map.setZoom(6);
		
		}
		

	}
	



}



