// @(#)jireh.js
var _MONTH_NAMES_ = ['','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
String.prototype.isValidDate = function()
{
    var x = this.trim();
    var o = x;
    x = x.replace(/-|\//g, '.');
    var p = x.split('.');
    if (p.length == 2) {
        p = [ new Date().getFullYear(), p[0], p[1] ];
    }
    if (p.length != 3) {
        alert('Invalid date: '+this+'.\nDate format is YYYY.MM.DD');
        return this;
    }
    var y = p[0];
    var m = p[1];
    var d = p[2];
    if (isNaN(y) || y<2000 || y>9999 || isNaN(m) || m<1 || m>12 || isNaN(d) || d<1 || d>31) {
        alert('Invalid date: '+this+'.\nDate format is YYYY.MM.DD\nInvalid year, month, or date.');
        return this;
    }
    var d2 = (y%4==0) ? 29 : 28;
    if (m==2 && d>29 || (m==2) && (y%4!=0) && d > 28) {
        alert('Invalid date: '+this+'.\nDate format is YYYY.MM.DD\nFebruary has only '+d2+' days.');
        return this;
    }
    if ((m==2 || m==4 || m==6 || m==9 || m==11) && d>30) {
        alert('Invalid date: '+this+'. Date format is YYYY.MM.DD\n'+_MONTH_NAMES_[m]+' has only 30 days.');
        return this;
    }
    m = (m<10) ? '0'+parseInt(m) : ''+parseInt(m);
    d = (d<10) ? '0'+parseInt(d) : ''+parseInt(d);
    var fmt = y+'.'+m+'.'+d;
    return fmt;
}

//"9/b/d".isValidDate();
//"999/1/1".isValidDate();
//"2007/2/29".isValidDate();
//"2008/2/29".isValidDate();
//"2008/6/31".isValidDate();
//"2008/6/30".isValidDate();

function _updateLocalTime()
{
  var e = document.getElementById('localtime');
  if (e != null) {
      e.innerHTML = _gettime(true,false);
  }
  _localTimer = setTimeout('_updateLocalTime()', 1000);
}

function _gettime(ampm,milli)
{
  var now = new Date()
  var month = now.getMonth() + 1
  if (month < 10) {
    month = '0'+month;
  }
  var day = now.getDate()
  if (day < 10) {
    day = '0'+day;
  }
  var hours = now.getHours();
  var apm = '';
  if (ampm) {
      apm = 'am';
      if (hours > 11) {
          apm = 'pm';
      }
      if (hours > 12) {
          hours = hours - 12;
      }
  }
  if (hours < 10) {
    hours = '0'+hours;
  }
  var minutes = now.getMinutes();
  if (minutes < 10) {
    minutes = '0'+minutes;
  }
  var seconds = now.getSeconds();
  if (seconds < 10) {
    seconds = '0'+seconds;
  }
  var ms = '';
  if (milli) {
      ms = now.getMilliseconds();
      if (ms < 10) {
          ms = '00'+ms;
      }
      else if (ms < 100) {
          ms = '0'+ms;
      }
      ms = '.'+ms;
  }
  
  return now.getFullYear()+'-'+month+'-'+day+' '+hours+':'+minutes+':'+seconds+ms+apm;
}

function _today()
{
  var now = new Date()
  var month = now.getMonth() + 1
  if (month < 10) {
    month = '0'+month;
  }
  var day = now.getDate()
  if (day < 10) {
    day = '0'+day;
  }
  return now.getFullYear()+'-'+month+'-'+day;
}

function Logger(listener)
{ 
    // 1-fatal 2-error, 3-warn, 4-info, 5-debug
    
    function clear()
    {
        this.buffer = this.controls+' listener='+this.listener+' ajax='+ajaxObject+'<br>';
        this.current = '';
        this.fireLogUpdated();
    }
    
    function info(msg)
    {
        if (this.logLevel < 4) {
            return;
        }
        this.current = _gettime(false,true)+': '+msg;
        this.buffer = this.buffer+this.current+'<br>';
        this.fireLogUpdated();
    }
    
    function setListener(listener)
    {
        this.listener = listener;
        //alert(listener.logUpdated);
    }
    
    function fireLogUpdated()
    {
        if (this.listener != null) {
            this.listener.logUpdated(this, this.buffer, this.current);
        }
        
    }
    
    function setLogLevel(level)
    {
        this.logLevel = level;
    }
    
    this.listener = listener;
    this.controls = '<a href="#" onclick="logger.clear()">Clear</a> '+
                    '<a href="#" onclick="">Refresh</a>';
                    
    this.buffer = this.controls+' listener='+this.listener+' ajax='+ajaxObject+'<br>';
    this.current = '';
    this.logLevel = 0;

    this.info = info;
    this.clear = clear;
    this.setListener = setListener;
    this.fireLogUpdated = fireLogUpdated;
    this.setLogLevel = setLogLevel;
}
var _nop = function(){}

var ajaxId = 1000;
var ajaxObject = '';
      var aaa = new Array(
         //'Msxml2.XMLHTTP.5.0',
         //'Msxml2.XMLHTTP.4.0',
         //'Msxml2.XMLHTTP.3.0',
         'Msxml2.XMLHTTP',
         'Microsoft.XMLHTTP');
      for (var i = 0; i<aaa.length; i++) {
        try {
           new ActiveXObject(aaa[i]);
           ajaxObject = aaa[i];
           break;
        }
        catch (ex) {
        }
      }
ajaxObject = ajaxObject+' minor='+window.navigator.appMinorVersion;
var logger = new Logger();

function AjaxStateChange(xid, ajax, async, listener)
{
    function stateChanged()
    {
        if (this.ajax == null) {
            return;
        }
        if (this.ajax.readyState < 3) {
            return;
        }
        logger.info('Ajax '+this.xid+': ready='+this.ajax.readyState+' status='+(this.ajax.readyState<=2?'':this.ajax.status));
        if (this.ajax.readyState == 3) {
            logger.info('Ajax '+this.xid+': headers='+this.ajax.getAllResponseHeaders);
        }
        if (this.ajax.readyState == 4) {
            if (this.async && this.listener != null) {
                if (this.ajax.status == 200) {
                    this.listener.processResponse(this.ajax);
                }
                else {
                    this.listener.processError(ajax);
                }
            }
            this.listener = null;
            this.ajax = null;
        }
    }
        
    this.xid = xid;
    this.ajax = ajax;
    this.async = async;
    this.listener = listener;
    
    this.stateChanged = stateChanged;
}

var ajaxGarbage = new Array();
var ajaxNoCache = true;

function AjaxRequest()
{
  function send(method, url, params, listener, async)
  {
    while (ajaxGarbage.length > 0) {
        var ax = ajaxGarbage.pop();
        if (ax != null) {
            ax[1].onreadystatechange = _nop;
            logger.info('Ajax GC '+ax[0]);
        }
    }
    var q = url.lastIndexOf('?');
    if (q > 0) {
        params = params+'&'+url.substr(q+1);
        url = url.substr(0,q);
    }
    method = method.toLowerCase();
    var ajax = false;
    if (window.XMLHttpRequest) {
      // Mozilla, Safari,...
      ajax = new XMLHttpRequest();
      //ajaxObject = 'XMLHttpRequest';
      if (ajax.overrideMimeType) {
        // set type accordingly to anticipated content type
        // ajax.overrideMimeType('text/xml');
        ajax.overrideMimeType('text/html');
      }
    }
    else if (window.ActiveXObject) {
      var msxmls = new Array(
         'Msxml2.XMLHTTP.5.0',
         'Msxml2.XMLHTTP.4.0',
         'Msxml2.XMLHTTP.3.0',
         'Msxml2.XMLHTTP',
         'Microsoft.XMLHTTP');
      for (var i = 0; i<msxmls.length; i++) {
        try {
           ajax = new ActiveXObject(msxmls[i]);
           //ajaxObject = msxmls[i];
           break;
        }
        catch (ex) {
        }
      }
    }
    if (!ajax) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    var xid = this.id;
    if (async && listener!=null) {
    ajax.onreadystatechange = function() {
      if (ajax.readyState < 3) {
          return;
      }
      logger.info('Ajax '+xid+': ready='+ajax.readyState+' status='+(ajax.readyState<=3?'':ajax.status));
      if (ajax.readyState == 3) {
          var t = typeof ajax.getAllResponseHeaders;
          if (t=='function') {
              logger.info('Ajax '+xid+': '+t+' headers='+ajax.getAllResponseHeaders());
          }
          else {
              logger.info('Ajax '+xid+': '+t+' headers='+ajax.getAllResponseHeaders);
          }
      }
      if (listener != null && async && ajax.readyState == 4) {
        if (ajax.status == 200) {
          listener.processResponse(ajax, url, params, xid);
        }
        else {
          listener.processError(ajax, url, params, xid);
        }
      }
      if (ajax.readyState == 4 && async) {
        var ax = new Array();
        ax.push(xid,ajax);
        ajaxGarbage.push(ax);
      }
    }
    }
    try {
      if (!async) {
        //document.body.style.cursor = 'wait';
      }
      if (method == 'post') {
        logger.info('Ajax '+this.id+': '+method+' '+url+' '+params+' '+async);
        ajax.open(method, url, async);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        ajax.setRequestHeader('Content-Length', params.length);
        ajax.setRequestHeader('Connection', "close");
        ajax.send(params);
      }
      else {
        logger.info('Ajax '+this.id+': '+method+' '+url+'?'+params+' '+async);
        params = params+'&_='+(new Date().getTime());
        ajax.open(method, url+'?'+params, async);
        ajax.send(null);
      }
    }
    catch (ex) {
        logger.info('Ajax '+this.id+': *** Exception: '+ex);
    }
    finally {
      if (!async) {
        //document.body.style.cursor = 'default';
      }
    }
    if (async) {
        logger.info('Ajax '+this.id+': -> returned');
    }
    else {
        
        logger.info('Ajax '+this.id+': -> '+ajax.readyState+' '+ajax.status+' '+ajax.getResponseHeader("Content-Type"));
        logger.info('Ajax '+this.id+': -> '+ajax.responseText);
    }

    if (listener != null && !async) {
        if (ajax.status == 200) {
          listener.processResponse(ajax, url, params);
        }
        else {
          listener.processError(ajax, url, params);
        }
    }

    return ajax;
  }

  this.id = ++ajaxId;
  this.send = send;
}

function AjaxHandler(targetId)
{
    function processResponse(ajax, url, params)
    {
        //alert('processResponse: '+ajax.responseText);
        var targetElement = document.getElementById(this.targetId);
        targetElement.innerHTML = ajax.responseText;
    }

    function processError(ajax, url, params)
    {
        //alert('processError: '+ajax.status);
        var targetElement = document.getElementById(this.targetId);
        targetElement.innerHTML = 'Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
    }
    
    this.targetId = targetId;
    this.processResponse = processResponse;
    this.processError = processError;
}

function _compose(form)
{
    if (form == null) {
        return "null";
    }
    var delimiter = '&';
    var elements = form.elements;
    var data = "";
    var value = "";
    var name = "";
    for (i = 0; i < elements.length; i++) {
        element = elements[i];
        name = element.name;
        if (element.type == "button") continue;
            if (element.type == "radio") { 
                if (element.checked) {
                    value = element.value;
                }
                else {
                    continue; 
                }
        } 
        else if (/select-.*/.test(element.type)) { //(n.type == "select-multiple") 
            var varArray = new Array;  
            for (k = 0; k < element.options.length; k++) {
                if (element.options[k].selected == true) {
                    varArray.push(element.options[k].value);
                }
            } 
            for (j = 0; j < varArray.length; j++) { 
                var strVal = varArray[j].replace(/&/g,"%26");
                strVal = strVal.replace(/\+/g, "%2b");
                var strVal = varArray[j];
                //data += name + "=" + encodeURIComponent(strVal) + delimiter;
                data += name + "=" + strVal + delimiter;
            }
            continue;     
        } 
        else if (element.type == "checkbox") {
            // see if this impacts any other places
            if (element.checked) {
                value = element.value;
            }
            else {
                continue;
            }
        } 
        else { 
            value = element.value; 
        } 
        //value = value.replace(/\+/g, "%2b");
        //value = encodeURIComponent(value);
        value = jcEncodeURI(value);
        data += name + "=" + value + delimiter;
    }
    if (!(data == "")) {
        data = data.substring(0, data.length-1);
    }
    return data;
}

function jcEncodeURI(value)
{
    value = encodeURI(value);
    value = value.replace(/&/g,"%26");
    value = value.replace(/=/g,"%3D");
    value = value.replace(/\+/g,"%2B");
    return value;
}

function MessageBox(title, id, titleId, contentId, ajaxMethod, ajaxUrl, width, height)
{
    this.title = title;
    this.id = id;
    this.titleId = titleId;
    this.contentId = contentId;
    this.ajaxMethod = ajaxMethod;
    this.ajaxUrl = ajaxUrl;
    this.width = width;
    this.height = height;
    
    function showLog()
    {
        var _box = document.getElementById(this.id);
        var _title = document.getElementById(this.titleId);
        var _content = document.getElementById(this.contentId);
        _title.innerHTML = 'Logger';
        _content.innerHTML = logger.buffer;
        _box.style.width = this.width;
        _box.style.height = this.height;
        _content.style.height = this.height - 20;
        _box.style.zIndex = 9;
        _box.style.visibility = 'visible';
        logger.setListener(this);
        logger.setLogLevel(5);
    }
    
    function hideLog()
    {
        var _box = document.getElementById(this.id);
        _box.style.visibility = 'hidden';
        logger.setLogLevel(0);
    }
    
    function logUpdated(logger, buffer, message)
    {
        if (this.title != 'Logger') {
            return;
        }
        var _content = document.getElementById(this.contentId);
        _content.innerHTML = buffer;    
    }
    
    function showBox(title, content)
    {
        var _box = document.getElementById(this.id);
        var _title = document.getElementById(this.titleId);
        var _content = document.getElementById(this.contentId);
        if (_box) {
             _title.innerHTML = title;
             _content.innerHTML = content;
             _box.style.visibility = 'visible';
        }
    }
    
    function hideBox()
    {
        var _box = document.getElementById(id);
        if (_box) {
             box.style.visibility = 'visible';
        }
    }
    
    function showBox2(params)
    {
        var _box = document.getElementById(this.id);
        var _title = document.getElementById(this.titleId);
        var _content = document.getElementById(this.contentId);

        _title.innerHTML = '<b>'+this.title+'</b>';
        _content.innerHTML = '...';
        _content.style.height = this.height - 20;
        _box.style.width = this.width;
        _box.style.height = this.height;
        _box.style.zIndex = 9;
        _box.style.visibility = 'visible';
        
        var ajax = new AjaxRequest().send(this.ajaxMethod, this.ajaxUrl, params, null, false);
        var content = '?';
        if (ajax.status == 200) {
            content = ajax.responseText;
        }
        else {
            content = "Error: status="+ajax.status;
        }
        _content.innerHTML = content;
        
    }
    
    this.showBox = showBox;
    this.hideBox = hideBox;
    this.showBox2 = showBox2;
    this.showLog = showLog;
    this.hideLog = hideLog;
    this.logUpdated = logUpdated;
}

function MessageTimer(tableId, alertId, alertText, timeoutCmd, timeoutSecs, ajaxUrl, ajaxParams, columns, rowtag)
{
    function processResponse(ajax)
    {
        //alert(ajax.responseText+"\n"+ajax.responseXML+"\n"+ajax.responseXML.documentElement);
        var xml = ajax.responseXML;
        if (xml == null || xml.documentElement == null) {
            if (typeof(DOMParser) != 'undefined') {
              xml = (new DOMParser()).parseFromString(ajax.responseText, "text/xml");
            }
        }
        if (xml == null || xml.documentElement == null) {
            this.restartTimer();
            return;
        }
        var cols = this.columns;
        var rtag = this.rowtag;
        
        var doc = xml.documentElement;
        var cfg = doc.getElementsByTagName('config');
        if (cfg != null && cfg.length > 0) {
            cfg = cfg.item(0);
            rtag = this.getAttribute(cfg.attributes, 'msgtag');
        }
        var app = doc.getElementsByTagName('append-table');
        if (app != null && app.length > 0) {
            app = app.item(0);
            cols = this.getAttribute(app.attributes, 'columns').split(',');
        }
        var upd = doc.getElementsByTagName('update-table');
        var updCols = null;
        var updTag = null;
        var updKey = null; 
        if (upd != null && upd.length > 0) {
            upd = upd.item(0);
            updCols = this.getAttribute(upd.attributes, 'columns').split(',');
            updTag = this.getAttribute(upd.attributes, 'tag');
            updKey = this.getAttribute(upd.attributes, 'key');
        }
        var txt = doc.getElementsByTagName('append-text');
        var txtTgt = null;
        if (txt != null && txt.length>0) {
            txt = txt.item(0);
            txtCols = this.getAttribute(txt.attributes, 'columns').split(',');
            txtTgt = this.getAttribute(txt.attributes, 'target');
        }

        var list = doc.childNodes;
        var cnt = 0;
        for (var ii=0; list!=null && ii<list.length; ++ii) {
            var m = list.item(ii);
            if (m.nodeName != rtag) {
                continue;
            }
            var x = m.attributes;
            var color = this.getAttribute(x,'color');
            if (cols != null) {
                var data = new Array();
                for (var jj=0; jj<cols.length; ++jj) {
                    if (cols[jj].length==0) {
                        data[jj] = null;
                    }
                    else {
                        data[jj] = this.getAttribute(x, cols[jj]);
                    }
                }
                this.addMessage(data);
                ++cnt;
            }
            if (updCols != null) {
                var data2 = new Array();
                for (var jj=0; jj<updCols.length; ++jj) {
                    if (updCols[jj].length==0) {
                        data2[jj] = null;
                    }
                    else {
                        data2[jj] = this.getAttribute(x, updCols[jj]);
                    }
                }
                this.updateMessage(updTag+this.getAttribute(x, updKey),data2);
            }
            if (txtCols != null) {
                var data3 = '';
                for (var jj=0; jj<txtCols.length; ++jj) {
                    if (txtCols[jj].length>=0) {
                        data3 = data3 + this.getAttribute(x, txtCols[jj]) + ' ';
                    }
                }
                this.appendText(txtTgt,data3,color);
            }
        }
        if (cnt > 0 && this.alertId != null) {
            var a = document.getElementById(this.alertId);
            if (a != null) {
                a.innerHTML = this.alertText;
            }
        }
        var table = document.getElementById(this.tableId);
        if (table.rows.length > this.maxMessages) {
            var data = new Array();
            for (var jj=0; jj<cols.length; ++jj) {
                if (cols[jj]=='timestamp') {
                    data[jj] = _gettime(false,false);
                }
                else if (cols[jj]==this.messageColumn) {
                    data[jj] = '...Too many messages, only first '+this.maxMessages+' displayed';
                }
                else {
                    data[jj] = '-';
                }
            }
            this.addMessage(data);
            this.status = 'idle';
        }
        else {
            this.restartTimer();
        }
    }

    function processError(ajax)
    {
        logger.info('MessageTimer: processError: '+ajax.status);
        this.restartTimer();
    }
    
    function clear()
    {
        if (this.status != 'idle') {
            return;
        }
        this.status = 'clear';
        var table = document.getElementById(this.tableId);
        if (table == null) {
            this.status = 'idle';
            return;
        }
        while (table.rows.length > 2) {
            table.deleteRow(2);
        }
        var a = document.getElementById(this.alertId);
        if (a != null) {
            a.innerHTML = '&nbsp;';
        }
        this.status = 'idle';
    }
    
    function restartTimer()
    {
        this.status = 'idle';
        this.timer = setTimeout(this.timeoutCmd, this.timeoutSecs);
    }
    
    function addMessage(data)
    {
        var table = document.getElementById(this.tableId);
        var idx = table.rows.length;
        var row = table.insertRow(idx);
        if (idx % 2 == 1) {
            row.className = 'tableRowOdd';
        }
        else {
            row.className = 'tableRowEven';
        }
        idx = idx - 1;
    
        var cell;
        for (var ii=0; ii<data.length; ++ii) {
            cell = row.insertCell(ii);
            if (data[ii]==null) {
                cell.innerHTML = '&nbsp;';
            }
            else {
                cell.innerHTML = data[ii]+'&nbsp;';
            }
            cell.className = (ii==0)?'tableCellLeft':'tableCellOther';
        }
    }
    
    function updateMessage(tag, data)
    {
        var tr = document.getElementById(tag);
        logger.info('updateMessage: '+tag+' '+data+' -> '+tr);
        if (tr == null) {
            return;
        }
        for (var ii=0; ii<data.length; ++ii) {
            if (data[ii]==null) {
                continue;
            }
            if (ii>=tr.cells.length) {
                break;
            }
            var dat = data[ii];
            var cell = tr.cells[ii];
            var cur = cell.innerHTML;
            var sp = cur.lastIndexOf('&nbsp;')==cur.length-6;
            if (sp) {
                cur = cur.substring(0,cur.length-6);
            }
            if (cur == dat) {
                continue;
            }
            sp = (sp) ? '&nbsp;' : '';
            if (dat.length==0) {
                cell.innerHTML = '&nbsp;';
            }
            else {
                cell.innerHTML = dat+sp;
            }
            cell.style.color = '#9900ff';
        }
    }
    
    function appendText(tgt, data, color)
    {
        var o = document.getElementById(tgt);
        if (o == null) {
            return;
        }
        var c1 = '';
        var c2 = '';
        if (color != null) {
            c1 = '<span style="color:'+color+';">';
            c2 = '</span>';
        }
        o.innerHTML = o.innerHTML+c1+data+c2+'<br>';
        if (o.scrollHeight) {
            o.scrollTop = o.scrollHeight;
        }
        if (typeof(java)!='undefined') {
            java.awt.Toolkit.getDefaultToolkit().beep();
        }
    }
    
    function getAttribute(attributes, name)
    {
        var node = attributes.getNamedItem(name);
        var value = '';
        if (node != null) {
            value = node.nodeValue;
        }
        return value;
    }
    
    function refresh()
    {
        if (this.status != 'idle') {
            this.timer = setTimeout(this.timeoutCmd, this.timeoutSecs);
            return;
        }
        if (document.getElementById(this.tableId) == null) {
            this.timer = setTimeout(this.timeoutCmd, this.timeoutSecs);
            return;
        }
        this.status = 'busy';
        new AjaxRequest().send('get', ajaxUrl, ajaxParams, this, true);
    }
    
    this.tableId = tableId;
    this.alertId = alertId;
    this.alertText = alertText;
    this.timer = null;
    this.timeoutSecs = timeoutSecs;
    this.timeoutCmd = timeoutCmd;
    this.status = 'idle';
    this.ajaxUrl = ajaxUrl;
    this.ajaxParams = ajaxParams;
    this.columns = (columns==null) ? null : columns.split(',');
    this.rowtag = rowtag;
    this.maxMessages = 30;
    this.messageColumn = 'text';
    
    this.processResponse = processResponse;
    this.processError = processError;
    this.addMessage = addMessage;
    this.getAttribute = getAttribute;
    this.refresh = refresh;
    this.restartTimer = restartTimer;
    this.clear = clear;
    this.updateMessage = updateMessage;
    this.appendText = appendText;
}

var asyncFormId = 1000;
AsyncFormController = {
    submit : function(f, c) {
        var x = ++asyncFormId;
        var n = 'af_iframe_'+(x);
        var d = document.createElement('div');
        d.id = 'af_div_'+x;
        d.innerHTML = '<iframe style="position:absolute;display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AsyncFormController.loaded(\''+n+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }
        f.setAttribute('target', n);
        if (c && typeof(c.onStart) == 'function') {
            c.onStart();
        }
        f.submit();
        return d.id;
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        var d = null;
        if (i.contentDocument) {
            d = i.contentDocument;
        }
        else if (i.contentWindow) {
            d = i.contentWindow.document;
        }
        else {
            d = window.frames[id].document;
        }
        if (d==null || d.location.href == "about:blank") {
            return;
        }
        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }
}
AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        if (i.contentDocument) {
            var d = i.contentDocument;
        } else if (i.contentWindow) {
            var d = i.contentWindow.document;
        } else {
            var d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }
        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }

}

function AsyncForm(id, formId, rspId, postScript)
{
    this.id = id;
    this.formId = formId;
    this.rspId = id;
    this.postScript = postScript;
    this.responseText = '[n/a]';
    
    this.onComplete = function(rsp)
    {
        this.responseText = rsp;
        if (rspId != null) {
            var e = document.getElementById(this.rspId);
            if (e) {
                e.innerHTML = rsp;
            }
        }
        if (postScript) {
            eval(postScript);
        }
    }
    
    this.submit = function()
    {
        this.responseText = '[n/a]';
        var f = document.getElementById(this.formId);
        AsyncFormController.submit(f, this);
        return true;
    }
}


function JCTabs(tabCount, headerId, contentId, styleDefault, styleSelected)
{
    function switchTab(theTab, tabNo)
    {
        for (ii = 1; ii <= this.tabCount; ii++) {
            //var tab = eval(this.headerId + ii);
            var tab = document.getElementById(this.headerId+ii);
            if (tab == null) {
                continue;
            }
            tab.className = this.styleDefault;
            var content = document.getElementById(this.contentId+ii);
            if (content) {
                content.style.position = '';
                content.style.display = 'none';
            }
        }
        if (theTab == null) {
           theTab = document.getElementById(this.headerId+tabNo);
        }
        theTab.className = this.styleSelected;
        var content = document.getElementById(this.contentId + tabNo);
        if (content) {
            content.style.position = ''; //'relative'
            content.style.display = '';
        }
    }
    
    this.tabCount = tabCount;
    this.headerId = headerId;
    this.contentId = contentId;
    this.styleDefault = styleDefault;
    this.styleSelected = styleSelected;
    
    this.switchTab = switchTab
}

function JCTabs2(tabCount, headerId, contentId)
{
    function switchTab(theTab, tabNo)
    {
        for (ii = 1; ii <= this.tabCount; ii++) {
            //var tab = eval(this.headerId + ii);
            var tab = document.getElementById(this.headerId+ii);
            var content = document.getElementById(this.contentId+ii);
            if (content) {
                content.style.position = '';
                content.style.display = 'none';
            }
        }
        var content = document.getElementById(this.contentId + tabNo);
        if (content) {
            content.style.position = ''; //'relative'
            content.style.display = '';
        }
    }
    
    this.tabCount = tabCount;
    this.headerId = headerId;
    this.contentId = contentId;
    
    this.switchTab = switchTab
}

function tableCellLeap(event, src, col)
{
    var keynum;
    if(window.event) {
        keynum = event.keyCode; //i.e.
    }
    else if(event.which) {
        keynum = event.which; // Netscape/Firefox/Opera
    }
    if (keynum==40 || keynum==38) {
        var tr = src.parentNode.parentNode;
        var nx = (keynum==40) ? tr.nextSibling : tr.previousSibling;
        if (nx && nx.nodeName == '#text') {
            nx = (keynum==40) ? nx.nextSibling : nx.previousSibling;
        }
        if (nx != null && nx.nodeName == 'TR') {
            var td = nx.cells[col];
            for (var ii=0; ii<td.childNodes.length; ++ii) {
                var nn = td.childNodes.item(ii);
                if (nn.nodeName == 'INPUT') {
                    nn.focus();
                    break;
                }
            }
        }
    }

    return true;
}

function stopBackspace(event)
{
    var keynum;
    if(window.event) {
        keynum = event.keyCode; //i.e.
    }
    else if(event.which) {
        keynum = event.which; // Netscape/Firefox/Opera
    }
    var target = (event.target? event.target : event.srcElement);
    if (keynum==8) {
        if (target.nodeName == 'INPUT' && target.type && target.type=='text') {
            return true;
        }
        return false;
    }
    return true;
}

var jcLanguage = 1;
var jcCurrentMain = '';

function jcSwitchLanguage(lang, load)
{
    if (jcLanguage == lang) {
    }
    jcLanguage = lang;
    if (lang == 1) {
      jcEnglishLanguage(load);
    }
    else {
      jcChineseLanguage(load);
    }
}

function jcEnglishLanguage(load)
{
    jcSwitchMenu('jcChineseMenu', 'jcEnglishMenu');
    jcSwitchMenu('jcChLangMenu', 'jcEnLangMenu');
    jcSwitchMenu('jcChMainLeft', 'jcEnMainLeft');
    jcLanguage = 1;
    document.getElementById('jcLanguageIndicator').innerHTML = '&#949;';
    if (load) {
        _load(jcMenuEnglishItem(jcCurrentMain));
    }
}

function jcChineseLanguage(load)
{
    jcSwitchMenu('jcEnglishMenu', 'jcChineseMenu');
    jcSwitchMenu('jcEnLangMenu', 'jcChLangMenu');
    jcSwitchMenu('jcEnMainLeft', 'jcChMainLeft');
    jcLanguage = 2;
    document.getElementById('jcLanguageIndicator').innerHTML = '&#945;';
    if (load) {
        _load(jcMenuChineseItem(jcCurrentMain));
    }
}

function jcSwitchMenu(id1, id2)
{
    var d1 = document.getElementById(id1);
    d1.style.position = 'absolute';
    d1.style.top = 0;
    d1.style.left = 0;
    d1.style.visibility = 'hidden';
    var d2 = document.getElementById(id2);
    d2.style.position = '';
    d2.style.visibility = 'visible';
}

function jcLinkOver(l)
{
    l.style.textDecoration = 'underline';
}

function jcLinkOut(l)
{
    l.style.textDecoration = 'none';
}

function jcInitialize()
{
    jcLanguage = 1;
    _load('_main.html', false);
    jcEnglishLanguage();
}

function _preview(f)
{
    _load('sundays/_preview.php?file=..'+f);
}

var jcWipCount = 0;
function _load(url, rec, target)
{
    if (target == null) {
        target = 'jcMainCenter';
    }
    var a = document.getElementById('jcMainCenter');
    var ajax = new AjaxRequest().send('get', url, '', new JCAjaxListener(target), true);
    if (target == 'jcMainCenter') {
        jcCurrentMain = url;
    }
    if (rec==null || rec) {
        jcAddHistory(url, jcLanguage, url, target);
    }
    jcWipOn();
    jcVisit(url);
}

function jcVisit(page)
{
    var ajax = false;
    if (window.XMLHttpRequest) {
      ajax = new XMLHttpRequest();
      if (ajax.overrideMimeType) {
        ajax.overrideMimeType('text/html');
      }
    }
    else if (window.ActiveXObject) {
      var msxmls = new Array(
         'Msxml2.XMLHTTP.5.0',
         'Msxml2.XMLHTTP.4.0',
         'Msxml2.XMLHTTP.3.0',
         'Msxml2.XMLHTTP',
         'Microsoft.XMLHTTP');
      for (var i = 0; i<msxmls.length; i++) {
        try {
           ajax = new ActiveXObject(msxmls[i]);
           break;
        }
        catch (ex) {
        }
      }
    }
    try {
        ajax.open('get', 'scripts/_visit.php?page='+page, true);
        ajax.send(null);
    }
    catch (ex) {
    }
}

function jcWipOn()
{
    ++jcWipCount;
    document.getElementById('jcWip').innerHTML = '<img src="images/wip.gif" border=0" style="margin-top: 4px;"/>';
}
function jcWipOff()
{
    --jcWipCount;
    if (jcWipCount <= 0) {
        jcWipCount = 0;
        document.getElementById('jcWip').innerHTML = '&nbsp;';
    }
}

function JCAjaxListener(targetId)
{
    function processResponse(ajax, url, params, xid)
    {
        //alert('JCAjaxListener.processResponse: '+ajax.responseText);
        var targetElement = document.getElementById(this.targetId);
        targetElement.innerHTML = ajax.responseText;
        var onload = document.getElementById('onload');
        if (onload != null && onload.onload != null) {
            var t = typeof onload.onload;
            //alert(onload.onload);
            if (t=='function') {
                onload.onload();
            }
            else {
                eval(onload.onload);
            }
        }
        jcWipOff();
    }

    function processError(ajax, url, params)
    {
        //alert('JCAjaxListener.processError: '+ajax.status);
        var targetElement = document.getElementById(this.targetId);
        targetElement.innerHTML = 'Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        jcWipOff();
    }
    
    this.targetId = targetId;
    this.processResponse = processResponse;
    this.processError = processError;
}

function jcMmPlay(line, id, f, name)
{
  var ss = document.getElementById('status');
  var mm = document.getElementById(id);
  if (line==null) {
    if (mm.x != null) {
      mm.x.style.color = '';
      mm.x = null;
      mm.f = '';
    }
    mm.innerHTML = "";
    return;
  }
  if (mm.f != f) {
    if (mm.x != null) {
      mm.x.style.color = '';
    }
    mm.innerHTML = "<embed src='../"+f+"' hidden=true autostart=true loop=false>";
    mm.f = f;
    mm.x = line;
    if (ss) {
      if (jcLanguage == 1) {
        ss.innerHTML = 'Playing: '+name;
        _counter(f);
      }
      else {
        ss.innerHTML = '&#27491;&#22312;&#25773;&#25918;: '+name;
      }
    }
    if (line) {
      line.style.color = '#6B8E23';
    }
  }
  else {
    mm.innerHTML = '';
    mm.f = '';
    if (ss) {
      ss.innerHTML = '&nbsp;';
    }
    line.style.color = '';
  }
  return false;
}

function jcMainOnload()
{
    jcUpcomingEvents();
    jcSundayServices2();
     jcVerseOfWeek();
    jcAuditVisitor();
}

function jcSundayServices2()
{
    var node = document.getElementById('jcSundayServices2');
    if (node == null) {
        return;
    }
    try {
        var ajax = new AjaxRequest().send('get', 'sundays/_sundays.php', 'lang='+jcLanguage, null, false);
        if (ajax.readyState == 4 && ajax.status == 200) {
            node.innerHTML = ajax.responseText;
        }
    }
    catch (ex) {
        alert('jcUpcomingEvents: ****'+ex.name+': '+ex.message);
    }
}

function jcUpcomingEvents()
{
    var node = document.getElementById('jcUpcomingEvents');
    if (node == null) {
        return;
    }
    try {
        var ajax = new AjaxRequest().send('get', 'events/_upcoming.php', 'box=0&lang='+jcLanguage, null, false);
        if (ajax.readyState == 4 && ajax.status == 200) {
            node.innerHTML = ajax.responseText;
        }
    }
    catch (ex) {
        alert('jcUpcomingEvents: ****'+ex.name+': '+ex.message);
    }
}

function jcVerseOfWeek()
{
    var node = document.getElementById('jcVerseOfWeek');
    if (node == null) {
        return;
    }
    try {
        var ajax = new AjaxRequest().send('get', 'sundays/_verse.php', 'lang='+jcLanguage, null, false);
        if (ajax.readyState == 4 && ajax.status == 200) {
            node.innerHTML = ajax.responseText;
        }
    }
    catch (ex) {
        alert('jcUpcomingEvents: ****'+ex.name+': '+ex.message);
    }
}

function jcAuditVisitor()
{
    jcSetHtml('vcount', null, '?');
    
    var pag = "scripts/_stats.php?_="+new Date();
    
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (req) {
        req.onreadystatechange = function () {
           if (req.readyState == 4) {
               if (req.status == 200) {
                   jcSetHtml('vcount', null, req.responseText);
               }
            }
        };
        req.open("get", pag, true);
        req.send(null);
    }
}

function jcSetHtml(id, e, h)
{
    if (e == null) {
        e = document.getElementById(id);
    }
    if (e != null) {
        e.innerHTML = h;
    }
    return e;
}

function jcHistoryChanged(hash, data)
{
    if (hash==null || data==null) {
        //alert('jcHistoryChanged: hash='+hash+' data='+data);
    }
    if (data) {
        jcSwitchLanguage(data.lang);
        var url = data.page;
        var ajax = new AjaxRequest().send('get', url, '', new JCAjaxListener(data.target), true);
    }
    else {
        jcInitialize();
    }
}

var jcHistoryData = {lang: 1, page: '_main.html', target: 'jcMainCenter'};

var jcHistoryId = 0;
function jcAddHistory(hash, lang, page, target)
{
    if (jcHistoryData != null && 
        jcHistoryData.lang == lang && 
        jcHistoryData.page == page &&
        jcHistoryData.target == target) {
        return;
    }
    jcHistoryData = {lang: lang, page: page, target: target};
    dhtmlHistory.add('jc'+(++jcHistoryId), jcHistoryData);
}

function jcSubmitComments(f, url)
{
  var params = _compose(f);
  var ajax = new AjaxRequest().send('post', url, params, new JCAjaxListener('jcMainCenter'), false);
}

var _s = null;
var _c = null;

function _select(s, d)
{
  if (_s == null) {
    _s = document.getElementById('x42');
    _c = document.getElementById('x42_');
  }
  if (d != null) {
    if (d < 1) {
      d = 1;
    }
    var dd = 'x'+((d<10)?'0':'')+d;
    var x = document.getElementById(dd+'_');
    var s = document.getElementById(dd);
    if (x == null) {
      s = document.getElementById('x01');
    }
  }
  if (_s == s) {
    return;
  }

  var c = document.getElementById(s.id+'_');
  if (c == null) {
   return;
  }
  if (_c != null) {
    _c.style.visibility = 'hidden';
    _c.style.position = 'absolute';
    _c.style.top = -2000;
  }
  c.style.position = 'relative';
  c.style.top = 0;
  c.style.visibility = 'visible';
  _c = c;

  s.style.fontSize = '16px';
  s.style.fontWeight = 'bold';
  s.style.border = '1px solid #7f7fff';
  if (_s != null) {
    _s.style.fontSize = '12px';
    _s.style.fontWeight = 'normal';
    _s.style.border = '0';
  }
  _s = s;
}

function _open(t, u)
{
    var w = window.open(u, t);
    w.focus();
}


function jcResetNonce()
{
    var jcSessionKey = jcRandomString(16);
    var cipher = rsaKey1.encrypt(jcSessionKey);
    cipher = hex2b64(cipher);
    cipher = jcEncodeURI(cipher);
    var ajax = new AjaxRequest().send('post', 'acts/_data3.php', 'data3='+cipher, null, false);
    var p = ajax.responseText.indexOf('|');
    //alert(ajax.responseText);
    var nonce = '[n/a]';
    if (p > 0) {
        var rsp = ajax.responseText.substring(p+1);
        rsp = new Base64().decode(rsp);
        rsp = TEADecrypt(rsp, jcSessionKey);
        var q = rsp.indexOf('?');
        if (q > 0) {
            nonce = rsp.substring(0,q);
            //alert(nonce);
            nonce = 1+parseInt(nonce);
        }
    }
    //alert(nonce);
    return [jcSessionKey, nonce];
}

function jcUserLogin(f)
{
    f.username.value = f.username.value.trim();
    f.password.value = f.password.value.trim();
    // if (f.username.value.length < 3 || f.password.value.length < 3) {
    //    alert('Please enter a valid user name and password.');
    //    return false;
    //}
    
    var x = jcResetNonce();
    var jcSessionKey = x[0];
    var nonce = x[1];

    var nxt = f._next.value;
    
    //var f = document.forms[0];
    f.jcNonce.value = new Base64().encode(TEAEncrypt(nonce+'     ', jcSessionKey));
    f.jcData1.value = new Base64().encode(TEAEncrypt(f.username.value+'     ', jcSessionKey));
    f.jcData2.value = new Base64().encode(TEAEncrypt(f.password.value+'     ', jcSessionKey));
    f.username.value = '';
    f.password.value = '';
    
    var params = _compose(f);
    var ajax = new AjaxRequest().send('post', 'members/_login.php', params, new JCAjaxListener('jcMainCenter'), false);
    
    return false;
}

var COLOR_SELECTED = "rgb(205,133,63)";
var COLOR_SELECTED1 = "rgb(205, 133, 63)";



function _tableRowEvenHover(tr)
{
  tr.className = 'tableRowEvenHover';
  if (tr.style.color != COLOR_SELECTED && tr.style.color != COLOR_SELECTED1) {
    tr.style.color = 'blue';
  }
}

function _tableRowOddHover(tr)
{
  tr.className = 'tableRowOddHover';
  if (tr.style.color != COLOR_SELECTED && tr.style.color != COLOR_SELECTED1) {
    tr.style.color = 'blue';
  }
}

function _tableRowEvenOrig(tr)
{
  tr.className = 'tableRowEvenOrig';
  //alert(tr.style.color);
  if (tr.style.color != COLOR_SELECTED && tr.style.color != COLOR_SELECTED1) {
    tr.style.color = 'black';
  }
}

function _tableRowOddOrig(tr)
{
  tr.className = 'tableRowOddOrig';
  if (tr.style.color != COLOR_SELECTED && tr.style.color != COLOR_SELECTED1) {
    tr.style.color = 'black';
  }
}



    function setBorder(tr, c, c2)
    {
        var np = tr.previousSibling;
        var n1 = null;
        var nx = null;
        var nn = tr.childNodes.length;
        for (var ii=0; ii<nn; ++ii) {
            var td = tr.childNodes[ii];
            if (td.nodeName != 'TD') {
                continue;
            }
            if (n1 == null) {
                n1 = td;
                if (n1.style) n1.style.borderLeftColor = c;
            }
            if (td.style) td.style.borderBottomColor = c;
            if (np==null) {
                if (td.style) td.style.borderTopColor = c;
            }
            nx = td;
        }
        nx.style.borderRightColor = c;
        if (np) {
        if (np.nodeName != 'TR') {
            np = np.previousSibling;
        }
        var n2 = np.childNodes.length
        for (var ii=0; ii<n2; ++ii) {
            var td = np.childNodes[ii];
            if (td.nodeName != 'TD') {
                continue;
            }
            if (td.style) td.style.borderBottomColor = c;
        }
        }
        tr.style.color=c2;
    }



// ~~~ JCXBlogs ~~~

function JCXBlogs(id, type)
{
    this.id = id;
    this.type = type;
    this.topicPage = 0;
    this.blogTopics = new Array();
    this.topicSelected = null;
    this.rowSelected = null;
    this.indexSelected = -1;
    this.blogsUrl = 'members/_xblogs.php';
    
    this.show = function show(n)
    {
    }
    
    this.topicPageUp = function()
    {
        --this.topicPage;
        this.refresh();
    }
    
    this.topicPageDown = function()
    {
        ++this.topicPage;
        this.refresh();
    }
    
    
    
    this.getTopics = function()
    {
        var params = 'x=getTopics&cat='+this.type;
    
        var ajax = new AjaxRequest().send('get', this.blogsUrl, params, null, false);
        if (ajax.status == 200) {
            //alert(ajax.responseText);
            try {
                this.blogTopics = new XMLObject(ajax, 'topic').data;
            }
            catch (ex) {
                this.processError(ajax, this.blogsUrl, params, ex);
                return;
            }
            if (ajax.responseText.indexOf('<?xml ')<0) {
                this.processError(ajax, this.blogsUrl, params);
                return;
            }
            var html = '<table cellspacing=0 cellpadding=2 class="rowtbl" width=100%>\n';
            for (var ii=1; ii<this.blogTopics.length; ++ii) {
                var row = this.blogTopics[ii];
                var cls = (ii%2 == 1) ? '1' : '2';
                var sty = (ii==1) ? ' style="border-top: 1px solid white;"' : '';
                html += '<tr class="c'+cls+'" onmouseover="this.style.cursor=\'pointer\';this.className=\'m'+cls+'\';" onmouseout="this.className=\'c'+cls+'\'" onclick="'+this.id+'.selectTopic(this, '+ii+')">\n';
                html += '<td class="c'+cls+'" width=65 nowrap>'+row.date.substring(0,10)+'</td>\n';
                html += '<td class="c'+cls+'" width=100>'+row.user+'</td>\n';
                html += '<td class="c'+cls+'">'+row.topic+'&nbsp;</td>\n';
                html += '</tr>\n';
            }
            html += '</table>';
            document.getElementById(this.id+'TopicList').innerHTML = html;
            document.getElementById(this.id+'TopicDetail').style.display = 'none';
            this.topicSelected = null;
            this.rowSelected = null;
            this.indexSelected = -1;
            this.newTopic(true);
        }
        else {
            this.processError(ajax, this.blogsUrl, params);
        }
    }
    
    this.createTopic = function()
    {
        var f = document.forms[this.id+'CreateForm'];
        f.btopic.value = f.btopic.value.trim();
        f.bcontent.value = f.bcontent.value.trim();
        if (f.btopic.value.length == 0 || f.bcontent.length == 0) {
            alert("Please enter proper Topic and Content.");
            return;
        }
        
        f.cat.value = this.type;
        f.topic.value = encodeURI(f.btopic.value);
        f.content.value = encodeURI(f.bcontent.value);
        
        var params = _compose(f);
        var ajax = new AjaxRequest().send('post', this.blogsUrl, params, null, false);
        if (ajax.status == 200) {
            //alert(ajax.responseText);
            f.reset();
            this.getTopics();
        }
        
    }
    
    this.createResponse = function()
    {
        if (this.topicSelected == null || this.rowSelected == null) {
            alert('No topic selected.');
            return;
        }
        var f = document.forms[this.id+'ResponseForm'];
        f.bsubject.value = f.bsubject.value.trim();
        f.bcontent.value = f.bcontent.value.trim();
        if (f.bsubject.value.length == 0 || f.bcontent.length == 0) {
            alert("Please enter proper Subject and Content.");
            return;
        }
        
        f.bid.value = this.rowSelected.id;
        f.subject.value = encodeURI(f.bsubject.value);
        f.content.value = encodeURI(f.bcontent.value);
        
        var params = _compose(f);
        var ajax = new AjaxRequest().send('post', this.blogsUrl, params, null, false);
        if (ajax.status == 200) {
            alert(ajax.responseText);
            f.reset();
            this.selectTopic(this.topicSelected, this.indexSelected);
        }
        
    }
    
    this.processResponse = function(ajax)
    {
        jcWipOff('jcaServiceListWip', 'jcaServiceInfo', '');
    }

    this.processError = function(ajax, url, params, ex)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')<br>'+
                  ajax.responseText;
        jcWipError('jcaServiceListWip', 'jcaServiceInfo', err);
    }
    
    this.selectTopic = function(tr, idx)
    {
        //#cd853f
        if (this.topicSelected != null) {
            setBorder(this.topicSelected, 'white', 'black');
        }
        setBorder(tr, COLOR_SELECTED, COLOR_SELECTED);
        this.topicSelected = tr;
        
        var row = this.blogTopics[idx];
        this.rowSelected = row;
        this.indexSelected = idx;
        
        document.getElementById(this.id+'TopicSelected').innerHTML = '<b>'+row.topic+'</b>';
        
        var params = 'x=getDetails&bid='+row.id;
        var ajax = new AjaxRequest().send('get', this.blogsUrl, params, null, false);
        if (ajax.status == 200) {
            try {
                this.blogDetails = new XMLObject(ajax, 'detail').data;
            }
            catch (ex) {
                this.processError(ajax, this.blogsUrl, params, ex);
                return;
            }
            var html = '<table cellspacing=0 cellpadding=2>\n';
            for (var ii=1; ii<this.blogDetails.length; ++ii) {
                var row = this.blogDetails[ii];
                html += '<tr><td class="blogs-detail" style="width:100px;"><b>'+row.user+'</b></td>'+
	                    '<td class="blogs-detail" style=""><b>'+row.subject+'</b></td></tr>\n';
                html += '<tr><td class="blogs-detail" style="width:100px;">'+row.date+'</td>'+
	                    '<td class="blogs-content" style="">'+row.content+'</td></tr>\n';
	    }
	    html += '</table>\n';
        }
        document.getElementById(this.id+'TopicContent').innerHTML = html;

        document.getElementById(this.id+'TopicDetail').style.display = '';
        this.newTopic(true);
        this.newResponse(true);
    }
    
    this.deselectTopic = function()
    {
        if (this.topicSelected != null) {
            setBorder(this.topicSelected, 'white', 'black');
            this.topicSelected = null;
            this.rowSelected = null;
            this.indexSelected = -1;
        }
        document.getElementById(this.id+'TopicDetail').style.display = 'none';
    }
    
    this.newTopic = function(x)
    {
    
        var td = document.getElementById(this.id+'NewTopic');
        if (td.style.display == 'none' && !x) {
            td.style.display = '';
            td.style.height = '136px';
            this.deselectTopic();
        }
        else {
            td.style.display = 'none';
        }
    }
    
    this.newResponse = function(x)
    {
        if (this.topicSelected == null) {
            alert('No topic selected.');
            return;
        }
        
        var td = document.getElementById(this.id+'NewResponse');
        if (td.style.display == 'none' && !x) {
            td.style.display = '';
            td.style.height = '136px';
        }
        else {
            td.style.display = 'none';
        }
    }
    
}

var JC_MEDIA = new Array();
JC_MEDIA['b'] = 'Book';
JC_MEDIA['p'] = 'Periodical';
JC_MEDIA['c'] = 'Cassette';
JC_MEDIA['v'] = 'Video';
JC_MEDIA['d'] = 'DVD';
var JC_LANG = new Array();
JC_LANG['1'] = 'English';
JC_LANG['2'] = 'Chinese';

function JCLibrary()
{
    this.items = new Array();
    
    this.showItem = function(n)
    {
        var html = '<table cellspacing=3 cellpadding=2 class="coltbl" width=100%>\n';
        var item = this.items[n];
        var img = item.libimg.trim();
        if (img.length == 0) {
            img = 'blank.jpg';
        }
        holdings = item.libcnt+' available: '+(item.libcnt-item.libout);
        html += '<tr><th width=1>Title</th><td width=99%>'+item.title+'</td></tr>'+
                '<tr><th>Author</th><td>'+item.author+'</td></tr>'+
                '<tr><th>Publisher</th><td>'+item.publisher+'</td></tr>'+
                '<tr><th>Info</th><td>'+(item.year+', '+JC_LANG[item.lang]+', '+JC_MEDIA[item.media])+'</td></tr>'+
                '<tr><th>Holdings</th><td>'+holdings+'</td></tr>'+
                '<tr><th>Location</th><td>'+item.libloc+'</td></tr>'+
                '<tr><td colspan=2><hr size=1></td></tr>'+
                '<tr><td colspan=2 valign=top><img src="library/images/'+img+'"/></td></tr>';
        html += '</table>';
        
        document.getElementById("jcLibraryItemDetail").innerHTML = html;
        jcLibraryTabs.select2(2);
    }
    
    this.getItems = function (x)
    {
        jcLibraryTabs.select2(1)
        var f = document.forms['jcLibraryForm'];
        f.x.value = 'search';
        var data = _compose(f);
        var ajax = new AjaxRequest().send('get', 'library/_library.php', data, this, true);
        jcWipOn();
    }

    this._items1 = function (ajax, x, t)
    {
        var html = '<table cellspacing=3 cellpadding=2 class="rowtbl" width=100%>\n';
        html += '<tr>\
                <th class="hh" width=90>Image</th>\
                <th class="hh">Title/Author</th>\
              </tr>';

        for (var ii=1; ii<this.items.length; ++ii) {
            var item = this.items[ii];
            var img = item.libimg.trim();
            if (img.length == 0) {
                img = 'blank.jpg';
            }
            holdings = item.libcnt+' available: '+(item.libcnt-item.libout);
            html += '<tr>'+
                    '<td valign=top><img title="Title: '+item.title+'\r\nAuthor: '+item.author+'\r\nHoldings: '+holdings+'\r\nLocation: '+item.libloc+'" class="xlink" onclick="jcLibrary.showItem('+ii+')" src="library/libimg.php?img=library/images/'+img+'"/></td>'+
                    '<td valign=top>'+
                    '<table cellspacing=0 cellpadding=1 class="coltbl">'+
                    '<tr><th>Title</th><td>'+item.title+'</td></tr>'+
                    '<tr><th>Author</th><td>'+item.author+'</td></tr>'+
                    '<tr><th>Publisher</th><td>'+item.publisher+'</td></tr>'+
                    '<tr><th>Info</th><td>'+(item.year+', '+JC_LANG[item.lang]+', '+JC_MEDIA[item.media])+'</td></tr>'+
                    '<tr><th>Holdings</th><td>'+holdings+'</td></tr>'+
                    '<tr><th>Location</th><td>'+item.libloc+'</td></tr>'+
                    '</table>'+
                    '</td>'+
                    '</tr>';
        }
        if (this.items.length==1) {
            html += '<tr><td>No match found.</td></tr>';
        }
        for (var ii=this.items.length; ii<3; ++ii) {
            html += '<tr><td colspan=2>&nbsp;</td></tr>';
        }
        html += '</table>';
        return html;
    }

    this._items2 = function (ajax, x, t)
    {
        var html = '<table cellspacing=3 cellpadding=2 class="rowtbl" width=100%>\n';
        html += '<tr>\
                <th class="table-header" width=100%>Image</th>\
              </tr></table>';
              
        html += '<table cellspacing=3 cellpadding=2 class="topic-box-content2" >\n';

        for (var ii=1; ii<this.items.length; ++ii) {
            html += '<tr>';
            var jj;
            for (jj=0; jj<8 && ii<this.items.length; ++jj, ++ii) {
                var item = this.items[ii];
                var img = item.libimg.trim();
                if (img.length == 0) {
                    img = 'blank.jpg';
                }
                holdings = item.libcnt+' available: '+(item.libcnt-item.libout);
                html += '<td valign=top><img title="Title: '+item.title+'\r\nAuthor: '+item.author+'\r\nHoldings: '+holdings+'\r\nLocation: '+item.libloc+'" class="xlink" onclick="jcLibrary.showItem('+ii+')" src="library/libimg.php?img=library/images/'+img+'"/></td>';
            }
            for (; jj<8; ++jj) {
                html += '<td width=90>&nbsp;</td>';
            }
            html += '</tr>\n';
        }
        if (this.items.length==1) {
            html += '<tr><td>No match found.</td></tr>';
        }
        html += '</table>';
        return html;
    }

    this._items3 = function (ajax, x, t)
    {
        var html = '<table cellspacing=3 cellpadding=2 class="rowtbl" width=100%>\n';
        html += '<tr>\
                <th class="hh" width=200>Title</th>\
                <th class="hh" width=100>Author</th>\
                <th class="hh" width=100>ISBN</th>\
                <th class="hh" width=100>Loc</th>\
                <th class="hh" width=0>H/A</th>\
                <th class="hh">Info</th>\
              </tr>';

        for (var ii=1; ii<this.items.length; ++ii) {
            var item = this.items[ii];
            html += '<tr onclick="jcLibrary.showItem('+ii+')" onmouseover="this.className=\'admin-tr-hover\'" onmouseout="this.className=\'admin-tr\'">'+
                    '<td valign=top><span class="xlink" onclick="jcLibrary.showItem('+ii+')">'+item.title+'</span></td>'+
                    '<td valign=top>'+item.author+'</td>'+
                    '<td valign=top>'+item.isbn+'</td>'+
                    '<td valign=top>'+(item.libloc)+'</td>'+
                    '<td valign=top>'+(item.libcnt+'/'+(item.libcnt-item.libout))+'</td>'+
                    '<td valign=top><nobr>'+(item.year+', '+JC_LANG[item.lang]+', '+JC_MEDIA[item.media])+'</nobr></td>'+
                    '</tr>';
        }
        if (this.items.length==1) {
            html += '<tr><td>No match found.</td></tr>';
        }
        for (var ii=this.items.length; ii<20; ++ii) {
            html += '<tr><td colspan=4>&nbsp;</td></tr>';
        }
        html += '</table>';
        return html;
    }

    this.processResponse = function(ajax)
    {
        this.items = new XMLObject(ajax, 'item').data;
        var f = document.forms['jcLibraryForm'];
	var l = f.display.length
	
	var x = 1;
	for (var ii=0; ii<l; ii++) {
	    if (f.display[ii].checked) {
	        x = f.display[ii].value;   
	    }
	}
	var html = '';
	if (x==2) {
	    html = this._items2();
	}
	else if (x==3) {
	    html = this._items3();
	}
	else {
	    html = this._items1();
	}
        document.getElementById('jcLibraryItems').innerHTML = html;
        jcWipOff('jcLibraryItemsWip', 'jcLibraryInfo', '&nbsp;', true);
    }
    
    this.processError = function (ajax, url, params)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        alert(err);
    }
    

}

function jcDownload(f)
{
    window.location = 'scripts/download.php?file='+f;
}

function XMLObject(ajax, tag)
{
    var xml = ajax.responseXML;
    if (xml == null || xml.documentElement == null) {
        if (typeof(DOMParser) != 'undefined') {
          xml = (new DOMParser()).parseFromString(ajax.responseText, "text/xml");
        }
    }
    
    this.data = new Array();
    
    var doc = xml.documentElement;
    var list = doc.childNodes;
    var cnt = 0;
    for (var ii=0; list!=null && ii<list.length; ++ii) {
        var m = list.item(ii);
        var o = new Array();
        if (m.nodeType != 1) {
            continue;
        }
        if (m.nodeName != 'display' && m.nodeName != tag) {
            continue;
        }
        var attrs = m.attributes;
        //var buf = '';
        for (var jj=0; jj<attrs.length; ++jj) {
            var a = attrs.item(jj);
            o[a.name] = a.value;
            //buf += a.name+'='+a.value+', ';
        }
        //alert(buf);
        this.data[cnt++] = o;
    }
}

function JCTabControl(tabId, contentId)
{
    this.select = function (theTab)
    {
       var ul = theTab.parentNode;
       var childNodes = ul.childNodes;
       var tabNo = 0;
       for (var ii=0; ii<childNodes.length; ++ii) {
           var node = childNodes[ii];
           if (node.nodeName != 'LI') {
               continue;
           }
           ++tabNo;
           var div = document.getElementById(this.contentId+tabNo);
           if (node == theTab) {
               node.className = 'tabactive';
               if (div) {
                   div.className = 'tabtop';
               }
           }
           else {
               node.className = 'tabitem';
               if (div) {
                   div.className = 'tabdiv';
               }
           }
       }
    }

    this.select2 = function (theTabNo)
    {
       var ul = document.getElementById(this.tabId);
       if (ul == null) {
           return;
       }
       var childNodes = ul.childNodes;
       var tabNo = 0;
       for (var ii=0; ii<childNodes.length; ++ii) {
           var node = childNodes[ii];
           if (node.nodeName != 'LI') {
               continue;
           }
           ++tabNo;
           var div = document.getElementById(this.contentId+tabNo);
           if (tabNo == theTabNo) {
               node.className = 'tabactive';
               if (div) {
                   div.className = 'tabtop';
               }
           }
           else {
               node.className = 'tabitem';
               if (div) {
                   div.className = 'tabdiv';
               }
           }
       }
    }
    
    this.click = function(theTab)
    {
       var ul = theTab.parentNode;
       var childNodes = ul.childNodes;
       var tabNo = 0;
       for (var ii=0; ii<childNodes.length; ++ii) {
           var node = childNodes[ii];
           if (node.nodeName != 'LI') {
               continue;
           }
           ++tabNo;
           var id = '_'+node.id;
           var div = document.getElementById(id);
           if (node == theTab) {
               node.className = 'tabactive';
               if (div) {
                   div.className = 'tabtop';
               }
           }
           else {
               node.className = 'tabitem';
               if (div) {
                   div.className = 'tabdiv';
               }
           }
       }
    }
    

    this.tabId = tabId;
    this.contentId = contentId;
}
var xtabs = new JCTabControl();

function XTable(r,o,s)
{
    this.r = (r==null) ? 'r' : r;
    this.o = (o==null) ? 'o' : o;
    this.s = (s==null) ? 's' : s;
    
    this.init = function(table, onclick)
    {
        var trs = table.rows;
        for (var ii=0; ii<trs.length; ++ii) {
            var tr = trs[ii];
            tr.onmouseover = function() { xtable.onMouseOver(this); };
            tr.onmouseout  = function() { xtable.onMouseOut(this); };
            if (onclick != null) {
                if (onclick == 'default') {
                    tr.onclick = function() { xtable.onClick(this); };
                }
            }
        }
    }
    
    this.onMouseOver = function(tr)
    {
        var x = tr.className.substr(0,1);
        if (x == this.r) {
            x = this.o+tr.className.substr(1);
            tr.className = x;
        }
    }

    this.onMouseOut = function(tr)
    {
        var x = tr.className.substr(0,1);
        if (x == this.o) {
            x = this.r+tr.className.substr(1);
            tr.className = x;
        }
    }

    this.onClick = function(tr)
    {
        var x = tr.className.substr(0,1);
        if (x == this.o || x == this.r) {
            x = this.s+tr.className.substr(1);
            tr.className = x;
        }
        var table = tr.parentNode;
        if (table.nodeName != 'TABLE') {
            table = table.parentNode;
        }
        var trs = table.rows;
        for (var ii=0; ii<trs.length; ++ii) {
            var tr2 = trs[ii];
            if (tr2 == tr) {
                continue;
            }
            var x = tr2.className.substr(0,1);
            if (x == this.s) {
                x = this.r+tr2.className.substr(1);
                tr2.className = x;
            }
        }
    }
}
var xtable = new XTable();


var jcLibrary = new JCLibrary();

var jcBlogs1 = new JCXBlogs('jcBlogs1', 'B');
var jcSuggs1 = new JCXBlogs('jcSuggs1', 'S');

// tabs
var jcCalendarTabs = new JCTabs2(3, 'zzz', '_calendar');
var jcLibraryTabs = new JCTabControl('libTabs','libTab');
var jcBulletin1Tabs = new JCTabControl(null, 'bulletin1Tab');
var blogTabs = new JCTabControl(null, 'blogTab');


