// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
CHARACTERLIMIT = 140;

function checkNewNoteLength()
{
	checkNoteLength($('#note_body'), $('#new_note_characters'))
}

function checkEditNoteLength()
{
	checkNoteLength($("#edit_note_form_actual textarea"), $('#edit_note_characters'))
}

function checkNoteLength(textarea, limitDisplay)
{
	newTotal = CHARACTERLIMIT - textarea.val().length;
	limitDisplay.html(newTotal);
}

function updateNote() 
{

	var form = $("#edit_note_form_actual");
	var editingNoteId = $("#editing_note_id").val();

	$.ajax({
		type: "post",
		dataType: "script",
		url: "/notes/" +  editingNoteId,
		data: form.serialize(),
		beforeSend: function(data) { $("#edit_note_buttons").hide(); $("#edit_note_message").show();},
		failure: function(data, status, exception) { $("#edit_note_buttons").show(); $("#edit_note_message").hide(); alert("Whoops! For some reason we couldn't update your note. Please try again.");}
	})
	
}

function editNote(noteID)
{
	
	var currentEditingNoteId = $("#editing_note_id").val();
	if (currentEditingNoteId != "")
	{
		$("#note_" + currentEditingNoteId).show();
	}
	
	var editingNote = "#note_" + noteID;
	var editingNoteText = jQuery.trim($(editingNote + " .body").text());
	
	$("#edit_note_form_actual textarea").val(editingNoteText);
		
	$("#editing_note_id").val(noteID);
	
	$("#edit_note").insertAfter(editingNote); 
	$(editingNote).hide(); 
	$("#edit_note").show();
	$("#edit_note_buttons").show();
	$("#edit_note_message").hide();
	
	checkEditNoteLength();

	$("#edit_note_form_actual textarea").focus();
}

function cancelEdit()
{
	$(".note").show();
	$("#edit_note").hide();
	$("#editing_note_id").val("");
}

function startNewNote()
{
	$("#new_note_form").show();
	$("#new_note_display").hide();
	$("#new_note_form textarea").val("");
	$("#new_note_form textarea").focus();
	$("#new_note_characters").html(CHARACTERLIMIT);
	$("#new_note_buttons").show();
	$("#new_note_message").hide();

}

function cancelNewNote()
{
	$("#new_note_form").hide();
	$("#new_note_display").show();	
}

function startCreateNote()
{
	$("#new_note_buttons").hide();
	$("#new_note_message").show();
}

function successCreateNote()
{
	cancelNewNote();
}

function failCreateNote()
{
	$("new_note_buttons").show();
	alert("Unable to create note");
}

function switchDeleteButtons(noteID)
{
	var deleteButtons = $("#delete_buttons_" + noteID);
	var deleteMessage = $("#delete_note_message");
	 
	deleteMessage.insertAfter(deleteButtons);
	deleteButtons.hide();
	deleteMessage.show(); 
}

//set up a fuction that will allow us to use links inside the edit div, without firing the edit 
//process
var editInterupt = function(e) {
    // Get the correct event in a cross-browser manner, then stop bubbling/propagation.
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}
