var oldSubmit;
var oldDown;
var oldUp;

function toggleInputStyle (form, textInput, value)
{
   if (value == "type")
   {
      oldSubmit = form.onsubmit;
      form.onsubmit=null;
      oldDown = textInput.onkeydown;
      textInput.onkeydown=null;
      oldUp = textInput.onkeyup;
      textInput.onkeyup=null;
   }

   else
   {
      resetKeyInfo ();
      form.onsubmit=oldSubmit;
      textInput.onkeydown=oldDown;
      textInput.onkeyup=oldUp;
   }
}

// These variables are only to be used by the reformatting stuff,
// although of necessity the lastTime gets reset by the submission of
// this form.

var lastValue = "";
var lastTime = 0;
var lastInterval = 0;
var lastChar = "";
var ignoreTiming = false;
var ignorePitch = false;

// Called on form submission
function resetKeyInfo ()
{
   lastTime = 0;
   lastInterval = 0;
   lastKeyIndex = -1;
}

// Called on keydown
function reformatValue (textInput, event)
{
   var now = new Date ();
   if (lastTime != 0)
   {
      var currentInterval = now - lastTime;
      if (lastInterval != 0)
      {
	 if (ignoreTiming)
	 {
	    lastValue += ' ';
	 }

	 else
	 {
	    // Interval calculation.
	    var diff = currentInterval - lastInterval;

	    if (diff > lastInterval * 0.1)
	    {
	       lastValue += (lastChar + "+ ");
	    }

	    else if (diff < -(lastInterval * 0.1))
	    {
	       lastValue += (lastChar + "- ");
	    }

	    else
	    {
	       lastValue += (lastChar + "= ");
	    }
	 }
      }
      lastInterval = currentInterval;
   }
   textInput.value = lastValue;
   lastTime = now;
}

var keys = "wertyuiopasdfghjkl;'zxcvbnm,./"
var lastKeyIndex = -1;

// This is called on key up
function eraseSpareCharacter (textInput)
{
   var str = textInput.value;
   // This is the key that was last hit
   var lastKeyVal = str.charAt (str.length - 1);
   if (lastKeyVal != 'q')
   {
      var currentKeyIndex = keys.indexOf (lastKeyVal);
      if (lastKeyIndex != -1)
      {
	 if (!ignorePitch)
	 {
	    diff = currentKeyIndex - lastKeyIndex;
	    if (diff > 0)
	    {
	       lastValue += 'u';
	    }

	    else if (diff < 0)
	    {
	       lastValue += 'd';
	    }

	    else
	    {
	       lastValue += 's';
	    }
	 }
      }
      lastKeyIndex = currentKeyIndex;
      textInput.value = lastValue;
   }

   else
   {
      textInput.value = lastValue;
      resetKeyInfo ();
   }
}

// Called when you hit the "reset" button
function resetInput (textInput)
{
   textInput.value = lastValue = "";
   resetKeyInfo ();
   textInput.focus ();
}

function timingOnOff (checkBox, textInput, otherBox)
{
   ignoreTiming = checkBox.checked;
   if (ignoreTiming) otherBox.checked = false;
   textInput.focus ();
}

function pitchOnOff (checkBox, textInput, otherBox)
{
   ignorePitch = checkBox.checked;
   if (ignorePitch) otherBox.checked = false;
   textInput.focus ();
}
