var autoSaveTimeout = null;
var jotText = "";
var jotted = (j == true) ? true : false;

//DOM is ready
$(document).ready(function() 
{
   $("#jot").focus();
   jotText = $("#jot").val();
   
   $(window).bind("resize", window_RESIZE);
   window_RESIZE();
   
   $("#jot").keyup(function(e) 
   {
      jotMessage("When you take a break from typing we'll save your progress.");
      clearTimeout(autoSaveTimeout);
      autoSaveTimeout = setTimeout(autoSave, 2500)
   });
   
   $("#jotForm").ajaxForm({beforeSubmit: jotRequest, dataType: 'xml', success: processXML});
   
   $('#saveDialog').jqm({modal: true});
   $('#errorDialog').jqm({modal: true});
   $('#mergeDialog').jqm({modal: true});
});

//Save jot
function autoSave()
{
   if ($("#jot").val() != jotText)
   {
      if (!jotted) $("#saveDialog").jqmShow();
      $("#jotForm").submit();
      if (!jotted) $("#jot").attr("disabled", true);
   }
   else
   {
      jotMessage("No change detected. No need to save.");
   }
   clearTimeout(autoSaveTimeout);
}

function doOverwrite()
{
   $("#f").val("1");
   autoSave();
}

function jotRequest(formData, jqForm, options) { 
    var queryString = $.param(formData);  
    return true; 
} 

function processXML(response, status)
{
   $("#f").val("0");
   if (status == "success")
   {
      var error = $('error', response).text();
      
      if (error == "")
      {
         var url = $('permalink', response).text();
         var merge = $('merge', response).text();
         var time = $('time', response).text();
         if (url != "" && !jotted)
         {
            location.href = url;
         }
         else if (merge == "CONFLICT" && jotted)
         {
            jotMerge();
         }
         else if (jotted)
         {
            jotMessage($('message', response).text());
            $("#time").val(time);
            jotText = $("#jot").val();
         }
         else
         {
            jotError("There was an error.");
         }
      }
      else
      {
         jotError("<p>Oops. Something went wrong!</p> " + error);
      }
   }
   else
   {
      jotError("<p>There was an error saving your note.</p> <p>Please try again later.</p>");
   }
}

function jotMessage(message)
{
   $("#message").html(stripTags(message));
   $("#saveDialog").jqmHide();
   $("#mergeDialog").jqmHide();
   $("#jot").attr("disabled", false);
}

function jotError(message)
{
   $("#errorMessage").html(message);
   $("#saveDialog").jqmHide();
   $("#mergeDialog").jqmHide();
   $("#errorDialog").jqmShow();
   $("#jot").attr("disabled", false);
   jotMessage(message);
}

function jotMerge()
{
   $("#saveDialog").jqmHide();
   $("#mergeDialog").jqmShow();
   $("#jot").attr("disabled", false);
}

function window_RESIZE(e)
{
   var h = document.getElementById("header").offsetHeight;
   $("#jot").css("height", ($(window).height() - (h + 20)) + "px");
}

function stripTags(html)
{
   return html.replace(/<\/?[^>]+>/gi, '');
}