/** 
 * WITO Embedding javascript
 *
 * witoQueryClass
 * - super cut-down version of jQuery
 *
 * * Functionally identical to facilitate swap-in/out
 * * Stand-alone (doesn't require wito)
 *
 */
var witoQueryClass = window.witoQueryClass = function(selector, context) {
    // strictly var witoQueryClass isn't really the class but an object instantiator
    return new witoQueryClass.prototype.init(selector, context);
}

witoQueryClass.browser = {
    msie: (document.all ? true : false),
    mozilla: /mozilla/.test( navigator.userAgent.toLowerCase() ) && !/(compatible|webkit)/.test( navigator.userAgent.toLowerCase() )
};

witoQueryClass.internal = {
    last_instance: 0
};


witoQueryClass.prototype = {
    init: function( selector, context ) {
        // init vars
        this.doc = document;
        this.elem = null;
        this.instance = witoQueryClass.internal.last_instance++;
        // parse selector
        if (typeof selector == "string") {
            if (selector.charAt(0) == '#') {
                // find element by id
                var sel_id = selector.substring(1);
                this.elem = document.getElementById( sel_id);
                // alert('matched on id: '+this.elem);
            } else if (selector.charAt(0) == '.') {
                // find element by class
                var sel_class = selector.substring(1);
                this.elem = this.__getElementByClass('*', sel_class)[0];
                // alert('matched on id: '+this.elem);
            } else if (selector.indexOf('.') != -1) {
                // find element by class, limited scope
                var sel_dot = selector.indexOf('.');
                var sel_tag = selector.substring(0,sel_dot);
                var sel_class = selector.substring(sel_dot+1);
                // for now, just use first one
                this.elem = this.__getElementByClass(sel_tag, sel_class)[0];
                // alert('matched on id: '+this.elem);
            } else {
                // find element by tag name
                var sel_id = selector;
                this.elem = document.getElementsByTagName( sel_id)[0];
                // alert('matched on tagname: '+this.elem);
            }
        } else if (typeof selector == "object") {
            this.elem = selector;
        }
        return(this);
    },
    // jquery equivalence
    jquery: "1.2.6"
}


/**
 * Internal function to find elements of a certain class
 */
witoQueryClass.prototype.__getElementByClass = function(tagName, className) {
    var all = null;
    if (tagName == '*') {
        all = document.all ? document.all : document.getElementsByTagName('*');
    } else {
        all = document.getElementsByTagName(tagName);
    }
    var elements = new Array();
    for (var e = 0; e < all.length; e++) {
        if (all[e].className == className) {
            elements[elements.length] = all[e];
        }
    }
    // insert null entry if not matches found
    if (elements.length == 0) elements[0] = null;
    return elements;
}


witoQueryClass.prototype.append = function(html) {
    if (!this.elem) return(null);
    if (html == '') return(null);
    var newBlock = this.__buildNewDomNode(html);
    var node = this.elem.appendChild(newBlock);
    return(witoQueryClass('#'+newBlock.id));
}


witoQueryClass.prototype.before = function(html) {
    if (!this.elem) return(null);
    if (html == '') return(null);
    var newBlock = this.__buildNewDomNode(html);        
    var parent = this.elem.parentNode;
    var node = parent.insertBefore(newBlock, this.elem);
    return(witoQueryClass('#'+newBlock.id));
}


witoQueryClass.prototype.remove = function() {
    if (!this.elem) return(null);
    this.elem.parentNode.removeChild(this.elem);
}


/**
 * Internal function to create a dom node from HTML
 */
witoQueryClass.prototype.__buildNewDomNode = function(html) {
    var newBlock = null;
    if (typeof(html) == "object") {
        newBlock = html;
        return(newBlock);
    }
    var newBlockID = null;
    // alert('@@'+html+'@@');
    if (html.charAt(0) == '<') {
        // cleave off first tag
        closepos = html.indexOf('>');
        tagcontent = html.substring(1,closepos);
        // split into parts
        // - key-values must not contain spaces
        parts = tagcontent.split(' ');
        newBlock = this.doc.createElement(parts[0]);
        for (var i=1 ; i<parts.length ; ++i) {
            eqpos = parts[i].indexOf('=');
            if (eqpos == -1) continue;
            key = parts[i].substring(0,eqpos);
            value = parts[i].substring(eqpos+1);
            value = value.replace(/"/g,'');
            this.__setAttribute(newBlock, key, value);
             if ((key == 'id') || (key == 'ID')) newBlockID = value;
            // alert('key['+key+'] value['+value+']');
        }

        /*
        flagged = false;
        if (!flagged) {
            flagged = false;
            alert('flag:'+closepos+'->'+i+' of '+html.length);
        }
        */

        // strip first <tagname> & last </tagname> from html
        for (i=html.length ; i>1 ; --i) {
            // search for the opening bracket of the closing tag
            if ((html.charAt(i-1) == '<') && (html.charAt(i) == '/')) {
                html = html.substring(closepos+1, i-1);
                break;
            }
        }
    } else {
        newBlock = this.doc.createElement('div');
    }
    // assign an id to the block we've just created
    if (!newBlockID) {
        if (!witoQueryClass.append_id_seq) witoQueryClass.append_id_seq = 1;
        newBlockID = (++witoQueryClass.append_id_seq);
        newBlock.setAttribute('id', newBlockID);
    }
    // protect against empty blocks
    if (html.length == 0) html = '&nbsp;';
    newBlock.innerHTML = html;
    newBlock.id = newBlockID;
    return(newBlock);    
}


witoQueryClass.prototype.__setAttribute = function (elem, attribute, value) {
    if (witoQueryClass.browser.msie) {
        if (attribute == 'style') {
            elem.style.cssText = value;
        } else {
            if (attribute == "class") attribute = "className";
            if (attribute == "for") attribute = "htmlFor";
            elem[attribute] = value;
        }
    } else {
        elem.setAttribute(key, value);
    }
}


witoQueryClass.prototype.bind = function(evtype, datapass, handler) {
    if (!this.elem) return(false);
    // attach event
    if (this.elem.addEventListener) { 
        this.elem.addEventListener(evtype, handler, false);
        return(true); 
    }
    else if (this.elem.attachEvent) { 
        return(this.elem.attachEvent("on" + evtype, handler)); 
    }
    else {
        return(false);
    }
}


witoQueryClass.prototype.unbind = function(evtype, handler) {
    if (!this.elem) return(false);
    if (this.elem.removeEventListener) { 
        this.elem.removeEventListener(evtype, handler, false);
        return(true); 
    }
    else if (this.elem.detachEvent) { 
        return(this.elem.detachEvent("on" + evtype, handler)); 
    }
    else {
        return(false);
    }
}


witoQueryClass.prototype.click = function(cbfunc) {
    this.bind('click', null, cbfunc);
}


witoQueryClass.prototype.keydown = function(cbfunc) {
    this.bind('keydown', null, cbfunc);
}


witoQueryClass.prototype.show = function() {
    if (!this.elem) return;
    this.elem.style.display = 'block';
}


witoQueryClass.prototype.hide = function() {
    if (!this.elem) return;
    this.elem.style.display = 'none';
}


witoQueryClass.prototype.animate = function(keys, timeframe, easing, callback) {
    // action each key as simple set
    for (prop in keys) {
        this.css(prop, keys[prop]);
    }
}


witoQueryClass.prototype.css = function(key, value) {
    // read anything, write limited
    if (arguments.length == 1) {
        if (!this.elem) return(0);
        // return style value
        var k = eval('this.elem.style.'+key);
        return(k);
    }
    if (!this.elem) return(0);
    // set style value
    if (key == 'opacity') {
        if (value == "show") {
            this.show();
        } else if (value == "hide") {
            this.hide();
        } else {
            this.elem.style.opacity = value;
            this.elem.style.MozOpacity = value;
            this.elem.style.filter = 'alpha(opacity='+(value*100)+')';
        }
    }
    if (key == 'filter')
        this.elem.style.filter = value;
    if (key == 'top')
        this.elem.style.top = value;
    if (key == 'left')
        this.elem.style.left = value;
    if (key == 'width')
        this.elem.style.width = value;
    if (key == 'maxWidth')
        this.elem.style.maxWidth = value;
    if (key == 'height') {
        // this property is sensitive in IE during init, so must protect access
        if (this.elem.style.height) {
            this.elem.style.height = value;
        }
    }
    if (key == 'marginTop')
        this.elem.style.marginTop = value;
    if (key == 'marginLeft')
        this.elem.style.marginLeft = value;
    if (key == 'marginRight')
        this.elem.style.marginRight = value;
    if (key == 'marginBottom')
        this.elem.style.marginBottom = value;
    if (key == 'z-index')
        this.elem.style.zIndex = value;
}


witoQueryClass.prototype.width = function() {
    return(this.css('width'));
}


witoQueryClass.prototype.height = function() {
    return(this.css('height'));
}


witoQueryClass.prototype.addClass = function(className) {
    if (!this.elem) return;
    this.elem.className += this.elem.className ? ' '+className : className;
}


witoQueryClass.prototype.removeClass = function(className) {
    if (!this.elem) return;
    var str = this.elem.className;
    // strip first instance of removing class
    var pos = str.indexOf(className);
    if (pos != -1) {
        this.elem.className = str.substring(0, pos) + str.substring(pos + className.length, str.length);
    }
}


witoQueryClass.prototype.html = function() {
    if (!this.elem) return('');
    if (arguments.length > 0) {
        this.elem.innerHTML = arguments[0];
    }
    return(this.elem.innerHTML);
}


witoQueryClass.prototype.val = function() {
    if (!this.elem) return(0);
    if (arguments.length > 0) {
        this.elem.value = arguments[0];
    }
    return(this.elem.value);
}


witoQueryClass.prototype.is = function(what) {
    if (!this.elem) return(false);
    return(this.elem != null);
}


witoQueryClass.prototype.using = function() {
    return('witoQueryClass');
}


/**
 * Clever jQuery trick to glue it all together
 * - give the init function the witoQuery prototype for instantiating as an object
 */
witoQueryClass.prototype.init.prototype = witoQueryClass.prototype;


/** 
 * WITO Embedding javascript
 *
 *   WITO
 *     javascript support file for embedded links
 *     sent to page by embed.module
 *
 * jQuery 1.2.6 or later
 *
 * Globals:
 *        witoGlobal
 */

/**
 *
 * INLINE SECTION
 *
 */
var witoGlobal = null;
// default query library (jQuery|witoQueryClass, gets checked)
var witoQuery = witoQueryClass;
if (window.jQuery)
    witoQuery = jQuery;
// temporarily force us to use witoQuery
// witoQuery = witoQueryClass;

/**
 * Embedding code to handle onload before binary-complete
 * - for Mozilla 
 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", wito_embed_onload, false);
}
/**
 * - for Internet Explorer
 */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var wito_script = document.getElementById("__ie_onload");
    wito_script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            wito_embed_onload(); // call the onload handler
        }
    };
/*@end @*/
/**
 * - for Safari
 */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            wito_embed_onload(); // call the onload handler
        }
    }, 10);
}
/**
 * - for other browsers
 */
window.onload = wito_embed_onload;


function wito_embed_onload() {
    // quit if this function has already been called
    if (arguments.callee.done) return;
    
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    
    // kill the timer
    if (_timer) {
        clearInterval(_timer);
        _timer = null;
    }
    
    witoGlobal = new witoClass();
    witoGlobal.init();
};


/**
 * witoClass
 * - blueprint for witoGlobal
 *
 */
function witoClass() {
    // constructor is empty
    // - because it can't access 'this'
}


witoClass.prototype.init = function() {
    // pre-requisites: none
    this.init_witoQuery();
    this.init_constants();
    this.init_vars();
    // [debug, optionally] delete thinker cookie
    // this.cookie(this.cookie_NAME, '', -1);
    // connect to wito server
    this.init_server();
    this.init_page();
    // pre-requisites: must have called init_server
    // branch-point: init_styles forks execution
    this.init_subscripts();
    this.init_styles();
    this.init_ajax();
    // if wito links found on page
    if (witoQuery('.'+this.pageLinkClass).is('*')) {
        // active mode
    } else {
        // library mode
    }
}


witoClass.prototype.init_witoQuery = function() {
    var version = witoQuery().jquery;
    var vnum = parseInt(version.replace(/\./ig,""));
    // check equivalency to jquery 1.2.6
    if (vnum < 126) {
        // default to witoQuery substitute
        witoQuery = witoQueryClass;
        // this.debug('Your version of jQuery needs to be 1.2.6 or later.  Reverting to witoQuery substitute.');
    }
}


witoClass.prototype.init_vars = function() {
    // session vars initialised in session_init
    this.toolbox = null;
    this.feedback_visible = true;
    this.serverName = '';
    this.page = null;
    // pre-init, don't know if we can communicate with server yet
    this.online = this.status_DONTKNOW;
    // assume not debugging
    this.DEBUG_LOSEC = 0;
    // initialise pacemaker
    this.heartbeat = new witoHeartbeatClass();
    this.heartbeat.init(this);
    // initialise update queue
    this.intUpdQueue = new witoInterfaceUpdateQueue();
    this.intUpdQueue.init(this);
}


witoClass.prototype.init_constants = function() {
    // internal
    this.valid = 0xC0FFEE;
    this.version = 105001; // V.XX.YYY

    // globals
    this.scriptName = 'wito_embed.js';
    this.serverReceiver = '/index.php?q=wito_receiver&';
    // this.rcvAlias = '/wito_rcv';
    this.rcvAlias = '/sites/all/modules/wito6/receiver';
    this.threadBaseID = 'wito_threadBase';
    this.pageLinkClass = 'wito_embed_link';

    // url (filter & escape)
    var urlnohash = location.href;
    if (urlnohash.charAt(urlnohash.length - 1) == '#') {
        // strip trailing empty fragment [#] (-1 is right |0|1|2|n-1|n|)
        urlnohash = urlnohash.substring(0, urlnohash.length - 1);
    }
    this.url = escape(urlnohash);

    /**
     * Constants
     * - duplicated server side
     */

    // constants (general)
    this.ref_UNSET = -1;

    // constants (status)
    this.status_ONLINE = 1;
    this.status_OFFLINE = 0;
    this.status_DONTKNOW = 2;

    // constants (timeouts in ms)
    this.timeout_CHECKINT = 1 * 1000;
    this.timeout_REQOVERDUE = 5 * 1000;
    this.timeout_REQEXPIRE = 10 * 1000;

    // constants (hashing)
    this.hash_tableCRC      = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D"; 
    this.hash_fieldsTOP     = null;
    this.hash_fieldsSESSION = ['data'];
    this.hash_fieldsTHREAD  = ['data','left','top','width','height','flagdisp','minishape','colour','z'];
    this.hash_fieldsPOST    = ['data','flagdisp'];

    // constants (flag)
    this.flag_BASE = 0x00000000;

    // action targets
    this.flag_targetMASK       = 0x0000F000;
    this.flag_targetSERVER     = this.flag_BASE;
    this.flag_targetTHREAD     = 0x00001000;
    this.flag_targetPOST       = 0x00002000;
    this.flag_targetSESSION    = 0x00004000;

    /**
     * action and edit (actionable) flags
     * + shares mask with action targets
     */
    this.flag_actionMASK             = 0x7FFF0FFF;
    this.flag_actionNONE             = 0x00000000;
    this.flag_actionUNCONFDEL        = 0x00000001;
    this.flag_actionEDIT             = 0x00000002;
    this.flag_actionAPPEND           = 0x00000004; // implemented using actionNEW on child
    this.flag_actionMOVE             = 0x00000008;
    this.flag_actionDELETE           = 0x00000010;
    this.flag_actionMINIMISE_RESTORE = 0x00000020;
    this.flag_actionCOLCHANGE        = 0x00000040;
    this.flag_actionCONFDEL          = 0x00000080;
    this.flag_actionRESIZE           = 0x00000100;
    this.flag_actionSELECT           = 0x00000200;
    this.flag_actionHIDE             = 0x00000400;
    this.flag_actionSHOW             = 0x00000800;
    this.flag_actionGET              = 0x00010000;
    this.flag_actionUPDATEALL  = this.flag_actionMASK;
    this.flag_actionNEW        = this.flag_actionUPDATEALL;

    /**
     * display flags
     * + independent domain
     */
    this.flag_displayMASK      = this.flag_actionMASK; // for no real reason
    this.flag_displayNONE      = this.flag_displayMASK; // hidden
    this.flag_displayVISIBLE   = 0x00000001;
    this.flag_displayDELETED   = 0x00000010;
    this.flag_displayMINIMISED = 0x00000040;
    this.flag_displayCONFDEL   = 0x00000080;
    this.flag_displaySELECTED  = 0x00000200;
    this.flag_displayVISIFSEL  = 0x00000400;
    this.flag_displayVISIFNOT  = 0x00000800;

    /**
     * 'session as' flags
     */
    this.flag_USASNONE  = 0x0;
    this.flag_USASUSER  = 0x1;
    this.flag_USASGROUP = 0x2;
    this.flag_USASALL   = 0x4;
    this.flag_USASOWNER = 0x8;

    // assume PHP session identification
    this.cookie_useCookie = false;

    // names
    this.cookie_NAME = 'WIThinkerOf';
    this.server_side_sessionList_NAME = 'sso_session_list';
    this.server_side_threadList_NAME = 'sso_thread_list';
    this.server_side_postList_NAME = 'sso_post_list';
    
    // operation success flags
    this.save_UNKNOWN = 0;
    this.save_SUCCESS = 1;
    this.save_FAIL = 2;
    this.save_PENDING = 3;
}


witoClass.prototype.init_server = function() {
    // get remote server name by scanning scripts
    var scripts = document.getElementsByTagName('script');
    for (var i=0 ; i<scripts.length ; ++i) {
        var thiscr = scripts[i];
        var len = thiscr.src.length;
        // find our script tag in the HTML
        if ((thiscr.src.substring(len - this.scriptName.length, len)) == this.scriptName) {
            // establish what protocol we're on
            this.protocol = thiscr.src.substring(0,7);
            if (thiscr.src.substring(0,8) == 'https://') {
                this.protocol = thiscr.src.substring(0,8);
            }
            var nextslash = thiscr.src.indexOf('/',this.protocol.length);
            this.serverName = thiscr.src.substring(this.protocol.length, nextslash);
        }
    }
}


/**
 *
 *
 * Sheets and Scripts
 * - attach stylesheets, preload images
 *
 * 
 */
witoClass.prototype.init_styles = function() {
    this.attach_stylesheet('wito_.css');
    // pre-cache images
    var imagepath = this.page_getAssetPath() + 'images/';
    this.attach_image(imagepath + 'backadd.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'backedit.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'backdel.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'arrow_right.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'arrow_down.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'deletex.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'editpen.gif', document.body, 'image/gif', 'wito_hidden');
    this.attach_image(imagepath + 'resize.gif', document.body, 'image/gif', 'wito_hidden');
    // attach backgrounds (dynamic)
    var style_inline = (" \r\n \
/* Image references */ \r\n \
div.wito_glyphright { background-image: url('"+imagepath+"arrow_right.gif'); } \r\n \
div.wito_glyphdown { background-image: url('"+imagepath+"arrow_down.gif'); } \r\n \
div.wito_deletex { background-image: url('"+imagepath+"deletex.gif'); } \r\n \
div.wito_editpen { background-image: url('"+imagepath+"editpen.gif'); } \r\n \
p a.wito_add { background-image: url('"+imagepath+"backadd.gif'); } \r\n \
p a.wito_sub { background-image: url('"+imagepath+"backsub.gif'); } \r\n \
p a.wito_edit { background-image: url('"+imagepath+"backedit.gif'); } \r\n \
p a.wito_delete { background-image: url('"+imagepath+"backdel.gif'); } \r\n \
a.wito_link_look { background-image: url('"+imagepath+"logo_thought.gif'); } \r\n \
");
    this.attach_styles(style_inline);
}


witoClass.prototype.attach_stylesheet = function(sheetname) {
    var url = this.page_getAssetPath() + 'css/' + sheetname;
    if (document.createStyleSheet) {
        document.createStyleSheet(url);
    } else {
        if (!document.getElementById('uidc'+sheetname)) {
            type = 'link';
            if (document.createElementNS && this.page.head.tagName == 'head') {
                var newobj = this.page.head.appendChild(document.createElementNS('http://www.w3.org/1999/xhtml', type));
            } else {
                var newobj = this.page.head.appendChild(document.createElement(type));
            }
            newobj.id = 'uidc'+sheetname;
            newobj.rel = 'stylesheet';
            newobj.href = url;
            newobj.type = 'text/css';
            newobj.media = 'screen';
        }
    }
}


witoClass.prototype.attach_styles = function(styles) {
    type = 'style';
    if (document.createStyleSheet) {
        // IE only
        var lineArray = styles.split("\r\n");
        var newobj = document.createStyleSheet();
        // add rules one at a time
        for (var i=0 ; i<lineArray.length ; ++i) {
            var posbraco = lineArray[i].indexOf('{');
            if (posbraco > 0) {
                var spec = lineArray[i].substring(0,posbraco);
                var posbracc = lineArray[i].indexOf('}');
                var rule = lineArray[i].substring(posbraco+1, posbracc);
                newobj.addRule(spec, rule);
            }
        }
    } else {
        // Firefox and Chrome
        if (document.createElementNS && this.page.head.tagName == 'head') {
            var newobj = this.page.head.appendChild(document.createElementNS('http://www.w3.org/1999/xhtml', type));
        } else {
            var newobj = this.page.head.appendChild(document.createElement(type));
        }
        if (witoQuery.browser.mozilla) {
            newobj.innerHTML = styles;
        } else {
            newobj.innerText = styles; // changed from innerHTML
        }
        newobj.type = 'text/css';
        newobj.media = 'screen';
    }
}


/**
 * attach_javascript
 * + bi-directional information flow
 */
witoClass.prototype.attach_javascript = function (url, callback, scriptname) {
    // if this particular script isn't attached yet
    if ((scriptname == null) || (!document.getElementById('uids'+scriptname))) {
        type = 'script';
        if (document.createElementNS && this.page.head.tagName == 'head') {
            var newobj = this.page.head.appendChild(document.createElementNS('http://www.w3.org/1999/xhtml', type));
        } else {
            var newobj = this.page.head.appendChild(document.createElement(type));
        }
        if (scriptname != null) {
            newobj.id = 'uidc'+scriptname;
        }
        newobj.src = url;
        newobj.type = 'text/javascript';
        this.attach_javascript_add_listener(newobj, callback, true);
    }
}


witoClass.prototype.attach_javascript_add_listener = function(newobj, callback, destroy) {
    if (witoQuery.browser.msie) {
        witoQuery(newobj).bind( "readystatechange", null, function() {
            if(newobj.readyState == "loaded") {
                callback(newobj);
                if (destroy) {
                    witoGlobal.page.head.removeChild(newobj);
                }
            }
        } );
    } else {
        witoQuery(newobj).bind( "load", null, function() {
            if (callback) callback(newobj);
            if (destroy) {
                witoGlobal.page.head.removeChild(newobj);
            }
        } );
    }
}


/**
 * attach_image
 * - single directional flow
 * - information up to server, not back
 * - doesn't require witoQuery
 * + also useful for caching images
 *
 * optional arguments
 * [3] = class
 */
witoClass.prototype.attach_image = function (url, base, type) {
    type = 'img';
    if (typeof(base) == 'string') {
        base = document.getElementById(base);
    }
    if (document.createElementNS) {
        var newobj = base.appendChild(document.createElementNS('http://www.w3.org/1999/xhtml', type));
    } else {
        var newobj = base.appendChild(document.createElement(type));
    }
    newobj.src = url;
    newobj.type = type;
    // optionally attach classname
    if (arguments.length > 3) {
        newobj.className = arguments[3];
    }
}


// get and set cookies
witoClass.prototype.cookie = function(name) {
    if (arguments.length == 1) {
        // get
        var parts = document.cookie.split( ';' );
        for (i=0; i<parts.length; i++)
        {
            var temp_cookie = parts[i].split('=');
            // trim left/right whitespace
            var cookie_name = temp_cookie[0].replace(/^\s+|\s+$/g, '');
            // if the extracted name matches passed check_name
            if (cookie_name == name) {
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if ( temp_cookie.length>1) {
                    return(unescape(temp_cookie[1].replace(/^\s+|\s+$/g, '')));
                }
            }
        }
        return(false);
    } else {
        // set
        var value = arguments[1];
        var expires = arguments[2];
        var domain = arguments[3];
        var secure = arguments[4];
        
        var today = new Date();
        msnow = today.getTime()
        today.setTime(msnow);
        var expires_date = new Date(msnow + expires);
        
        document.cookie = name + "=" +escape(value) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
        (";path=/") + 
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    }
}


/**
 *
 *
 * Component subscripts
 *
 *
 */
witoClass.prototype.init_subscripts = function() {
    scriptpath = this.page_getAssetPath() + 'js/';
    // this.attach_javascript(scriptpath + 'jquery.something.js', null, null);
}


/**
 *
 *
 * Page operations
 *
 * 
 */
witoClass.prototype.init_page = function() {
    // generic object for page
    this.page = new Object();
    // create thread container div
    witoQuery('body').append('<div id="'+this.threadBaseID+'"></div>');
    this.page.threadBase = witoQuery('#'+this.threadBaseID);
    // find wito links in page
    if (witoQuery('.'+this.pageLinkClass).is('*')) {
        witoQuery('.'+this.pageLinkClass).click(function(e) {
            witoGlobal.page_link_click();
            witoGlobal.event_stop_bubble(e);
        });
    }
    this.page.head = document.getElementsByTagName('head')[0];
}


witoClass.prototype.page_link_click = function() {
    // work out if we're in online/offline mode
    if (this.online == this.status_ONLINE) {
        var session = this.sessionList.getCurrent();
        if ((session) && (session.threadList)) {
            // create a new thread
            var thread = session.threadList.new_thread();
            thread.renderAttachShow();
            thread.edit();
            // show toolbox if this is the first thread
            var tcount = session.threadList.getCount();
            showToolbox = false;
            if (tcount > 0) showToolbox = true;
            if (showToolbox && (this.toolbox == null)) {
                this.toolbox = new witoToolboxClass();
                this.toolbox.init(this, this.sessionList);
                this.toolbox.show();
            }
        } else {
            this.warning('Session thread list has yet to be initialised.');
        }
    }
    if (this.online == this.OFFLINE) {
        // this.debug('offline');
    }
    if (this.online == this.DONTKNOW) {
        // this.debug('don\'t know');
    }
}


witoClass.prototype.page_getAssetPath = function() {
    var assetpath = this.protocol + this.serverName + this.rcvAlias + '/';
    return(assetpath);
}


/**
 *
 *
 * Server operations
 * - ajax posts
 *
 *
 */
witoClass.prototype.init_ajax = function() {
    // create update sequence array
    this.ajax_update_seq = new Array();
    // insert blank [0] entry, so all updates are 1-based (+ve & 'true')
    this.ajax_update_seq[0] = new Object();
    // connect with server
    this.ajax_server_init();
}


witoClass.prototype.ajax_countOutstanding = function() {
    // ignore entry[0]
    return(this.ajax_update_seq.length - 1);
}


witoClass.prototype.ajax_callback_get_data = function() {
    // symmetric with variable server writes into javascript file
    return(retDataObj);
}


witoClass.prototype.ajax_prep = function(action) {
    var postObj = new Object();
    // include session basics
    postObj.url = this.url;
    // if no domainID defined, put onto test domain
    if (!window.wito_domainID) wito_domainID = 1;
    postObj.domain_id = wito_domainID;
    // only post cookie if cookie attached to sessionList
    if (this.sessionList) {
        if (this.sessionList.cookie) {
            postObj.cookie = this.sessionList.cookie;
            // this.debug('firing cookie with request: '+postObj.cookie);
        }
    }
    // include action
    postObj.action = action;
    return(postObj);
}


witoClass.prototype.ajax_post = function (postObj, cbfunc) {
    var postUrl = this.protocol + this.serverName + this.serverReceiver + 'type=js&';
    // collapse postObj into url
    postUrl += this.__object_toURL(postObj);
    this.attach_javascript(postUrl, cbfunc, null);
}


witoClass.prototype.ajax_push = function (postObj) {
    var postUrl = this.protocol + this.serverName + this.serverReceiver + 'type=img&';
    // collapse postObj into url
    postUrl += this.__object_toURL(postObj);
    this.attach_image(postUrl, document.body, 'image/gif');
}


/**
 * Send an ajax post
 * + remember requests
 * + reconcile returns against requests
 * + check the result status of the queue
 */
witoClass.prototype.ajax_update = function(postObj) {
    // attach sequence number and store this post object
    postObj.update_seq = this.ajax_update_seq.length;
    // tag this request with time dispatched
    var d = new Date();
    var msnow = d.getTime();
    // tag this request with additional data (local time, version, hash, aggregate)
    postObj.version_embed = this.version;
    postObj.time_dispatched = msnow;
    postObj.time_failed_attempts = 0;
    if (this.hash) {
        // some requests are fired before startup/hashing complete
        postObj.top__hval = this.hash.hval;
        postObj.top__hchild = this.hash.hchild;
    }
    // record post object in sequence array
    this.ajax_update_seq[postObj.update_seq] = postObj;
    // fire post
    this.ajax_post(postObj, this.ajax_update_callback);
    // TO DO - setup repeating callback to check queue
}


witoClass.prototype.ajax_update_callback = function() {
    // function loses 'this' object context on callback
    var context = witoGlobal;
    if (this.valid) context = this;
    var rdo = context.ajax_callback_get_data();

    if (!rdo.update_seq) {
        // improperly formed packet from server
    }
    else if (!context.ajax_update_seq[rdo.update_seq]) {
        // if we can't match update sequence number, this must be an unknown or late request, so ignore
    }
    else if (rdo.errorcode) {
        // if error returned, report
        context.error('Error ('+rdo.errorcode+'): '+rdo.message);
    }
    else {
        var postObj = context.ajax_update_seq[rdo.update_seq];
        // check and action operation success flag, if defined/required
        if (rdo.saveSuccess) {
            switch(rdo.saveSuccess) {
                case context.save_SUCCESS :
                    // no action required
                    break;
                case context.save_PENDING :
                    // action immediately
                    // insert re-ref code here
                    break;
                case context.save_FAIL :
                    // notify user
                    break;
            }
        }
        // flag request as 'resolved' in update queue
        context.ajax_update_seq[rdo.update_seq] = null;
        // collapse list back if empty
        var collapsePoint = -1;
        // find last valid value
        for (var i=0 ; i<context.ajax_update_seq.length ; ++i) {
            if (context.ajax_update_seq[i] != null)
                collapsePoint = i;
        }
        context.ajax_update_seq.length = collapsePoint+1;
        // context.debug(context.__arrayToString(context.ajax_update_seq));
        // callback function if set
        if (postObj.callback) {
            postObj.callback(rdo, context);
        }
        // process updates (if not already processed by callback)
        if (rdo[context.server_side_sessionList_NAME]) {
            context.sessionList.compare(rdo[context.server_side_sessionList_NAME]);
            context.intUpdQueue.process();
        }
        // schedule next heartbeat if set (0 means cancel)
        if (rdo.timetobeat) {
            context.heartbeat.schedule(rdo.timetobeat);
        } else {
            context.heartbeat.cancel();
        }
    }
}


witoClass.prototype.ajax_update_checkup = function() {
    // not in use
    var context = witoGlobal;
    if (this.valid) context = this;
    // see if there are pending requests
    if (context.ajax_countOutstanding()) {
        // get the time now
        var d = new Date();
        msnow = d.getTime();
        // setup outstanding tally(s)
        var outstanding = 0;
        var outstanding_overdue = 0;
        var outstanding_expired = 0;
        // see when each valid request was sent
        for (var i=1 ; i<context.ajax_update_seq.length ; ++i) {
            var ipo = context.ajax_update_seq[i];
            // skip resolved requests
            if (ipo == null) continue;
            outstanding++;
            // find out how long this request has been outstanding
            var diff = msnow - ipo.time_dispatched;
            // handle overdue request
            if (diff > context.timeout_REQOVERDUE) {
                outstanding_overdue++;
            }
            // handle request expire
            if (diff > context.timeout_REQEXPIRE) {
                outstanding_expired++;
            }
            /**
             * TO DO
             * + write code to handle each of these
             * - for now, just ignore
             */
            outstanding = 0;
        }
        // renew the checkup callback
        if (outstanding) {
            setTimeout(context.ajax_update_checkup, this.timeout_CHECKINT);
        }
    }
}


witoClass.prototype.ajax_server_init = function() {
    // post to server
    var postObj = this.ajax_prep(this.flag_actionINIT | this.flag_targetSERVER);
    if (this.cookie_useCookie) {
        // append cookie to request only is using cookies
        postObj.cookie = this.cookie(this.cookie_NAME);
    }
    postObj.callback = this.ajax_server_init_callback;
    this.ajax_update(postObj);
}


witoClass.prototype.ajax_server_init_callback = function(rdo, context){
    if (!rdo[context.server_side_sessionList_NAME]) {
        if (rdo.errorcode) {
            context.error('Error ('+rdo.errorcode+'): '+rdo.message);
        } else {
            context.error('Invalid response from receiver.');
        }
    } else {
        // inherit debug level from server
        if (rdo.DEBUG_SECSTATE) {
            context.DEBUG_LOSEC = rdo.DEBUG_SECSTATE;
        }
        context.session_init(rdo);
        context.factory_init();
        // remove sessionList from rdo to mark as processed
        rdo[context.server_side_sessionList_NAME] = null;
    }
}


/**
 *
 * Session
 * 
 */
witoClass.prototype.session_init = function(rdo) {
    // rdo comes from server, use as basis
    if (rdo.default_session) {
        temp = new witoSessionListClass();
        temp.wito = this;
        temp.recv_default(rdo.default_session);
    }
    if (rdo.default_thread) {
        // temporarily instantiate a threadList so we can call recv_default (for class tidiness)
        temp = new witoThreadListClass();
        temp.wito = this;
        temp.recv_default(rdo.default_thread);
    }
    if (rdo.default_post) {
        temp = new witoPostListClass();
        temp.wito = this;
        temp.recv_default(rdo.default_post);
    }
    
    // process received session list
    this.sessionList = new witoSessionListClass();
    this.sessionList.init(this, rdo);
    
    // set & use cookies if returned by server
    if (rdo.cookie) {
        this.cookie(this.cookie_NAME, rdo.cookie, 7 * 24 * 60 * 60 * 1000, false, false);
        this.cookie_useCookie = true;
    }
    if (this.cookie_useCookie) {
        this.sessionList.cookie = this.cookie(this.cookie_NAME);
        if (!this.sessionList.cookie) {
            // if unable to set cookie, just remember
            this.sessionList.cookie = rdo.cookie;
        }
    }
    
    // init top-level hash, then cascade-down to setup aggregates
    this.hash = new witoHashClass();
    this.hash.init(this, this.hash_fieldsTOP, this, this.sessionList, null);
    this.hash.hash_calculate(false); // top level hash so no need to cascade up
    this.hash.hash_aggregate(false, true, "|");
    // this.debug(this.hash.debugHashTree('|SESS|THRD|POST|'));
}


/**
 *
 * Genericised functions
 * 
 */
witoClass.prototype.generic_compareList = function(obj, latest, name) {
    var compared = new Array();
    // compare server's session list
    for (var i = 0 ; i<latest.length ; ++i) {
        var sso = latest[i];
        if (!sso) continue;
        // this.debug(name+' list['+i+'] '+this.__objectToString(sso));
        var sref = sso.ref;
        var cso = obj.get(sref);
        // this.debug('searching for '+name+' ref '+sref+', got obj['+cso+']');
        if (!cso) {
            // skip deleted threads
            if (sso.flagdisp & this.flag_displayDELETED) continue;
            // this.debug('creating new '+name+' ref('+sref+')');
            // sso <name> doesn't exist locally (as cso), create (from ListClass)
            obj.receive(sso);
        } else {
            // server session has corresponding local session, compare
            cso.compare(sso);
        }
        compared[compared.length] = sref;
    }
}


witoClass.prototype.generic_processUpdateToQueue = function(obj, latest, name) {
    // this.debug('process update '+name+' ref('+obj.ref+')');
    // diff latest properties against stored
    for (prop in latest) {
        // skip hashes (at this stage)
        if ((prop == 'hval') || (prop == 'hchild')) continue;
        var propType = typeof(latest[prop]);
        // can't do simple comparison of lists
        if ((propType == 'object') || (propType == 'array')) continue;
        if (latest[prop] != obj[prop]) {
            this.intUpdQueue.add(obj, prop, obj[prop], latest[prop]);
            // this.debug(prop + ' is different ('+obj[prop]+','+latest[prop]+')');
        }
    }
}


witoClass.prototype.generic_get = function(obj, ref, name) {
    if (ref == null) return(null);
    if (ref <= obj.list.length) {
        var elem = obj.list[ref];
        if (!elem) return(null);
        if (ref == elem.ref)
            return(elem);
    }
    // this.wito.warning('Attempt to access '+name+' reference '+ref+', not found in '+name+'List.');
    return(null);
}


/**
 *
 * Session class
 *
 */
witoSessionClass = function() {
    // constructor (session)
}


witoSessionClass.prototype.init = function(wito, sessionList) {
    this.wito = wito;
    this.sessionList = sessionList;
    this.threadList = new witoThreadListClass();
    this.threadList.init(this.wito, this);
    this.hash = new witoHashClass();
    this.hash.init(wito, this.wito.hash_fieldsSESSION, this, this.threadList, this.wito);
}


witoSessionClass.prototype.clone = function() { 
    // this object does not contain any objects, so use the lightweight copy code
    var temp = new witoSessionClass();
    temp.copyFrom(this);
    return temp; 
}


witoSessionClass.prototype.copyFrom = function(master) {
    var keymaster = master;
    if (arguments.length > 1) keymaster = arguments[1];
    for (key in keymaster) {
        if (master[key] != undefined) {
            this[key] = master[key];
        }
    }
}


// implements UpdateableInterface
witoSessionClass.prototype.compare = function(latest) {
    // compare hash to see if we need to update
    if (this.hash.hval != latest.hval) {
        this.update(latest);
    }
    // if children updated
    if (this.hash.hchild != latest.hchild) {
        // see if sublist defined in latest, else fire update request
        if (this.threadList && latest[this.wito.server_side_threadList_NAME]) {
            this.threadList.compare(latest[this.wito.server_side_threadList_NAME]);
        } else {
            this.updateFireRequest();
        }
    }
}


witoSessionClass.prototype.update = function(latest) {
    // decide if this is a populated update, or a thin update which needs populating
    if (!this.incomplete(latest)) {
        this.wito.generic_processUpdateToQueue(this, latest, 'session');
    } else {
        this.updateFireRequest();
    }
}


witoSessionClass.prototype.updateFireRequest = function() {
    // this.wito.debug('fire update session ref('+this.ref+')');
    var postObj = this.wito.ajax_prep(this.wito.flag_actionGET | this.wito.flag_targetSESSION);
    postObj.session = this.createPartial(this.wito.flag_actionGET);
    this.wito.ajax_update(postObj);
}


witoSessionClass.prototype.incomplete = function(obj) {
    if (!obj) obj = this;
    return(!obj.flagedit);
    // return(obj.data == undefined);
}


// implements UpdateableVisualInterface
witoSessionClass.prototype.updateUI = function(prop, before, after) {
    switch(prop) {
        case 'data' :
            var update = after;
            if (this.wito.toolbox) {
                if (this.wito.toolbox.isVisible()) {
                    update = this.wito.toolbox.sessionSelect.makeDisplayText(this.ref, after, this.threadList.getCount());
                }
            }
            witoQuery('#' + 'wito_sess_opt-' + this.ref).html(update);
            break;
        default :
            // this.wito.debug(prop+' has changed ('+before+','+after+')');
            break;
    }
}


witoSessionClass.prototype.show = function(postToServer) {
    this.threadList.show();
    /**
     * haven't decided about this yet
     * 
    if (postToServer) {
        var postObj = this.wito.ajax_prep(this.wito.flag_actionSHOW | this.wito.flag_targetSESSION);
        postObj.session = this.createPartial(this.wito.flag_actionSHOW);
        this.wito.ajax_update(postObj);
    }
     */
}


witoSessionClass.prototype.hide = function(postToServer) {
    this.threadList.hide();
    /**
     * haven't decided about this yet
     * 
    if (postToServer) {
        var postObj = this.wito.ajax_prep(this.wito.flag_actionHIDE | this.wito.flag_targetSESSION);
        postObj.session = this.createPartial(this.wito.flag_actionHIDE);
        this.wito.ajax_update(postObj);
    }
     */
}


witoSessionClass.prototype.setCurrent = function(postToServer) {
    this.sessionList.setCurrent(this.ref);
    if (postToServer) {
        // pass session up to server
        var postObj = this.wito.ajax_prep(this.wito.flag_actionSELECT | this.wito.flag_targetSESSION);
        postObj.session = this.createPartial(this.wito.flag_actionSELECT);
        this.wito.ajax_update(postObj);
    }
}


witoSessionClass.prototype.createPartial = function(action) {
    // rehash before sending to server, [run-time] cascade aggregates
    this.hash.hash_calculate(true);             // cascade up (hval)
    this.hash.hash_aggregate(true, true, "|");  // cascade up and down (hchild)
    // send sub-object to server
    var pso = new Object;
    pso.ref = this.ref;
    pso.hval = this.hash.hval;
    pso.hchild = this.hash.hchild;
    if (action & this.wito.flag_actionSELECT) {
        pso.flagdisp = this.flagdisp;
    }
    if (action & this.wito.flag_actionEDIT) {
        pso.flagedit = this.flagedit;
    }
    return(pso);
}


witoSessionClass.prototype.isSelected = function() {
    return(this.flagdisp & this.wito.flag_displaySELECTED);
}


witoSessionClass.prototype.isVisible = function() {
    return(this.flagdisp & this.wito.flag_displayVISIBLE);
}


witoSessionClass.prototype.isDeleted = function() {
    return(this.flagdisp & this.wito.flag_displayDELETED);
}


witoSessionClass.prototype.edit_begin = function(edobj) {
    if (this.editing != null) {
        // if we were previously editing this object
        if (this.editing.obj == edobj) {
            // just commit and return
            this.editing.commitCurrent();
            // note duplication because of return
            this.editing = null;
            return;
        } else {
            // otherwise commit and flow into edit
            this.editing.commitCurrent();
            this.editing = null;
        }
        // destroy old object
    }
    this.editing = new witoEditingClass();
    this.editing.init(this.wito, this, edobj);
}





/**
 * witoSessionList
 *   list of sessions
 *  
 * implements
 *   ListInterface
 */
witoSessionListClass = function() {
    // constructor (sessionList)
}


witoSessionListClass.prototype.init = function(wito, rdo) {
    this.list = new Array();
    this.wito = wito;
    this.parent = null;
    // initialise vars
    this.toolbox = null;           // toolbox for showing session list
    this.current = 0;
    this.flagdisp = this.wito.flag_displayVISIBLE;
    this.editing = null;           // all sessions created with editing
    // add passed sessions to list
    this.recv_sessions(rdo[this.wito.server_side_sessionList_NAME]);
    // setup selected (and pass up)
    var sess = this.deriveCurrent();
    sess.setCurrent();
    this.current = sess.ref;
}


witoSessionListClass.prototype.clone = function() {
    // this object does not contain any objects, so use the lightweight copy code
    var temp = new witoSessionListClass();
    for (key in this) { 
        temp[key] = this[key]; 
    } 
    return temp;
}


witoSessionListClass.prototype.get_default = function() {
    if (this.wito.default_session) return(this.wito.default_session);
    var session = new witoSessionClass();
    // session ref is initially unassigned
    session.ref = this.wito.ref_UNSET;
    // default display (show if selected) and edit (read only) settings
    session.data = 'no title';
    session.flagdisp = this.wito.flag_displayVISIBLE | this.wito.flag_displayVISIFSEL; // new sessions are visible by default
    session.flagedit = this.wito.flag_actionNONE;
    // setup constants
    session.addOffsetX = 0;
    session.addOffsetY = 0;
    session.addOffsetXinc = 15;
    session.addOffsetYinc = 30;
    session.addOffsetXmod = 105;
    session.addOffsetYmod = 210;
    // cache default
    this.wito.default_session = session;
    return(this.wito.default_session);
}


witoSessionListClass.prototype.recv_default = function(server_session) {
    session = this.get_default();
    // overwrite with defaults from server
    session.copyFrom(server_session);
    // set as default (redundant)
    this.wito.default_session = session;
}


witoSessionListClass.prototype.new_session = function(template) {
    if (!template) template = this.get_default();
    // copy template to create new object
    session = template.clone();
    session.init(this.wito, this);
    session.ref = this.wito.ref_UNSET;
    // add to list (overwrites ref)
    this.add(session);
    // pass session up to server
    var postObj = this.wito.ajax_prep(this.wito.flag_actionNEW | this.wito.flag_targetSESSION);
    postObj.session = session.createPartial(this.wito.flag_actionNEW);
    postObj.callback = this.new_session_callback;
    this.wito.ajax_update(postObj);
    return(session);
}


witoSessionListClass.prototype.new_session_callback = function(rdo, context){
    // remember 'this' is a postObj (following an ajax callback) not a witoSessionList
    var new_session = context.sessionList.get(this.session.ref);
    var old_session = context.sessionList.getCurrent();
    context.toolbox.sessionSelect.renderAttachOption(new_session);
    context.toolbox.sessionSelect.forceTo(new_session.ref);
    if (old_session) old_session.hide();
    new_session.setCurrent(true); // new session then fires 'select' request
    if (context.feedback_visible) {
        new_session.show();
    }
    // adding a session, there must now be at least two
    context.toolbox.sessionSelect.show();
}


witoSessionListClass.prototype.recv_session = function(recvd) {
    template = this.get_default();
    // copy template to create new object
    session = template.clone();
    session.init(this.wito, this);
    session.ref = this.wito.ref_UNSET; // copyFrom will set with recvd.ref
    // only copy in the fields already defined (from default)
    session.copyFrom(recvd, session);
    if (recvd[this.wito.server_side_threadList_NAME]) {
        var tlist = recvd[this.wito.server_side_threadList_NAME];
        for (var i=0 ; i<tlist.length ; ++i) {
            var t = tlist[i];
            session.threadList.recv_thread(t);
        }
    }
    this.add(session);
    // if session was added incomplete, fire request to server to update
    if (session.incomplete(recvd)) {
        session.updateFireRequest();
    }
    return(session);
}


witoSessionListClass.prototype.recv_sessions = function(rdo_sessOOM) {
    // rdo_sessOOM = return data object - sessions (one or more)
    if (typeof(rdo_sessOOM.length) == 'undefined') {
        this.recv_session(rdo_sessOOM);
    }
    else {
        for (var i = 0 ; i<rdo_sessOOM.length ; ++i) {
            this.recv_session(rdo_sessOOM[i]);
        }
    }
}


// implement ListInterface
witoSessionListClass.prototype.compare = function(latest) {
    this.wito.generic_compareList(this, latest, 'session');
}


witoSessionListClass.prototype.add = function(sess) {
    // rehash before adding to list, [init-time] delay cascading
    sess.hash.hash_calculate(false);
    if (sess.ref == this.wito.ref_UNSET) {
        // assign sess identifier (if not recvd from server)
        sess.ref = this.list.length;
    }
    // append to sessionList
    this.list[sess.ref] = sess;
}


witoSessionListClass.prototype.get = function(ref) {
    return(this.wito.generic_get(this, ref, 'session'));
}


witoSessionListClass.prototype.getList = function() {
    return(this.list);
}


witoSessionListClass.prototype.receive = function(latest) {
    return(this.recv_session(latest));
}


witoSessionListClass.prototype.deriveCurrent = function() {
    // work through all sessions and test flags to find current
    for (i=0 ; i<this.list.length ; ++i) {
        var session = this.list[i];
        // debugString += 'session '+i+' flagdisp '+session.flagdisp+'\r\n';
        if (session.isSelected()) {
            // this.wito.debug('selecting session ref '+session.ref);
            return(this.get(session.ref));
        }
    }
    // if not found
    return(this.getLast());
}


/**
 * Session list class keeps track of current session
 * - although wito also caches (wito.session) so could use that
 */
witoSessionListClass.prototype.getCurrent = function() {
    var ref = this.current;
    if (ref > (this.list.length - 1)) return(null);
    return(this.get(ref));
}


witoSessionListClass.prototype.setCurrent = function(ref) {
    if (ref > (this.list.length - 1)) return(null);
    this.current = ref;
    var session = this.get(ref);
    this.wito.session = session;
    // check count of current session
    if (session.threadList.count == 0) {
        this.wito.heartbeat.suspend();
    }
    if (session.threadList.count > 0) {
        this.wito.heartbeat.resume();
    }
    return(session);
}


witoSessionListClass.prototype.getNext = function() {
    return(this.getDelta(1));
}


witoSessionListClass.prototype.getPrevious = function() {
    return(this.getDelta(-1));
}


witoSessionListClass.prototype.getDelta = function(delta) {
    var ref = this.current + delta;
    if (ref > (this.list.length - 1)) ref = 0;
    if (ref < 0) ref = this.list.length - 1;
    return(this.get(ref));
}


witoSessionListClass.prototype.getLast = function() {
    var ref = this.list.length - 1;
    // this.wito.debug(this.wito.__objectToString(this.get(ref)));
    return(this.get(ref));
}


witoSessionListClass.prototype.getCount = function() {
    return(this.list.length);
}


witoSessionListClass.prototype.show = function(toolbox) {
    this.toolbox = toolbox;
    for (i=0 ; i<this.list.length ; ++i) {
        var session = this.list[i];
        toolbox.addSelectOption(session);
    }
}


witoSessionListClass.prototype.isVisible = function() {
    return(this.flagdisp & this.wito.flag_displayVISIBLE);
}


witoSessionListClass.prototype.feedback_toggle = function() {
    var session = this.getCurrent();
    if (this.isVisible()) {
        if (session) session.hide();
        this.flagdisp &= (this.wito.flag_displayVISIBLE ^ this.wito.flag_displayMASK);
        witoQuery('#wito_hide').html('Show feedback');
    } else {
        if (session) session.show();        
        this.flagdisp |= this.wito.flag_displayVISIBLE;
        witoQuery('#wito_hide').html('Hide feedback');
    }
}


/**
 *
 * Toolbox
 *
 */
witoToolboxClass = function() {
    // constructor (toolbox)
}


witoToolboxClass.prototype.init = function(wito, sessionList) {
    this.wito = wito;
    this.sessionSelect = null;
    // create hidden toolbox
    this.attach(this.render());
    // attach listeners
    witoQuery('#wito_hide').bind('click', null, this.event_feedback_toggle(this));
    witoQuery('#wito_session_new').bind('click', null, this.event_session_new(this));
    // attach session list to toolbox
    sessionList.show(this);
    this.visible = true;
}


witoToolboxClass.prototype.attach = function(html) {
    // protect against repeat calls
    if (this.jq) return;
    // append to end of thread base div
    this.wito.page.threadBase.append(html);
    this.jq = witoQuery('#wito_toolbox');
}


witoToolboxClass.prototype.render = function() {
    var imagepath = this.wito.page_getAssetPath() + 'images/';
    var html = '';
    html += '<div class="wito_toolbox" id="wito_toolbox">';
    // hide/show all feedback
    html += '<p class="wito_toolbox_button wito_toolbox_button_text"><a id="wito_hide" href="#">'
    // html += '<img src="'+imagepath+'arrow.gif" alt="Hide feedback" />';
    html += 'Hide feedback';
    html += '</a></p>';
    // hide my feedback
    // hide others
    // session display mode (cycles all, mine on top, just session one at a time)
    // create new session
    html += '<p class="wito_toolbox_button wito_toolbox_button_text last"><a id="wito_session_new" href="#">New session</a></p>';
    // create new thread
    // save, saving, saved button
    html += '<div class="wito_clear"></div>';
    html += '&nbsp;';
    html += '</div>';
    return(html);
}


witoToolboxClass.prototype.addSelectOption = function(session) {
    // build sessionSelect object
    if (!this.sessionSelect) {
        this.sessionSelect = new witoSessionSelectClass();
        this.sessionSelect.init(this.wito, this);
    }
    // attach (hidden)
    this.sessionSelect.renderAttachOption(session);
    // show if multiple sessions
    if (this.sessionSelect.getCount() >= 2) {
        this.sessionSelect.show();
    }
}


witoToolboxClass.prototype.show = function() {
    this.jq.animate({height: "show", opacity: "show"},1000,null);
}


witoToolboxClass.prototype.isVisible = function() {
    return(this.visible);
}


witoToolboxClass.prototype.event_feedback_toggle = function(context) {
    return( function(e) {
        context.wito.sessionList.feedback_toggle();
        context.wito.event_stop_bubble(e);
    });
}


witoToolboxClass.prototype.event_session_new = function(context) {
    return( function(e) {
        context.wito.sessionList.new_session();
        context.wito.event_stop_bubble(e);
    });
}


/**
 *
 * Toolbox::SessionSelect
 *
 */
witoSessionSelectClass = function() {
    // constructor (sessionSelect)
}


witoSessionSelectClass.prototype.init = function(wito, toolbox) {
    this.wito = wito;
    this.toolbox = toolbox;
    this.optionSeq = 0;
    this.toolbox.jq.append(this.render());
    this.jq = witoQuery('#wito_sessionSelect');
    // attach change listeners
    this.jq.bind('change', null, this.event_change(this));
    witoQuery('#wito_sessionSelect_prev').bind('click', null, this.event_clickDelta(this, -1));
    witoQuery('#wito_sessionSelect_next').bind('click', null, this.event_clickDelta(this, 1));
}


witoSessionSelectClass.prototype.render = function() {
    var html = '';
    html += '<div id="wito_sessionSelect_outer" style="display:none;">'
    html += '<p class="wito_toolbox_button"><a id="wito_sessionSelect_prev" class="pointer" href="#">&laquo;</a></p>';
    html += '<p class="wito_toolbox_elem">';
    html += '<select name="wito_sessionSelect" id="wito_sessionSelect">';
    html += '</select>';
    html += '</p>';
    html += '<p class="wito_toolbox_button"><a id="wito_sessionSelect_next" class="pointer" href="#">&raquo;</a></p>';
    html += '<div class="wito_clear"></div>';
    html += '</div>';
    return(html);
}


witoSessionSelectClass.prototype.event_change = function(context) {
    return( function(e) {
        context.change(e);
    });
}


witoSessionSelectClass.prototype.change = function(e) {
    var new_session = this.wito.sessionList.get(this.jq.val());
    var old_session = this.wito.session;
    // out with the old, in with the new
    if (new_session.ref != old_session.ref) {
        old_session.hide();
        if (this.wito.feedback_visible) {
            new_session.show();
        }
        // change current session
        new_session.setCurrent(true);
    }
}


witoSessionSelectClass.prototype.event_clickDelta = function(context, delta) {
    return( function(e) {
        context.clickDelta(delta);
        context.wito.event_stop_bubble(e);
    });
}


witoSessionSelectClass.prototype.clickDelta = function(delta) {
    var new_session = this.wito.sessionList.getDelta(delta);
    this.wito.session.hide();
    this.forceTo(new_session.ref);
    if (this.wito.feedback_visible) {
        new_session.show();
    }
    new_session.setCurrent(true);
}


witoSessionSelectClass.prototype.renderAttachOption = function(session) {
    var html = '';
    var owner = session.flagedit & this.wito.flag_USASUSER;
    html += '<option ';
    html += 'value="'+session.ref+'" ';
    html += 'name="wito_sess_opt-'+session.ref+'" ';
    html += 'id="wito_sess_opt-'+session.ref+'" ';
    html += 'class="'+(owner ? 'wito_sess_iam' : '')+'" ';
    if (this.wito.session.ref == session.ref) {
        html += 'selected="selected" ';
    }
    html += '>';
    html += this.makeDisplayText(session.ref, session.data, session.threadList.getCount());
    html += '</option>';
    this.jq.append(html);
    this.optionSeq++;
}


witoSessionSelectClass.prototype.makeDisplayText = function(ref, data, count) {
    var text = ( data == "" ? 'untitled' : data)+' ('+count+')';
    return(text);
}


witoSessionSelectClass.prototype.getCount = function() {
    return(this.optionSeq);
}


witoSessionSelectClass.prototype.forceTo = function(ref) {
    this.jq.val(ref);
}


witoSessionSelectClass.prototype.show = function() {
    var outer = witoQuery('#wito_sessionSelect_outer');
    outer.show();
}


witoSessionSelectClass.prototype.hide = function() {
    var outer = witoQuery('#wito_sessionSelect_outer');
    outer.hide();
}



/**
 *
 * Edit
 * - aggregated global editing code
 *   + edits are object managed, so easy to multitask
 * - user can only edit one field at a time
 *
 */
witoClass.prototype.edit_begin = function(edobj) {
    var session = this.sessionList.getCurrent(); if (!session) return;
    session.edit_begin(edobj);
}


witoClass.prototype.edit_commitCurrent = function(edobj) {
    var session = this.sessionList.getCurrent(); if (!session) return;
    if (!session.editing) return;
    session.editing.commitCurrent();
    session.editing = null;
}


/**
 *
 * Text editing manager
 *
 */
witoEditingClass = function() {
    // constructor (editing)
}


witoEditingClass.prototype.init = function(wito, session, edobj) {
    this.wito = wito;
    this.parent = session;
    this.obj = edobj;
    if (this.obj.className == 'witoThreadClass') {
        // edit thread title
        this.id = 'wito_thread_paratbar-' + this.obj.ref;
    } else {
        // edit post
        this.id = 'wito_post-' + this.obj.postList.thread.ref + '-' + this.obj.ref + '_data';
    }
    // replace text with editable text field
    var src = new Object();
    src.jq = witoQuery('#'+this.id);
    src.text = src.jq.html();
    // set textarea box dimensions to match replacing paragraph's
    src.text_pos_px = -1;
    src.text_height = src.jq.height();
    if (src.text_height.indexOf) if ((src.text_pos_px = src.text_height.indexOf('px'))) src.text_height = src.text_height.substr(0,src.text_pos_px);
    // set default colours
    src.colBack = 'FFFFFF';
    src.colText = '000000';
    src.text_minHeight = 0;
    // call listener if attached to correct height/colour/button text etc.
    if (this.obj.textEditListener) {
        this.obj.textEditListener(src);
    }
    var newtext = '<textarea class="wito_editbox" '+
        'type="text" id="text_'+this.id+'" '+
        'style="height:'+src.text_height+'px;'+
        (src.text_minHeight ? 'min-height:'+src.text_minHeight+'px;' : '')+
        'background-color:#'+src.colBack+';'+
        'color:#'+src.colText+';'+
        '" '+
        'wordwrap="true" '+
        '>'+src.text+'</textarea>';
    src.jq.html(newtext);
    // clean up
    src = null;
    // read back textarea
    this.jq = witoQuery('#text_'+this.id);
    // make dummy listener ready for first-key check
    this.dummyChecked = false;
    // check caret into edit box
    this.setCaret('text_'+this.id);
    // check keydown
    this.jq.keydown(this.event_keydown(this));
    // listen for click outside box to end edit
    witoQuery(document).click(this.event_click(this));
}


witoEditingClass.prototype.destroy = function() {
    if (this.dummy) {
        this.dummy.destroy();
    }
    this.dummy = null;
}


witoEditingClass.prototype.setCaret = function(target_id) {
    var target = document.getElementById(target_id);
    if (target.createTextRange) {
        var range = target.createTextRange();
        range.collapse(false);
        range.select();
    } else if (target.setSelectionRange) {
        target.focus();
        var ilen = target.value.length;
        target.setSelectionRange(ilen, ilen);
    }
}


witoEditingClass.prototype.commitCurrent = function() {
    // return edit field to read-only text
    var targetjq = witoQuery('#'+this.id);
    var newdata = this.jq.val();
    targetjq.html(newdata);
    // transform clicked button back (if needed)
    var thread = null;
    if (this.obj.className == 'witoThreadClass') {
        // thread submit/edit button is identical
        thread = this.obj;
    } else {
        witoQuery('#wito_post_edit_hook-'+this.obj.postList.thread.ref+'-'+this.obj.ref).html('edit');
    }
    // tell the object to update itself
    // - because this could be triggered by another edit beginning
    this.obj.commitEdit(newdata);
    if (thread) {
        thread.applyDimensionIfHeightChange();
    }
    // clean up
    this.destroy();
}


witoEditingClass.prototype.checkDummy = function() {
    this.dummyChecked = true;
    // if the [thread/post] has an autoGrow policy...
    if (this.obj.autoGrow) {
        // and that policy says grow...
        if (this.obj.autoGrow()) {
            this.dummy = new witoEditingDummyClass();
            this.dummy.init(this.wito, this, this.jq);
        }
    }
}

witoEditingClass.prototype.event_keydown = function(context) {
    return( function(e) {
        if (!e) var e = window.event;
        key = (e.keyCode ? e.keyCode : e.which);
        if (!context.dummyChecked) context.checkDummy();
        // catch return keystrokes
        if (key == 13) {
            context.wito.edit_commitCurrent();
            context.wito.event_stop_bubble(e);
            return(false);
        }
        return(true);
    });
}


witoEditingClass.prototype.event_click = function(context) {
    return( function(e) {
        if (!e) var e = window.event;
        var evtarget = (witoQuery.browser.msie ? e.srcElement : e.target);
        if (evtarget.id == 'text_'+context.id) {
            // ignore clicks on text box
        } else {
            context.wito.edit_commitCurrent();
        }
        return(true);
    });
}


witoEditingClass.prototype.textUpdatedListener = function() {
    if (this.obj.textUpdatedListener)
        this.obj.textUpdatedListener();
}


witoEditingDummyClass = function() {
    // constructor (editing)
}


witoEditingDummyClass.prototype.init = function(wito, edi, tajq) {
    // single editing mode, could list-ise like threads
    this.ref = 0;
    this.wito = wito;
    this.editing = edi;
    this.tajq = tajq;
    this.delay = 400;
    this.minHeight = this.tajq.css('min-height');
    // setup dummy
    var html = '<div id="wito_dummy-'+this.ref+'" class="wito_dummy" style="'+
        'font-size:'+this.tajq.css('font-size')+';'+
		'font-family:'+this.tajq.css('font-family')+';'+
		'line-height:'+this.tajq.css('line-height')+';'+
		'min-height:'+this.minHeight+';'+
        'width:'+this.tajq.width()+'px;'+
        'padding:'+this.tajq.css('padding')+';'+
    '"></div>';
    this.wito.page.threadBase.append(html);
    this.dumjq = witoQuery('#wito_dummy-'+this.ref);
    // this.wito.debug(this.wito.__objectToString(this.dumjq));
    // setup callback
    var cbfunc = this.event_callback(this);
    this.callback = setInterval(cbfunc, this.delay);
}


witoEditingDummyClass.prototype.destroy = function() {
    // clear callback
    clearInterval(this.callback);
    // detach dummy
    
}


witoEditingDummyClass.prototype.beat = function() {
    // get the text (+10 letters) from the textarea and set it to dummy
    this.dumjq.html(this.tajq.val()+' word word');
    var dumjq_height = this.dumjq.height();
    var tajq_height = this.tajq.height();
    // this.wito.debug('dummy '+dumjq_height+', textarea '+tajq_height);
    if (tajq_height != dumjq_height) {
        this.tajq.height(dumjq_height);
        this.editing.textUpdatedListener();
    }
}


witoEditingDummyClass.prototype.event_callback = function(context) {
    return( function(e) {
        context.beat();
    });
}


/**
 *
 *
 * Object factory
 *
 *
 */

/**
 * factory_init is:
 * - called by init_ajax callback
 * - the first time objects are written to the page
 * pre-requisites: init_page 
 */
witoClass.prototype.factory_init = function() {
    this.online = this.status_ONLINE;
    // loop through current session threads and display
    var session = this.sessionList.getCurrent();
    if (session) session.show();
    // if list of sessions, show sessionbox
    var count = this.sessionList.getCount();
    var showToolbox = false;
    this.toolbox = null;
    if (count > 1) {
        // multiple sessions, show
        showToolbox = true;
    } else if (count == 1) {
        // single session, check for thoughts
        var tcount = session.threadList.getCount();
        if (tcount > 0) {
            showToolbox = true;
        }
    }
    // only display toolbox if appropriate
    if (showToolbox) {
        this.toolbox = new witoToolboxClass();
        this.toolbox.init(this, this.sessionList);
        this.toolbox.show();
    }
}


/**
 * witoThreadList
 *   wito -> session -> threadList
 *  
 * implements
 *   ListInterface
 */
witoThreadListClass = function() {
    // constructor (threadList)
}

/**
 * witoPostList
 *   wito -> session -> threadList -> thread -> postList
 *  
 * implements
 *   ListInterface
 */
witoPostListClass = function() {
    // constructor (postList)
}

// no threadList clone

witoPostListClass.prototype.clone = function() {
    // this object does not contain any objects, so use the lightweight copy code
    var temp = new witoPostListClass();
    for (key in this) { 
        temp[key] = this[key]; 
    } 
    return temp;
}


witoThreadListClass.prototype.init = function(wito, session) {
    this.list = new Array();
    this.wito = wito;
    this.session = session;
    this.parent = this.session;
    this.maxz = 0;
    this.count = 0;
}


witoPostListClass.prototype.init = function(wito, thread) {
    this.list = new Array();
    this.wito = wito;
    this.thread = thread;
    this.parent = this.thread;
    this.count = 0;
}


/**
 * get_default thread
 *   default attribute inheritance
 *     local: static values defined here
 */
witoThreadListClass.prototype.get_default = function() {
    if (this.wito.default_thread) return(this.wito.default_thread);
    // thread.init not called until clone produces real thread
    var thread = new witoThreadClass();
    // default values heres should be overwritten by server values
    thread.left = 200;
    thread.top = 200;
    thread.width = 200;
    thread.height = 200;
    thread.data = 'Enter your comment here';
    thread.flagdisp = this.wito.flag_displayVISIBLE;
    thread.flagedit = this.wito.flag_actionEDIT | this.wito.flag_actionAPPEND;
    thread.colour = 0xFFFF33; // yellow
    // start at lowest z
    thread.z = 1;
    // [derived] simple colour Maths
    thread.colourAdd = 0x204080;
    thread.colourTop = 0xFFFFFF;
    thread.colourSub = thread.colourAdd;
    thread.colourBase = thread.colour;
    // constants
    thread.widthShadow = 5;
    thread.heightShadow = 5;
    thread.shadowOffset = 15;
    thread.heightTitlebar = 20; // assume single line only, must read back
    thread.heightStatusbar = 18;
    thread.heightMinPost = 96; // below which we expand the thread height on new_post
    thread.heightMinConfdel = 96; // below which we expand the thread height to show confirmation message
    thread.heightMinEmptyTitleTextarea = 75;
    thread.widthTitlebarIcon = 21;
    thread.widthTitlebarIcons = 2 + (3 * thread.widthTitlebarIcon); // 63 for three icons (>,e,x), 46 for two (>,x)
    thread.widthMin = 160;
    // expanded-state settings
    thread.marginTopExp = 0;
    thread.marginLeftExp = 0;
    // minimised-state settings
    thread.minishape = 'arrow';
    thread.marginTopMini = 20;
    thread.marginLeftMini = 26;
    // colour thresholds
    thread.backgroundColourThreshold = 0x66;
    // place holders
    thread.postList = null; // initialised on thread.init()
    thread.postBase = null; // initialised on thread.attach()
    // thread ref is initially unassigned
    thread.ref = this.wito.ref_UNSET;
    // cache default
    this.wito.default_thread = thread;
    return(this.wito.default_thread);
}


witoPostListClass.prototype.get_default = function() {
    if (this.wito.default_post) return(this.wito.default_post);
    var post = new witoPostClass();
    // post.init not called until clone produces real post
    post.data = 'Enter your comment here';
    post.flagdisp = this.wito.flag_displayVISIBLE;
    post.flagedit = this.wito.flag_actionEDIT;
    // post ref is initially unassigned
    post.ref = this.wito.ref_UNSET;
    // cache default
    this.wito.default_post = post;
    return(this.wito.default_post);
}


witoThreadListClass.prototype.recv_default = function(server_thread) {
    thread = this.get_default();
    // overwrite with defaults from server
    thread.copyFrom(server_thread);
    // set as default (redundant)
    this.wito.default_thread = thread;
}


witoPostListClass.prototype.recv_default = function(server_post) {
    post = this.get_default();
    // overwrite with defaults from server
    post.copyFrom(server_post);
    // set as default (redundant)
    this.wito.default_post = post;
}


witoThreadListClass.prototype.new_thread = function(template) {
    if (!template) template = this.get_default();
    // copy template to create new object
    thread = template.clone();
    thread.init(this.wito, this);
    thread.offsetPosition();
    // add to list
    this.add(thread);
    // raise thread to top
    this.bringToFront(thread);
    // pass thread up to server
    var postObj = this.wito.ajax_prep(this.wito.flag_actionNEW | this.wito.flag_targetTHREAD);
    postObj.thread = thread.createPartial(this.wito.flag_actionNEW);
    // this.wito.debug(thread.hash.debugHash('thread'));
    // this.wito.debug(thread.threadList.session.hash.debugHash('session'));
    this.wito.ajax_update(postObj);
    // this.wito.debug(this.wito.__objectToString(postObj.thread));
    return(thread);
}


witoPostListClass.prototype.new_post = function(template) {
    if (!template) template = this.get_default();
    // copy template to create new object
    post = template.clone();
    post.init(this.wito, this);
    this.add(post);
    // pass thread up to server
    var postObj = this.wito.ajax_prep(this.wito.flag_actionNEW | this.wito.flag_targetPOST);
    postObj.post = post.createPartial(this.wito.flag_actionNEW);
    this.wito.ajax_update(postObj);
    return(post);
}


witoThreadListClass.prototype.recv_thread = function(recvd) {
    template = this.get_default();
    // copy template to create new object
    thread = template.clone();
    thread.init(this.wito, this);
    // only copy in the fields already defined (from default)
    thread.copyFrom(recvd, thread);
    if (recvd[this.wito.server_side_postList_NAME]) {
        var plist = recvd[this.wito.server_side_postList_NAME];
        for (var i=0 ; i<plist.length ; ++i) {
            var p = plist[i];
            thread.postList.recv_post(p);
        }
    }
    this.add(thread);
    // this.wito.debug('part thread received '+this.wito.__objectToString(recvd));
    // this.wito.debug('corresponding thread currently '+this.wito.__objectToString(thread));
    // if thread was added incomplete, fire request to server to update
    if (thread.incomplete(recvd)) {
        thread.updateFireRequest();
    }
    return(thread);
}


witoPostListClass.prototype.recv_post = function(recvd) {
    template = this.get_default();
    // copy template to create new object
    post = template.clone();
    post.init(this.wito, this);
    // only copy in the fields already defined (from default)
    post.copyFrom(recvd, post);
    this.add(post);
    // if post was added incomplete, fire request to server to update
    if (post.incomplete(recvd)) {
        post.updateFireRequest();
    }
    return(post);
}


// implement ListInterface
witoThreadListClass.prototype.compare = function(latest) {
    this.wito.generic_compareList(this, latest, 'thread');
}


witoPostListClass.prototype.compare = function(latest) {
    this.wito.generic_compareList(this, latest, 'post');
}


witoThreadListClass.prototype.add = function(thread) {
    // rehash before adding to list, [init-time] delay cascading
    thread.hash.hash_calculate(false);
    if (thread.ref != this.wito.ref_UNSET) {
        // use ref in thread
    } else {
        // assign thread identifier (ref, not db id)
        thread.ref = this.list.length;
    }
    // append to threadList
    this.list[thread.ref] = thread;
    // update threadList derived vars
    this.checkMaxZ(thread.z);
    this.count++;
    // if count now non-zero, resume heartbeats
    if (this.count > 0) {
        this.wito.heartbeat.resume();
    }
    // update UI component
    this.session.updateUI('data',this.session.data,this.session.data);
}


witoPostListClass.prototype.add = function(post) {
    // rehash before adding to list, [init-time] delay cascading
    post.hash.hash_calculate(false);
    if (post.ref != this.wito.ref_UNSET) {
        // use ref in post
    } else {
        // assign post identifier (ref, not db id)
        post.ref = this.list.length;
    }
    // append to threadList
    this.list[post.ref] = post;
    this.count++;
}


witoThreadListClass.prototype.remove = function(thread) {
    // nullify reference
    this.list[thread.ref] = null;
    // update count
    this.count--;
    // if count now zero, suspend heartbeats
    if (this.count == 0) {
        this.wito.heartbeat.suspend();
    }
    // update UI component
    this.session.updateUI('data',this.session.data,this.session.data);
}


witoThreadListClass.prototype.get = function(ref) {
    return(this.wito.generic_get(this, ref, 'thread'));
}


witoPostListClass.prototype.get = function(ref) {
    return(this.wito.generic_get(this, ref, 'post'));
}


witoThreadListClass.prototype.getList = function() {
    return(this.list);
}


witoPostListClass.prototype.getList = function() {
    return(this.list);
}


witoThreadListClass.prototype.receive = function(latest) {
    return(this.recv_thread(latest));
}


witoPostListClass.prototype.receive = function(latest) {
    return(this.recv_post(latest));
}


witoThreadListClass.prototype.getCount = function() {
    return(this.count);
}


witoThreadListClass.prototype.show = function() {
    for (i=0 ; i<this.list.length ; ++i) {
        var thread = this.list[i];
        if (thread) {
            thread.renderAttachShow();
        }
    }
}


witoThreadListClass.prototype.hide = function() {
    for (i=0 ; i<this.list.length ; ++i) {
        var thread = this.list[i];
        if (thread) {
            thread.hide();
            thread.detach();
        }
    }
}


witoThreadListClass.prototype.checkMaxZ = function(z) {
    if (z > this.maxz) this.maxz = z;
}


witoThreadListClass.prototype.bringToFront = function(thread) {
    this.maxz++;
    thread.z = this.maxz;
    // if thread is visible, update
    if (thread.jq) {
        thread.jq.css('z-index', thread.z);
    }
}


/**
 * Blueprint for thread
 * - wito -> session -> threadList -> thread
 * 
 * Blueprint for post
 * - wito -> session -> threadList -> thread -> postList -> post
 * 
 */
function witoThreadClass() {
    // constructor (thread)
}

function witoPostClass() {
    // constructor (post)
}


witoThreadClass.prototype.init = function(wito, threadList) {
    this.wito = wito;
    this.className = "witoThreadClass";
    this.threadList = threadList;
    this.postList = new witoPostListClass()
    this.postList.init(this.wito, this);
    this.hash = new witoHashClass();
    this.hash.init(wito, this.wito.hash_fieldsTHREAD, this, this.postList, this.threadList.parent);
    this.locked = false;
}


witoPostClass.prototype.init = function(wito, postList) {
    this.wito = wito;
    this.postList = postList;
    this.className = "witoPostClass";
    this.hash = new witoHashClass();
    this.hash.init(wito, this.wito.hash_fieldsPOST, this, null, this.postList.parent);
    // posts have no children, i.e. no one below to pass up aggregates/zeros
    this.hash.hchild = 0;
    this.locked = false;
}


witoThreadClass.prototype.clone = function() { 
    // clone object properties
    var temp = new witoThreadClass(); 
    temp.copyFrom(this);
    // clone sub-objects
    if (this.postList)
        temp.postList = this.postList.clone();
    return temp; 
}


witoPostClass.prototype.clone = function() { 
    // this object does not contain any objects, so use the lightweight copy code
    var temp = new witoPostClass();
    temp.copyFrom(this);
    return temp; 
}


/**
 * copyFrom
 * - copies data from master object into this object
 * + optionally specify keymaster, incase copying from hostile object
 */
witoThreadClass.prototype.copyFrom = function(master) {
    var keymaster = master;
    if (arguments.length > 1) keymaster = arguments[1];
    for (key in keymaster) {
        if (master[key] != undefined) {
            this[key] = master[key];
        }
    }
}


witoPostClass.prototype.copyFrom = function(master) {
    var keymaster = master;
    if (arguments.length > 1) keymaster = arguments[1];
    for (key in keymaster) {
        if (master[key] != undefined) {
            this[key] = master[key];
        }
    }
}


// implements UpdateableInterface
witoThreadClass.prototype.compare = function(latest) {
    // compare hash to see if we need to update
    if (this.hash.hval != latest.hval) {
        this.update(latest);
    }
    // if children updated
    if (this.hash.hchild != latest.hchild) {
        // see if sublist defined in latest, else fire update request
        if (this.postList && latest[this.wito.server_side_postList_NAME]) {
            this.postList.compare(latest[this.wito.server_side_postList_NAME]);
        } else {
            this.updateFireRequest();
        }
    }
}


witoPostClass.prototype.compare = function(latest) {
    // compare hash to see if we need to update
    if (this.hash.hval != latest.hval) {
        this.update(latest);
    }
    // no children to update
}


witoThreadClass.prototype.update = function(latest) {
    // decide if this is a populated update, or a thin update which needs populating
    if (!this.incomplete(latest)) {
        // this.wito.debug('rest of thread update received '+this.wito.__objectToString(latest));
        this.wito.generic_processUpdateToQueue(this, latest, 'thread');
    } else {
        this.updateFireRequest();
    }
}


witoPostClass.prototype.update = function(latest) {
    if (!this.incomplete(latest)) {
        this.wito.generic_processUpdateToQueue(this, latest, 'post');
    } else {
        this.updateFireRequest();
    }
}


witoThreadClass.prototype.updateFireRequest = function() {
    // this.wito.debug('fire update thread ref('+this.ref+')');
    var postObj = this.wito.ajax_prep(this.wito.flag_actionGET | this.wito.flag_targetTHREAD);
    postObj.thread = this.createPartial(this.wito.flag_actionGET);
    this.wito.ajax_update(postObj);
}


witoPostClass.prototype.updateFireRequest = function() {
    // this.wito.debug('fire update post ref('+this.ref+')');
    var postObj = this.wito.ajax_prep(this.wito.flag_actionGET | this.wito.flag_targetPOST);
    postObj.post = this.createPartial(this.wito.flag_actionGET);
    this.wito.ajax_update(postObj);
}


witoThreadClass.prototype.incomplete = function(obj) {
    if (!obj) obj = this;
    return(!obj.flagedit);
    // return(obj.data == undefined);
}


witoPostClass.prototype.incomplete = function(obj) {
    if (!obj) obj = this;
    return(!obj.flagedit);
    // return(obj.data == undefined);
}


witoThreadClass.prototype.lock = function() {
    if (!this.locked) this.updateUI('beginUpdate');
    this.locked = true;
}


witoPostClass.prototype.lock = function() {
    this.locked = true;
}


witoThreadClass.prototype.unlock = function() {
    if (this.locked) this.updateUI('endUpdate');
    this.locked = false;
}


witoPostClass.prototype.unlock = function() {
    this.locked = false;
}


// implements UpdateableVisualInterface
witoThreadClass.prototype.updateUI = function(prop, before, after) {
    // handle deletes up front
    if ((prop == 'flagdisp') &&
        (after == this.wito.flag_displayDELETED) &&
        (before != this.wito.flag_displayDELETED)) {
        this.deletex(false);
    }

    // for everything else, only make UI change if object is now visible
    if (!this.isVisible()) return;
    if (!this.jq) {
        // create UI element to update
        this.renderAttachShow();
    } else {
        // ...or update existing UI element
        // this.wito.debug(prop+' now '+after+"px");
        switch(prop) {
            case 'top' :
            case 'left' :
            case 'topleft' :
                this.updateUI('fadeOut');
                this.jq.animate({top: this.top+"px", left: this.left+"px"});
                this.updateUI('fadeIn');
                break;
            case 'width' :
            case 'height' :
            case 'widthheight' :
                // width/height updated (this[prop] = after)
                this.applyDimensionChangeUIonly(true);
                // foreign updates may have changed titlebar height, so test/update
                this.applyDimensionIfHeightChange();
                break;
            case 'z' :
                this.jq.css('z-index', after);
                break;
            case 'colour' :
                this.colchange(after, false);
                break;
            case 'data' :
                witoQuery('#wito_thread_paratbar-' + this.ref).html(after);
                // text changes in titlebar may have changed height
                this.applyDimensionIfHeightChange();
                break;
            case 'flagdisp' :
                // find changed bits by XOR
                var bitdiff = before ^ after;
                // this.wito.debug(prop+' has changed ('+before+','+after+'), bitdiff '+bitdiff);
                // if bit is set, use action to change but don't update the server
                if (bitdiff & this.wito.flag_displayMINIMISED) {
                    this.minimise_restore(after & this.wito.flag_displayMINIMISED, false);
                }
                if (bitdiff & this.wito.flag_displayCONFDEL) {
                    this.confdel_unconfdel(after & this.wito.flag_displayCONFDEL, false);
                }
                break;
            case 'fadeOut' :
                this.jq.animate({opacity: 0.5},500);
                break;
            case 'fadeIn' :
                this.jq.animate({opacity: 1.0},500);
                break;
            case 'skip' :
            default :
                // other changes don't necessarily have a visual component
                // this.wito.debug(prop+' has changed ('+before+','+after+')');
                break;
        }
    }
}


witoPostClass.prototype.updateUI = function(prop, before, after) {
    // handle deletes up front
    if ((prop == 'flagdisp') &&
        (after == this.wito.flag_displayDELETED) &&
        (before != this.wito.flag_displayDELETED)) {
        this.deletex(false);
    }

    if (!this.isVisible()) return;
    if (!this.jq) {
        // create UI element to update
        this.renderAttachShow();
    } else {
        // ...or update existing UI element
        switch(prop) {
            case 'data' :
                witoQuery('#' + 'wito_post-' + this.postList.thread.ref + '-' + this.ref + '_data').html(after);
                break;
            case 'skip' :
            default :
                // this.wito.debug(prop+' has changed ('+before+','+after+')');
                break;
        }
    }
}


/**
 * move the new thread so sequential adds don't overlap
 */
witoThreadClass.prototype.offsetPosition = function() {
    this.left += this.threadList.session.addOffsetX;
    this.top += this.threadList.session.addOffsetY;
    this.threadList.session.addOffsetX = (this.threadList.session.addOffsetX + this.threadList.session.addOffsetXinc) % this.threadList.session.addOffsetXmod;
    this.threadList.session.addOffsetY = (this.threadList.session.addOffsetY + this.threadList.session.addOffsetYinc) % this.threadList.session.addOffsetYmod;
}


witoThreadClass.prototype.renderCalc = function(minimised) {
    var dx = 0, dy = this.height;
    // look for two optional arguments
    if (arguments.length == 3) {
        dx = arguments[1];
        dy = arguments[2];
        // fix up dy in this conditional (was previously in 'shadowHeightRight =' assignment)
        dy = dy - this.heightAdd;
    }
    // calculate margins depending on background state
    this.marginLeft = this.marginLeftExp;
    this.marginTop = this.marginTopExp;
    if (minimised) {
        this.marginLeft = this.marginLeftMini;
        this.marginTop = this.marginTopMini;
    }
    // additional width = margin left (if any) + shadow right
    this.widthAdd = this.marginLeft + this.widthShadow;
    // additional height = margin top (if any) + titlebar + statusbar + shadow bottom
    this.heightAdd = this.marginTop + this.heightTitlebar + this.heightStatusbar + this.heightShadow;
    this.shadowHeightRight = (minimised ? this.shadowOffset : dy+this.heightTitlebar+this.heightStatusbar-this.shadowOffset+4);
}


/**
 * render the thread as html
 */
witoThreadClass.prototype.render = function() {
    var draggable = true;
    // states
    var minimised = this.isMinimised();
    var confdel = this.isConfdel();
    var visible = this.isVisible();
    // available buttons/options/functions
    var appendable = this.isAppendable();
    var minimiseable = appendable;
    var deleteable = appendable;
    var editable = appendable;
    var resizeable = appendable;
    var colourable = appendable;
    var connectable = appendable;
    var imagepath = this.wito.page_getAssetPath() + 'images/';
    // colour maths stored in thread
    var html = '';
    // don't show invisible threads
    if (!visible && !confdel) return('');
    // calculate derived dimensional vars
    this.renderCalc(minimised);
    this.colComputeVarients();
    // output html
    html += '<div class="wito_thread'+
                (confdel ? '_archived' : '')+
                (minimised ? ' wito_thread_minimised' : '')+
                '" '+
                'style="top:'+(this.top-this.marginTop)+'px;left:'+(this.left-this.marginLeft)+'px;width:'+(this.width+this.widthAdd)+'px;'+
                'height:'+(minimised ? this.heightAdd : this.height+this.heightAdd)+'px;'+
                'z-index:'+this.z+';' +
                'color:#'+this.colourText+';'+
                '" '+
                'id="wito_thread-'+this.ref+'"'+
            '>';
    html += '<img class="wito_yellow'+
                (draggable ? 'arrowptr' : 'arrownot')+'" '+
                'style="'+
                    'display: '+(minimised ? 'block' : 'none')+'; '+'" '+
                'src="'+imagepath+'yellowarrow.gif" '+
                'id="wito_thread_'+(draggable ? 'arrowptr' : 'arrownot')+'-'+this.ref+'" '+
            '/>';
    // render titlebar (slightly lighter)
    html += '<div class="wito_'+(draggable ? 'titlebar' : 'titlenot')+'" '+
                'id="wito_thread_'+(draggable ? 'titlebar' : 'titlenot')+'-'+this.ref+'" '+
                'style="width:'+this.width+'px;min-height:'+this.heightTitlebar+';'+
                'background-color:#'+this.colourLighten+';'+
                'margin-top:'+this.marginTop+'px;margin-left:'+this.marginLeft+'px;" '+
            '>';
    if (minimiseable) {
        html += '<div class="wito_titlebar_button wito_titlebar_button_left wito_glyphright '+(minimised ? '' : 'wito_glyphdown')+ '" '+
                    'id="wito_thread_arrowglyph-'+this.ref+'"'+
                '>';
        html += '<a href="#" id="wito_thread_minimise_restore_hook-'+this.ref+'">';
        html += '<img src="'+imagepath+'arrow_spacer.gif" border="0" '+
                'alt=">" '+
                '/>';
        html += '</a></div><!-- #wito_thread_arrowglyph-'+this.ref+' -->';
    }
    if (deleteable) {
        html += '<div class="wito_titlebar_button wito_titlebar_button_right wito_deletex" '+
                    'id="wito_thread_confdel-'+this.ref+'"'+
                '>';
        html += '<a href="#" id="wito_thread_confdel_hook-'+this.ref+'">';
        html += '<img src="'+imagepath+'arrow_spacer.gif" alt="delete" border="0" />';
        html += '</a></div><!-- wito_thread_confdel-'+this.ref+' -->';
    }
    if (editable) {
        html += '<div class="wito_titlebar_button wito_titlebar_button_right wito_editpen" '+
                    'id="wito_thread_editpen-'+this.ref+'"'+
                '>';
        html += '<a href="#" id="wito_thread_edit_hook-'+this.ref+'">';
        html += '<img id="wito_thread_editpen_img-'+this.ref+'" src="'+imagepath+'arrow_spacer.gif" alt="edit title" border="0" />';
        html += '</a></div><!-- wito_thread_editpen-'+this.ref+' -->';
    }
    html += '<p class="wito_titlebar_text" '+
                'id="wito_thread_'+(draggable ? "paratbar" : "paratnot")+'-'+this.ref+'" '+
            '>'+(this.data ? this.data : '&nbsp;')+'</p>';
    html += '</div><!-- #wito_thread_titlebar-'+this.ref+' -->';
    // render posts
    html += '<div class="wito_thread_posts'+(minimised ? ' wito_minimised' : '')+'" '+
                'id="wito_thread_posts-'+this.ref+'"'+
                'style="width:'+this.width+'px;height:'+this.height+'px;'+
                'background-color:#'+this.colourBack+';'+
                'margin-left:'+this.marginLeft+'px;" '+
            '>';
    // button seperator
    html += '<div class="wito_clear" id="wito_thread_button_sep-'+this.ref+'"></div>';
    // restore & confirm button (only visible in archived threads)
    if (confdel) {
        html += '<div class="wito_post">';
        html += '<p class="wito_button wito_archived_button wito_button_restore" '+
                    'id="wito_thread_restore-'+this.ref+'"'+
                '>';
        html += '<a href="#" '+
                    'class="wito_archived_button wito_button_restore" '+
                    'id="wito_thread_restore_hook-'+this.ref+'">restore</a>';
        html += '</p><!-- #wito_thread_restore-'+this.ref+'-->';
        html += '<p class="wito_button wito_archived_button wito_button_confdel" '+
                    'id="wito_thread_delete-'+this.ref+'"'+
                '>';
        html += '<a href="#" '+
                    'class="wito_archived_button wito_button_confdel" '+
                    'id="wito_thread_delete_hook-'+this.ref+'">delete</a>';
        html += '</p><!-- #wito_thread_delete-'+this.ref+'-->';
        html += '<p class="wito_data" '+
                    'id="wito_thread_confdel_text-'+this.ref+'"'+
                '>';
        html += 'Are you sure you want to delete this thread, and all the posts it contains?  Click <em>Restore</em> to undo.';
        html += '</p><!-- #wito_thread_confdel_text-'+this.ref+'-->';
        html += '</div>';
    }
    // testing out removal of this para
    //   doesn't seem to be anything, but I'm cautious to remove it
    // html += '<p style="clear: both;"></p>';
    html += '</div><!-- #wito_thread_posts-'+this.ref+' -->';
    // thread status bar
    html += '<div class="wito_thread_status'+(minimised ? ' wito_minimised' : '')+'" '+
                'id="wito_thread_status-'+this.ref+'" '+
                'style="width:'+this.width+'px;height:'+this.heightStatusbar+'px;'+
                'background-color:#'+this.colourBack+';'+
                'margin-left:'+this.marginLeft+'px;" '+
            '>';
    if (!confdel) {
        // add/append link
        if (appendable) {
            html += '<p class="wito_statusbar_button wito_add" id="wito_thread_add-'+this.ref+'"'+'>';
            html += '<a href="#" id="wito_thread_add_hook-'+this.ref+'">';
            html += '<img id="wito_thread_add_img-'+this.ref+'" src="'+imagepath+'backadd.gif" alt="Add more detail" border="0" />';
            html += '</a></p>';
        }
        if (colourable) {
            nextCol = this.colNext(this.colour);
            html += '<div class="wito_statusbar_button wito_linkto" '+
                        'id="wito_thread_linkto-'+this.ref+'" '+
                        'style="background-color:#'+this.colourBack+';"'+
                    '>';
            html += '<a href="#" id="wito_thread_linkto_hook-'+this.ref+'">';
            html += '<img id="wito_thread_linkto_img-'+this.ref+'" src="'+imagepath+'arrow_spacer.gif" alt="Link to another" border="0" />';
            html += '</a></div><!-- #wito_thread_linkto-'+this.ref+' -->';
        }
        if (connectable) {
            nextCol = this.colNext(this.colour);
            html += '<div class="wito_statusbar_button wito_colchange" '+
                        'id="wito_thread_colchange-'+this.ref+'" '+
                        'style="background-color:#'+this.wito.padHex(nextCol,6)+';"'+
                    '>';
            html += '<a href="#" id="wito_thread_colchange_hook-'+this.ref+'">';
            html += '<img id="wito_thread_colchange_img-'+this.ref+'" src="'+imagepath+'arrow_spacer.gif" alt="Change colour" border="0" />';
            html += '</a></div><!-- #wito_thread_colchange-'+this.ref+' -->';
        }
    }
    if (resizeable) {
        html += '<p class="wito_statusbar_button wito_resize" id="wito_resize-'+this.ref+'"'+'>';
        html += '<a href="#" id="wito_thread_resize_hook-'+this.ref+'">';
        html += '<img id="wito_resize_img-'+this.ref+'" src="'+imagepath+'resize.gif" alt="resize thread" border="0" />';
        html += '</a></p>';
    }
    html += '</div><!-- #wito_thread_status-'+this.ref+' -->';
    // shadows
    html += '<div class="wito_shadow wito_shadow_right" id="wito_shadow_right-'+this.ref+'" '+
            'style="height:'+this.shadowHeightRight+'px;top:-'+(this.shadowHeightRight-5)+'px;" '+
            '></div>';
    html += '<div class="wito_shadow wito_shadow_bottom" id="wito_shadow_bottom-'+this.ref+'" '+
            'style="width:'+(minimised ? this.width - this.shadowOffset : this.width-10)+'px;top:'+(minimised ? 0 : 0)+'px;" '+
            '>&nbsp;</div>';
    html += '</div><!-- #wito_thread-'+this.ref+' -->';
    return(html);
}


/**
 * render the post as html
 */
witoPostClass.prototype.render = function() {
    var editable = this.isEditable();
    var visible = this.isVisible();
    var html = '';
    if (visible) {
        html += '<div class="wito_post" '+
                    'id="wito_post-'+this.postList.thread.ref+'-'+this.ref+'"'+
                '>';
        html += '<p class="wito_data" '+
                    'id="wito_post-'+this.postList.thread.ref+'-'+this.ref+'_data"'+
                '>'+this.data+'</p>';
        if (editable) {
            html += '<div class="wito_buttons">';
            html += '<p class="wito_button wito_edit">';
    
            html += '<a href="#" '+
                        'class="wito_button wito_edit"'+
                        'id="wito_post_edit_hook-'+this.postList.thread.ref+'-'+this.ref+'" '+
                    '>edit</a></p>';
            html += '<p class="wito_button wito_button_last wito_delete">';
            html += '<a href="#" '+
                        'class="wito_button wito_delete"'+
                        'id="wito_post_delete_hook-'+this.postList.thread.ref+'-'+this.ref+'" '+
                    '>delete</a></p>';
            html += '&nbsp;</div><!-- wito_post wito_buttons -->';
            html += '<div class="wito_clear">&nbsp;</div>';
        }
        html += '</div><!-- #wito_post-'+this.postList.thread.ref+'-'+this.ref+' -->';
    }
    return(html);
}


/**
 * attach thread html to page
 */
witoThreadClass.prototype.attach = function(html) {
    // protect against repeat calls
    if (this.jq) return;
    // append to end of thread base div
    this.wito.page.threadBase.append(html);
    this.jq = witoQuery('#wito_thread-'+this.ref);
    // read back variable heights and reset outer container height
    this.applyDimensionIfHeightChange();
    // if thread is visible, attach event handlers
    if (this.isVisible()) {
        if (this.isConfdel()) {
            // attach confirm delete thread events
            this.event_delete_function = this.event_delete(this);
            witoQuery('#wito_thread_delete_hook-'+this.ref).bind('click', null, this.event_delete_function);
            this.event_unconfdel_function = this.event_unconfdel(this);
            witoQuery('#wito_thread_restore_hook-'+this.ref).bind('click', null, this.event_unconfdel_function);
            // reuse titlebar buttons for delete restore (in this context)
            this.event_edit_function = this.event_unconfdel(this);
            witoQuery('#wito_thread_edit_hook-'+this.ref).bind('click', null, this.event_unconfdel_function);
            // confdel hook is used to confirm the delete (in this context)
            this.event_confdel_function = this.event_delete(this);
            witoQuery('#wito_thread_confdel_hook-'+this.ref).bind('click', null, this.event_delete_function);
        } else {
            // setup postBase for newly attached thread
            this.postBase = witoQuery('#wito_thread_button_sep-'+this.ref)
            // attach normal thread events
            this.event_iconvis_show_function = this.event_iconvis(this, true);
            var tbar = witoQuery('#wito_thread_titlebar-'+this.ref);
            tbar.bind('mouseover', null, this.event_iconvis_show_function);
            this.event_iconvis_hide_function = this.event_iconvis(this, false);
            tbar.bind('mouseout', null, this.event_iconvis_hide_function);
            this.event_edit_function = this.event_edit(this);
            witoQuery('#wito_thread_edit_hook-'+this.ref).bind('click', null, this.event_edit_function);
            this.event_confdel_function = this.event_confdel(this);
            witoQuery('#wito_thread_confdel_hook-'+this.ref).bind('click', null, this.event_confdel_function);
            this.event_minimise_restore_function = this.event_minimise_restore(this);
            witoQuery('#wito_thread_minimise_restore_hook-'+this.ref).bind('click', null, this.event_minimise_restore_function);
            this.event_add_function = this.event_add(this)
            witoQuery('#wito_thread_add_hook-'+this.ref).bind('click', null, this.event_add_function);
            this.event_colchange_function = this.event_colchange(this)
            witoQuery('#wito_thread_colchange_hook-'+this.ref).bind('click', null, this.event_colchange_function);
            // extra careful on the mousedown event handlers
            this.event_drag_paratbar_function = this.event_dragStart(this, 'wito_thread_paratbar-'+this.ref);
            witoQuery('#wito_thread_paratbar-'+this.ref).bind('mousedown', null, this.event_drag_paratbar_function);
            this.event_drag_titlebar_function = this.event_dragStart(this, 'wito_thread_titlebar-'+this.ref);
            witoQuery('#wito_thread_titlebar-'+this.ref).bind('mousedown', null, this.event_drag_titlebar_function);
            this.event_drag_arrow_function = this.event_dragStart(this, 'wito_thread_arrowptr-'+this.ref);
            witoQuery('#wito_thread_arrowptr-'+this.ref).bind('mousedown', null, this.event_drag_arrow_function);
            this.event_drag_posts_function = this.event_dragStart(this, 'wito_thread_posts-'+this.ref, 'wito_post-'+this.ref);
            witoQuery('#wito_thread_posts-'+this.ref).bind('mousedown', null, this.event_drag_posts_function);
            this.event_resize_drag_function = this.event_resizeStart(this, 'wito_resize_img-'+this.ref);
            witoQuery('#wito_thread_resize_hook-'+this.ref).bind('mousedown', null, this.event_resize_drag_function);
            this.event_resize_click_function = this.event_ignore(this);
            witoQuery('#wito_thread_resize_hook-'+this.ref).bind('click', null, this.event_resize_click_function);
        }
    }
}


/**
 * attach post html to thread
 */
witoPostClass.prototype.attach = function(html) {
    // protect against repeat calls
    if (this.jq) return;
    if (this.isVisible()) {
        // insert post before add button
        this.postList.thread.postBase.before(html);
        this.jq = witoQuery('#wito_post-'+this.postList.thread.ref+'-'+this.ref);
        // add events to this post
        this.event_edit_function = this.event_edit(this);
        this.event_delete_function = this.event_delete(this);
        witoQuery('#wito_post_edit_hook-'+this.postList.thread.ref+'-'+this.ref).bind('click', null, this.event_edit_function);
        witoQuery('#wito_post_delete_hook-'+this.postList.thread.ref+'-'+this.ref).bind('click', null, this.event_delete_function);
    }
}


/**
 * detach the thread by unhooking all events and removing html
 */
witoThreadClass.prototype.detach = function() {
    if (!this.jq) return;
    if (this.postList.list.length > 0) {
        for (var i=0 ; i<this.postList.list.length ; ++i) {
            var post = this.postList.list[i];
            if (post) {
                post.detach();
            }
        }
    }
    // detach normal thread events
    if (this.event_edit_function)
        witoQuery('#wito_thread_edit_hook-'+this.ref).unbind('click', this.event_edit_function);
    if (this.event_confdel_function)
        witoQuery('#wito_thread_confdel_hook-'+this.ref).unbind('click', this.event_confdel_function);
    if (this.event_minimise_restore_function)
        witoQuery('#wito_thread_minimise_restore_hook-'+this.ref).unbind('click', this.event_minimise_restore_function);
    if (this.event_add_function)
        witoQuery('#wito_thread_add_hook-'+this.ref).unbind('click', this.event_add_function);
    if (this.event_drag_paratbar_function)
        witoQuery('#wito_thread_paratbar-'+this.ref).unbind('mousedown', this.event_drag_paratbar_function);
    if (this.event_drag_arrow_function)
        witoQuery('#wito_thread_arrowptr-'+this.ref).unbind('mousedown', this.event_drag_arrow_function);
    if (this.event_drag_posts_function)
        witoQuery('#wito_thread_posts-'+this.ref).unbind('mousedown', this.event_drag_posts_function);
    if (this.event_resize_drag_function)
        witoQuery('#wito_thread_resize_hook-'+this.ref).unbind('mousedown', null, this.event_resize_drag_function);
    // detach confdel thread events
    if (this.event_delete_function)
        witoQuery('#wito_thread_delete_hook-'+this.ref).unbind('click', this.event_delete_function);
    if (this.event_unconfdel_function)
        witoQuery('#wito_thread_restore_hook-'+this.ref).unbind('click', this.event_unconfdel_function);

    // delete html from page
    this.jq.remove();
    this.jq = null;
}


/**
 * attach post html to thread
 */
witoPostClass.prototype.detach = function(html) {
    if (!this.jq) return;
    // detach events from this post
    witoQuery('#wito_post_edit_hook-'+this.postList.thread.ref+'-'+this.ref).unbind('click', this.event_edit_function);
    witoQuery('#wito_post_delete_hook-'+this.postList.thread.ref+'-'+this.ref).unbind('click', this.event_delete_function);
    this.jq.remove();
    this.jq = null;
}


witoThreadClass.prototype.renderAttachShow = function() {
    // protect against multiple calls
    if (this.jq) return;
    if (this.attach) {
        this.attach(this.render());
        // if thread has posts, attach posts
        if (this.postList.list.length > 0) {
            if (this.isVisible() && !this.isConfdel()) {
                for (var i=0 ; i<this.postList.list.length ; ++i) {
                    var post = this.postList.list[i];
                    if (post) {
                        post.renderAttachShow();
                    }
                }
            }
        }
        this.show();
    }
}


witoPostClass.prototype.renderAttachShow = function() {
    // protect against multiple calls
    if (this.jq) return;
    if (this.attach) {
        this.attach(this.render());
        this.show();
    }
}


/**
 * display the thread by making it visible
 */
witoThreadClass.prototype.show = function() {
    if (!this.jq) return;
    this.jq.show();
}


witoPostClass.prototype.show = function() {
    // post visibility/show controlled by thread vis/show
    // may extend in order to scroll pane to this post
}


/**
 * hide the thread by making it display none
 */
witoThreadClass.prototype.hide = function() {
    if (!this.jq) return;
    this.jq.hide();
}


witoPostClass.prototype.hide = function() {
    if (!this.jq) return;
    this.jq.hide();
}


/**
 * begin editing this thread
 * - change title to editable textfield, set cursor etc.
 */
witoThreadClass.prototype.edit = function() {
    this.wito.edit_begin(this);
}


/**
 * test if a thread is visible
 */
witoThreadClass.prototype.isVisible = function() {
    return(this.flagdisp & this.wito.flag_displayVISIBLE);
}


/**
 * test if a post is visible
 * - really testing whether we should attach events or not
 */
witoPostClass.prototype.isVisible = function() {
    // post visibility limited by thread
    return((this.flagdisp & this.wito.flag_displayVISIBLE) && this.postList.thread.isVisible());
}


witoThreadClass.prototype.isConfdel = function() {
 // test if a thread is confirm-delete mode
    return(this.flagdisp & this.wito.flag_displayCONFDEL);
}


witoThreadClass.prototype.isMinimised = function() {
    return(this.flagdisp & this.wito.flag_displayMINIMISED);
}


witoThreadClass.prototype.isAppendable = function() {
    return(this.flagedit & this.wito.flag_actionAPPEND);
}


witoThreadClass.prototype.isEditable = function() {
    return(this.flagedit & this.wito.flag_actionEDIT);
}


witoPostClass.prototype.isEditable = function() {
    return(this.flagedit & this.wito.flag_actionEDIT);
}


witoThreadClass.prototype.isDeleted = function() {
    return(this.flagdisp & this.wito.flag_displayDELETED);
}


witoPostClass.prototype.isDeleted = function() {
    return(this.flagdisp & this.wito.flag_displayDELETED);
}


witoThreadClass.prototype.event_dragStart = function(context, matchid) {
    var matchwild = matchid;
    // if wildcard (3rd) argument given, try and match to that also
    if (arguments.length == 3) {
        matchwild = arguments[2];
    }
    return( function(e) {
        if (context.locked) return;
        var evtarget = (witoQuery.browser.msie ? event.srcElement : e.target);
        var evcompare = evtarget.id.substr(0,matchwild.length);
        // context.wito.debug('drag start: matching click('+evtarget.id+') to either ('+matchid+') or ('+matchwild+')');
        if ((evtarget.id == matchid) ||
            (evcompare == matchwild)) {
            // calculate scrollbar bounding box
            var withinScrollbar = false;
            // client X/Y is the mouse coord
            var minX = context.left+context.marginLeft;
            var minY = context.top+context.marginTop;
            var maxX = minX + context.width;
            var maxY = minY + context.heightTitlebar + context.height;
            var scrollWidth = 16;
            // don't need to trap against minX/Y because listener attached to inner div
            withinScollbar = (e.clientX > (maxX - scrollWidth));

            var s;
            s  = 'min '+minX+' '+minY+'\r\n';
            s += 'max '+maxX+' '+maxY+'\r\n';
            s += 'e '+e.clientX+' '+e.clientY+'\r\n';
            s += 'within='+(withinScollbar ? 'yes' : 'no')+'\r\n';
            //this.wito.debug(s);

            if (!withinScollbar) {
                context.dragStart(e, false);
                context.wito.event_stop_bubble(e);
                // attach document listener for mousemove & mouseup
                context.event_dragging_function = context.event_dragging(context);
                context.event_dragStop_function = context.event_dragStop(context);
                witoQuery(document).bind('mousemove', null, context.event_dragging_function);
                witoQuery(document).bind('mouseup', null, context.event_dragStop_function);
            } else {
                // ignore clicks in scrollbar
            }
        }
    });
}


witoThreadClass.prototype.event_resizeStart = function(context, matchid) {
    return( function(e) {
        if (context.locked) return;
        var evtarget = (witoQuery.browser.msie ? event.srcElement : e.target);
        if (evtarget.id == matchid) {
            context.dragStart(e, true);
            context.wito.event_stop_bubble(e);
            // attach document listener for mousemove & mouseup
            context.event_dragging_function = context.event_dragging(context);
            context.event_dragStop_function = context.event_dragStop(context);
            witoQuery(document).bind('mousemove', null, context.event_dragging_function);
            witoQuery(document).bind('mouseup', null, context.event_dragStop_function);
        }
    });
}


witoThreadClass.prototype.event_ignore = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.wito.event_stop_bubble(e);
    });
}


witoThreadClass.prototype.dragStart = function(e, resize) {
    // this.wito.debug(this.wito.__objectToString(e.target));
    // bring thread to front
    this.threadList.bringToFront(this);
    // create drag in progress (dip) container
    this.dip = new Object();
    this.dip.resize = resize;
    // record initial div coords
    if (this.dip.resize) {
        this.dip.minWidth = this.widthMin;
        this.dip.minHeight = this.heightAdd; // threads bound by titlebar + statusbar height
        this.dip.startX = parseInt(this.jq.css('width'));
        this.dip.startY = parseInt(this.jq.css('height'));
    } else {
        this.dip.startX = parseInt(this.jq.css('left'));
        this.dip.startY = parseInt(this.jq.css('top'));
    }
    // record initial mouse coords
    this.dip.offsetX = e.clientX;
    this.dip.offsetY = e.clientY;
    // make dragging object semi-transparent
    this.jq.animate({opacity: 0.5},100);
}


witoThreadClass.prototype.event_dragging = function(context) {
    return( function(e) {
        // if (context.locked) stop the dragging;
        context.dragging(e);
        context.wito.event_stop_bubble(e);
    });
}


witoThreadClass.prototype.dragging = function(e) {
    var dx = this.dip.startX + e.clientX - this.dip.offsetX;
    var dy = this.dip.startY + e.clientY - this.dip.offsetY;
    // update css properties based on drag distance
    if (this.dip.resize) {
        if ((dx < this.dip.minWidth) || (dy < this.dip.minHeight)) return;
        this.heightTitlebar = witoQuery('#wito_thread_titlebar-'+this.ref).height();
        this.applyDimensionChange(dx, dy, true);
        this.dip.minHeight = this.heightAdd;
    } else {
        this.jq.css('left', '' + dx + 'px');
        this.jq.css('top', '' + dy + 'px');
    }
}


witoThreadClass.prototype.event_dragStop = function(context) {
    return( function(e) {
        context.dragStop(e);
        context.wito.event_stop_bubble(e);
        // release events
        witoQuery(document).unbind('mousemove', context.event_dragging_function);
        witoQuery(document).unbind('mouseup', context.event_dragStop_function);
    });
}


witoThreadClass.prototype.dragStop = function(e) {
    var flag = null;
    // record final position
    if (this.dip.resize) {
        this.width = parseInt(this.jq.css('width')) - this.widthAdd;
        this.height = parseInt(this.jq.css('height')) - this.heightAdd;
        this.heightTitlebar = witoQuery('#wito_thread_titlebar-'+this.ref).height();
        this.applyDimensionChangeUIonly(true);
        flag = this.wito.flag_actionRESIZE;
    } else {
        this.top = parseInt(this.jq.css('top')) + this.marginTop;
        this.left = parseInt(this.jq.css('left')) + this.marginLeft;
        flag = this.wito.flag_actionMOVE;
    }
    // fire a post to record the position/size
    var postObj = this.wito.ajax_prep(flag | this.wito.flag_targetTHREAD);
    // create partial thread object for update
    postObj.thread = this.createPartial(flag);
    this.wito.ajax_update(postObj);
    // collect redundant dip object
    this.dip = null;
    // make the div opaque again
    this.jq.animate({opacity: 1.0},100);
}


witoThreadClass.prototype.applyDimensionChange = function(dx, dy, snap) {
    this.renderCalc(this.isMinimised(), dx, dy);
    witoQuery('#wito_thread_titlebar-'+this.ref).css('width', ''+(dx-this.widthAdd)+'px');
    witoQuery('#wito_thread_posts-'+this.ref).css('width', ''+(dx-this.widthAdd)+'px');
    witoQuery('#wito_thread_posts-'+this.ref).css('height', ''+(dy-this.heightAdd)+'px');
    witoQuery('#wito_thread_status-'+this.ref).css('width', ''+(dx-this.widthAdd)+'px');
    witoQuery('#wito_shadow_bottom-'+this.ref).css('width', ''+(dx-this.widthAdd-this.shadowOffset)+'px');
    witoQuery('#wito_shadow_right-'+this.ref).css('height', ''+this.shadowHeightRight+'px');
    witoQuery('#wito_shadow_right-'+this.ref).css('top', ''+(0-this.shadowHeightRight+5)+'px');
    if (snap) {
        this.jq.css('width',dx+"px");
        this.jq.css('height',dy+"px");
    } else {
        this.jq.animate({width: dx+"px", height: dy+"px"});
    }
}


witoThreadClass.prototype.applyDimensionChangeUIonly = function(snap) {
    var minimised = this.isMinimised()
    this.renderCalc(minimised);
    tbar_jq = witoQuery('#wito_thread_titlebar-'+this.ref);
    tbar_jq.css('width', ''+(this.width)+'px');
    tbar_jq.css('marginTop',this.marginTop+'px');
    tbar_jq.css('marginLeft',this.marginLeft+'px');
    post_jq = witoQuery('#wito_thread_posts-'+this.ref);
    post_jq.css('width', ''+(this.width)+'px');
    post_jq.css('height', ''+(this.height)+'px');
    post_jq.css('marginLeft',this.marginLeft+'px');
    stat_jq = witoQuery('#wito_thread_status-'+this.ref);
    stat_jq.css('width', ''+(this.width)+'px');
    stat_jq.css('marginLeft',this.marginLeft+'px');
    witoQuery('#wito_shadow_bottom-'+this.ref).css('width', ''+(this.width-this.shadowOffset)+'px');
    shdr_jq = witoQuery('#wito_shadow_right-'+this.ref);
    shdr_jq.css('height', ''+this.shadowHeightRight+'px');
    shdr_jq.css('top', ''+(0-this.shadowHeightRight+5)+'px');
    var heightActual = (minimised ? this.heightAdd : this.height+this.heightAdd);
    if (snap) {
        // adjust outer container
        this.jq.css('top', this.top-this.marginTop+'px');
        this.jq.css('left', this.left-this.marginLeft+'px');
        this.jq.css('width',this.width+this.widthAdd+"px");
        this.jq.css('height',heightActual+"px");
    } else {
        this.jq.animate({
            top: this.top-this.marginTop+"px",
            left: this.left-this.marginLeft+"px",
            width: this.width+this.widthAdd+"px",
            height: this.height+this.heightAdd+"px"
        });
    }
}


witoThreadClass.prototype.applyDimensionIfHeightChange = function() {
    var heightTitlebarBefore = this.heightTitlebar;
    this.heightTitlebar = witoQuery('#wito_thread_titlebar-'+this.ref).height();
    if (this.heightTitlebar != heightTitlebarBefore) {
        // apply change to UI
        this.applyDimensionChangeUIonly(true);
    }
    // this.wito.debug(heightTitlebarBefore+' -> '+this.heightTitlebar+"\r\n"+this.height+' + '+this.heightAdd);
}


/**
 * create a partial copy of this object
 * - for sending updates to the server
 */
witoThreadClass.prototype.createPartial = function(action) {
    // rehash before sending to server, [run-time] cascade aggregates
    this.hash.hash_calculate(true);             // cascade up (hval)
    this.hash.hash_aggregate(true, true, "|");  // cascade up and down (hchild)
    // this.wito.debug(this.wito.hash.debugHashTree('|SESS|THRD|POST|'));
    // post sub object (thread)
    var pso = new Object;
    // reference by session [ref] -> thread [ref]
    pso.session = new Object;
    pso.session.ref = this.threadList.session.ref;
    pso.session.hval = this.threadList.session.hash.hval;
    pso.session.hchild = this.threadList.session.hash.hchild;
    pso.ref = this.ref;
    if (action & this.wito.flag_actionGET) {
        // send no attributes
    }
    if (action & this.wito.flag_actionMOVE) {
        pso.top = this.top;
        pso.left = this.left;
        pso.z = this.z;
    }
    if (action & this.wito.flag_actionRESIZE) {
        pso.width = this.width;
        pso.height = this.height;
        pso.z = this.z;
    }
    if (action & this.wito.flag_actionEDIT) {
        pso.data = this.data;
        pso.colour = this.colour;
        pso.width = this.width;
        pso.height = this.height;
        pso.minishape = this.minishape;
    }
    if ((action & this.wito.flag_actionCONFDEL) ||
        (action & this.wito.flag_actionUNCONFDEL)) {
        pso.height = this.height;
        pso.flagdisp = this.flagdisp;
    }
    if ((action & this.wito.flag_actionMINIMISE_RESTORE) ||
        (action & this.wito.flag_actionDELETE)) {
        pso.flagdisp = this.flagdisp;
    }
    if (action & this.wito.flag_actionCOLCHANGE) {
        pso.colour = this.colour;
    }
    // don't send edit flags (append, edit, move)
    return(pso);
}


/**
 * create a partial copy of this object
 * - for sending updates to the server
 */
witoPostClass.prototype.createPartial = function(action) {
    // rehash before sending to server, [run-time] cascade aggregates
    this.hash.hash_calculate(true);             // cascade up (hval)
    // this.wito.debug(this.hash.debugHash('post'));
    // this.wito.debug(this.postList.thread.hash.debugHash('thread'));
    // this.wito.debug(this.postList.thread.threadList.session.hash.debugHash('session'));
    // post sub object (thread)
    var pso = new Object;
    // reference by session [ref] -> thread [ref] -> post [ref]
    pso.session = new Object;
    pso.session.ref = this.postList.thread.threadList.session.ref;
    pso.session.hval = this.postList.thread.threadList.session.hash.hval;
    pso.session.hchild = this.postList.thread.threadList.session.hash.hchild;
    pso.thread = new Object;
    pso.thread.ref = this.postList.thread.ref;
    pso.thread.hval = this.postList.thread.hash.hval;
    pso.thread.hchild = this.postList.thread.hash.hchild;
    pso.ref = this.ref;
    if (action & this.wito.flag_actionEDIT) {
        pso.data = this.data;
    }
    if ((action & this.wito.flag_actionMINIMISE_RESTORE) ||
        (action & this.wito.flag_actionDELETE)) {
        pso.flagdisp = this.flagdisp;
    }
    return(pso);
}


witoThreadClass.prototype.makeRoomInPostArea = function(minHeight, updateUI,  updateServer) {
    if (this.height < minHeight) {
        var flag = this.wito.flag_actionRESIZE;
        this.height = minHeight;
        if (updateUI) {
            // resize thread to show post area
            this.applyDimensionChangeUIonly(false);
        }
        if (updateServer) {
            // fire a post to record the position/size
            var postObj = this.wito.ajax_prep(flag | this.wito.flag_targetTHREAD);
            postObj.thread = this.createPartial(flag);
            this.wito.ajax_update(postObj);
        }
    }
}


/**
 * minimise or restore this thread
 * - EvHF
 */
witoThreadClass.prototype.event_minimise_restore = function (context) {
    return(function(e) {
        if (context.locked) return;
        context.minimise_restore(!context.isMinimised(), true);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * minimise or restore this thread
 */
witoThreadClass.prototype.minimise_restore = function(minimise, fireToServer) {
    var temp_jq = null;
    if (minimise) {
        // minimising
        witoQuery('#wito_thread_arrowptr-'+this.ref).show();
        witoQuery('#wito_thread_posts-'+this.ref).hide();
        witoQuery('#wito_thread_arrowglyph-'+this.ref).removeClass('wito_glyphdown');
        witoQuery('#wito_thread_status-'+this.ref).hide();
        this.jq.addClass('wito_thread_minimised');
        // logical OR the flag (force set)
        this.flagdisp |= this.wito.flag_displayMINIMISED;
    } else {
        // expanding
        witoQuery('#wito_thread_posts-'+this.ref).show();
        witoQuery('#wito_thread_arrowptr-'+this.ref).hide();
        witoQuery('#wito_thread_arrowglyph-'+this.ref).addClass('wito_glyphdown');
        witoQuery('#wito_thread_status-'+this.ref).show();
        this.jq.removeClass('wito_thread_minimised');
        // logical AND the inverse flag (force clear)
        this.flagdisp &= (this.wito.flag_displayMASK ^ this.wito.flag_displayMINIMISED);
    }
    // read titlebar height as it may have been affected by add/removal of wito_thread_minimised
    this.heightTitlebar = witoQuery('#wito_thread_titlebar-'+this.ref).height();
    this.applyDimensionChangeUIonly(true);
    // fire request to server to remember
    if (fireToServer) {
        var postObj = this.wito.ajax_prep(this.wito.flag_actionMINIMISE_RESTORE | this.wito.flag_targetTHREAD);
        postObj.thread = this.createPartial(this.wito.flag_actionMINIMISE_RESTORE);
        this.wito.ajax_update(postObj);    
    }
}


/**
 * confirm delete thread
 * - thread event handler factory
 *   - returns event handler function
 */
witoThreadClass.prototype.event_confdel = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.confdel_unconfdel(true, true);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * restore a near-deleted thread
 * - EvHF
 */
witoThreadClass.prototype.event_unconfdel = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.confdel_unconfdel(false, true);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * outline a thread to confirm delete
 */
witoThreadClass.prototype.confdel_unconfdel = function(confdel, fireToServer) {
    this.hide();
    this.detach();
    var action = this.wito.flag_actionNONE;
    if (confdel) {
        // flag thread as not conventionally displayable (goes to confirm-delete state)
        this.flagdisp |= this.wito.flag_displayCONFDEL;
        // force confirm-delete mode threads to appear in full, not minimised
        this.flagdisp &= (this.wito.flag_displayMASK ^ this.wito.flag_displayMINIMISED);        
        // and must be a minimum height (and must be set on the server to avoid update wierdness)
        this.makeRoomInPostArea(this.heightMinConfdel, false, false);
        action = this.wito.flag_actionCONFDEL;
    } else {
        // flag thread as normal (displayable)
        this.flagdisp &= (this.wito.flag_displayMASK ^ this.wito.flag_displayCONFDEL);        
        action = this.wito.flag_actionUNCONFDEL;
    }
    // re-attach 'confdel' view
    this.renderAttachShow();
    if (fireToServer) {
        // fire request to server to archive
        var postObj = this.wito.ajax_prep(action | this.wito.flag_targetTHREAD);
        postObj.thread = this.createPartial(action);
        this.wito.ajax_update(postObj);    
    }
}


/**
 * delete post
 * - post event handler factory
 *   - returns event handler function
 */
witoPostClass.prototype.event_delete = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.deletex(true);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * delete post
 */
witoPostClass.prototype.deletex = function(fireToServer) {
    this.hide();
    this.detach();
    // flag post as not displayable
    this.flagdisp = this.wito.flag_displayDELETED;
    if (fireToServer) {
        // fire request to server to archive
        var postObj = this.wito.ajax_prep(this.wito.flag_actionDELETE | this.wito.flag_targetPOST);
        postObj.post = this.createPartial(this.wito.flag_actionDELETE);
        this.wito.ajax_update(postObj);    
    }
}


/**
 * actually delete a thread
 * - EvHF
 */
witoThreadClass.prototype.event_delete = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.deletex(true);
        context.wito.event_stop_bubble(e);
    });
}


witoThreadClass.prototype.deletex = function(fireToServer) {
    this.hide();
    this.detach();
    // flag thread as not displayable
    this.flagdisp = this.wito.flag_displayDELETED;
    // tell threadList this is being deleted
    this.threadList.remove(this);
    if (fireToServer) {
        // fire request to server to archive
        var postObj = this.wito.ajax_prep(this.wito.flag_actionDELETE | this.wito.flag_targetTHREAD);
        postObj.thread = this.createPartial(this.wito.flag_actionDELETE);
        this.wito.ajax_update(postObj);
    }
}


/**
 * edit thread title
 * - thread EvHF (event handler factory)
 *   - returns event handler function
 */
witoThreadClass.prototype.event_edit = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.wito.edit_begin(context);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * following an edit_end, update the thread
 */
witoThreadClass.prototype.commitEdit = function(data) {
    this.data = data;
    // pass thread edit to server
    var postObj = this.wito.ajax_prep(this.wito.flag_actionEDIT | this.wito.flag_targetTHREAD);
    postObj.thread = this.createPartial(this.wito.flag_actionEDIT);
    this.wito.ajax_update(postObj);
}


/**
 * edit post
 * - EvHF
 */
witoPostClass.prototype.event_edit = function(context) {
    return( function(e) {
        if (context.locked) return;
        context.wito.edit_begin(context);
        context.wito.event_stop_bubble(e);
    });
}


/**
 * following an edit_end, update the post
 */
witoPostClass.prototype.commitEdit = function(data) {
    this.data = data;
    // pass post edit to server
    var postObj = this.wito.ajax_prep(this.wito.flag_actionEDIT | this.wito.flag_targetPOST);
    postObj.post = this.createPartial(this.wito.flag_actionEDIT);
    this.wito.ajax_update(postObj);
}


/**
 * update icon visibility (typically on hover)
 */
witoThreadClass.prototype.event_iconvis = function(context, vis) {
    return( function(e) {
        // context.wito.debug(context.ref+': '+vis);
        witoQuery('#wito_thread_arrowglyph-'+context.ref).css('visibility',(vis?'visible':'hidden'));
        witoQuery('#wito_thread_editpen-'+context.ref).css('visibility',(vis?'visible':'hidden'));
        witoQuery('#wito_thread_confdel-'+context.ref).css('visibility',(vis?'visible':'hidden'));
    });
}


/**
 * add post to thread
 * - EvHF
 */
witoThreadClass.prototype.event_add = function(context) {
    return( function(e) {
        if (context.locked) return;
        // create a new post
        var post = context.postList.new_post();
        if (post.attach) {
            post.attach(post.render());
            post.show();
            // edit after showing
            context.wito.edit_begin(post);
            context.makeRoomInPostArea(context.heightMinPost, true, true);
        }
        context.wito.event_stop_bubble(e);
        // this.wito.debug('add post to thread '+this.ref);
    });
}


witoThreadClass.prototype.event_colchange = function(context) {
    return( function(e) {
        if (context.locked) return;
        /**
         *
        var debugstr =
            'colour['+context.colour+','+context.wito.padHex(context.colour,6)+'] '+
            'add['+context.colourAdd+','+context.wito.padHex(context.colourAdd,6)+'] '+
            'equals['+(context.colour + context.colourAdd)+','+context.wito.padHex((context.colour + context.colourAdd),6)+'] '+
            'modded['+context.colNext(context.colour)+','+context.wito.padHex(context.colNext(context.colour),6)+']';
        context.wito.debugCacheMess(debugstr);
         */
        context.colchange(context.colNext(context.colour), true);
        context.wito.event_stop_bubble(e);
    });
}


witoThreadClass.prototype.colchange = function(newColour, fireToServer) {
    this.colour = newColour;
    this.colComputeVarients();
    if (this.isMinimised()) {
        witoQuery('#wito_thread_titlenot-'+this.ref).css('backgroundColor', '#'+this.colourLighten);
    } else {
        witoQuery('#wito_thread_titlebar-'+this.ref).css('backgroundColor', '#'+this.colourLighten);
    }
    // dark backgrounds need white text
    this.jq.css('color','#'+this.colourText);
    witoQuery('#wito_thread_posts-'+this.ref).css('backgroundColor', '#'+this.colourBack);
    witoQuery('#wito_thread_status-'+this.ref).css('backgroundColor', '#'+this.colourBack);
    // update next colour icon
    nextCol = this.colNext(this.colour);
    witoQuery('#wito_thread_colchange-'+this.ref).css('backgroundColor', '#'+(this.wito.padHex(nextCol,6)));
    // set the default thread so that all future creations come up this colour
    this.wito.default_thread.colour = this.colour;
    // fire if firing
    if (fireToServer) {
        // fire request to server to archive
        var postObj = this.wito.ajax_prep(this.wito.flag_actionCOLCHANGE | this.wito.flag_targetTHREAD);
        postObj.thread = this.createPartial(this.wito.flag_actionCOLCHANGE);
        this.wito.ajax_update(postObj);
    }
}


witoThreadClass.prototype.colNext = function(col) {
    // col += this.colourAdd;
    // if (col > this.colourTop) col = 0x000000;
    col -= this.colourSub;
    if (col <= 0) col = this.colourBase;
    return(col);
}


witoThreadClass.prototype.colComputeVarients = function() {
    var lightText = this.wito.colourThreshold(this.colour, this.backgroundColourThreshold);
    this.colourBack = this.wito.padHex(this.colour,6);
    this.colourLighten = this.wito.padHex(this.wito.colourLighten(this.colour, 0.02,lightText),6);
    this.colourText = this.wito.padHex((lightText?'FFFFFF':'000000'),6);
}


witoThreadClass.prototype.textEditListener = function(src) {
    // if src.text is object default (e.g. Insert comment here), scrub
    if (src.text == this.wito.default_thread.data) {
        src.text = '';
        src.text_height = this.heightMinEmptyTitleTextarea;
        src.text_minHeight = src.text_height;
    }
    // set colours to match thread
    src.colBack = this.colourLighten;
    src.colText = this.colourText;
}


witoPostClass.prototype.textEditListener = function(src) {
    // blank out default text on edit
    if (src.text == this.wito.default_post.data) {
        src.text = '';
    }
    // set colours to post parent (thread) background
    src.colBack = this.postList.thread.colourBack;
    src.colText = this.postList.thread.colourText;
    // transform edit button to submit
    witoQuery('#wito_post_edit_hook-'+this.postList.thread.ref+'-'+this.ref).html('submit');
}


witoThreadClass.prototype.textUpdatedListener = function() {
    // modify thread accordingly
    this.heightTitlebar = witoQuery('#wito_thread_titlebar-'+this.ref).height();
    this.applyDimensionChangeUIonly(true);
}


witoPostClass.prototype.textUpdatedListener = function() {
}


witoThreadClass.prototype.autoGrow = function() {
    return(true);
}


witoPostClass.prototype.autoGrow = function() {
    return(false);
}


/**
 *
 * UI functions
 * - non jQuery/witoQuery user interactions
 *
 */
witoClass.prototype.drag_mouse_up_down_move = function(e) {
    var eventext = (witoQuery.browser.msie ? event : e);
    var evtarget = (witoQuery.browser.msie ? event.srcElement : e.target);
    var context = null;
    // jQuery compatible
    if (e.data) context = e.data;
    // witoQuery compatible
    if (arguments[1]) context = arguments[1];
    if (!context) return;
    
    if (eventext.type == 'mousedown') {
        if (evtarget.id == context.dragCatch) {
            context.dragging = true;
            // call .start function
            if (context.options.start) {
                context.options.start(eventext, context.options.context);
            }
        }
    } else if (eventext.type == 'mouseup') {
        if (context.dragging) {
            // call .stop function
            if (context.options.stop) {
                context.options.stop(eventext, context.options.context);
            }
            context.dragging = false;
        }
    } else if (eventext.type == 'mousemove') {
        if (context.dragging) {
            // call .drag function
            if (context.options.drag) {
                context.options.drag(eventext, context.options.context);
            }
        }
    }
}


/**
 *
 * Hash class
 *
 */
witoHashClass = function() {
    // constructor (hash)
}
 

witoHashClass.prototype.init = function(wito, fields, obj, childList, parent) {
    this.wito = wito;
    this.serial = '';
    this.hval = 0;
    this.hchild = -1;   // less likely than 0 which is the empty set hash
    this.fields = fields;
    this.obj = obj;                 // e.g. Thread
    this.childList = childList;     // e.g. PostList
    this.parent = parent;           // e.g. Session
}


witoHashClass.prototype.convertUTF8 = function(str) {
    for(var c, i = -1, l = (str = str.split("")).length, o = String.fromCharCode; ++i < l;
        str[i] = (c = str[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : str[i]
    );
    return(str+"");
}


witoHashClass.prototype.crc32 = function(str) {
    var table = this.wito.hash_tableCRC;
    var crc = 0 ^ (-1);
    var x = 0;
    var y = 0;
    for( var i = 0, iTop = str.length; i < iTop; i++ ) {
        y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
        x = "0x" + table.substr( y * 9, 8 );
        crc = ( crc >>> 8 ) ^ x;
    }    
    return(crc ^ (-1));
}
   

witoHashClass.prototype.serialise = function() {
    var str = '';
    for(key in this.fields) {
        if (str.length > 0) str += ';';
        str += this.obj[this.fields[key]];
        //str+=this.fields[key];
    }
    // this.serial = this.convertUTF8(str);
    this.serial = str;
    return(this.serial);
}


witoHashClass.prototype.hash_calculate = function(cascadeUp) {
    this.serialise();
    this.hval = this.crc32(this.serial);
    // this.wito.debug('hval('+this.hval+') serial('+this.serial+')');
    // tell parent to re-aggregate
    if (cascadeUp && this.parent) {
        this.parent.hash.hash_aggregate(cascadeUp, false, false);
    }
    return(this.hval);
}


witoHashClass.prototype.hash_aggregate = function(cascadeUp, cascadeDown, debugLevel) {
    if (debugLevel === false) debugLevel = "";
    var debugStr = "";
    if (!this.childList) {
        this.hchild = 0;
        return('');
        return(debugLevel+"No children");
    }
    // get list of children
    var objArr = this.childList.getList();
    var newChildAgg = 0;
    // aggregate child hashes
    for (var i=0 ; i<objArr.length ; ++i) {
        // ignore deleted entries (null)
        if (!objArr[i]) continue
        // ignore flagged deleted entries (some clients won't have them at all, say after refresh)
        if (objArr[i].isDeleted()) continue;
        // cascade changes down tree
        if (cascadeDown) {
            var downStr = objArr[i].hash.hash_aggregate(cascadeUp, cascadeDown, debugLevel+'  '+this.wito.pad(i)+'| ');
            if (downStr) debugStr += "\r\n"+downStr;
        }
        var childChildAgg = objArr[i].hash.hchild;
        newChildAgg ^= childChildAgg;
        var childHash = objArr[i].hash.hval;
        newChildAgg ^= childHash;
        debugStr += "\r\n"+debugLevel + '. '+this.wito.pad(i)+'| h('+childHash+') a('+childChildAgg+')';
    }
    // if (i>0) debugStr += debugLevel + '-=-=-=-=-=-#';
    // this.wito.debug('aggregateValue('+newChildAgg+') from '+objArr.length+' sources');
    // has anything changed
    if (newChildAgg != this.hchild) {
        this.hchild = newChildAgg;
        // cascade on change (tell parent to re-aggregate)
        if (cascadeUp && this.parent) {
            this.parent.hash.hash_aggregate(cascadeUp, cascadeDown, debugLevel+"");
        }
    }
    // return used only for debugging data
    return(debugStr);
}


witoHashClass.prototype.debugHash = function(key) {
    var debugHash = (key ? key + "\r\n" : '') + 'v('+this.hval+') ch(' + this.hchild +')';
    return(debugHash);
}


witoHashClass.prototype.debugHashTree = function(key) {
    var debugHashTree = this.hash_aggregate(false, true, "|");
    debugHashTree = key + "\r\n" + debugHashTree + "\r\n\r\n" + 'Overall v('+this.hval+') ch(' + this.hchild +')';
    return(debugHashTree);
}


/**
 *
 * InterfaceUpdateQueue class
 *
 */
witoInterfaceUpdateQueue = function() {
    // constructor (update queue)
}
 

witoInterfaceUpdateQueueElement = function() {
    // constructor (update queue element)
}


witoInterfaceUpdateQueue.prototype.init = function(wito) {
    this.wito = wito;
    this.q = new Array();
    this.anim = new Object();
}


witoInterfaceUpdateQueueElement.prototype.init = function(wito, q, obj, prop, before, after) {
    this.wito = wito;
    this.q = q;
    this.obj = obj;
    this.prop = prop;
    this.before = before;
    this.after = after;
    this.ref = -1;
}


witoInterfaceUpdateQueue.prototype.add = function(obj, prop, before, after) {
    // store update in array
    var elem = new witoInterfaceUpdateQueueElement();
    elem.init(this.wito, this, obj, prop, before, after);
    // add to list
    elem.ref = this.q.length;
    this.q[elem.ref] = elem;
    // this.wito.debug('adding update to queue: '+this.wito.__objectToString(elem));
}


witoInterfaceUpdateQueue.prototype.inQueue = function(name) {
    for (var i=0 ; i<this.q.length ; ++i) {
        var elem = this.q[i];
        if (elem == null) continue;
        if (elem.prop == name)
            return(elem);
    }
    return(null);
}


witoInterfaceUpdateQueue.prototype.process = function() {
    if (this.q.length == 0) return;
    // process inanimates (selected non-animated UI updates that have to be done first)
    var priorities = ['flagdisp'];
    for (var i=0 ; i<priorities.length ; ++i) {
        var elem = this.inQueue(priorities[i]);
        // if (elem == null) continue; - not necessary
        if (elem) {
            // lock object
            elem.obj.lock();
            // update property
            elem.obj[elem.prop] = elem.after;
            // update derived variables based on property
            this.processDerived(elem.obj, elem.prop);
            // update UI
            elem.obj.updateUI(elem.prop, elem.before, elem.after);
            // skip this entry next time
            elem.prop = 'skip';
        }
    }
    // update local data = object = cso
    for (var i=0 ; i<this.q.length ; ++i) {
        var elem = this.q[i];
        if (elem == null) continue;
        // lock object
        elem.obj.lock();
        // update property
        elem.obj[elem.prop] = elem.after;
        // update derived variables based on property
        this.processDerived(elem.obj, elem.prop);
        // this.wito.debug('updated '+elem.prop+' from '+elem.before+' to '+elem.obj[elem.prop]);
        // rehash element accordingly and cascade up
        if (elem.obj.hash) elem.obj.hash.hash_calculate(true);
    }
    // hunt for double-ups (note: UI only, update already done)
    var doubleUps = [['top','left'],['width','height']];
    for (var i=0 ; i<doubleUps.length ; ++i) {
        var elemT = this.inQueue(doubleUps[i][0]);
        var elemL = this.inQueue(doubleUps[i][1]);
        if (elemT && elemL) {
            if (elemT.obj == elemL.obj) {
                // convert T to TL
                elemT.prop += elemL.prop
                // skip L
                elemL.prop = 'skip';
            }
        }
    }
    // show queue
    // this.wito.debug(this.debugQueue());
    // process remaining UI updates
    for (var i=0 ; i<this.q.length ; ++i) {
        var elem = this.q[i];
        if (elem == null) continue;
        // update UI
        elem.obj.updateUI(elem.prop, elem.before, elem.after);
    }
    // unlock objects
    for (var i=0 ; i<this.q.length ; ++i) {
        var elem = this.q[i];
        if (elem == null) continue;
        elem.obj.unlock();
    }
    // scrub queue
    this.q.length = 0;
}


witoInterfaceUpdateQueue.prototype.processDerived = function(obj, prop) {
    switch (prop) {
        case 'z' :
            if (obj.threadList) {
                obj.threadList.checkMaxZ(obj[prop]);
            }
            break;
    }
}


witoInterfaceUpdateQueue.prototype.debugQueue = function() {
    var str = "";
    for (var i=0 ; i<this.q.length ; ++i) {
        var elem = this.q[i];
        if (elem == null) continue;
        str += '['+i+'] '+elem.prop+' from '+elem.before+' to '+elem.after + "\r\n";
    }
    return(str);
}


/**
 *
 *
 * Event handler
 *
 *
 */
witoClass.prototype.event_stop_bubble = function(e) {
    if (!e) var e = window.event;
    // ie
    e.cancelBubble = true;
    e.returnValue = false;
    // ff
    if (e.preventDefault) e.preventDefault();
    if (e.stopPropagation) e.stopPropagation();
}


/**
 *
 *
 * Heartbeat pacemaker
 *
 *
 */
witoHeartbeatClass = function() {
    // constructor (heartbeat pacemaker)
}
 

witoHeartbeatClass.prototype.init = function(wito) {
    this.wito = wito;
    this.time = 0;
    this.nextBeat = null;
    this.suspended = false;
}


witoHeartbeatClass.prototype.event_heartbeat = function(context) {
    return( function(e) {
        context.beat();
    });
}


witoHeartbeatClass.prototype.cancel = function() {
    if (this.nextBeat) {
        // cancel current 'next' beat
        clearTimeout(this.nextBeat);
        this.nextBeat = null;
    }
}


witoHeartbeatClass.prototype.schedule = function(time) {
    // no heartbeat unless connected to server
    if (this.wito.online != this.wito.status_ONLINE) return;
    // find out if we're waiting on the server for anything else
    if (this.wito.ajax_countOutstanding()) return;
    // set min interval
    if (time < 1000) time = 1000;
    this.time = time;
    this.reschedule();
}


witoHeartbeatClass.prototype.reschedule = function() {
    // need to resume before issuing schedule/reschedule
    if (this.suspended) return;
    // only one heartbeat at a time
    this.cancel();
    // schedule beat
    this.nextBeat = setTimeout(this.event_heartbeat(this), this.time);
}


witoHeartbeatClass.prototype.beat = function() {
    var beat = true;
    // no heartbeat unless connected to server, but we once were connected
    if (this.wito.online != this.wito.status_ONLINE) beat = false;
    // find out if we're waiting on the server for anything else
    if (this.wito.ajax_countOutstanding()) beat = false;
    // get current session
    var session = this.wito.sessionList.getCurrent();
    if (session == null) beat = false;
    // beat, or schedule next beat
    if (beat) {
        // fire 'none' update to server
        var postObj = session.wito.ajax_prep(this.wito.flag_actionNONE | this.wito.flag_targetSESSION);
        postObj.session = session.createPartial(this.wito.flag_actionNONE);
        this.wito.ajax_update(postObj);
        // this.wito.debug('heartbeat (update request) sent');
    } else {
        this.reschedule();
    }
}


witoHeartbeatClass.prototype.suspend = function() {
    if (!this.suspended) {
        this.cancel();
        this.suspended = true;
    }
}


witoHeartbeatClass.prototype.resume = function() {
    if (this.suspended) {
        if (!this.time) this.time = 1000;
        this.suspended = false;
        this.schedule(this.time);
    }
}


/**
 *
 *
 * Helper functions
 *   __function name
 * 
 *
 */

/**
 * __object_toURL
 *
 * Input
 *  object to convert into string
 *  prepend (optional)
 */
witoClass.prototype.__object_toURL = function(obj) {
    var str='';
    var prepend='';
    // prepend is an optional parameter
    if (arguments.length == 2) {
        prepend = arguments[1] + '__';
    }
    for(prop in obj) {
        if (typeof(obj[prop]) == 'object') {
            // trailing &amp; comes from call down to _toURL()
            str += this.__object_toURL(obj[prop], prepend + prop);
        } else if (typeof(obj[prop]) == 'function') {
            // exclude functions
        } else {
            str += prepend + prop + '=' + escape(obj[prop]) + '&';
        }
    }
    return(str);
}


witoClass.prototype.__objectToString = function(obj) {
    str='';
    for(prop in obj) {
        if (typeof(prop) == "function") continue;
        str+=prop + " value :"+ obj[prop]+"\n";
    }
    return(str);
}


witoClass.prototype.__arrayToString = function(obj) {
    str='';
    for(var i=0 ; i<obj.length ; ++i) {
        var k = obj[i];
        str += '['+i+'] '+ (k ? k : 'NULL') +"\n";
    }
    return(str);
}


witoClass.prototype.pad = function(num) {
    var str = "";
    if (num <= 99) str+="0";
    if (num <= 9) str+="0";
    str+=num;
    return(str);
}


witoClass.prototype.padHex = function(num,len) {
    var k = num.toString(16);
    var pad = '';
    for (var i=k.length ; i<len ; ++i) {
        pad += '0';
    }
    return(''+pad+k);
}


witoClass.prototype.colourThreshold = function(colour, threshold) {
    var b = 0.114*(colour & 0x0000FF), g = 0.587*((colour & 0x00FF00) >> 8), r = 0.299*((colour & 0xFF0000) >> 16);
    var gr = Math.sqrt(r*r + g*g + b*b);
    // this.debug('r['+r+'] g['+g+'] b['+b+'] -> grey['+gr+']');
    return(gr < threshold);
}


witoClass.prototype.colourLighten = function(colour, amt, lighten) {
    var c = new Array();
    // force lighten flag to be consistent
    lighten = true;
    c[0] = (colour & 0x0000FF);
    c[1] = (colour & 0x00FF00) >> 8;
    c[2] = (colour & 0xFF0000) >> 16;
    // amt [0-1], amount to lighten where 0 = none, 1 = white
    if (lighten) {
        amt *= -1;
    }
    for (var i=0 ; i<3 ; ++i) {
        c[i] = Math.round(c[i] + (amt * 0xFF));
        if (c[i] > 0xFF) c[i] = 0xFF;
        if (c[i] < 0x00) c[i] = 0x00;
    }
    var outcol = c[0] + (c[1] << 8) + (c[2] << 16);
    // this.debug('r['+c[2]+'] g['+c[1]+'] b['+c[0]+']');
    return(outcol);
}


witoClass.prototype.debug = function(mess) {
    if (this.DEBUG_LOSEC) {
        alert(mess);
    }
}


witoClass.prototype.debugCacheMess = function(mess) {
    if (this.DEBUG_LOSEC) {
        if (!this.debugCache) this.debugCache = new Array();
        this.debugCache[this.debugCache.length] = mess;
        if (this.debugCache.length >= 20) this.debugCacheClear();
    }
}


witoClass.prototype.debugCacheClear = function() {
    if (this.DEBUG_LOSEC) {
        var str = '';
        for (var i=0 ; i<this.debugCache.length ; ++i) {
            str += this.debugCache[i] + "\r\n";
        }
        alert(str);
        this.debugCache.length = 0;
        this.debugCache = null;
    }
}


witoClass.prototype.warning = function(mess) {
    alert(mess);
}


witoClass.prototype.error = function(mess) {
    alert(mess);
}



