var QTmsgCount;
var QTorigCount;

function setMsgCount(count) {
    QTmsgCount = count;
    QTorigCount = count;
    // alert('setting count=' + count);
}

// These get added as event handlers on page load
function registerPostMessageHandlers() {
 Event.observe('postmessagebutton', 'click', QT_showPostMessageForm);
 Event.observe('postcancelbutton', 'click', QT_handlePostCancel);
 // TODO: add Upload an image handler
}

// Also gets called on load
// If the post message form has any content, open it so user doesn't
// freak out if they hit the back butten then come back and their message
// isn't visible because the page state has returned to closed form
function openPostMessageIfContent() {
  if ($F('message') != undefined && $F('message').length > 0) {
     QT_showPostMessageForm();
  }
}

function QT_showPostMessageForm () {
  Event.stopObserving('postmessagebutton', 'click', QT_showPostMessageForm);
  // Event.observe('postmessagesubmit', 'click', QT_postMessage); Punting on xmlhttprequest for now

  // Disable the sort link since it may not be obvious that it's a link away
  // and will thus lose the current message. Ideally it would be handled
  // entirely with javascript and DOM manipulation.
  $('sortreverse').oldhref = $('sortreverse').href; // stash current value for later restore
  $('sortreverse').href = '#';
  Event.observe('sortreverse', 'click', QT_alertSortDisabled);

  Effect.BlindDown('postmessageform', Object.extend({ duration: 0.25, afterFinishInternal:function(){Effect.Fade('postmessagebutton', Object.extend({ duration: 0.25, to: 0.3, afterFinishInternal:function(){_focusFirstEmpty('postmessageform')}}))}}));
  // Took awhile to discover that Field.focus needs to be there rather than
  // just a successive function call. Apparently guarantees that form is
  // completely 'in place' before attempting to access one if its children. 
}

function QT_hidePostMessageForm () {
  // Event.stopObserving('postmessagesubmit', 'click', QT_postMessage); Punting on xmlhttprequest for now

  $('sortreverse').href = $('sortreverse').oldhref;
  Effect.Appear('postmessagebutton', Object.extend({ duration: 0.25, afterFinishInternal:function() {Effect.BlindUp('postmessageform', Object.extend({ duration: 0.25}))}}));
  Event.observe('postmessagebutton', 'click', QT_showPostMessageForm);
  Event.stopObserving('sortreverse', 'click', QT_alertSortDisabled);
  Event.stopObserving('postcancelbutton', 'click', QT_buttonNoOp);
}

function QT_handlePostCancel () {
  var OK = true;
  if ($F('message') != undefined && $F('message').length > 0 &&
    !$F('message').match(/^\s*$/)) {
    OK = window.confirm("You will lose the message you started to type. OK?");
  }
  if (OK) {
    $('message').value = '';
    QT_hidePostMessageForm();
  }
}

function QT_postMessage() {
  if ($F('message').match(/^\s*$/)) {
	alert("You haven't typed a message yet.");
  	return;
  }
  var pars = Form.serialize('postmessageform');
  // alert("Sending QTmsgCount = " + QTmsgCount);
  pars += '&xmlhttprequest=1&curmsgcount=' + QTmsgCount + '&origmsgcount=' + QTorigCount;
  var url = '/cgi-bin/post.cgi';
 
  $('postmessagesubmit').value = 'Posting message...';
  Event.stopObserving('postcancelbutton', 'click', QT_handlePostCancel);
  Event.observe('postcancelbutton', 'click', QT_buttonNoOp);

  Event.stopObserving('postmessagesubmit', 'click', QT_postMessage);

  var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: QT_showResponse });

  
}

function QT_buttonNoOp() {
  alert('This button is not active now');
}

function QT_showResponse(originalRequest) {
  $('postmessagesubmit').value = 'Done';
  // alert("response\n" + originalRequest.responseText);  

  var insertSpot = document.getElementById('hiddenInsert');
  while (insertSpot.hasChildNodes()) insertSpot.removeChild(insertSpot.lastChild);  // clean out first
  var result = originalRequest.responseText.match(/^-?\d+[\n\r]*/m);
  var rowText = originalRequest.responseText.replace(/^-?\d+[\n\r]*/m, "");
  if (result == null || result.length == 0 || result[0] <= 0) { // we have an error
     alert("Error posting message: " + rowText);
     QT_hidePostMessageForm();
     $('message').value = '';
     registerPostMessageHandlers();
     return;
  }
  if (window.HTMLElement) { // browser supports createRange()
     var range = document.createRange();
     range.selectNodeContents(insertSpot);
     insertSpot.appendChild(range.createContextualFragment("<table>" + rowText + "</table>"));
  }
  else {
     insertSpot.innerHTML = "<table>" + rowText + "</table>";
  }

  // Clone and insert rows
  var insertBeforeElem = document.getElementById('firstMessageRow');
  var insertedRow = document.getElementById("insertedRow"); // comes from server
  // Get all siblings
  var allInsertedRows = insertedRow.parentNode.childNodes;
  var length = allInsertedRows.length;
  var lastInsertedRow;
  for (var i = 0; i < length; i++) {
    if (allInsertedRows[i].nodeName != "TR") // With Mozilla we get text too
       continue;
    var newNode = allInsertedRows[i].cloneNode(true);
    insertBeforeElem.parentNode.insertBefore(newNode, insertBeforeElem);
    //new Insertion[Before](insertBeforeElem, newNode);
    lastInsertedRow = newNode;
    QTmsgCount++;
  }

  // Re-designate firstMessageRow
  insertBeforeElem.removeAttribute("id");
  lastInsertedRow.setAttribute("id", "firstMessageRow");

  while (insertSpot.hasChildNodes()) insertSpot.removeChild(insertSpot.lastChild);  // clean out
  $('message').value = '';

  QT_hidePostMessageForm();
  registerPostMessageHandlers();
}

// Set the focus on the first form element that doesn't already have text
function _focusFirstEmpty(form) {

  // Because the form elements don't come in order, first we do the
  // the inputs, then the textarea(s)
  var foundelement = Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        element.tagName.toLowerCase() == 'input' &&
        (element.value == undefined || element.value.length == 0)});

  if (foundelement == undefined) {
    foundelement = Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        element.tagName.toLowerCase() == 'textarea' && 
        (element.value == undefined || element.value.length == 0)});
  }

  if (foundelement != undefined) {
    Field.focus(foundelement);
  }
  else {
    Field.focus('message');
  }
}

function QT_alertSortDisabled () {
  alert("The reverse-sort button is disabled while the message-posting form is displayed.");
}
