/*!
 * Texai dialog JavaScript library.
 * http://texai.org
 *
 * Copyright (C) Oct 3, 2010 Stephen L. Reed.
 *
 * This JavaScript program is free software; you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

var xmlHttpRequest = getXmlHttpRequestObject();

// Called when the page is loaded by the browser and builds the document object model according to the value of location.hash .
function main() {
  buildDOM();
}

// Builds the document object model according to the value of location.hash .
function buildDOM() {
  if (location.hash == "#chat" || location.hash == "#rchat") {
    if (location.hash == "#chat") {
      $("body").addClass("normal-background");
    } else {
      $("body").addClass("no-contrast-background");
    }
    $("#menu").remove();
    $("#header").remove();
    if (location.hash == "#chat") {
      $("#main").addClass("rounded-top rounded-bottom");
      $("#main").addClass("fixed-width");
      $("#footer").addClass("rounded-bottom");
    }
    $("#content").addClass("rounded-top");
    $("<div id=\"div_chat\" style=\"height: 480px; width: 100%; overflow: auto; background-color: #f0f9f0; font-size:110%; border: 1px solid #ccc;\"></div>" +
      "<p>" +
      "<form id=\"frmmain\" name=\"frmmain\" onsubmit=\"return blockSubmit();\">" +
      "  <input type=\"text\" id=\"txt_message\" name=\"txt_message\" style=\"width: 100%;\" />" +
      "  <input type=\"button\" name=\"btn_send_chat\" id=\"btn_send_chat\" value=\"Send\" onclick=\"javascript:sendChatText();\" />" +
      "  <p>" +
      "</form>").appendTo("#padded-content");
    if (location.hash == "#chat") {
      $("<div class=\"popup-link\"><a href=\"http://texai.org#rchat\" onClick=\"return popup(this)\">resizable chat</a></div>").appendTo("#padded-content");
    }
    $("<p><span class=\"texai-font\">Texai</span>&trade;<span class=\"texai-font\"> &copy; 2010</span></p>").appendTo("#footer");
    resizeChat();
    $(window).bind("resize", resizeChat);
  } else {
    $("body").addClass("normal-background");
    $("#main").addClass("rounded-top rounded-bottom fixed-width");
    $("#header").addClass("rounded-top");
    $("<h1 id=\"texai-h1\">Texai</h1>").appendTo("#header");
    $("#texai-h1").addClass("texai-font");
    $("#padded-content").addClass("homepage-padded-content");
    $("#footer").addClass("rounded-bottom");
    $("<h3>&trade;</h3>").appendTo("#header");
    $("<h2>your artificial intelligence</h2>").appendTo("#header");
    $("<div id=\"columns\"><div class=\"left column\"></div><div class=\"right column\"></div></div>").appendTo("#padded-content");
    $("<p>We are a start-up company creating artificial intelligence.  Texai combines existing approaches for knowledge representation " +
      "and natural language processing, which are constrained to operate in a cognitively-plausible manner.  Its envisioned dialog " +
      "system can be taught new knowledge and skills.</p>").appendTo($(".left"));
    $("<img src=\"images/man-thinking-192x197.png\" alt=\"a man thinking while studing his laptop\" /><br>").appendTo(".left");
    $("<img src=\"images/its-computer-helped-me.png\" alt=\"a sample Texai syntax tree\" />").appendTo(".right");
    $("<p>Stephen L. Reed, Founder<br>" +
      "Austin, Texas<br>" +
      "email: stephenreed@yahoo.com</p>").appendTo($(".right"));
    $("<p><span class=\"texai-font\">Texai</span>&trade;<span class=\"texai-font\"> &copy; 2010</span></p>").appendTo("#footer");
  }
// alert("after appendTo");
}

// Resets the document object model.
function resetDOM() {
  $("body").empty(); // remove all content from the body
  $("body").removeClass(); // remove all CSS classes from the body
  $("<div id=\"main\">\n" +
    "  <div id=\"header\"></div>\n" +
    "  <div id=\"menu\"></div>\n" +
    "  <div id=\"content\">\n" +
    "    <div id=\"padded-content\"></div>\n" +
    "  </div>\n" +
    "  <div id=\"footer\"></div>\n" +
    "</div>").appendTo("body");
}

// Starts the dialog chat process.
function startChat() {
  resizeChat();
  // say hello to the chat server
  if (xmlHttpRequest.readyState == 4 || xmlHttpRequest.readyState == 0) {
    xmlHttpRequest.open("POST", 'getChat', true);
    xmlHttpRequest.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xmlHttpRequest.send('hello');
    xmlHttpRequest.onreadystatechange=receiveChatText;
  }
  //Set the focus to the chat input field.
  focusTextMessage();

  if (winH < 650) {
    window.scrollTo(1,232);
  }
}

// Resizes the chat pane to accommodate the browser window.  The event parameter is ignored.
function resizeChat(event) {
  var winH = 0;
  if ( typeof(window.innerHeight ) == 'number') {
    //Non-IE
    winH = window.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight) {
    //IE 6+ in 'standards compliant mode'
    winH = document.documentElement.clientHeight;
  }
  else if (document.body && document.body.clientHeight) {
    //IE 4 compatible
    winH = document.body.clientHeight;
  }
  var chat_div = document.getElementById('div_chat');
  var heightOtherElements;
  if (location.hash == "#chat") {
    heightOtherElements = 200;
  } else {
    heightOtherElements = 160;
  }
  var chat_height = winH - heightOtherElements;
  if (chat_height < 200) {
    chat_height = 200;
  }
  chat_div.style.height = chat_height + 'px';
}

// Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  else {
    document.getElementById('p_status').innerHTML = 'Status: Could not create XmlHttpRequest Object.  Consider upgrading your browser.';
    return null;
  }
}

// Sends the chat message to the server
function sendChatText() {
  var inputField = document.getElementById('txt_message');
  if(inputField.value == '') {
    alert("You have not entered a message.");
    return;
  }
  if (xmlHttpRequest.readyState == 4 || xmlHttpRequest.readyState == 0) {
    xmlHttpRequest.open("POST", 'getChat', true);
    xmlHttpRequest.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    var text = inputField.value;
    xmlHttpRequest.send(text);
    xmlHttpRequest.onreadystatechange=receiveChatText;
    inputField.value = '';
    var chat_div = document.getElementById('div_chat');
    chat_div.innerHTML += text + '<br>';
  }
}

// Handles the return of chat text
function receiveChatText() {
  if (xmlHttpRequest.readyState == 4) {
    var text = xmlHttpRequest.responseText;
    var chat_div = document.getElementById('div_chat');
    chat_div.innerHTML += '<font color=#0000ff>' + text + '</font>';
    while (chat_div.innerHTML.length > 50000) {
      var index = chat_div.innerHTML.indexOf('<br>');
      if (index == -1) {
        break;
      }
      chat_div.innerHTML = chat_div.innerHTML.substr(index + 4);
    }
    chat_div.scrollTop = chat_div.scrollHeight;
  }
}

// Sets the focus to the chat input field
function focusTextMessage() {
  document.getElementById('txt_message').focus();
}

// Handles when the user presses enter.  Instead of submitting the form, we
// send a new message to the server and return false.
function blockSubmit() {
  sendChatText();
  return false;
}

// Creates a popup chat window.
function popup(mylink) {
  if (!window.focus) {
    return true;
  }
  var href;
  if (typeof(mylink) == 'string') {
    href=mylink;
  } else {
    href=mylink.href;
  }
  window.open(href, 'Texai', 'width=800,height=600,resizable=yes, location=no');  // Chrome forces location=yes
  location.hash = ''; // indicate the home page
  resetDOM();
  buildDOM();
  return false;
}


