/* Copyright © 2004–2006 Charles C. Fu <URL:http://www.web-i18n.net/> */

var isTest = false;
/*
isTest = String(document.location).match(/fjunk/)
  != null;
*/

function debug(node, msg) {
  /* Only emit debugs for Forum Testing topics. */
  if (isTest)
    appendClass(node, msg);
}

function getCookie(name) {
  return unescape(document.cookie.match(new RegExp(name + "=([^;]*)"))[1]);
}

function toggleSidebar() {
  var style = document.getElementById("sidebar-CSS");
  style.disabled = ! style.disabled;
}

function inTree(nodes, node) {
  for (var i = 0; i < nodes.length; ++i)
    if (nodes[i] == node.parentNode)
      return true;
  return false;
}

function isDescendent(ancestor, descendent) {
  if (! descendent)
    return false;
  if (descendent.parentNode == ancestor)
    return true;
  return isDescendent(ancestor, descendent.parentNode);
}

function nodeInsertedFixupListener(event) {
  var target = event.target;
  if (target.name == 'body')
    target.cols = 80;
  // else if (target.className == "postlistdate")
    // target.style.display = "block"; // Firefox bug workaround
  else
    fixName(target);
}

var didFixup = false;
/* language fixups specific to the C/J/K board */
function fixup() {
  if (didFixup)
    return;
  didFixup = true;
  if (document.forms["msgform"])
    document.forms["msgform"].body.cols = 80;
  fixForumListDescriptions();
  fixNames(document.body);
  //fixAdminTitles();
  //fixCP();
  fixLinks();

  rotateLanguages();
  window.setInterval("rotateLanguages()", 15000);
  //  rotateNotices();
}

function fixLinks() {
  for (var i = 0; i < document.links.length; ++i)
    document.links[i].href =
      document.links[i].href.replace
      (/^http:\/\/(?:com1|www).runboard.com\/bcjkdramasincalifornia\.f(f)?/, 
      'http://CJKDramas.com/$1$1');
}

function fixAdminTitles() {
  var itals = document.body.getElementsByTagName("i");
  for (var i = 0; i < itals.length; ++i)
    fixAdminTitle(itals[i]);
}

/* Set languages for ccwf's custom C/J/K board title. */
function fixAdminTitle(el) {
  if (el.className == "Adm") {
    setLang(el, "zh-TW");
    setLang(el.parentNode, "ko-KR");
  }
}

/* No longer necessary */
function fixCP() {
  var els = document.body.getElementsByTagName("a");
  for (var i = 0; i < els.length; ++i)
    if (els[i].href.match(/&cpwmbname=.*/)) {
      els[i].href =
	els[i].href.replace(/&cpwmbname=.*/,
			    '&cpwmbname=C/J/K+Dramas+in+California');
      return;
    }
}

/* Guess languages for parts of C/J/K forum list descriptions. */
function fixForumListDescriptions() {
  var lang = [ "en-US", "zh-TW", "ja-JP", "ko-KR" ];
  var spans = document.body.getElementsByTagName("span");
  for (var i = 0; i < spans.length; ++i)
    if (spans[i].className == "forumlistdescription") {
      var desc = spans[i];
      var locDescs = desc.removeChild(desc.firstChild).nodeValue.split(/ \/ /);
      var firstIsNotEnglish = ! locDescs[0].match(/[A-Z]/);
      for (var j = 0; j < locDescs.length; ++j) {
	if (j != 0)
	  desc.appendChild(document.createTextNode(" / "));
	var span = document.createElement("span");
	setLang(span, lang[j + firstIsNotEnglish]);
	span.appendChild(document.createTextNode(locDescs[j]));
	desc.appendChild(span);
      }
    }
}

/* Guess languages for parts of C/J/K Drama board topic/post titles. */
function fixNames(node) {
  var spans = node.getElementsByTagName("span");
  for (var i = 0; i < spans.length; ++i)
    fixName(spans[i]);
}

function fixName(span) {
  if (! span.fixedTitle)
    switch (span.className) {
    case "postlistpostname":
    case "topiclisttopicname":
      fixTitle(span);
      break;
    case "locationtopic":
      fixTitle(span.getElementsByTagName("a")[0]);
      break;
    }
}

function titleModifiedListener(event) {
  fixTitle(event.currentTarget);
}

/* Guess languages for parts of a C/J/K Drama board topic/post title. */
function fixTitle(title) {
  if (!title || ! title.hasChildNodes())
    return;

  var txtNode = title.firstChild;
  if (txtNode.nodeType != 3)	// 3 == TEXT_NODE
    txtNode = txtNode.nextSibling;
  if (! txtNode) {
    if (document.addEventListener)
      title.addEventListener('DOMNodeInserted', titleModifiedListener, false);
    return;
  }

  if (! txtNode.nodeValue.match(/^[\u0000-\u007f\s]*$/)) {
    var parts =
      txtNode.nodeValue.match(/^( ?(Re: ?)?([^:：]+(?:: |：)))([^\(]+)( \(.*\).*)?$/);
    if (parts) {
      txtNode.nodeValue = parts[1];
      var span = document.createElement("span");
      if (parts[3].match(/^J[- ]/))
	setLang(span, 'ja-JP');
      else if (parts[3].match(/^K[- ]/))
	setLang(span, 'ko-KR');
      else if (parts[3].match(/^TW?\/C[- ]/))
	setLang(span, 'zh');
      else if (parts[3].match(/^C[- ]|中国/))
	setLang(span, 'zh-CN');
      else if (parts[3].match(/^TW?[- ]/))
	setLang(span, 'zh-TW');
      else if (parts[3].match(/^HK[- ]/))
	setLang(span, 'zh-HK');
      else if (parts[3].match(/^SG[- ]/))
	setLang(span, 'zh-SG');
      else if (String(document.location).match(/\.fanime/))
	setLang(span, 'ja-JP');
      else if (String(document.location).match(/\.fchineseforum/))
	setLang(span, 'zh-TW');
      span.appendChild(document.createTextNode(parts[4]));
      title.appendChild(span);
      if (parts[5])
	title.appendChild(document.createTextNode(parts[5]));
    } else if (String(document.location).match(/\.fanime/)) {
      var parts =
	txtNode.nodeValue.match(/^(( *Re: ?)?(Ep [0-9]+: )?)([^\(]+)( \(.*\).*)?$/);
      if (parts) {
	txtNode.nodeValue = parts[1] ? parts[1] : '';
	var span = document.createElement("span");
	setLang(span, 'ja-JP');
	span.appendChild(document.createTextNode(parts[4]));
	title.appendChild(span);
	if (parts[5])
	  title.appendChild(document.createTextNode(parts[5]));
      }
    }
  }
  title.fixedTitle = true;
}


function rotateNotices() {
  var i = 1;
  for (var chld = document.getElementById("notices").firstChild;
       chld != null; chld = chld.nextSibling)
    if (chld.tagName) {
      window.setTimeout("document.body.className = 'notice-'+" + i, i * 4000);
      ++i;
    }
}

var lang = 0;
var editLabels = [ "Edit", "編輯", "編集", "편집", "编辑" ];
var quoteLabels = [ "Quote", "引用", "引用", "인용문", "引用" ];
var replyLabels = [ "Reply", "回復", "ﾘﾌﾟﾗｲ", "답장", "回复" ];
var langs = [ "en-US", "zh-TW", "ja-JP", "ko-KR", "zh-CN" ];

function rotateLanguages() {
  var spans = document.getElementsByTagName("span");
  for (var i = 0; i < spans.length; ++i) {
    var span = spans[i];
    switch (span.className.split(" ")[0]) {
    case "post_list_edit":
      span.firstChild.nodeValue = editLabels[lang];
      span.lang = langs[lang];
      span.className = "post_list_edit " + langs[lang];
      break;
    case "post_list_reply":
      span.firstChild.nodeValue = replyLabels[lang];
      span.lang = langs[lang];
      span.className = "post_list_reply " + langs[lang];
      break;
    case "post_list_quote":
      span.firstChild.nodeValue = quoteLabels[lang];
      span.lang = langs[lang];
      span.className = "post_list_quote " + langs[lang];
      if (document.title.match(/^J[- ]/))
	lang = 2 - lang;
      else if (document.title.match(/^K[- ]/))
	lang = 3 - lang;
      else if (document.title.match(/(TW?(\/C)?|HK)[- ]/))
	lang = 1 - lang;
      else if (document.title.match(/(C|SG)[- ]/))
	lang = 4 - lang;
      else
	lang = ++lang % 4;
      break;
    }
  }
}

function tagName(node) {
  var name = node.tagName;
  if (name)
    return name.toLowerCase();
  return null;
}

function secondCellUnused(tableRow) {
  var children = tableRow.childNodes;
  var i = 0;
  while (tagName(children[i]) != 'td')
    ++i;
  do
    ++i;
  while (tagName(children[i]) != 'td');
  return children[i];
}

function secondCell(tableRow) {
  var child = tableRow.firstChild;
  while (tagName(child) != 'td')
    child = child.nextSibling;
  do
    child = child.nextSibling;
  while (tagName(child) != 'td');
  return child;
}

function lastTableRow() {
  var rows = document.getElementsByTagName("tr");
  return rows[rows.length - 1];
}

function postLoadUnused() {
  var postCellChildren =
    secondCell(lastTableRow().parentNode.firstChild).childNodes;

  /* Find span.postlistpostname. */
  var i = 0;
  while (tagName(postCellChildren[i]) != 'span')
    ++i;
  fixNames(postCellChildren[i]);	// Fix span.postlistpostname.

  /* Find span.postlistpostbody. */
  do
    ++i;
  while (tagName(postCellChildren[i]) != 'span');
  /* Fix span.postlistpostbody. */
  replaceElements(postCellChildren[i], descendentOfSpanSequence,
		  spanTemplate, "u");
  replaceElements(postCellChildren[i], descendentOfBlockSequence,
		  divTemplate, "b");
}

function postLoad() {
  var child =
    secondCell(lastTableRow().parentNode.firstChild).firstChild;

  /* Find span.postlistpostname. */
  while (tagName(child) != 'span')
    child = child.nextSibling;
  fixNames(child);		// Fix span.postlistpostname.

  /* Find span.postlistpostbody. */
  do
    child = child.nextSibling;
  while (tagName(child) != 'span');
  /* Fix span.postlistpostbody. */
  replaceElements(child, descendentOfSpanSequence,
		  spanTemplate, "u");
  replaceElements(child, descendentOfBlockSequence,
		  divTemplate, "b");
}

var color = [ "black", "blue", "cyan", "darkgreen", "green", "orange",
	      "pink", "purple", "red", "silver", "skyblue", "yellow" ];
var mood = [ "angry", "confused", "coolio", "cryin", "evil", "exclamation",
	     "grin", "happy", "impressed", "keen", "lickme", "lmao", "looksy",
	     "mad", "nerd", "nocomment", "orgasmic", "puzzled", "sad",
	     "shocked", "sneaky", "snigger", "squeeze", "sunglasses", "tongue",
	     "whistle", "wince", "wink", "yawn", "yelp", "yikes", "yo" ];
function addSmiley(e) {
  standardizeEvent(e);
  var selColor = color[integer_divide(e.layerX, 15)];
  addElement("[img]http://www.web-i18n.net/~ccwf/img/Smackdown5/smileys/"
	     + selColor + "/"
	     + mood[integer_divide(e.layerY, 15)] + selColor + ".gif[/img]",
	     "");
}

function track() {
  var url = "http://track.web-i18n.net/page.html?";
  if (false) {
    var now = new Date();
    url += "TZ=" + (now.getTimezoneOffset() / 60);
    url += "&date=" + encodeURIComponent(now.toLocaleString());
    url + "&ms=" + now.getMilliseconds();
    if (navigator.language)
      url += "&lang=" + navigator.language;
    if (navigator.userLanguage)
      url += "&uL=" + navigator.userLanguage;
    if (navigator.systemLanguage)
      url += "&sL=" + navigator.systemLanguage;
  } else {
    if (document.referrer)
      url += 'referer=' + encodeURIComponent(document.referrer)
  }
  document.getElementById("track").src = url;
}

if (false && document.addEventListener) {
  listeners = [nodeInsertedListener, nodeInsertedFixupListener];
  document.addEventListener('DOMNodeInserted',
			    nodeInsertedFixupListener, false);
} else {
  listeners = [];
}
