$(document).ready(function(){
	
	function updateTextile(){
		$('#naveditor').val(htmlToTextile('#primaryNav'));
	}
	
	// Make sure that main level widths are correct
	function masterUpdate(){
		//Toggle Save Button
		stateChanged();
		
		//Update Widths
		var size = $('#primaryNav').children().size();
		size = Math.floor( 100 / ( size - 1 ) ) + '%';
		$('#primaryNav li').removeAttr('style');
		$('#primaryNav').children().css('width', size);
		
		// Assign first primary li as 'home'
		$('#primaryNav li').removeAttr('id');
		$('#primaryNav li:first').attr('id', 'home');
		
		$('ul').sortable({ connectWith: 'ul', tolerance: 'pointer' })
		   .bind('sortupdate', function( e, ui ) { 
				masterUpdate();
				updateTextile();
			});
	}
	
	function stateChanged(){
		$('#save').addClass('ready');
		$('#message').removeClass('saved').html('Click "Save" in the bottom right to generate a link for this site map version.');
	}
	
	
	$("#save.ready").live("click", function(){
		$.ajax({
			type: "POST",
			url: "/",
			data: ({data: $('#naveditor').val()}),
			dataType: "html",
			success: function(map_id){
				$(this).removeClass('ready');
				$('#message').addClass('saved').html('Link to this Sitemap: <a href="http://www.sitemapengine.com/#' + map_id + '">http://www.sitemapengine.com/#' + map_id + '</a>');
			}
		});
	});
	
	$('#naveditor').keyup(function(e){
		if(e.keyCode != 32 && e.keyCode != 56 && e.keyCode != 42 && e.keyCode != 13 && e.keyCode != 16){
			$(this).trigger('update');
		}
	});
	
	$('#naveditor').bind("update", function(){
		//update height
		var rows = $(this).val().split("\n").length;
		if(rows < 30) $(this).attr('rows', rows + 1);
		else $(this).attr('rows', 30);
		
		//update sitemap
		var textile = $(this).val();
		var html = textileToHtml(textile);
		$('#primaryNav').html(html);
		masterUpdate();
	});
	
	
	if(location.hash.length > 0){
		$.get( "/" + location.hash.substr(1), function(textile){
			$('#naveditor').val(textile);
			$('#naveditor').trigger('update');
		});
	}
	$('#naveditor').trigger('update');
});
