// usrmsg_submit.js - shared code for submitting user msgs through AJAX 
//
// Note: - ajax.js must be included on the same HTML page as this script
//     - PATH_RELROOT = relative path to site root
//     - an IS_GBK boolean variable must be defined and initialized before using AJAX calls
//     - similarly, a jumpToFirstPageWhenAddNewMsg boolean variable must be set
//
// V1.0 - 2007-09-14
// V1.1 - 2008-12-3: set 'truefrom' thru AJAX
// V1.1.1 - 2009-01-15: add setTruefrom and move code in V1.1 after html redirection in ShowEditForm()
// V1.2 - 2009-03-02: add support for opt1 & opt2
// V1.2.1 - 2010-04-15: update cloneFromTemplate() to cater for new tpl code of href="#"

var statusbar, msgTypeDesc, insertPoint;
var truefrom = '';  // V1.1

// Clean up and restore original state after processing...
function cleanup(msg,returnFromError)
{
  SetInnerText (statusbar, msg);
  findObj('formUserMsg').style.display = 'block';
  ToggleElementDisplay('addmsg',returnFromError);
  curAjaxHandling = '';    // reset semaphor
  if (returnFromError) 
    ScrollToElement('ajaxstatus', false);
  else
    findObj('user_response').value = '';
}   /* cleanup */

// Clone given template HTML node and fill with user msg data from given XML root element
function cloneFromTemplate (tpl, idPrefix, root)
{
  newNode = tpl.cloneNode(true);
  htmlTpl = new String( newNode.innerHTML );   // make a copy of the template HTML code
  hp = getFirstChildValue (root, "homepage");
  indent = parseInt(getFirstChildValue (root, "indentlevel"));
  msgid = getFirstChildValue (root, "msgid");
  score = getFirstChildValue (root, "score");
  flags = getFirstChildValue (root, "flags");

  htmlTpl = htmlTpl.replace('href="#"', 'href="'+ hp + '"');   // V1.2.1
  htmlTpl = htmlTpl.replace('href="homepage"', 'href="'+ hp + '"');
  htmlTpl = htmlTpl.replace(/\[msgid\]/g, msgid);
  htmlTpl = htmlTpl.replace('[msgdate]', getFirstChildValue (root, "msgdate"));
  htmlTpl = htmlTpl.replace('[msg_indent]', indent);
  htmlTpl = htmlTpl.replace('[msgtime]', getFirstChildValue (root, "msgtime"));
  htmlTpl = htmlTpl.replace('[new_or_reply]', (indent > 0 ? "回應" : "留言"));
  htmlTpl = htmlTpl.replace('[newmsgbox_tpl]', 'newmsgbox_'+msgid);
  htmlTpl = htmlTpl.replace('[score]', score);
  true_flag = getFirstChildValue (root, "true_flag");
  if (true_flag == "OK") true_flag = "";
  htmlTpl = htmlTpl.replace('[true_flag]', true_flag);
  htmlTpl = htmlTpl.replace('[usermsg_tpl]', 'usermsg_'+msgid);
  htmlTpl = htmlTpl.replace('[msgtophdr_display]',
          'display:' + ((flags != 0) || (hp != '?') || (score > 0) ? "block" : "none"));
  htmlTpl = htmlTpl.replace('[msgicon1_display]', 
          'display:' + ((flags & 1) != 0 ? "inline" : "none"));
  htmlTpl = htmlTpl.replace('[msgicon2_display]', 
          'display:' + ((flags & 2) != 0 ? "inline" : "none"));
  htmlTpl = htmlTpl.replace('[msgicon4_display]', 
          'display:' + ((flags & 4) != 0 ? "inline" : "none"));
  htmlTpl = htmlTpl.replace('[score_display]', 
          'display:' + (score > 0 ? "inline" : "none"));
  htmlTpl = htmlTpl.replace('[homepage_display]', 
          'display:' + (hp != '?' ? "inline" : "none"));
  htmlTpl = htmlTpl.replace(/title=/g, 'style=');
  htmlTpl = htmlTpl.replace(/\[name\]/g, getFirstChildValue (root, "name"));
  htmlTpl = htmlTpl.replace('[parent]', getFirstChildValue (root, "parent"));
  htmlTpl = htmlTpl.replace('[place]', getFirstChildValue (root, "place"));
  htmlTpl = htmlTpl.replace('[msg_content]', getFirstChildValue (root, "msg"));
  opt1 = getFirstChildValue (root, "opt1");
  htmlTpl = htmlTpl.replace('[opt1]', opt1);
  htmlTpl = htmlTpl.replace('[opt1_display]',
          'display:' + (opt1 != "&nbsp;" ? "inline" : "none"));
  opt2 = getFirstChildValue (root, "opt2");
  htmlTpl = htmlTpl.replace('[opt2]', opt2);
  htmlTpl = htmlTpl.replace('[opt2_display]',
          'display:' + (opt2 != "&nbsp;" ? "inline" : "none"));
  newNode.innerHTML = htmlTpl;

  newNode.id = idPrefix+msgid;
  newNode.className = idPrefix+indent;
  return newNode;
}   /* cloneFromTemplate */

// Return the 1st child of given element identified by given tag name
function getFirstChild(element, tagname)
{
  return element.getElementsByTagName(tagname).item(0).firstChild;
}   /* getFirstChild */

// Return the value of the 1st child of given element identified by given tag name
function getFirstChildValue(element, tagname)
{
  return getFirstChild(element, tagname).data;
}   /* getFirstChildValue */

// Event handler for AJAX return from form submission
function handleFormReturn()
{
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;

  // catching potential errors with IE and Opera
  if (!xmlResponse || !xmlResponse.documentElement) {
    cleanup('資料有錯誤，請再嘗試。', true);
    throw("Invalid XML structure:\n" + xmlHttp.responseText);
  }
  // catching potential errors with Firefox
  var rootNodeName = xmlResponse.documentElement.nodeName;
  if (rootNodeName == "parsererror") {
    cleanup('資料發現錯誤，請再嘗試。', true);
    throw("Invalid XML structure");
  }

  try {
    // obtain the XML's document element
    xmlRoot = xmlResponse.documentElement;
    // obtain field values...
    result = getFirstChildValue (xmlRoot, "result");
    if (result == "OK") {
    tpl = findObj("newmsgbox_tpl");
    newboxNode = cloneFromTemplate (tpl, "newmsgbox_", xmlRoot);
    newboxNode.style.display = (IS_GBK ? "block" : "none");
    parentId = getFirstChildValue (xmlRoot, "parent");
    tpl.parentNode.insertBefore (newboxNode, insertPoint.nextSibling);

    tpl = findObj("usermsg_tpl");
    newNode = cloneFromTemplate (tpl, "usermsg_", xmlRoot);
    newNode.style.display = "block";
    tpl.parentNode.insertBefore (newNode, newboxNode);  // insert before new msg box just created

    var msgid = getFirstChildValue (xmlRoot, "msgid");
    var parent = getFirstChildValue (xmlRoot, "parent");
    var ptr = (msgid != parent ? "↑↑↑" : "↓↓↓");
    cleanup(ptr + ' 成功新增' + msgTypeDesc + '。 '+ ptr, false);
    ScrollToElement( (msgid != parent ? "ajaxstatus" : newNode.id), false);
    } else
      cleanup(result, true);
  } catch(e) {
    cleanup('資料出現錯誤，請再嘗試。'+e.toString(), true);
  }
}   /* handleFormReturn */

// Seek for the newmsgbox of the last reply of given msg.  Return newmsgbox of that msg if no reply.
function seekLastReply(parentId)
{
  alldivs = findObj('addmsg').parentNode.getElementsByTagName('div');
  i = 0;
  // skip to parent msg
  while (i < alldivs.length && alldivs[i].id != 'usermsg_'+parentId) { i++; }
  parentIdx = i++;
  lastNewMsgBoxIdx = i++;  // new msg box of parent msg itself
  // loop until reaching next indent level 0 msg or end of list
  while (i < alldivs.length) {
    if (alldivs[i].className == 'usermsg_0') break;
  if (alldivs[i].className == 'newmsgbox_1') lastNewMsgBoxIdx = i;  // is newmsgbox of a reply
    i++;
  }
  return alldivs[lastNewMsgBoxIdx];
}   /* seekLastReply */

// Scroll the page to make given element visible on screen
function ScrollToElement(id, alignTop)
{
  element = findObj(id);
  if (element)
    element.scrollIntoView(alignTop);
}   /* ScrollToElement */

// Set truefrom after getting its value thru' ajax
function setTruefrom()
{
  cleanupAjax();
  truefrom = findObj("comefrom").value;
}   /* setTruefrom */

// Turn on the edit form and move it to appropriate position if it is a reply
function ShowEditForm(parentId)
{
  if (curAjaxHandling == 'formSubmit') {
  alert('正處理上一個指示，請稍後再試。');    // another form submit in progress
  return;
  }
  
  findObj('parent').value = parentId;
  formDiv = findObj('addmsg');
  if (parentId <= 0) {  // add new msg: place at top of msg list
    if (jumpToFirstPageWhenAddNewMsg) {
    findObj('openform').value = 'yes';  // For gbk, if add new msg in pg>0, jump to 1st page with form opened...
    findObj('formUserMsg').submit();
    return;
  }
  msgTypeDesc = (IS_GBK ? '留言' : '回應');    // only reply for non-gbk pages
  insertPoint = findObj('usermsg_tpl');
    formDiv.parentNode.insertBefore (formDiv, insertPoint);
  } else {  // add new reply: place after last reply of parent thread
  msgTypeDesc = '回應';
    insertPoint = seekLastReply(parentId);
    formDiv.parentNode.insertBefore (formDiv, insertPoint.nextSibling);
  }
  if (truefrom == '') {   // V1.1, V1.1.1
    LoadObjValueAsync(PATH_RELROOT+'loadfile.php', 'msg=geoip_xml', 'comefrom', setTruefrom);
  }
  SetInnerText(findObj('content_label'), '你的' + msgTypeDesc + ' *');
  findObj('butSubmit').value = '加入' + msgTypeDesc;
  ToggleElementDisplay('addmsg',true);
  statusbar = findObj('ajaxstatus');
  statusbar.parentNode.insertBefore (statusbar, formDiv);
  statusbar.style.display = 'none';
  findObj('submitterName').focus();
}   /* ShowEditForm */

// function to add a msg
function SubmitMsg()
{
  validateForm('name','','R','email','','NisEmail','user_response','','R');

  if (document._returnValue) {
    if (curAjaxHandling)
    if (curAjaxHandling == 'formSubmit') {
      alert('正處理上一個指示，請稍後再試。');    // another form submit in progress
    return;
    } else if (curAjaxHandling != '') {
      xmlHttp.abort();  // force termination of other less important request and continue form submission...
    }

    curAjaxHandling = 'formSubmit';
  var form = findObj('formUserMsg');

    form.style.display = 'none';
    statusbar.style.display = 'block';
    SetInnerText (statusbar, '正在處理你的' + msgTypeDesc + '，請稍候...');
  handleServerResponse = handleFormReturn;
    ajaxSubmitForm(form, PATH_RELROOT+'msg_submit.php');
  }  
}   /* SubmitMsg */

// Customize timeout handling
timeoutHandler = function myTimeoutHandler()
{
  _defaultTimeoutHandler();   // Default timeout handler
  cleanup ('處理逾時仍未完成，請再嘗試。', true);
}   /* timeoutHandler / myTimeoutHandler */

// end of script
