
var xmlHttp = null;
var tmpName;
var nofReceived = 0;

function newInput()
{
  var inputNode = document.getElementById("story-input");

  var storyText = document.getElementById("story-text");
  var boldSpan = document.createElement("span");
  boldSpan.style.fontWeight = 'bold';
  boldSpan.appendChild(document.createTextNode(inputNode.value))
  storyText.appendChild(boldSpan);
  storyText.appendChild(document.createElement("br"));

  processInput(inputNode.value);
  inputNode.value = "";
}

function initStory(newTmpName, input)
{
    tmpName = newTmpName;
    processInput(null);
    inputNode = document.getElementById("story-input");
    inputNode.onkeyup = window.inputKeyUp;
    inputNode.focus();
    inputNode.select();
}


function processInput(input)
{
    if (typeof XMLHttpRequest != 'undefined')
        xmlHttp = new XMLHttpRequest();

    if (!xmlHttp)
    {
        try
        {
            xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                xmlHttp  = null;
            }
        }
    }
    if (xmlHttp)
    {
        var query
         = "cgi-bin/fizmo.cgi"
         + "?input=" + input
         + "&quetzalname=" + tmpName;
        xmlHttp.open('GET', query, true);
        xmlHttp.onreadystatechange = receiveData;
        xmlHttp.send(null);
    }
}


function appendStoryText(text)
{
    var storyText = document.getElementById("story-text");
    var lines = text.split("\n");

    for (var i=0; i<lines.length; i++)
    {
        if (i != 0)
            storyText.appendChild(document.createElement("br"));
        storyText.appendChild(document.createTextNode(lines[i]));
    }

    Hyphenator.run();

    var storyDemo= document.getElementById("story-demo");
    storyDemo.scrollTop = storyDemo.scrollHeight;

    nofReceived++;
    if (nofReceived == 2)
    {
        var hint = document.getElementById("hint");
        //hint.removeChild(hint.childNodes[0]);
        hint.style.color = '';
        hint.style.fontWeight = '';
        hint.childNodes[0].nodeValue
            = 'Type your command here and press Enter:';
    }
}


function receiveData()
{
    if (xmlHttp.readyState == 4)
    {
        if (xmlHttp.responseText != '')
        {
            appendStoryText(xmlHttp.responseText);
        }
        else
        {
            inputNode.disabled = true;
            inputNode.blur();
        }
    }
}

function inputKeyUp(e, key)
{
  if (!key)
  {
      if (typeof(event) == "undefined")
          key = e.keyCode; // for FF
      else
          key = event.keyCode; // for IE
  }

  if (key == 13)
  {
      newInput();
  }
}

