// @(#)_admin.js

// ~~~
// ~~~ Common Functions
// ~~~

function jcAdminWipOn(wipId)
{
    document.getElementById(wipId).innerHTML = '<image src="../images/wip.admin.gif"/>';
}

function jcAdminWipOff(wipId, infId, status)
{
    var wip = status.indexOf('[*info*]');
    var inf = '';
    if (wip > 0) {
        inf = status.substr(wip+8);
        wip = status.substr(0, wip);
    }
    else {
        wip = status;
    }
    document.getElementById(wipId).innerHTML = wip+'&nbsp;';
    document.getElementById(infId).innerHTML = '<table cellspacing=0 cellpadding=0 style="font-family: courier; font-size: 11px; color: green;">'+inf+'</table>';
}

function jcaWipOn(wipId, infId, info)
{
    document.getElementById(wipId).innerHTML = '<image style="padding-top: 2px;" src="../images/wip.admin.gif"/>&nbsp;<span style="padding-bottom: 5px;">'+info+'</span>';
    document.getElementById(infId).innerHTML = '&nbsp;';
}

function jcaWipOff(wipId, infId, wip, append)
{
    var info = '';
    var p = wip.indexOf('[*info*]');
    if (p >= 0) {
        info = wip.substring(p+8);
        wip = wip.substring(0,p);
    }
    document.getElementById(wipId).innerHTML = wip+'&nbsp;';
    var inf = document.getElementById(infId);
    if (append) {
        inf.innerHTML = inf.innerHTML + '<br>' +info;
    }
    else {
        inf.innerHTML = info+'&nbsp;';;
    }
}

function jcaWipError(wipId, infId, info)
{
    var p = info.indexOf('[*info*]');
    if (p >= 0) {
        info = info.substring(p+8);
    }
    document.getElementById(wipId).innerHTML = '&nbsp;';
    document.getElementById(infId).innerHTML = info+'&nbsp;';
}

function jcaValidateDate(inp)
{
    var d = inp.value.trim();
    if (d.length == 0) {
        return;
    }
    inp.value = d.isValidDate();
}

var rsa_e = "010001";
var rsa_n = "cf2441c5c6f66ec5fffaad62767571592aedce0b776bf2835f13dace6fd8d681f98aacabaf4c2f39fca7de3b4230f289f0d621f997fd5643258df9c6de1a8b3f278b654cabfe52de6be8b82b0d9d698304e79d486e3147da9936f5a2b81b6fffd7c74b8c0acd1e16de1299edc70374067f52b4e621b09d197d099ad3738e6d63";
    rsa_n = "C31B9A019E6EEF18E88ECAC4EB6B74CEC9194514D668C99A49C68931BBB82B75DD996C1A7BD83F568A1313403DF42AFDC567909DA38F687E9D34FF7CBD5A19946ACDB8D4A4C32B710556EE824204E0BD7677DF14355452DD55D258B347C10038DF021DD0043AB0C5FB3CE2794D088986FC7523D352949DF8773B2F110222FEF5";

var rsaKey1 = new RSAKey();
rsaKey1.setPublic(rsa_n, rsa_e);

function jcRandomString(len)
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz~@#$^*()_-{}|][!:;,./";
	var s = '';
	for (var i=0; i<len; i++) {
		var r = Math.floor(Math.random() * chars.length);
		s += chars.substring(r, r+1);
	}
	return s;
}

function jcAdminNonce()
{
    var jcSessionKey = jcRandomString(16);
    var cipher = rsaKey1.encrypt(jcSessionKey);
    cipher = hex2b64(cipher);
    cipher = jcEncodeURI(cipher);
    var ajax = new AjaxRequest().send('post', '_data3.php', 'data3='+cipher, null, false);
    var p = ajax.responseText.indexOf('|');
    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 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 JCAdminAjaxListener(handler, wipId)
{
    function processResponse(ajax, url, params, xid)
    {
        this.handler(ajax);
        if (wipId) {
            document.getElementById(wipId).innerHTML = '&nbps;';
        }
    }

    function processError(ajax, url, params)
    {
        if (wipId) {
            document.getElementById(wipId).innerHTML = '&nbps;';
        }
    }
    
    this.handler = handler;
    this.wipId = wipId;
    this.processResponse = processResponse;
    this.processError = processError;
}

// ~~~
// ~~~ Sunday Services
// ~~~

var jcAdminServicesPage = 0;
function JCAService()
{
    this.servicePage = 0;
    this.serviceList = new Array();
    

    this.show = function show(n)
    {
        if (n < 0 || n >= this.serviceList.length) {
            return;
        }
        var service = this.serviceList[n];
        var f = document.forms['jcaServiceForm'];
        f.reset();
        f.serviceDate.value = service.date;
        f.serviceLang.selectedIndex = service.lang == '1' ? 0 : 1;
        f.serviceTitle.value = service.title;
        f.serviceVerse.value = service.verse;
        f.serviceText.value = service.text;
    }
    
    this.pageUp = function()
    {
        --this.servicePage;
        this.refresh();
    }
    
    this.pageDown = function()
    {
        ++this.servicePage;
        this.refresh();
    }
    
    this.refresh = function()
    {
        var s = document.getElementById('jcaServiceListLang');
        var params = 'lang='+s.options[s.selectedIndex].value+
                     '&page='+this.servicePage;
    
        var ajax = new AjaxRequest().send('get', '_services.php', params, null, false);
        if (ajax.status == 200) {
            try {
                this.serviceList = new XMLObject(ajax, 'service').data;
            }
            catch (ex) {
                this.processError(ajax, '_services.php', params, ex);
                return;
            }
            if (ajax.responseText.indexOf('<?xml ')<0) {
                this.processError(ajax, '_services.php', params);
                return;
            }
            var html = '<table cellspacing=2 cellpadding=2 width=100% class="admrowtbl">\n';
            html += '<tr><th style="width: 350px">Date</th><th>Bulletin</th><th>Sermon</th></tr>\n';
            for (var ii=1; ii<this.serviceList.length; ++ii) {
                var service = this.serviceList[ii];
                html += '<tr><td><span class="xlink" onclick="jcaService.show('+ii+')">'+service.date+' - '+service.title+'</span></td><td><nobr>';
                var pipe = '';
                if (service.doc.length > 0) {
                    html += '<a href="../sundays/'+service.doc+'">doc</a>';
                    pipe = ' ';
                }
                if (service.pdf.length > 0) {
                    html += pipe+'<a href="../sundays/'+service.pdf+'">pdf</a>';
                    pipe = ' ';
                }
                pipe = '';
                html += '</nobr></td><td><nobr>';
                if (service.mp3.length > 0) {
                    html += pipe+'<a href="../sundays/'+service.mp3+'">mp3</a>';
                    pipe = ' ';
                }
                if (service.wav.length > 0) {
                    html += pipe+'<a href="../sundays/'+service.wav+'">wav</a>';
                    pipe = ' ';
                }
                html += '</nobr></td></tr>';
            }
            html += '</table>';
            document.getElementById('jcaServiceList').innerHTML = html;
            jcaWipOff('jcaServiceListWip', 'jcaServiceInfo', '');
        }
        else {
            this.processError(ajax, '_services.php', params);
        }
    }
    
    this.save = function()
    {
        var f = document.forms['jcaServiceForm'];
        f.op.value = 'save';
        f.title.value = encodeURI(f.serviceTitle.value);
        f.verse.value = encodeURI(f.serviceVerse.value);
        f.text.value = encodeURI(f.serviceText.value);

        var asyncForm = new AsyncForm('service', 'jcaServiceForm', null, 'jcaService.uploadComplete(this)');
        asyncForm.submit();
        jcaWipOn('jcaServiceWip', 'jcaServiceInfo','Processing...');
    }
    
    this.remove = function()
    {
        var f = document.forms['jcaServiceForm'];
        var date = f.serviceDate.value;
        var lang = f.serviceLang.value;
        var title = f.serviceTitle.value;
        var lang2 = (lang=='1') ? 'English' : 'Chinese';
        
        if (confirm('Please confirm to delete this record:\n('+lang2+') '+date+' - '+title)) {
            var params = 'op=delete&serviceDate='+date+'&serviceLang='+lang;
	    var ajax = new AjaxRequest().send('post', '_services.php', params, null, false);
            if (ajax.status == 200) {
                jcaWipOff('jcaServiceWip', 'jcaServiceInfo', ajax.responseText);
                this.refresh();
                var f = document.forms['jcaServiceForm'];
                f.serviceFile1.value = '';
                f.serviceFile2.value = '';
            }
            else {
                var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')<br>'+ajax.responseText;
                jcaWipError('jcaServiceWip', 'jcaServiceInfo', err);
            }
        }
        
    }
    
    this.uploadComplete = function(a)
    {
        jcaWipOff('jcaServiceWip', 'jcaServiceInfo', a.responseText);
        this.refresh();
        var f = document.forms['jcaServiceForm'];
        f.serviceFile1.value = '';
        f.serviceFile2.value = '';
        jcaWipOff('jcaServiceWip', 'jcaServiceInfo', a.responseText);
   }
    
    this.processResponse = function(ajax)
    {
        jcaWipOff('jcaServiceListWip', 'jcaServiceInfo', '');
    }

    this.processError = function(ajax, url, params, ex)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')<br>'+
                  ajax.responseText;
        jcaWipError('jcaServiceListWip', 'jcaServiceInfo', err);
    }
}
var jcaService = new JCAService();

function JCAUpload()
{
    this.upload = function()
    {
        var f = document.forms.jcaUploadForm;
        f.op.value = 'upload';

        var asyncForm = new AsyncForm('editor', 'jcaUploadForm', null, 'jcaUpload.uploadComplete(this)');
        asyncForm.submit();
        jcaWipOn('jcaUploadWip', 'jcaUploadInfo','Uploading...');
    }
    
    this.uploadComplete = function(a)
    {
        jcaWipOff('jcaUploadWip', 'jcaUploadInfo', a.responseText);
        var f = document.forms.jcaUploadForm;
        f.reset();
    }
}
var jcaUpload = new JCAUpload();

function JCEvent()
{
    this.id = '';
    this.date = '';
    this.date2 = '';
    this.time = '';
    this.sequence = 1;
    this.enDesc = '';
    this.enUrl = '';
    this.enImage = '';
    this.chDesc = '';
    this.chUrl = '';
    this.chImage = '';
    this.status = '';

    this.events = new Array();
    
    this.show = function()
    {
        var f = document.forms['jcaEventForm'];
        f.eid.value = this.id;
        f.edate.value = this.date;
        f.edate2.value = this.date2;
        f.etime.value = this.time;
        f.eseq.value = this.sequence;
        f.edesc1.value = this.enDesc;
        f.eurl1.value = this.enUrl;
        f.eimage1.value = this.enImage;
        f.edesc2.value = this.chDesc;
        f.eurl2.value = this.chUrl;
        f.eimage2.value = this.chImage;
        f.estatus.selectedIndex = this.status;
    }
    
    this.newEvent = function newEvent()
    {
        var f = document.forms['jcaEventForm'];
        f.eid.value = '';
        f.edate.value = '';
        f.edate2.value = '';
        f.etime.value = '';
        f.eseq.value = '1';
        f.edesc1.value = '';
        f.eurl1.value = '';
        f.eimage1.value = '';
        f.edesc2.value = '';
        f.eurl2.value = '';
        f.eimage2.value = '';
        f.estatus.selectedIndex = 0;
    }

    this.saveEvent = function saveEvent(op)
    {
        var f = document.forms['jcaEventForm'];
        f.edate.value = f.edate.value.trim();
        f.edate2.value = f.edate2.value.trim();
        f.etime.value = f.etime.value.trim();
        f.eseq.value = f.eseq.value.trim();
        f.edesc1.value = f.edesc1.value.trim();
        f.eurl1.value = f.eurl1.value.trim();
        f.eimage1.value = f.eimage1.value.trim();
        f.edesc2.value = f.edesc2.value.trim();
        f.eurl2.value = f.eurl2.value.trim();
        f.eimage2.value = f.eimage2.value.trim();
        if ((f.eid.value=='' || f.eid.value == '0') && op=='delete') {
            alert('You cannot delete a new event.');
            return;
        }
        if (f.edate.value == '' || f.edesc1.value=='') {
            alert('Please enter event date and description.');
            return;
        }
        if (op=='delete') {
            var cnf = confirm('You are about to delete this event from the server:\n\n'+f.edate.value+': '+f.edesc1.value+'\n\nPlease confirm.');
            if (!cnf) {
                return;
            }
            f.x.value = 'delete';
        }
        else if (f.eid.value=='' || f.eid.value=='0') {
            f.x.value = 'insert';
        }
        else {
            f.x.value = 'update';
        }
        var data = _compose(f);
        var ajax = new AjaxRequest().send('get', '_events.php', data, null, false);
        this.getEvents();
        this.newEvent();
        jcaWipOff('jcaEventWip', 'jcaEventInfo', ajax.responseText);
    }
    
    this.getEvents = function (x)
    {
        var form = document.getElementById('jcaEventForm');
        var date1 = document.getElementById('eventsQueryDate').value;
        new AjaxRequest().send('get', '_events.php', 'date='+date1, this, true);
        jcaWipOn('jcaEventListWip', 'jcaEventInfo', '&nbsp;');
    }

    this._events3 = function (x,t)
    {
      var z = document.getElementById('jcaEventList');
      var html = '';
        if (x == null || x.documentElement == null) {
            if (typeof(DOMParser) != 'undefined') {
              x = (new DOMParser()).parseFromString(t, "text/xml");
            }
        }
      x = x.documentElement;
      var nl = x.childNodes;
      var jj = 0;
    
      html += '<table width=100% class="admrowtbl"><tr><th width=5%>Date</th><th>Description</th></tr>';
      for (var ii=1; ii<nl.length+1; ++ii) {
        var item = nl.item(ii-1);
        if (item.nodeName != 'event') {
          continue;
        }
        ++jj;
        var attrs = item.attributes;
    
        var ev = new JCEvent();
        ev.id = attrs.getNamedItem('id').value;
        ev.date = attrs.getNamedItem('date').value;
        ev.date2 = attrs.getNamedItem('date2').value;
        ev.time = attrs.getNamedItem('time').value;
        ev.sequence = attrs.getNamedItem('seq').value;
        ev.status = attrs.getNamedItem('status').value;
    
        var style = (ev.status == '0') ? " style='color: #aaaaff'" : "";
        var style2 = (ev.status == '0') ? " style='color: #aaaaaa'" : "";
        if (ev.status == '2') {
            style2=" style='color: brown'";
        }
    
        var dx = '<td nowrap '+style2+'>'+ev.date;
        if (ev.date2 != null && ev.date2 != '') {
          dx += ' - '+ev.date2;
        }
        var dy = '&nbsp;';
        if (ev.time != null && ev.time != '') {
          dy += '<span '+style2+'>&nbsp;&nbsp;&nbsp;'+ev.time+'</span>';
        }
        dx += '</td>';
    
        var english = item.getElementsByTagName('english').item(0);
        var chinese = item.getElementsByTagName('chinese').item(0);
    
        ev.enDesc = english.attributes.getNamedItem('desc').value;
        ev.chDesc = chinese.attributes.getNamedItem('desc').value;
    
        ev.enUrl = english.attributes.getNamedItem('url').value;
        ev.chUrl = chinese.attributes.getNamedItem('url').value;
    
        ev.enImage = english.attributes.getNamedItem('image').value;
        ev.chImage = chinese.attributes.getNamedItem('image').value;
    
        html += '<tr style="cursor:pointer;">';
        html += dx;
        html += '<td><a class="xlink" '+style+' onclick="jcEvent.preview('+ii+')">'+ev.enDesc+'</a></td>';
        html += '</tr>';
        html += '<tr class="admrowdot">';
        html += '<td nowrap>'+dy+'</td>';
        html += '<td><a class="xlink" '+style+' onclick="jcEvent.preview('+ii+')">'+ev.chDesc+'</a></td>';
        html += '</tr>';
    
        this.events[ii] = ev;
      }
      html += '<tr><td>&nbsp;</td><td>&nbsp;</td></tr>';
      html += '</table>';
      z.innerHTML = html;
    }

    this.processResponse = function(ajax)
    {
        this._events3(ajax.responseXML, ajax.responseText);
        jcaWipOff('jcaEventListWip', 'jcaEventInfo', '&nbsp;', true);
    }
    
    this.processError = function (ajax, url, params)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        jcaWipError('jcaEventListWip', 'jcaEventInfo', err);
    }
    
    this.preview = function(id)
    {
        this.events[id].show();
    }
}

var jcEvent = new JCEvent();


// ~~~ Admin: Users ~~~

function JCUser()
{
    this.uid = '';
    this.name = '';
    this.pass = '';
    this.auth = '';

    this.show = function ()
    {
        var f = document.forms.userForm;
        f.userId.value   = this.uid;
        f.userName.value = this.name;
        f.userPass.value = '';
        f.userPass2.value = '';
        f.userAuth.value = this.auth;
        f.userStatus.selectedIndex = (this.status=='A') ? 0 : 1;
    }

    this.clear = function ()
    {
        var f = document.forms.userForm;
        f.userId.value   = '';
        f.userName.value = '';
        f.userPass.value = '';
        f.userPass2.value = '';
        f.userAuth.value = '';
        f.userStatus.selectedIndex = 1;
    }

    this.save = function ()
    {
        var e = '';
        var f = document.forms.userForm;
        var uid = f.userId.value.trim();
        if (uid.length < 3 || uid.length > 32) {
            e += "User ID must be between 3 and 32 characters.\n";
        }
        var name = f.userName.value;
        if (name.length < 3 || name.length > 64) {
            e += "User Name must be between 3 and 64 characters.\n";
        }
        var pass = f.userPass.value;
        if (pass.length > 0 && (pass.length < 3 || pass.length > 32)) {
            e += "Password must be between 3 and 32 characters.\n";
        }
        var pass2 = f.userPass2.value;
        if (pass != pass2) {
            e += "Passwords do not match each other.\n";
        }
        if (e.length > 0) {
            alert(e);
            return;
        }
        var auth = f.userAuth.value.trim();
        if (auth == '') {
            auth = 0;
        }

        var x = jcAdminNonce();
        var data3 = x[0];
        var nonce = x[1];
        var base64 = new Base64();
        f.nonce.value = base64.encode(TEAEncrypt(nonce+'       ', data3));
        f.data1.value = base64.encode(TEAEncrypt(uid+'       ', data3));
        f.data2.value = base64.encode(TEAEncrypt(name+'       ', data3));
        f.data3.value = (pass.length==0) ? '' : base64.encode(TEAEncrypt(pass+'       ', data3));
        f.data4.value = base64.encode(TEAEncrypt(auth+'       ', data3));

        var uid = f.userId.value;
        var uname = f.userName.value;
        f.userId.value = '';
        f.userName.value = '';
        f.userPass.value = '';
        //f.userAuth.value = '';
        f.op.value = 'save';

        var params = _compose(f);
        new AjaxRequest().send('post', '_users.php', params, this, true);

        f.userId.value = uid;
        f.userName.value = uname;
        
        jcaWipOn('jcaUserWip', 'jcaUserInfo', '');

    }
    
    this.select = function(ii)
    {
        var o = this.data[ii];
        this.uid = o.id;
        this.pass = '';
        this.name = o.name;
        this.auth = o.auth;
        this.status = o.status;
        this.show();
    }

    this.remove = function ()
    {
        var f = document.forms.userForm;
        var uid = f.userId.value.trim();
        if (uid.length < 3 || uid.length > 32) {
            alert("Please enter a valid User ID.");
            return;
        }
        if (!confirm("Please confirm to delete user:\n"+uid)) {
            return;
        }

        var x = jcAdminNonce();
        var data3 = x[0];
        var nonce = x[1];

        var base64 = new Base64();
        nonce = base64.encode(TEAEncrypt(nonce+'       ', data3));
        nonce = jcEncodeURI(nonce);
        uid = base64.encode(TEAEncrypt(uid+'       ', data3));
        uid = jcEncodeURI(uid);
        
        var uid2 = f.userId.value;
        var uname = f.userName.value;
        f.userId.value = '';
        f.userName.value = '';
        f.userPass.value = '';
        
        new AjaxRequest().send('post', '_users.php', 'op=delete&data1='+uid+'&nonce='+nonce, this, true);

        f.userId.value = uid2;
        f.userName.value = uname;

        jcaWipOn('jcaUserWip', 'jcaUserInfo', '');
        
    }

    this.processResponse = function (ajax)
    {
        jcaWipOff('jcaUserWip', 'jcaUserInfo', ajax.responseText);
        this.getUsers();
    }

    this.processError = function (ajax, url, params)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        jcaWipOff('jcaUserWip', 'jcaUserInfo', err);
    }

    this.getUsers = function()
    {
        var ajax = new AjaxRequest().send('get', '_users.php', 'op=get', null, false);
        this.data = new XMLObject(ajax, 'user').data;
        var disp = this.data[0];
        var html = '<table cellspacing=2 cellpadding=0 class="admrowtbl" width=100%>\n';
        html += '<tr>';
        for (x in disp) {
            html += '<th>'+disp[x]+'</th>';
        }
        html += '</tr>';
        for (var ii=1; ii<this.data.length; ++ii) {
            var o = this.data[ii];
            html += '<tr onclick="jcUser.select('+ii+')" style="cursor:pointer;">';
            for (x in disp) {
                html += '<td>'+o[x]+'</td>';
            }
            html += '</tr>\n';
        }
        html += '</table>';
        document.getElementById('jcPreviewUsers').innerHTML = html;
    }
    
    this.saveProfile = function()
    {
        var e = '';
        var f = document.forms.profileForm;
        var uid = f.userId.value.trim();
        if (uid.length < 3 || uid.length > 32) {
            e += "User ID must be between 3 and 32 characters.\n";
        }
        var name = f.userName.value;
        if (name.length < 3 || name.length > 64) {
            e += "User Name must be between 3 and 64 characters.\n";
        }
        var pass = f.userPass.value;
        if (pass.length > 0 && (pass.length < 3 || pass.length > 32)) {
            e += "Password must be between 3 and 32 characters.\n";
        }
        var pass2 = f.userPass2.value;
        if (pass != pass2) {
            e += "Passwords do not match each other.\n";
        }
        if (e.length > 0) {
            alert(e);
            return;
        }
        var auth = f.userAuth.value.trim();
        if (auth == '') {
            auth = 0;
        }

        var x = jcAdminNonce();
        var data3 = x[0];
        var nonce = x[1];
        var base64 = new Base64();
        f.nonce.value = base64.encode(TEAEncrypt(nonce+'       ', data3));
        f.data1.value = base64.encode(TEAEncrypt(uid+'       ', data3));
        f.data2.value = base64.encode(TEAEncrypt(name+'       ', data3));
        f.data3.value = (pass.length==0) ? '' : base64.encode(TEAEncrypt(pass+'       ', data3));
        f.data4.value = base64.encode(TEAEncrypt(auth+'       ', data3));

        var uid = f.userId.value;
        var uname = f.userName.value;
        f.userId.value = '';
        f.userName.value = '';
        f.userPass.value = '';
        //f.userAuth.value = '';
        f.op.value = 'save';

        var params = _compose(f);
        new AjaxRequest().send('post', '_users.php', params, this, true);

        f.userId.value = uid;
        f.userName.value = uname;
        
        jcaWipOn('jcaUserWip', 'jcaUserInfo', '');
    }
}

var jcUser = new JCUser();

function JCAEditor()
{
    this.data = null;
    this.selectedData = -1;
    this.edited = false;
    
    this.getForm = function()
    {
        return document.forms.jcaEditorForm;
    }
    
    this.ls = function()
    {
        var ds = document.getElementById('jcaEditorDirSelect');
        var dir = ds.options[ds.selectedIndex].value;
        
        var ajax = new AjaxRequest().send('get', '_editor.php', 'op=ls&dir='+dir, null, false);
        this.data = new XMLObject(ajax, 'file').data;
        var disp = this.data[0];
        var html = '<table cellspacing=0 cellpadding=1 width=100%>\n';
        html += '<tr>';
        //for (x in disp) {
        //    html += '<td>'+disp[x]+'</td>';
        //}
        html += '</tr>';
        for (var ii=1; ii<this.data.length; ++ii) {
            var o = this.data[ii];
            html += '<tr onclick="jcaEditor.select('+ii+')" style="cursor:pointer;">';
                html += '<td>'+o['name']+'</td>';
            html += '</tr>\n';
        }
        html += '</table>';
        document.getElementById('jcaEditorFileList').innerHTML = html;
    }
    
    this.lsImages = function()
    {
        var ds = document.getElementById('jcaEditorDirSelect');
        var dir = ds.options[ds.selectedIndex].value;
        
        var ajax = new AjaxRequest().send('get', '_editor.php', 'op=lsImages&dir='+dir, null, false);
        this.imageData = new XMLObject(ajax, 'image').data;
        var disp = this.imageData[0];
        var html = '<table cellspacing=0 cellpadding=1 class="admrowtbl" width="1">\n';
        for (var ii=1; ii<this.imageData.length; ++ii) {
            var o = this.imageData[ii];
            html += '<tr>';
            html += '<td><img onclick="jcaEditor.selectImage('+ii+')" class="admin-img" src="../images/thumbnail.php?img='+o.dir+'/'+o.name+'" alt="'+o.name+'" style="cursor:pointer;"/></td>';
            if (++ii<this.imageData.length) {
                o = this.imageData[ii];
                html += '<td><img onclick="jcaEditor.selectImage('+ii+')" class="admin-img" src="../images/thumbnail.php?img='+o.dir+'/'+o.name+'" alt="'+o.name+'" style="cursor:pointer"/></td>';
            }
            else {
                html += "<td>&nbsp;</td>";
            }
            html += '</tr>\n';
        }
        html += '</table>';
        document.getElementById('jcaEditorImageList').innerHTML = html;
    }
    
    this.selectImage = function(ii)
    {
        //var h = location.href;
        //var q = h.indexOf('?');
        //if (q > 0) {
        //    
        //}
        var o = this.imageData[ii];
        editor1.insertImage(o.dir+"/"+o.name);
    }
    
    this.select = function(ii)
    {
        var o = this.data[ii];
        if (this.edited || (this.selectedData>=0 && this.data[this.selectedData].changed)) {
            if (!confirm('You are editing a document.\nYou will lose any changes made.\nContinue?')) {
                return;
            }
        }
        var dir = this.data[ii]['dir'];
        var file = this.data[ii]['name'];
        var ajax = new AjaxRequest().send('get', '_editor.php', 'op=cat&dir='+dir+'&file='+file, null, false);
        var frame = document.getElementById('rtfPanel1');
        var html = ajax.responseText;
        var t1 = html.indexOf('<!-- >>>title>>> -->');
        var t2 = html.indexOf('<!-- <<<title<<< -->');
        var title = html.substring(t1+20, t2).trim();
        var d1 = html.indexOf('>>>date>>>');
        var d2 = html.indexOf('<<<date<<<');
        var date = html.substring(d1+10,d2).trim();
        var c1 = html.indexOf('>>>chinese>>>');
        var c2 = html.indexOf('<<<chinese<<<');
        var chi = (c1>0 && c2>0) ? html.substring(c1+13,c2).trim() : '';
        var m1 = html.indexOf('<!-- <<<box1<<< -->');
        var m2 = html.indexOf('<!-- >>>box2>>> -->', m1);
        
        var core = html.substring(m1+19, m2);
        //frame.contentWindow.document.body.innerHTML = core;
        
        var f = this.getForm();
        f.editFile.value = file;
        f.editTitle.value = title;
        f.editDate.value = date;
        
        if (this.getDesignMode()) {
            this.setDesignMode(false);
        }
        document.getElementById('jcaEditorTitle').innerHTML = title;
        this.setHtml(core);
        
        o.changed = false;
        this.selectedData = ii;
        this.edited = false;
    }
    
    this.changeTitle = function(inp)
    {
        document.getElementById('jcaEditorTitle').innerHTML = inp.value;
    }
    
    this.save = function(mv)
    {
        var f = this.getForm();
        var file = f.editFile.value.trim();
        var date = f.editDate.value;
        if (file.length <=0 || date.length < 10) {
            alert('File, Date are required!');
            return;
        }
        var title = f.editTitle.value;
        
        if (mv == null) {
            mv = '';
        }
        
        var frame = document.getElementById('rtfPanel1');
        var html = '\
      <!-- >>>file>>>'+file+' -->\n\
      <!-- >>>date>>>'+date+'<<<date<<< -->\n\
      <!-- >>>edit>>>'+(new Date())+'<<<edit<<< -->\n\
      <!-- >>>user>>>'+jcaUserId+'<<<user<<< -->\n\
      <!-- >>>chinese>>>'+''+'<<<chinese<<< -->\n\
      <div style="margin: 0px; padding: 0px; width: 100%"/>\n\
      <!-- >>>box1>>> -->\n\
      <table width=100% cellspacing=0 cellpadding=0 class="boxgrp">\n\
        <tr>\n\
          <th width="100%">\n\
            <!-- >>>title>>> -->'+title+'<!-- <<<title<<< -->\n\
          </th>\n\
        </tr>\n\
        <tr>\n\
          <td>\n\
      <!-- <<<box1<<< -->';
       
       html += frame.contentWindow.document.body.innerHTML;
       
       html += '<!-- >>>box2>>> -->\n\
          </td>\n\
        </tr>\n\
      </table>\n\
      <!-- <<<box2<<< -->\n\
      </div>\n\
      <!-- <<<file<<<'+file+' -->\n';
      
        f.op.value = 'save';
        f.mv.value = mv;
        f.editHtml.value = jcEncodeURI(html);
        var asyncForm = new AsyncForm('editor', 'jcaEditorForm', null, 'jcaEditor.saveComplete(this)');
        asyncForm.submit();
        jcaWipOn('jcaEditorWip', 'jcaEditorInfo','Saving...');
    }
    
    this.moveToEvents = function()
    {
        var f = this.getForm();
        var file = f.editFile.value.trim();
        var title = f.editTitle.value.trim();
        var date = f.editDate.value.trim();
        if (file.length <=0 || title.length<=0 || date.length <=0) {
            alert('File, Title, and Date must be provided!');
            return;
        }
        this.save('mv');
        this.ls();
        this.lsImages();
        this.clear(true);
    }
    
    this.saveComplete = function(a)
    {
        jcaWipOff('jcaEditorWip', 'jcaEditorInfo', a.responseText);
        this.ls();
    }
    
    this.clear = function(force)
    {
        if (!force && !confirm('Are you sure to clear editing data?')) {
            return;
        }
        var frame = document.getElementById('rtfPanel1');
        frame.contentWindow.document.body.innerHTML = '';
        
        var f = this.getForm();
        f.editTitle.value = '';
        f.editFile.value = '';
        f.editDate.value = '';
        f.editDate2.value = '';
        
        document.getElementById('jcaEditorTitle').innerHTML = '[Title]';
        
        document.getElementById('jcaEditorWip').innerHTML = '&nbsp;';
        document.getElementById('jcaEditorInfo').innerHTML = '&nbsp;';
        document.getElementById('jcaEditorMode').innerHTML = '&nbsp;';
        
        this.selectedData = -1;
        this.edited = false;
    }
    
    this.setDesignMode = function(flag)
    {
        if (this.getDesignMode() == flag) {
            return;
        }
        //var editButton = document.forms.jcaEditorForm.editEditButton;
        var editButton = document.getElementById('jcaEditorEdit');
        if (flag) {
            editButton.value = "Preview";
        }
        else {
            editButton.value = "Edit";
        }
        var html = this.getHtml();
        editor1.setDesignMode(flag);
        this.setHtml(html);
    }
    
    this.edit = function(inp)
    {
        var mode = document.getElementById('jcaEditorMode');
        var flag = false;
        if (inp.value == 'Edit') {
            inp.value = 'Preview';
            flag = true;
            if (this.selectedData >= 0) {
                this.data[this.selectedData].changed = true;
            }
            this.edited = true;
            mode.innerHTML = '<span style="text-decoration: blink; color: red; font-size:12px;">edit</span>&nbsp;';
        }
        else {
            inp.value = 'Edit';
            flag = flag;
            mode.innerHTML = '<span style="font-size:12px;">preview</span>&nbsp;';
        }
        
        var html = this.getHtml();
        editor1.setDesignMode(flag);
        this.setHtml(html);
    }
    
    this.getHtml = function()
    {
        var frame = document.getElementById('rtfPanel1');
        return frame.contentWindow.document.body.innerHTML;
    }
    

    this.setHtml = function(html)
    {
        this.html = html;
        setTimeout('jcaEditor.setHtml2()', 100);
    }
    
    this.setHtml2 = function(html)
    {
        if (html == null) {
            html = this.html;
        }
        var frame = document.getElementById('rtfPanel1');
        var doc = frame.contentWindow.document;
        if (doc.body) doc.body.innerHTML = html;
    }
    
    this.getDesignMode = function()
    {
        return editor1.getDesignMode();
    }
    
    this.changeDir = function(d)
    {
        var f =  document.forms.jcaEditorForm;
        var dir = d.options[d.selectedIndex].text;
        if (dir == 'scratch') {
            document.getElementById('jcaEditorMove').disabled = false;
        }
        else {
            document.getElementById('jcaEditorMove').disabled = true;
        }
        f.editDir.value = dir;
        this.clear(true);
        this.ls();
        this.lsImages();
    }
    
    this.upload = function()
    {
        var ds = document.getElementById('jcaEditorDirSelect');
        var dir = ds.options[ds.selectedIndex].value;

        var f = document.forms.jcaEditorUpload;
        f.op.value = 'upload';
        f.dir1.value = dir;

        var asyncForm = new AsyncForm('editor', 'jcaEditorUpload', null, 'jcaEditor.uploadComplete(this)');
        asyncForm.submit();
        jcaWipOn('jcaEditorUploadWip', 'jcaEditorInfo','Uploading...');
    }
    
    this.uploadComplete = function(a)
    {
        jcaWipOff('jcaEditorUploadWip', 'jcaEditorInfo', a.responseText);
        var f = document.forms.jcaEditorUpload;
        f.reset();
    }
}
var jcaEditor = new JCAEditor();


// ~~~ JCA Library ~~~

var jcaActivity = new Array();
jcaActivity['b'] = 'Borrow';
jcaActivity['i'] = 'Inventory';
jcaActivity['p'] = 'Purchase';
jcaActivity['d'] = 'Donate';

function JCALibrary()
{
    this.items = new Array();
    
    this.showItem = function(n)
    {
        var f = document.forms['jcaLibraryForm'];

        var item = this.items[n];

        f.libid.value     = item.libid;
        f.isbn.value      = item.isbn;
        f.title.value     = item.title;
        f.author.value    = item.author;
        f.publisher.value = item.publisher;
        f.year.value      = item.year;
        f.media.value     = item.media;
        f.lang.value      = item.lang;
        f.summary.value   = item.summary;
        f.libloc.value    = item.libloc;
        f.libcnt.value    = item.libcnt;
        f.libout.value    = item.libout;
        f.libimg.value    = item.libimg;
        f.status.selectedIndex = this.status;
        document.getElementById('jcaLibraryItemInfo').innerHTML =
          item.modified+' '+item.moduser;
        
        var html = '<table class="admrowtbl" cellspacing=0 cellpadding=2 style="">';
        for (var ii=0; ii<3; ++ii) {
            html += '<tr>'+
            '<td style="width:70;">&nbsp;</td>'+
            '<td style="width:75;">&nbsp;</td>'+
            '<td style="width:100;">&nbsp;</td>'+
            '<td style="width:135;">&nbsp;</td>'+
            '<td style="">&nbsp;</td></tr>';
        }
        html += '</table>';
        document.getElementById('jcaLibraryActivityList').innerHTML = html;
        
        if (item.libimg.length > 0) {
            document.getElementById('jcaLibimg2').innerHTML = '<image src="../library/libimg.php?img=library/images/'+item.libimg+'"/>';
        }
        else {
            document.getElementById('jcaLibimg2').innerHTML = '<image src="../library/libimg.php?img=library/images/'+item.libimg+'"/>';
        }
        
        this.getActivities();
    }
    
    this.newItem = function()
    {
        var f = document.forms['jcaLibraryForm'];
        f.libid.value     = 0;
        f.isbn.value      = '';
        f.title.value     = '';
        f.author.value    = '';
        f.publisher.value = '';
        f.year.value      = '';
        f.media.selectedIndex = 0;
        f.lang.selectedIndex = 0;
        f.summary.value   = '';
        f.libloc.value    = '';
        f.libcnt.value    = 0;
        f.libout.value    = 0;
        f.libimg.value    = '';
        f.status.selectedIndex = 0;
        document.getElementById('jcaLibraryItemInfo').innerHTML = '';
        
        var html = '<table class="admrowtbl" cellspacing=0 cellpadding=2 style="">';
        for (var ii=0; ii<3; ++ii) {
            html += '<tr>'+
            '<td style="width:70;">&nbsp;</td>'+
            '<td style="width:75;">&nbsp;</td>'+
            '<td style="width:100;">&nbsp;</td>'+
            '<td style="width:135;">&nbsp;</td>'+
            '<td style="">&nbsp;</td></tr>';
        }
        html += '</table>';
        document.getElementById('jcaLibraryActivityList').innerHTML = html;
        
        var f = document.forms['jcaLibOpsForm'];
        f.opdate.value = '';
        f.opcode.selectedIndex = 0;
        f.opuser.value = '';
        f.opcomment.value = '';

    }
    
    this.deleteItem = function()
    {
        var f = document.forms['jcaLibraryForm'];
        if ((f.libid.value=='' || f.libid.value <= 0)) {
            alert('You cannot delete a new event.');
            return;
        }
        var cnf = confirm('You are about to delete this item from library:\n'+
          '\nISBN: '+f.isbn.value+
          '\nTitle: '+f.title.value+
          '\nAuthor: '+f.author.value+
          '\nPublisher: '+f.publisher.value+'\n'+
          '\nPlease confirm.');
        if (!cnf) {
            return;
        }
        f.x.value = 'delete';
        var ajax = new AjaxRequest().send('get', '_library.php', 'x=delete&libid='+f.libid.value, null, false);
        this.getItems();
        this.newItem();
        jcaWipOff('jcaLibraryWip', 'jcaLibraryInfo', ajax.responseText);
    }
    
    this.saveItem = function(op)
    {
        var f = document.forms['jcaLibraryForm'];
        f.libid.value     = f.libid.value.trim();
        f.isbn.value      = f.isbn.value.trim();
        f.title.value     = f.title.value.trim();
        f.author.value    = f.author.value.trim();
        f.publisher.value = f.publisher.value.trim();
        f.year.value      = f.year.value.trim();
        f.media.value     = f.media.value.trim();
        f.lang.value      = f.lang.value.trim();
        f.summary.value   = f.summary.value.trim();
        f.libloc.value    = f.libloc.value.trim();
        f.libcnt.value    = f.libcnt.value.trim();
        f.libimg.value    = f.libimg.value.trim();

        f.title2.value = encodeURI(f.title2.value);
        f.author2.value = encodeURI(f.author2.value);
        f.publisher2.value = encodeURI(f.publisher2.value);
        f.summary2.value = encodeURI(f.author2.value);

        if (f.title.value == '' || f.title.value=='') {
            alert('Please enter a title.');
            return;
        }
        else if (f.libid.value=='' || f.libid.value=='0') {
            f.x.value = 'insert';
        }
        else {
            f.x.value = 'update';
        }
        var data = _compose(f);
        var ajax = new AjaxRequest().send('get', '_library.php', data, null, false);
        this.getItems();
        if (f.libid.value <= 0) {
            this.newItem();
        }
        jcaWipOff('jcaLibraryWip', 'jcaLibraryInfo', ajax.responseText);
    }
    
    this.getItems = function (x)
    {
        var f = document.forms['jcaLibraryForm'];
        f.x.value = 'get';
        var ajax = new AjaxRequest().send('get', '_library.php', '', this, true);
        jcaWipOn('jcaLibraryItemsWip', 'jcaLibraryInfo', '&nbsp;', true);
    }

    this.getItems2 = function (x)
    {
        var f = document.forms['jcaLibraryForm'];
        f.x.value = 'get';
        var data = _compose(f);
        var ajax = new AjaxRequest().send('get', '_library.php', data, this, true);
        jcaWipOn('jcaLibraryItemsWip', 'jcaLibraryInfo', '&nbsp;');
    }

    this._items = function (ajax, x, t)
    {
        this.items = new XMLObject(ajax, 'item').data;
        var html = '<table cellspacing=2 cellpadding=0 class="admrowtbl" width=100%">\n';
        html += '<tr><th>Title</th><th>Author</th><th>Location</th><th width=10>#</th><th width=10>Out</th></tr>\n';
        for (var ii=1; ii<this.items.length; ++ii) {
            var item = this.items[ii];
            var r = 1+ii%2;
            html += '<tr class="admrowdot" style="cursor:pointer;" onclick="jcaLibrary.showItem('+ii+')">'+
                    '<td><span class="xlink" onclick="jcaLibrary.showItem('+ii+')">'+item.title+'</span>&nbsp;</td>'+
                    '<td>'+item.author+'&nbsp;</td>'+
                    '<td>'+item.libloc+'</td>'+
                    '<td>'+(item.libcnt)+'</td>'+
                    '<td>'+(item.libout)+'</td>'+
                    '</tr>';
        }
        for (var ii=this.items.length; ii<20; ++ii) {
            html += '<tr><td colspan=5>&nbsp;</td></tr>';
        }
        html += '</table>';
        document.getElementById('jcaLibraryItems').innerHTML = html;
        jcaWipOff('jcaLibraryItemsWip', 'jcaLibraryInfo', '&nbsp;', true);
    }

    this.processResponse = function(ajax)
    {
        if (ajax.responseText == 'Session timeout') {
            document.location.reload();
            return;
        }
        this._items(ajax, ajax.responseXML, ajax.responseText);
        jcaWipOff('jcaLibraryItemsWip', 'jcaLibraryInfo', '&nbsp;', true);
    }
    
    this.processError = function (ajax, url, params)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        jcaWipError('jcaLibraryItemsWip', 'jcaLibraryInfo', err, true);
    }
    
    this.getActivities = function()
    {
        var f = document.forms['jcaLibraryForm'];
        var libid = f.libid.value;
        if (f.libid.value <= 0) {
            return;
        }
        
        var ajax = new AjaxRequest().send('get', '_library.php', 'x=getActivities&libid='+libid, null, false);
        this.activities = new XMLObject(ajax, 'activity').data;
        
        var html = '<table class="admrowtbl" cellspacing=0 cellpadding=2 style="">';
        for (var ii=1; ii<this.activities.length; ++ii) {
            var a = this.activities[ii];
            var r = '';
            if (a.opcode=='b' && a.opdate2=='') {
                r = "<span class='xlink' onclick='jcaLibrary.returnActivity("+ii+")'>&gt;return</return>";
            }
            else {
                r = a.opdate2.substring(0,10);
            }
            html += '<tr>'+
            '<td style="width:70;">'+a.opdate.substring(0,10)+'</td>'+
            '<td style="width:75;">'+jcaActivity[a.opcode]+'</td>'+
            '<td style="width:100;">'+a.opuid+'</td>'+
            '<td style="width:135;">'+a.comment+'</td>'+
            '<td style="">'+r+'</td></tr>';
        }
        html += '</table>';
        document.getElementById('jcaLibraryActivityList').innerHTML = html;
        
    }
    
    this.enterActivity = function()
    {
        var f = document.forms['jcaLibraryForm'];
        var libid = f.libid.value;
        if (f.libid.value <= 0) {
            alert("Please select a valid library item to enter an activity.");
            return;
        }
        
        var item = 'Please confirm you are entering an activity for\n\n'+
        '   Title:\t'+f.title.value+'\n'+
        '   Author:\t'+f.author.value+'\n\n';

        var f = document.forms['jcaLibOpsForm'];
        f.opdate.value = f.opdate.value.trim();
        f.opuser.value = f.opuser.value.trim();
        f.opcomment.value = f.opcomment.value.trim();
        
        if (f.opdate.value == '' || f.opuser.value == '' || f.opcode.selectedIndex == 0) {
            alert("Enter Activity:\n    Date, Activity and User must have proper values!");
            return;
        }

        var act = item+'   --- Activity ---\n'+
        '   Date:\t\t'+f.opdate.value+'\n'+
        '   Activity:\t'+f.opcode.options[f.opcode.selectedIndex].text+'\n'+
        '   User:\t\t'+f.opuser.value;
        

        var cnf = confirm(act);
        if (!cnf) {
            return;
        }
        
        f.libid.value = libid;
        f.x.value = 'enterActivity';
        var data = _compose(f);
        var ajax = new AjaxRequest().send('get', '_library.php', data, null, false);

        jcaWipOff('jcaLibraryWip', 'jcaLibraryInfo', ajax.responseText);
        
        if (ajax.responseText == 'Entered.') {
            this.getActivities(libid);
        }
    }
    
    this.returnActivity = function(kk)
    {
        var a = this.activities[kk];
        var f = document.forms['jcaLibraryForm'];
        var libid = f.libid.value;
        if (f.libid.value <= 0 || a.libid <= 0) {
            alert("Please select a valid library item to return.");
            return;
        }
        if (a.opcode != 'b') {
            alert("Only borrow can be returned.");
            return;
        }
        if (a.opdate2 != '') {
            alert("Already returned.");
            return;
        }
        var item = 'You are about to return borrowed item\n\n'+
        '   Title:\t'+f.title.value+'\n'+
        '   Author:\t'+f.author.value+'\n\n';
        var act = item+'   --- Activity ---\n'+
        '   Date:\t\t'+a.opdate+'\n'+
        '   Activity:\t'+jcaActivity[a.opcode]+'\n'+
        '   User:\t\t'+a.opuid;

        var cnf = confirm(act+'\n\nPlease confirm.');
        if (!cnf) {
            return;
        }
        var data = 'x=returnActivity&libid='+a.libid+'&opid='+a.opid;
        var ajax = new AjaxRequest().send('get', '_library.php', data, null, false);
        jcaWipOff('jcaLibraryWip', 'jcaLibraryInfo', ajax.responseText);
        if (ajax.responseText == 'Returned.') {
            this.getActivities(libid);
        }
        
    }
}

var jcaLibrary = new JCALibrary();


// ~~~ JCA Blogs ~~~

function JCABlogs()
{
    this.items = new Array();
    
    this.showItem = function(n)
    {
        var f = document.forms['jcaBlogsForm'];

        var item = this.items[n];

        f.bid.value      = item.id;
        f.date1.value    = item.date1.substring(0,10);
        f.date2.value    = item.date2.substring(0,10);
        f.title.value    = item.topic;
        f.content.value  = item.content;
        f.status.value   = item.status;
        f.modified.value = item.date;
        f.uid.value      = item.uid;
        
        document.getElementById('jcaBlogsSaveButton').value = 'Update';
        document.getElementById('jcaBlogsDeleteButton').disabled = false;
        document.getElementById('jcaBlogsWip').innerHTML = '&nbsp;';
    }
    
    this.newItem = function()
    {
        var f = document.forms['jcaBlogsForm'];
        f.bid.value      = 0;
        f.date1.value    = '';
        f.date2.value    = '';
        f.title.value    = '';
        f.content.value  = '';
        f.status.value   = 'I';
        f.modified.value = '';
        f.uid.value      = '';
        
        document.getElementById('jcaBlogsSaveButton').value = 'Create';
        document.getElementById('jcaBlogsDeleteButton').disabled = true;
        document.getElementById('jcaBlogsWip').innerHTML = '&nbsp;';
    }
    
    this.saveItem = function(op)
    {
        var f = document.forms['jcaBlogsForm'];
        f.bid.value      = f.bid.value.trim();
        f.date1.value    = f.date1.value.trim();
        f.date2.value    = f.date2.value.trim();
        f.title.value    = f.title.value.trim();
        f.content.value  = f.content.value.trim();
        f.status.value   = f.status.value.trim();
        f.modified.value = f.modified.value.trim();
        f.uid.value      = f.uid.value.trim();

        if (f.date1.value == '' || f.date1.value=='') {
            alert('Please enter a starting date.');
            return;
        }
        if (f.title.value == '' || f.title.value=='') {
            alert('Please enter a title.');
            return;
        }
        if (f.content.value == '' || f.content.value=='') {
            alert('Please enter content.');
            return;
        }
        if (f.bid.value=='' || f.bid.value=='0') {
            f.x.value = 'createHeadline';
        }
        else {
            f.x.value = 'updateHeadline';
        }
        var data = _compose(f);
        var ajax = new AjaxRequest().send('post', '_xblogs.php', data, null, false);
        this.getItems();
        if (f.bid.value <= 0) {
            this.newItem();
        }
        jcaWipOff('jcaBlogsWip', 'jcaBlogsInfo', ajax.responseText);
    }
    
    this.getItems = function ()
    {
        var f = document.forms['jcaBlogsForm'];
        var ajax = new AjaxRequest().send('get', '_xblogs.php', 'x=getHeadlines', this, true);
        jcaWipOn('jcaBlogsItemsWip', 'jcaBlogsInfo', '&nbsp;', true);
    }

    this.deleteItem = function ()
    {
        var f = document.forms['jcaBlogsForm'];
        var bid = f.bid.value.trim();
        if (bid <= 0 || bid == '') {
            alert('Please select a valid item to delete.');
            return;
        }
        var f = document.forms['jcaBlogsForm'];
        var ajax = new AjaxRequest().send('post', '_xblogs.php', 'x=deleteHeadline&bid='+bid, null, false);
        this.getItems();
        this.newItem();
        jcaWipOff('jcaBlogsWip', 'jcaBlogsInfo', ajax.responseText);
    }

    this._items = function (ajax, x, t)
    {
        this.items = new XMLObject(ajax, 'topic').data;
        var html = '<table cellspacing=0 cellpadding=2 class="admcoltbl" width=100%>\n';
        for (var ii=1; ii<this.items.length; ++ii) {
            var item = this.items[ii];
            var color = (item.status == 'A') ? '' : 'color: #aaa;';
            html += '<tr onclick="jcaBlogs.showItem('+ii+')" onmouseover="this.className=\'admin-tr-hover\'" onmouseout="this.className=\'admin-tr\'"><th style="'+color+'" colspan=2>'+item.topic+'</th></tr>';
            html += '<tr><td style="padding-left: 15px; font-style:italic" colspan=2>'+item.datestr+' By '+item.user+'&nbsp;&nbsp;&nbsp; ('+item.date1.substring(0,10)+' - '+item.date2.substring(0,10)+')</td></tr>';
            html += '<tr><td style="padding-left: 15px; border-bottom: 1px solid #ccc;">'+item.content+'</td></tr>';
        }
        for (var ii=this.items.length; ii<20; ++ii) {
            html += '<tr><td colspan=4>&nbsp;</td></tr>';
        }
        html += '</table>';
        document.getElementById('jcaBlogsItems').innerHTML = html;
        jcaWipOff('jcaBlogsItemsWip', 'jcaBlogsInfo', '&nbsp;', true);
    }

    this.processResponse = function(ajax)
    {
        if (ajax.responseText == 'Session timeout') {
            document.location.reload();
            return;
        }
        this._items(ajax, ajax.responseXML, ajax.responseText);
        jcaWipOff('jcaLibraryItemsWip', 'jcaLibraryInfo', '&nbsp;', true);
    }
    
    this.processError = function (ajax, url, params)
    {
        var err = '[*info*]Error: (status='+ajax.status+')(url='+url+')(params='+params+')';
        jcaWipError('jcaLibraryItemsWip', 'jcaLibraryInfo', err, true);
    }    
}

var jcaBlogs = new JCABlogs();
