// JavaScript used by all pages

// THESE SCRIPTS ARE THE COPYRIGHT OF JOHN LIDDIARD (C) 2005 AND MAY NOT BE
// COPIED OR USED WITHOUT HIS EXPLICIT CONSENT


// ======================= CONFIGURATION PARAMETRES =======================================
var cookie_prefix='brookfarmbandb';
var history_unwanted_text_re = /Brook Farm Bed and Breakfast\s*-\s*/gi;
var whatsnew_page = ''; // set to whatnew page if it is present eg 'info/whatsnew.htm'
var history_limit = 15; // Increase to 15 or so for history to be displayed
var search_page = '';
var ajax_extend_top_menu = true;            // set to 'true' to enable extensions such as in-page editing
var debug_flag = 1;
var vertical_menu_style = 'bar'; // can be links, bar, tabbed
var horizontal_menu_style = 'bar';
var vertical_menu_width = 210;
var default_menu_group = 'All';
var default_style = 'sitestyle.css';
var style_folder = 'sys_look/';
var path_prefix = '';
var tip_processing_script = 'sys_cgi-bin/ticker_display.cgi';
var tip_processing_method = 'none'; // 'none', 'ajax', 'iframe' etc
var ajax_security_check_script = 'sys_cgi-bin/ajax_security_check.cgi';

// Arrays listing js libraries in the order we want them loaded (they may load further
// stuff). initial libraries are loaded asap. more libraries are loaded later.
var jslib = 'js-lib/';

// initially needed
var initial_libraries = ['prototype.js'];
// used later
var more_libraries = ['cookies.js'];
// ===================== END CONFIGURATION PARAMETRES =====================================

// Style info - global with defaults
var Look = {
    Folder: style_folder,
    Sheet:  default_style,
    Deafult:default_style
    };

// Secondary config - derived - global
var cgibin = path_prefix+"sys_cgi-bin/";
var login_cookie = cookie_prefix+'lc';
var user_cookie = cookie_prefix+'uc';
var time_cookie = cookie_prefix+'tc';
var group_cookie = cookie_prefix+'gc';
var history_cookie = cookie_prefix+'history';
var style_cookie = cookie_prefix+'sc';
var usr_menu_cookie = cookie_prefix+'umenu';
var picbrowser_cookie = cookie_prefix+'pb';
var cgi_params_cookie = cookie_prefix+'cgi_p';

// write to either this doc window or a named window
function write_on_wdow(text,wdow){
    if (wdow) {
        wdow.document.write (text);
        }
    else {
        document.write (text);
        }
    }

// ==================== Start of all docs ===============================

// Prefix for web path resolution - global
var prefix = "";
function set_path(path) {
    if (path) {
        path_prefix = path;
        path_prefix = path_prefix.replace ( /[\/]+$/, '/');
        cgibin = path_prefix+"sys_cgi-bin/";
        }
    }

// Reference the appropriate style sheet and libraries
function include_style(path,wdow,s_file) {
    if (path) {
        path_prefix = path;
        path_prefix = path_prefix.replace ( /[\/]+$/, '/');
        cgibin = path_prefix+"sys_cgi-bin/";
        }
    var alt_style = getCookie(style_cookie);
    if (alt_style){
        Look['Sheet']=alt_style;
        }
    var derived_style = s_file || Look['Sheet'];
    var text='<link rel=stylesheet type="text/css" href="'+path_prefix+Look['Folder']+derived_style+'">';
    write_on_wdow (text,wdow);

    // The initial libraries needed to kick things off
    load_some_libraries(initial_libraries, wdow);
    // More libraries
    load_some_libraries(more_libraries, wdow);

    }

// ================== Load thrid party libraries ==============================
// load any defined libraries
function load_some_libraries(lib_id, wdow){
    if (    (typeof lib_id == 'object')
            &&
            (lib_id.length>0)
            &&
            (typeof jslib == 'string')
        ){
        for (var libIx in lib_id){
            var libraryName = lib_id[libIx];
            include_lib (path_prefix+style_folder+jslib+libraryName,wdow);
            }
        }
    }

// A way of including a javascript library passed as a parameter
function include_lib (libraryPath, wdow){
    //alert(libraryPath);
    //return;
    try {
        write_on_wdow ('<script type="text/javascript" src="'+libraryPath+'"><\/script>', wdow);
        }
    catch (e) {
        alert (e);
        }
    }

// ================== Start of all doc bodies ==============================

var Biscuit_Tin;

function page_start(wdow) {

    // Cookies by oo method from cookies.js
    Biscuit_Tin = new CookieJar({
        expires:60*60*24*365,   // seconds => 1 year
        path: '/'
        });

    // delete any param passing cookie, so it is clean for any uses in the page
    deleteCookie(cgi_params_cookie);
    // DEBUG
    test_stuff();
    }


// ================== End of all docs ====================================

// Display all the end of page stuff
function page_end(ctr_name,wdow) {
    page_end_ticker(wdow);
    horizontal_menu_bar(wdow);
    page_end_credit(wdow);
    page_end_ctr(ctr_name,wdow);
    tip_prepare(wdow);
    page_end_diag(wdow);
    page_end_cookie_diag(wdow);
    }

// Display a credit to me! -----
function page_end_credit(wdow) {
    write_on_wdow ('<br><br><br>',wdow);
    write_on_wdow ('<p class="fn">Web engineering by<br> <a href=http://www.jlunderwater.co.uk/index.htm target=_top>',wdow);
    write_on_wdow ('<img align=middle src='+path_prefix+'graphics/uwlinkbtn.jpg border=0 alt="John Liddiard Underwater" width=115 height=74></a>',wdow);
    write_on_wdow ('<br><br>',wdow);
    write_on_wdow ('<a href="http://1and1.co.uk/xml/init/?k_id=10558033" target="_blank"><img align=middle src="http://banner.1and1.co.uk/xml/banner?size=6&number=1" width="140" height="28"  border="0"/></a></p>',wdow);
    write_on_wdow ('<br><br><br>',wdow);
    }

// Put a counter at the end of the page -----
function page_end_ctr(ctr_name,wdow) {
    var ctrurl;
    var cn;

    // specified counter
    if (ctr_name) {
        cn = ctr_name;
        }

    else {
        // no counter specified or assumed, so don't render it.
        cn = null;
        }

    if (cn===null || cn=='' || cn==' ' || cn.indexOf('.htm')>=0 || cn.indexOf('<!')>=0){
        cn = null;
        }

    if (cn){
        var ctr_link_params = 'ctr='+cn;
        ctrurl = cgilink('counter_image.cgi', ctr_link_params);
        var ctr_link = '<img src='+ctrurl+' width=1 height=1 border=0>';
        write_on_wdow (ctr_link, wdow);

        // use counter id to track history as pages are laoded
        add_page_history(cn,wdow);

        // create a top 'floating' menu bar control for display
        // once the page has loaded
        create_top_menu_control(cn);
        }

    }

// Jumps to a location within a page -----
function pageJump(label_name,wdow) {
    if (wdow) {
        wdow.location.hash=label_name;
        }
    else {
        location.hash=label_name;
        }
    }

// ================== History Record ====================================
// records pages visited, with counts and when visited
// used for quick links to history
// may also be useful for histeresis in the way pages & links behave

// object of pages, each page is an obj of time and count
// global to the page
var hist_obj = new Object();

// given a hist obj (or any obj), makes sure it is set to the hist obj in the cookie
function load_hist_obj(){
    var max_retries = 5;
    var ct=0;
    while ( (!Object.keys(hist_obj) || Object.keys(hist_obj).length<1) && ct<max_retries){
        hist_obj = Biscuit_Tin.get (history_cookie);
        ct++;
        }
    if (ct>1){
        //debug("GET HIST OBJ repeat = "+ct+"\n"+Object.toJSON(hist_obj));
        }
    // clean up old style cookies
    old_cookie_cleanup(history_cookie);
    }

function save_hist_obj(){
    if (hist_obj && Object.keys(hist_obj).length>0){
        // Cut the history down to size
        trim_history ();
        //save a valid hiostory in a cookie
        Biscuit_Tin.put(history_cookie, hist_obj);
        }
    else if (typeof hist_obj != 'undef'){
        // kill the cookie completely if the history is empty
        Biscuit_Tin.remove(history_cookie);
        }
    }

function trim_history (){
    // Stop the history object from growing too big

    // adjust limit down if we are nearing cookie capacity (4096 in IE and web specs)
    var lhlim = history_limit;
    if (4096 - document.cookie.length < 150){
        var cur_l = Object.keys(hist_obj).length;
        if (cur_l < lhlim){
            lhlim = cur_l-2;
            }
        else {
            lhlim = lhlim-2;
            }
        }
    // Loop round, killing 1 at a time
    var ct=0; // prevent infinite loops
    var oldest_time;
    var oldest_item;
    while (Object.keys(hist_obj).length>lhlim && ct<5){
        // identify the oldest item
        Object.keys(hist_obj).each(function(page){
            if ( !oldest_time || (hist_obj[page].p_time < oldest_time) ){
                oldest_time = hist_obj[page].p_time;
                oldest_item = page;
                }
            });

        // trim the object to the limit by not copying the oldest item
        // or any items we should have skipped
        var hobj2 = new Object();
        Object.keys(hist_obj).each(function(page){
            if (    (page != oldest_item)
                    &&
                    (!skip_index(page))
                ){

                var page_info_obj = new Object ();
                page_info_obj.p_title = hist_obj[page].p_title;
                page_info_obj.p_time  = hist_obj[page].p_time;

                var new_hist_item_obj = new Object();
                new_hist_item_obj[page] = page_info_obj;

                Object.extend (hobj2, new_hist_item_obj);
                }
            });
        ct++;
        hist_obj = hobj2;
        }
    }

// Adds the specified page to the history
function add_page_history (sys_page, wdow) {

    var page = derive_page_address(sys_page);

    var sys_time = new Date();
    var time_now = parseInt(sys_time.getTime()/1000); // Seconds, not ms

    // Get any previous page history from the cookie
    load_hist_obj();

    // some pages just don't get recorded
    if (page == ''){
        // do nothing to hist obj
        }
    else if (skip_index(page)){
        // do nothing to hist obj
        }
    // if it is already in the history, simply update the time and count
    else if (   hist_obj &&
            hist_obj[page] &&
            hist_obj[page].p_time
        ){
        hist_obj[page].p_time = time_now;
        }
    else {
        var page_info_obj = new Object ();
        page_info_obj.p_title = title_tidy(document.title);
        page_info_obj.p_time  = time_now;

        var new_hist_item_obj = new Object();
        new_hist_item_obj[page] = page_info_obj;

        if (hist_obj){
            Object.extend (hist_obj, new_hist_item_obj);
            }
        else {
            hist_obj = new_hist_item_obj;
            }
        }


    // Save the revised history obj
    save_hist_obj();
    }

// turn what may be a page address or counter into a simple address within the site
function derive_page_address(page){
    if (typeof page == 'string') {
        page=page.replace(/^[\.\/\/]+/, '');
        page=page.replace(/\.[a-zA-Z0-9]+$/, '');
        return page;
        }
    else {
        return '';
        }
    }

// look for pages that we don't include, like those already in the menu
function skip_index(page){
    if (page == 'home_page'){
        return 1;
        }

    if (page == 'error1'){
        return 1;
        }

    if (page == 'ctr'){
        return 1;
        }

    if (page.indexOf('user_script_counter')>=0){
        return 1;
        }

    if (page.indexOf('goto')>=0){
        return 1;
        }

    return;
    }

// actually create the control to select from history, whatsnew, search etc.
function create_top_menu_control(sys_page){

    var current_page = derive_page_address(sys_page);

    // Get any previous page history from the cookie
    load_hist_obj();

    // assemble the page list from the cookie
    var hist_list = new Array();

    if (hist_obj) {
        hist_list = Object.keys(hist_obj);
        if (hist_list.length>1){
            hist_list.sort(hist_cmp);
            }
        }

    var hist_op2 = new Array();
    // no display if no history
    if (hist_list.length>0){
        // make an array of all the selection components
        hist_list.each(function(hist_page){
            // some pages just don't get shown in the history
            if ( hist_op2.length > history_limit){
                // don't show if the history is getting too long
                }
            else if (hist_page == current_page){
                // don't show current page
                }
            else if (skip_index(hist_page)){
                // don't show pages we are supposed to ignore
                }
            else if (contains_garbage(hist_page)) {
                 //don't show pages containing garbage
                }
            else if (   hist_obj &&
                    hist_obj[hist_page] &&
                    hist_obj[hist_page].p_title
                ){
                var hsel = '<option value="'+hist_page+'">'+hist_obj[hist_page].p_title;
                //alert (hsel);
                hist_op2.push(hsel);
                }
            });
        }

    var op1 ='';
    op1 += '\n<div class="hm" id="history_bar_div">';
    op1 += '<center><form id="hist_bar_form" method="post">';

    var op2 ='';
    // Edit page button?
    if (ajax_extend_top_menu){
        op2 += '<span id=extend_hist_bar></span>';
        }

    // History menu?
    if (history_limit>0 && hist_list.length>0 && hist_op2.length>0){
        op2 += ' ';
        op2 += '<select name="history_menu" onChange="return hist_go(this.form);">';
        op2 += hist_op2.join('\n');
        op2 += '</select>';
        op2 += '<input type="submit" value="Go" onClick="return hist_go(this.form);">';
        }

    // Whatsnew button?
    if (    (typeof whatsnew_page == 'string')
            &&
            (whatsnew_page.length>2)
        ){
        op2 += ' ';
        op2 += '<input type="submit" value="What&#146;s New" onClick="return whats_new_go(this.form);">';
        }

    // Search Bar?
    if (    (typeof search_page == 'string')
            &&
            (search_page.length>2)
        ){
        op2 += ' ';
        op2 += '<input type="textfield" name="search_terms" size="20" maxlength="100">';
        op2 += '<input type="submit" value="Search" onClick="return search_go(this.form);">';
        }

    var op3 ='';
    op3 += '</center></form>';
    op3 += '</div>\n';

    if (op2.length>0){
        write_on_wdow (op1+op2+op3);
        $('history_bar_div').style.visibility="hidden";

        var op4 ='\n<script>document.onLoad = activate_history_select();</script>\n';
        write_on_wdow (op4);
        }
    }

// sort compare function for history
function hist_cmp(a,b){

    // Get any previous page history from the cookie
    load_hist_obj();

    // hist_sort_by is a global config that
    // names the attribute to sort by

    var a_m = hist_obj[a].p_time;
    var b_m = hist_obj[b].p_time;

    // number (time?) sorts to highest first
    if (typeof(a_m) == 'number'){
        if (a_m < b_m) return 1;
        if (a_m > b_m) return -1;
        return 0;
        }
    // anything else sorts to lowest first
    if (a_m > b_m) return 1;
    if (a_m < b_m) return -1;
    return 0;
    }

// tidy up a title
function title_tidy (title_text){
    title_text = title_text.replace(/<[^>]+>/gi, ''); // remove any formatting tags
    title_text = title_text.replace(/\([^\)]+\)/gi, ''); // remove any parenthesis
    title_text = title_text.replace(history_unwanted_text_re, ''); // remove any others
    title_text = title_text.replace(/\&amp\;/gi, 'and'); // amphersand
    title_text = title_text.replace(/[\"\']+/gi, 'and'); // punctuation
    return title_text;
    }

// history control is only activated on load
function activate_history_select(){
    try{
        var hm_id = $("history_bar_div");
        if (hm_id){
            var co_ords = new guess_history_co_ords();
            hm_id.style.position="absolute";
            hm_id.style.left=co_ords.c_left;
            hm_id.style.top=co_ords.c_top;
            hm_id.style.visibility="visible";
            }
        maybe_extend_history_select();
        }
    catch(e){
        debug(e);
        }
    }

function guess_history_co_ords(){
    this.c_left = '0px';
    this.c_top = '0px';
    if (document.getElementsByTagName("h1")){
        var first_h1 = document.getElementsByTagName("h1")[0];
        if (first_h1){
            this.c_left = first_h1.offsetLeft;
            this.c_top = first_h1.offsetTop;
            //alert('h1 found LEFT:'+this.c_left+' TOP:'+this.c_top);
            }
        }
    return;
    }

// actually navigate to the selected history page, when the go button is clicked
function hist_go(hmf){
    var page = hmf.history_menu.value;
    var site = get_site_base_addr();
    //alert ('http://'+site +'/'+ page + '.htm');
    top.location.href = 'http://'+site +'/'+ page + '.htm';
    return false;
    }

function search_go(sf){
    if (typeof search_page == 'string'){
        var site = get_site_base_addr();
        var sterms = 'search_terms='+sf.search_terms.value;
        document.location.href = 'http://'+site +'/'+ search_page + '?'+ sterms;
        }
    return false;
    }

function whats_new_go(sf){
    if (typeof whatsnew_page == 'string'){
        var site = get_site_base_addr();
        top.location.href = 'http://'+site +'/'+ whatsnew_page;
        }
    return false;
    }

// The history select bar may be extended later (eg. edit?)
function maybe_extend_history_select(){
    if (typeof Ajax == 'object'){
        var ck_url = path_prefix+ajax_security_check_script;
        var folder_explorer_page = get_current_page_id();
        var folder_explorer_folder = folder_explorer_page.replace(  /[^\\\/]+$/i,'' );

        try {
            var req_by_ajax  =  new Ajax.Request (
                    ck_url,
                    {
                        method:'put',
                        parameters: {
                                        folder_explorer_page: folder_explorer_page,
                                        folder_explorer_folder: folder_explorer_folder,
                                        ajax: 'ajax',
                                        cmd: 'Edit'
                                        },

                        onSuccess: function(transport){
                            var response = conditional_unenc_it(transport.responseText);
                            //alert('Success\n' + response);
                            //alert(typeof response);
                            if (    (typeof response == 'string')
                                    &&
                                    (response.match(/^EDIT\-OK/))
                                ){
                                // check passed, so enable editing
                                response = response.replace(/^EDIT-OK[\s]*/,'');
                                add_edit_button_to_hist_select(response);
                                }
                            else {
                                // do nothing
                                //alert('Security fail\n' + response);
                                }
                            },

                        onFailure: function(){
                            // do nothing
                            //alert('Something went wrong\n' + ajax_security_check);
                            }
                    }
                );
            }
        catch (e){
            debug(ck_url + '\n' + e);
            }
        }
    }

// if the security check passes, add an edit control to the end of the history/search bar
function add_edit_button_to_hist_select(security_resp){

    var lc = getCookie(login_cookie);

    var xp = lc.split('||')[1];
    var xu = lc.split('||')[0];

    op = '\n<input id="hb_lcl_edit_page" type="submit" name="lcl_edit_page" value="Edit Page" onClick="return edit_go(this.form);">';
    op += '<input id="hb_u" type="hidden" name="u" value="'+xu+'">';
    op += '<input id="hb_p" type="hidden" name="p" value="'+xp+'">';

    // Other parameters are built from the returned cgi info
    var resp_lines = new Array ();
    resp_lines = security_resp.split('\n');

    resp_lines.each(function(resp_line){
        if (contains_garbage(resp_line)) {
            return;
            }

        if (resp_line.indexOf('=')>=0){
            var f_name = resp_line.split('=')[0];
            var f_val = resp_line.split('=')[1];
            op += '<input id="hb_'+f_name+'" type="hidden" name="'+f_name+'" value="'+f_val+'">';
            }
        });

    //debug (op);

    $("extend_hist_bar").insert(op+'&nbsp;');

    }

function edit_go (hist_form) {
    //
    $("hist_bar_form").action = cgibin + $F("hb_lcl_edit_actn");
    //debug ('GO '+$("hist_bar_form").action);
    return true;
    }


// ====== AJAX garbage detection - covers for a glitch in Prototype =======
// spot/ignore any ajax stuff that amy creeps in
function contains_garbage (wanted_a_string){
    if (typeof wanted_a_string != 'string' ){
        return true;
        }
    if (    (wanted_a_string.indexOf('function (')>=0)
            ||
            (wanted_a_string.indexOf('var ')>=0)
            ||
            (wanted_a_string.indexOf(');')>=0)
            ||
            (wanted_a_string.indexOf('return this;')>=0)
        ){
        return true;
        }
    return false;
    }

// ================== Menu Display ====================================

// Submits any form, a means of causing a page to navigate
function autosub(form_name){
    document.body.style.cursor = "progress"; //# Could also consider 'wait'
    document.forms[form_name].submit();
    }

function menuLoad(){
    var wname = '../sys_menu/menu.htm';
    try { // in case parent is out of scope?
        parent.menu.location=wname;
        }
    catch(e){
        }
    }

var ml_1 = '<tr><td class=';
var ml_1a = ' id=';
var ml_1T = '<tr><td style="text-align:center;font-style:normal;font-size:10pt;margin:0pt;padding:3px;border-collapse:collapse;" class=';
var ml_1aT = ' id=';
var ml_1H = '<nobr><span class=';
var ml_1aH = ' id=';
var ml_2 = ' onClick="return click_menu_item(';
var ml_2T = ' onClick="return click_tab_item(';
var ml_2a = ')" onMouseOut="return unhover_menu_item(event,';
var ml_2b = ')" onMouseOver="return hover_menu_item(event,';
var ml_2c = ')" onContextMenu="return right_click_menu_item(event,';
var ml_3 = ')">&nbsp;';
var ml_3T = ')">';
var ml_4 = '&nbsp;</td></tr>\n\n';
var ml_4T = '</td></tr>\n\n';
var ml_4H = '&nbsp;</span></nobr>\n\n';

function build_v_menu_item (item_to, item_label, ix, active){
    var lbl_name = "'"+item_label+"'"; // not used
    var item_id = "'"+item_label+'_V'+ix+"'";
    var click_to = "'"+item_to+"'";
    var itm_style = 'mnu';
    if (active){itm_style='mnu_active'};
    return   ml_1+itm_style
            +ml_1a+item_id
            +ml_2+click_to
            +ml_2a+item_id+",'"+itm_style+"'"
            +ml_2b+item_id+",'"+itm_style+"'"
            +ml_2c+item_id
            +ml_3+item_label
            +ml_4+'\n';
    }

function build_t_menu_item (item_to, item_label, ix, active){
    var lbl_name = "'"+item_label+"'"; // not used
    var item_id = "'"+item_label+'_T'+ix+"'";
    var click_to = "'"+(item_to||item_label)+"'";
    var vlabel = vtab_from_text (item_label);
    var itm_style = 'mnu';
    if (active){itm_style='mnu_active'};
    return   ml_1T+itm_style
            +ml_1aT+item_id
            +ml_2T+click_to
            +ml_2a+item_id+",'"+itm_style+"'"
            +ml_2b+item_id+",'"+itm_style+"'"
            +ml_2c+item_id
            +ml_3T+vlabel
            +ml_4T+'\n';
    }

// Creates a vertical repesentation of a string, char below char
function vtab_from_text (label_text){
    label_text = label_text.toUpperCase() || 'undefined';
    var c1;
    var vertical_form = label_text.substring(0,1);
    for (i=1; i<label_text.length; i++){
        c1 = label_text.substring(i,i+1);
        vertical_form = vertical_form + "<br>\n"+ c1;
        }
    return vertical_form;
    }

function build_h_menu_item (item_to, item_label, ix, active){
    var lbl_name = "'"+item_label+"'";// not used
    var item_id = "'"+item_label+'_H'+ix+"'";
    var click_to = "'"+item_to+"'";
    var itm_style = 'mnu';
    if (active){itm_style='mnu_active'};
    return   ml_1H+itm_style
            +ml_1aH+item_id
            +ml_2+click_to
            +ml_2a+item_id+",'"+itm_style+"'"
            +ml_2b+item_id+",'"+itm_style+"'"
            +ml_2c+item_id
            +ml_3+item_label
            +ml_4H+'\n';
    }


function click_menu_item(click_to){
    //debug(path_prefix+'='+click_to);
    top.location.href = path_prefix+click_to;
    }
function hover_menu_item(event_id, item_id, itm_style){
    try{
        locate_and_show_tip(event_id,item_id);
        if (itm_style=='mnu_active'){
            return;
            }
        $(item_id).className="mnu_on";
        }
    catch (e) {
        }
    }

function unhover_menu_item(event_id, item_id, itm_style){
    try{
        cPrev();
        $(item_id).className=itm_style;
        }
    catch (e) {
        }
    }

function click_tab_item(click_to){
    //record global for the group
    current_group = click_to;
    if (    current_group
            && (current_group != 'Groups')
            && (current_group != 'HorizontalMenu')
        ){
        setCookie(group_cookie, current_group);
        }
    var GroupList = new menu_group_list();
    refresh_v_menu(current_group, GroupList)
    }


function locate_and_show_tip(event_id, item_id){
    var itm_label = item_id.split('_')[0];
    var itm_tag = item_id.split('_')[1];
    var itm_tag_type = itm_tag.replace(/[0-9]+/gi, '');
    var itm_tag_ix = itm_tag.replace(/[A-Z]+/gi, '');

    var tip;
    if (itm_tag_type == 'T') {
        // tip for group
        var GroupList = new menu_group_list();
        tip = GroupList[itm_label].tip;
        }
    else {
        // tip for menu item
        var Menu_Item = new menu_item_const(Menu_Data[itm_tag_ix]);
        tip = Menu_Item.tip;
        }
    if (tip){
        dPrev(tip,event_id,(itm_tag_type == 'T')||(itm_tag_type == 'V'));
        }
    }


function right_click_menu_item(event_id, item_id){
    var itm_label = item_id.split('_')[0];
    var itm_tag = item_id.split('_')[1];
    var itm_tag_type = itm_tag.replace(/[0-9]+/gi, '');
    var itm_tag_ix = itm_tag.replace(/[A-Z]+/gi, '');

    // find the current page
    var current_page = get_current_page_id();
    var current_group = derive_initial_group();

    // Is it configurable?
    var Menu_Item = new menu_item_const(Menu_Data[itm_tag_ix]);
    if (    (Menu_Item.name != 'User Config')
         && (Menu_Item.name.search('[U]')<0)
        ){
        return false;
        }
    if (current_group == 'Groups'){
        return false;
        }
    if (current_group == 'HorizontalManu'){
        return false;
        }

    // Guess and correct the button name
    var btn_name = title_tidy(top.document.title);
    btn_name = prompt('Set "User Config" to "' + current_page + '." Please edit/confirm the button name', btn_name);
    if (btn_name == null) {
        //-"CANCEL returns null -> return false
        return false;
        }
    // tidy again - get rid of any unwanted punctuation
    btn_name = title_tidy(btn_name);

    var umenu_data = getCookie(usr_menu_cookie);
    var new_umenu_item = itm_tag_ix + '::' + btn_name + ' [U]::' + current_page;
    var update_made=0;
    if (umenu_data && umenu_data.length>10){
        // existing menu data exists
        var new_umenu_data='';
        for (var umenu_ix in (umenu_data.split('||'))){
            var umenu_item = umenu_data.split('||')[umenu_ix];
            if (contains_garbage(umenu_item)) {
                continue;
                }
            var umenu_item_ix = umenu_item.split('::')[0];

            // is the slot still user configurable?
            Menu_Item = new menu_item_const(Menu_Data[umenu_item_ix]);
            if (    (Menu_Item.name != 'User Config')
                 && (Menu_Item.name.search('[U]')<0)
                ){
                update_made++;
                continue;
                }

            //debug(umenu_ix +'\n'+umenu_item+'\n'+umenu_item_ix+'\n'+itm_tag_ix+'\nupdate_made'+update_made);

            if (umenu_item_ix==itm_tag_ix){
                // Skip if an item with this number has already been updated
                if (update_made>0){
                    update_made++;
                    continue;
                    }
                // Skip if no button defined
                if (btn_name == ''){
                    update_made++;
                    continue;
                    }
                if (btn_name == '[U]'){
                    update_made++;
                    continue;
                    }
                //swap in the new item
                umenu_item = new_umenu_item;
                update_made++;
                }
            // extend the data ready for saving later
            if (new_umenu_data.length>0){
                new_umenu_data += '||' + umenu_item;
                }
            else {
                new_umenu_data = umenu_item;
                }
            }
        if (update_made>0){
            // swap data for new
            umenu_data = new_umenu_data;
            }
        else {
            // else, not found, so append,
            umenu_data += '||' + new_umenu_item;
            update_made++;
            }

        }
    else {
        // none exists, so we can set it by itself, save & exit
        umenu_data = new_umenu_item;
        update_made++;
        }

    if (update_made>0){
        setCookie(usr_menu_cookie, umenu_data);

        // replace it in the menu
        Menu_Data[itm_tag_ix] =         btn_name + ' [U]'
                                +'||' + current_page
                                +'||' + Menu_Item.security
                                +'||' + Menu_Item.group
                                +'||' + Menu_Item.tip ;

        refresh_v_menu(Menu_Item.group)
        }
    return false;
    }

function update_menu_data_for_user(){
    var umenu_data = getCookie(usr_menu_cookie);
    if (!umenu_data){
        return;
        }
    if (umenu_data.length<11){
        return;
        }

    for (var umenu_ix in (umenu_data.split('||'))){
        var umenu_item = umenu_data.split('||')[umenu_ix];
        if (contains_garbage(umenu_item)) {
            continue;
            }
        var umenu_item_ix = umenu_item.split('::')[0];
        var umenu_item_label = umenu_item.split('::')[1];
        var umenu_item_link = umenu_item.split('::')[2];

        // tidy again - get rid of any unwanted punctuation
        umenu_item_label = title_tidy(umenu_item_label);

        // Make sure any user buttons are clearly labelled
        if (umenu_item_label.search('[U]')<0){
            umenu_item_label +=' [U]';
            }

        // is it still aconfigurable item?
        var Menu_Item = new menu_item_const(Menu_Data[umenu_item_ix]);
        if (    (Menu_Item.name != 'User Config')
             && (Menu_Item.name.search('[U]')<0)
            ){
            continue;
            }

        // replace it in the menu
        var new_umenu_line =            umenu_item_label
                                +'||' + umenu_item_link
                                +'||' + Menu_Item.security
                                +'||' + Menu_Item.group
                                +'||' + Menu_Item.tip ;

        Menu_Data[umenu_item_ix] = new_umenu_line;
        }
    }


//===================================================================
// put together the V & H menus as prescribed by menu.js file
//=============== VERTICAL MENU ======================================
var current_group;
function vertical_menu_bar(wdow) {

    // adjust/maintain width of menu frame
    try {
        if (        vertical_menu_width
                 && window
                 && window.parent
                 && window.parent.document
                 ){
            var fset = window.parent.document.getElementsByTagName("frameset")[0];
            fset.cols = vertical_menu_width+",*";
            }
        }
    catch (exception_obj){
        }

    var GroupList = new menu_group_list();
    var current_group = derive_initial_group(GroupList);
    update_menu_data_for_user();

    // multiple styles of vertical menu....
    if ((! check_browser_capability()) || (vertical_menu_style == 'links')){
        // default menu - straight forward links
        write_on_wdow('<div id="Vmenu_area">'+links_v_menu()+'</div>', wdow);
        }
    else if((vertical_menu_style == 'tabbed') && (GroupList.length>2)){
        // Menu grouped by tabs
        write_on_wdow('<div id="Vmenu_area">'+tabbed_v_menu(current_group, GroupList)+'</div>', wdow);
        }
    else if(vertical_menu_style == 'bar'){
        // Simple bar of options, no tabs or groups
        write_on_wdow('<div id="Vmenu_area">'+bar_v_menu(current_group, GroupList)+'</div>', wdow);
        }
    // Default - bar
    else {
        // Simple bar of options, no tabs or groups
        write_on_wdow('<div id="Vmenu_area">'+bar_v_menu(current_group, GroupList)+'</div>', wdow);
        }

    // Counter
    var set_ctr_string = '<img src="../sys_cgi-bin/counter_image.cgi" width=1 height=1 border=0>';

    // only do counter if more than 1 mins since last here last time
    var tc = getCookie(time_cookie);
    last_time = parseInt(tc);
    // this time
    var sys_time = new Date();
    var the_time = sys_time.getTime();
    setCookie(time_cookie, the_time+' ');

    if (((the_time-last_time)/(1000*60))>1){
        document.write(set_ctr_string);
        //debug ('counter\n'+(the_time-last_time)/1000 + ' seconds');
        }
    else {
        //debug ('no counter\n'+(the_time-last_time)/1000+ ' seconds');
        }
    }

// Various options for vertical menus follow....

// Tabbed bar menu, each tag changing the group
function tabbed_v_menu (selected_group, GroupList){
    var op = '<table class=all_menu width=100%><tr><td class=all_menu valign=top width=100%><table class=all_menu valign=top width=100%>';

    // find the current page
    var current_page = get_current_page_id();

    // loop through menu data array, displaying each item in current group
    for (var Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if ( (! Menu_Item) || (! Menu_Item.name) || (! Menu_Item.link)){
            continue;
            };
        // Security test to be inserted. Next if fails;
        if (Menu_Item.security != user_security_ok(Menu_Item.security)){
            continue;
            }
        // Check for applicable group
        if (Menu_Item.group && (Menu_Item.group == 'HorizontalMenu')){
            continue;
            };
        if (Menu_Item.group && selected_group && (Menu_Item.group != selected_group)){
            continue;
            };
        // Display menu line
        op += build_v_menu_item ( Menu_Item.link, Menu_Item.name, Menu_Index, (Menu_Item.link==current_page) );
        }
    op += '</table></td><td class=all_menu valign=top><table class=all_menu valign=top>';
    // loop through groups object, displaying each group
    var gix=1;
    for (var Group in GroupList){
        if (Group == 'length'){
            continue;
            }
        if (! GroupList[Group].security){
            continue;
            }
        if (GroupList[Group].security != user_security_ok(GroupList[Group].security)){
            continue;
            };
        // Display group item
        op += build_t_menu_item ( '', GroupList[Group].groupname, gix, (GroupList[Group].groupname == selected_group) );
        gix++;
        }
    op += '</table></td></tr></table><br clear=all>';
    return op;
    }

// Simple bar of options, no tabs or groups
function bar_v_menu (selected_group, GroupList){
    var op = '<p class="mr"><table class=all_menu>';

    // find the current page
    var current_page = get_current_page_id();

    // loop through menu data array, displaying each item
    for (var Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if ( (! Menu_Item) || (! Menu_Item.name) || (! Menu_Item.link)){
            continue;
            };
        // Security test to be inserted. Next if fails;
        if (Menu_Item.security != user_security_ok(Menu_Item.security)){
            continue;
            }
        // Check for applicable group
        if (Menu_Item.group && (Menu_Item.group == 'HorizontalMenu')){
            continue;
            };
        if (Menu_Item.group && selected_group && (Menu_Item.group != selected_group)){
            continue;
            };
        // Display menu line
        op += build_v_menu_item ( Menu_Item.link, Menu_Item.name, Menu_Index, (Menu_Item.link==current_page) );
        }
    op += '</table></p><br clear=all>';
    return op;
    }

// A default vertical menu - for situations when browser doesn't want to help
function links_v_menu (selected_group, GroupList){
    var op = '<p class="mr"><table class=all_menu>';
    // loop through menu data array, displaying each item
    for (var Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if ( (! Menu_Item) || (! Menu_Item.name) || (! Menu_Item.link)){
            continue;
            };
        // Security test to be inserted. Next if fails;
        if (Menu_Item.security != user_security_ok(Menu_Item.security)){
            continue;
            }
        // Check for applicable group
        if (Menu_Item.group && (Menu_Item.group == 'HorizontalMenu')){
            continue;
            };
        if (Menu_Item.group && selected_group && (Menu_Item.group != selected_group)){
            continue;
            };
        // Display simple menu link - no script used in link
        op += '<tr><td align=right>';
        op += '<a href='+path_prefix+Menu_Item.link+' target=_top>'+Menu_Item.name+'</a>';
        op += '</td></tr>';
        }
    op += '</table></p><br clear=all>';
    return op;
    }

// refresh a specified menu
function refresh_v_menu(current_group, GroupList){
    // Parameters - optional - make best guess if missing
    current_group = current_group || derive_initial_group(GroupList);
    GroupList = GroupList || (new menu_group_list());

    // Delete old menu
    var menu_elem = document.getElementById('Vmenu_area');
    while (menu_elem.childNodes.length>0){
        menu_elem.removeChild(menu_elem.firstChild);
        }
    // refresh menu in appropriate style....
    if ((! check_browser_capability()) || (vertical_menu_style == 'links')){
        // default menu - straight forward links
        menu_elem.innerHTML = links_v_menu(current_group, GroupList);
        }
    else if((vertical_menu_style == 'tabbed') && (GroupList.length>2)){
        // Menu grouped by tabs
        menu_elem.innerHTML = tabbed_v_menu(current_group, GroupList);
        }
    else if(vertical_menu_style == 'bar'){
        // Simple bar of options, no tabs or groups
        menu_elem.innerHTML = bar_v_menu(current_group, GroupList);
        }
    // Default - bar
    else {
        // Simple bar of options, no tabs or groups
        menu_elem.innerHTML = bar_v_menu(current_group, GroupList);
        }
    }

//================== HORIZONTAL MENU ==========================================
function horizontal_menu_bar(wdow) {
    var GroupList = new menu_group_list();
    var current_group = derive_initial_group(GroupList);
    // multiple styles of vertical menu....
    if ((! check_browser_capability()) || (horizontal_menu_style == 'links')){
        // default menu - straight forward links
        write_on_wdow (links_h_menu(current_group, GroupList),wdow);
        }
    else if(horizontal_menu_style == 'bar'){
        // Simple bar of options, no tabs or groups
        write_on_wdow (bar_h_menu(current_group, GroupList),wdow);
        }
    // Default - bar
    else {
        // Simple bar of options, no tabs or groups
        write_on_wdow (bar_h_menu(current_group, GroupList),wdow);
        }
    }

// Various options for horizontal menus follow....
// Simple bar of options, no tabs or groups
function bar_h_menu(selected_group, GroupList){
    var op = '<p class="mc">';

    // find the current page
    var current_page = get_current_page_id();

    // loop through menu data array, displaying each item
    for (var Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if ( (! Menu_Item) || (! Menu_Item.name) || (! Menu_Item.link)){
            continue;
            };
        // User configs don't go into horizontal menu
        if (    (Menu_Item.name == 'User Config')
             || (Menu_Item.name.search('[U]')>=0)
            ){
            continue;
            }

        // Security test to be inserted. Next if fails;
        if (Menu_Item.security != user_security_ok(Menu_Item.security)){
            continue;
            }
        // Check for applicable group
        if (Menu_Item.group && (Menu_Item.group != 'HorizontalMenu')){
            continue;
            };
        // Display flashy menu line
        op += build_h_menu_item ( Menu_Item.link, Menu_Item.name, Menu_Index, (Menu_Item.link==current_page) );
        }
    op += '</p><br clear=all>';
    return op;
    }

// A default horizontal menu - for situations when browser doesn't want to help
function links_h_menu (selected_group, GroupList){
    var op = '<p class="mc">';
    // loop through menu data array, displaying each item
    for (var Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if ( (! Menu_Item) || (! Menu_Item.name) || (! Menu_Item.link)){
            continue;
            };
        // Security test to be inserted. Next if fails;
        if (Menu_Item.security != user_security_ok(Menu_Item.security)){
            continue;
            }
        // Check for applicable group
        if (Menu_Item.group && (Menu_Item.group != 'HorizontalMenu')){
            continue;
            };
        // Display simpler menu link
        op += '<nobr>[';
        op += '<a href='+path_prefix+Menu_Item.link+' target=_top>'+Menu_Item.name+'</a>';
        op += ']</nobr> ';
        }
    op += '</p><br clear=all>';
    return op;
    }


// Constructor fn for a menu group list
// Extract the menu groups and build a list
function menu_group_list() {
    // loop through menu data array, building list of groups
    this.length=0;
    for (Menu_Index in Menu_Data){
        var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);
        if (! Menu_Item){
            continue;
            };
        if (        Menu_Item.group
                &&  Menu_Item.name
                && (Menu_Item.group == 'Groups')
                ){
            this[Menu_Item.name] = new menu_group_item(Menu_Item);
            this.length++;
            }
        }
    }

// Constructor for menu group extracted from menu item
function menu_group_item(Menu_Item){
    this.groupname = title_tidy(Menu_Item.name||'none');
    this.security = Menu_Item.security||'All';
    this.tip = Menu_Item.tip||'';
    }

// Constructoir for menu item extracted from text version
function menu_item_const(Menu_Item){
    if (Menu_Item.length<4){
        return;
        }
    this.name = title_tidy(Menu_Item.split('||')[0]||'');
    this.link = Menu_Item.split('||')[1]||'';
    this.security = Menu_Item.split('||')[2]||'All';
    this.group = Menu_Item.split('||')[3]||'';
    this.tip = title_tidy(Menu_Item.split('||')[4]||'');
    }

// Find which group/tab is currently in use, or closest guess.
function derive_initial_group(GroupList){
    GroupList = GroupList || (new menu_group_list());
    var last_group = getCookie(group_cookie)||default_menu_group;
    var current_page = get_current_page_id();
    // refresh menu in appropriate style....
    if ((! check_browser_capability()) || (vertical_menu_style == 'links')){
        return default_menu_group;
        }

    else if((vertical_menu_style == 'tabbed') && (GroupList.length>2)){
        // Tabbed - groups
        var exact_match;
        var close_match;
        // loop through menu data array, looking for group/page
        for (var Menu_Index in Menu_Data){
            var Menu_Item = new menu_item_const(Menu_Data[Menu_Index]);

            if (        Menu_Item.link
                     && (Menu_Item.link == current_page)
                     && Menu_Item.name
                     && Menu_Item.group
                     && (Menu_Item.group != 'Groups')

                ){
                if (Menu_Item.group == last_group){
                    exact_match = last_group;
                    return exact_match;
                    }
                if (!close_match){
                    close_match = Menu_Item.group;
                    }
                }
            }
        if (exact_match) {
            //debug("exact="+exact_match+'\npage='+current_page);
            return exact_match;
            }
        if (close_match) {
            //debug("close="+close_match+'\npage='+current_page);
            return close_match||default_menu_group;
            }
        //debug("last="+last_group+'\npage='+current_page);
        return last_group;
        }
    else if(vertical_menu_style == 'bar'){
        // bar explicitly selected, so no grouping
        return default_menu_group;
        }
    else {
        // Default - bar, so no grouping
        return default_menu_group;
        }
    }

//-------------------------------------------------------------------
// Browesr capability - returns true if browser supports all
// needed functionality for the menu system

function check_browser_capability() {
    brs_v = navigator.appVersion;
    if (parseInt(brs_v) >= 5) return true;
    var ua=navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    if (MSIEOffset>=0) {
        var iev = parseFloat(ua.substring(MSIEOffset+5, ua.indexOf(";",MSIEOffset)));
        if (iev >= 5) return true;
        }
    // before v5, so work in reduced menu...
    return false;
    }

//=======================Security related =========================

function xrieval(eref_level, esection, op2){
    // inline reveal fn

    var ref_level = dec_cg_param(eref_level);
    var section = dec_cg_param(esection);
    var dec_op2 = dec_cg_param(op2);
    var authority = get_authority(login_cookie);
    if (check_authority (authority, ref_level)){
        //alert(cookieDump() + '\n' + authority);
        write_on_wdow (dec_op2);
        }
    return;
    }

// do whatever decoding is necessary
function dec_cg_param (enc_cg){

    // unescape uri
    var dec_cg = decodeURIComponent(enc_cg);
    // remove other encoding
    var unenc_cg = unenc_it(dec_cg);
    return unenc_cg;
    }

// turn decimal and dot back into text
// - nothing that secure, just designed to stop idle curiosity
function unenc_it (hinp){
    var inp="";
    var hinp_chars =new Array();
    hinp_chars = hinp.split('.');
    var hkey = parseInt(hinp_chars.pop())%256; // last item is the key

    hinp_chars.each(function(hc_ext){
        if (contains_garbage(hc_ext)) {
            return;
            }
        var hc_pi = parseInt(hc_ext);
        if (hc_pi>255 ){
            return;
            }
        var hch1 = parseInt(hc_pi)%256;
        var hch2=(hch1^hkey)%256;
        var hc_str = String.fromCharCode(hch2);
        inp = inp + hc_str;
        });
    return inp;
    }


// Make it into a decimal and dot string
function enc_it (inp){
    // numbers from x22 to xEE
    var hkey = parseInt(16*parseInt(Math.random()*12+2)+parseInt(Math.random()*12+2))%256;
    var hinp = " ";
    var ch1;
    var ch2;
    for (var chix=0; chix<inp.length; chix++ ) {
        ch1 = inp.charCodeAt(chix)%256;
        ch2= parseInt(ch1^hkey);
        hinp = hinp+"."+ch2;
//      alert (chix+'\n'+ch1+'\n'+ch2+'\n'+hinp);
        }
    hinp=hinp.substr(2);
    hinp=hinp+"."+hkey;
    return hinp;
    }

function conditional_unenc_it (hinp){
    if (typeof hinp != 'string'){
        return hinp.toString;
        }
    if (!hinp){  //empty str
        return "";
        }
    if (    (hinp.match(/[^0-9\.]{1}/)) || // anything other than 0-9 or dot
            (hinp.indexOf('.')==-1)      // or no dots in it
        ){
        // not crypted
        return hinp;
        }
    return unenc_it (hinp);
    }

function conditional_enc_it (inp){
    if (!inp){ //empty str
        return "";
        }

    if (    (inp.match(/[^0-9\.]{1}/)) || // anything other than 0-9 or dot
            (inp.indexOf('.')==-1)       // or no dots in it
        ){
        // not crypted
        // alert(inp);
        return enc_it (inp);
        }
    return inp;
    }


var AuthCache = new Array;
function get_authority (cookiename){
    // get any long term user info from cookie
    // usr||pw||authority
    // authority has optional -L, -X

    // this gets called a lot when sorting out menus, so first try cache
    if (typeof AuthCache[cookiename] == 'string'){
        return AuthCache[cookiename];
        }

    var tmp_ck = getCookie(cookiename);
    if (typeof tmp_ck == 'string' && tmp_ck && tmp_ck.split('||')[2] ) {
        var auth = tmp_ck.split('||')[2];
        AuthCache[cookiename] = auth;

        //alert ('Set:\n'+AuthCache[cookiename]);
        return (auth);
        }
    return 'All';
    }

function user_security_ok (req_level){
    // authority of a remembered user
    var usr_level=get_authority(user_cookie);
    // authority of a logged in user
    var auth_level=get_authority(login_cookie);

    // Simple exit if visible to all
    if (req_level == 'All'){
        return req_level;
        }

    // trim -L from end
    var subreq=req_level;
    if (req_level.indexOf('-')>0) {
        subreq=req_level.split('-')[0];
        //debug('user_level='+usr_level+'\nauth_level='+auth_level+'\nreq_level='+req_level+'\nsubreq='+subreq);
        }

    // looking for login specific level - get from user_authority
    if (req_level.indexOf('-L')>0){
        // -X inverts the filter
        // as inverted, both usr & login auth are important
        if (req_level.indexOf('-X')>0){
            if (check_authority(usr_level,subreq)){
                return 'All';
                }
            else if (check_authority(auth_level,subreq)){
                return 'All';
                }
            else {
                return req_level;
                }
            }
        // filter not inverted
        if (check_authority(usr_level,subreq)){
            return req_level;
            }
        }

    // looking for authority of a logged in user - get from li_authority

    // -X inverts the filter
    if (req_level.indexOf('-X')>0){
        if (check_authority(auth_level,subreq)){
            return 'All';
            }
        else {
            return req_level;
            }

        }
    // Filter not inverted
    if (check_authority(auth_level,subreq)){
        return req_level;
        }

    // Anything else is All

    return 'All';
    }

//check the reuired level is as good as or better than the user's level
function check_authority (user_auth, req_auth){
    // quick solution for 'All'
    if (req_auth=='All'){
        return true;
        }

    // quick solution for exact match
    if (user_auth == req_auth){
        return true;
        }

    // quick solution for grouping numbers
    var sra= req_auth.replace(/[\d]+/, '');
    if (user_auth == sra){
        return true;
        }

    // user_auth contains a digit, and $req_auth is in the same group
    // but they are not the same (as shown above)
    var sua = user_auth.replace(/[\d]+/, '');
    if ((sua != user_auth)&&(sua == sra)){
        return false;
        }
    // (can now ignore grouping numbers)

    // now check actual levels
    var auth_levels = '|'+ list_security_cats().join('|')+'|';
    if (auth_levels.indexOf('|'+user_auth+'|') >= auth_levels.indexOf('|'+req_auth+'|')){
        return 1;
        }
    return false;
    }


//list all security levels
function list_security_cats () {
    return Security_Levels;
    }

// =================== Preview tips - on status bar and in popup =======================
// (Nothing to do with page level tips)

var currentdescription;
var tid;
var i=0;

// Clear the tip
function cPrev() {
    window.clearTimeout(tid);
    currentdescription=' ';
    // link to code for popup tool tips
    clear_tool_tip();
    window.status=' ';
    i = 0;
    return true;
    }

// Show the tip
function dPrev(description,evt,frameflag) {
    evt=(evt)?evt:event;
    window.clearTimeout(tid);
    currentdescription=' '+description;
    i = 0;

    // link to code for popup tool tips
    // frame flag used by menu to tell tip to pop in main window
    if (frameflag) {
        show_frame_tool_tip(currentdescription,evt);
        }
    else {
        show_tool_tip(currentdescription,evt);
        }

    if (currentdescription.length>100) {
        currentdescription='          '+description+'          ';
        window.status=currentdescription;
        scrollStatus();
        return true;
        }
    else {
        window.status=currentdescription;
        return true;
        }

    return true;
    }

// Scroll long tips
function scrollStatus() {
    window.status = currentdescription.substring(i,currentdescription.length) + currentdescription.substring(0,i-1);
    if (i < currentdescription.length) {
        i++;
        }
    else {
        i = 0;
        }
    tid = setTimeout('scrollStatus()',150);
    return true;
    }

// filter click action to only link for real events.
function cFilter(description) {
    window.clearTimeout(tid);
    window.status=' ';
    currentdescription=' '+description;
    i = 0;
    return true;
    }


//===========================ticker info in a box========================

function page_end_ticker(wdow) {
    try{ // in case a tip processing script is not defined
        if (tip_processing_script && (tip_processing_script.length>10)){


            if (tip_processing_method == 'iframe'){
                var tipcall = path_prefix+tip_processing_script+'?from='+get_current_page_id();
                write_on_wdow ('<div id="ticker_div">',wdow);
                write_on_wdow ('<p class=c><center><table class=bdr width=80%><tr><td>',wdow);
                write_on_wdow ('<IFRAME src="'+tipcall, wdow);
                write_on_wdow ('" width=100% height=200 border=0 frameborder=0 name="ticker" id="ticker" marginheight=0 marginwidth=0 align=middle standby="loading...">',wdow);

                write_on_wdow ('<script type="text/javascript" language="JavaScript"><!-- hide from browser');
                write_on_wdow ('ticker.document.body.onLoad = activate_ticker_frame();',wdow);
                write_on_wdow ('//--></script>',wdow);

                write_on_wdow ('</IFRAME></td></tr></table></center></p>',wdow);
                write_on_wdow ('</div>',wdow);
                }
            else if (tip_processing_method == 'ajax' && typeof Ajax == 'object'){

                write_on_wdow ('<div id="ticker_div">',wdow);
                ticker_by_ajax ();
                write_on_wdow ('</div>',wdow);
                }
            }
        }
    catch(e){
        debug(e);
        }
    return;
    }

function ticker_by_ajax() {
    var upd_by_ajax = new Ajax.Updater(
        'ticker_div',
        path_prefix+tip_processing_script, {
            method: 'put',
            parameters: {
                            from: get_current_page_id(),
                            ajax: 'ajax',
                            path_base: path_prefix
                            }
            }
        );
    }

//===========================tool tips in a pseudo window========================

// Init tip system for later content
var tipon=0;
var tipid;
function tip_prepare(wdow) {
    // may need to quit early for old browsers...
    if (tipon) return;
    if (!document.getElementById)return;
    tipon ++;
    var tip_style1="position:absolute;top:0px;left:0px;background-color:#ffffe8;";
    var tip_style2="color:black;font-size:10pt;text-align:left;font-family:Arial;border-width:1;border-color=black;border-style:solid;padding:3px 3px;";

    write_on_wdow ('<div id="tipdiv" style="'+tip_style1+tip_style2+'" visible:false>',wdow);
    write_on_wdow ('tip', wdow);
    write_on_wdow ('</div>',wdow);

    tipid = $("tipdiv");

    $("tipdiv").style.visibility="hidden";
    return;
    }

function getPageEventCoords(evt) {
    var coords = {left:0, top:0};
    if (evt.pageX) {
        coords.left = evt.pageX;
        coords.top = evt.pageY;
        }
    else if (evt.clientX) {
        coords.left =
            evt.clientX + document.body.scrollLeft - document.body.clientLeft;
        coords.top =
            evt.clientY + document.body.scrollTop - document.body.clientTop;
        // include html element space, if applicable
        if (document.body.parentElement && document.body.parentElement.clientLeft) {
            var bodParent = document.body.parentElement;
            coords.left += bodParent.scrollLeft - bodParent.clientLeft;
            coords.top += bodParent.scrollTop - bodParent.clientTop;
            }
        }
    return coords;
    }

function show_tool_tip(tip,evt){
    if (!tipid) return;
    if (!tip) return;
    if (!document.createTextNode) return;

    // kill any leading date stuff, as most likely hovering on a date anyway
    var ntip=tip.replace(/^\s*[0-9]{1,2}-[a-z]{3}\s*/i,'');
    var ntip=ntip.replace(/^\s*is\s*/,'');

    var coords = getPageEventCoords(evt);
    var tipmsg = document.createTextNode(ntip);
    var oldmsg = tipid.replaceChild(tipmsg, tipid.firstChild);

    var units = (typeof tipid.style.left == "string")?"px":0;
    tipid.style.left=(coords.left>width_trip(tip))?(width_trip(tip)+units):(coords.left+20+units);
    tipid.style.top=coords.top+15+units;

    tipid.style.visibility="visible";
    tipid.style.zIndex=1000;
    }

// Tip code for displaying tip in other frame
var frtipid;
function show_frame_tool_tip(tip,evt){
    if (!tip) return;
    // confirm support for functionality
    try{
        if (!parent) return;
        if (!parent.frames[1]) return;
        if (!parent.frames[1].document) return;
        if (!parent.frames[1].document.getElementById) return;
        if (!document.createTextNode) return;

        // Get the id of the tip popup
        frtipid=parent.frames[1].$("tipdiv");
        if (!frtipid) return;

        // kill any leading date stuff, as most likely hovering on a date anyway
        var ntip=tip.replace(/^\s*[0-9]{1,2}-[a-z]{3}\s*/i,'');
        var ntip=ntip.replace(/^\s*is\s*/,'');

        var coords = getPageEventCoords(evt);

        var units = (typeof frtipid.style.left == "string")?"px":0;
        var left_offset=3;
        var top_offset=5;

        // allow for scrolling of other window
        if (parent.frames[1].document.body.scrollTop){
            top_offset+= parent.frames[1].document.body.scrollTop;
            }

        var tipmsg = parent.frames[1].document.createTextNode(ntip);
        var oldmsg = frtipid.replaceChild(tipmsg, frtipid.firstChild);

        frtipid.style.left = left_offset+units;
        frtipid.style.top=coords.top+top_offset+units;
        frtipid.style.visibility="visible";
        frtipid.style.zIndex=1000;
        }
    catch(e){
        return;
        }
    }

// Erase any tips displayed in this or other frame - no need to be clever and track it,
// just clear everything
function clear_tool_tip(){
    if (tipid) {
        if (tipid.style.visibility){
            tipid.style.visibility="hidden";
            tipid.style.zIndex=0;
            }
        }
    if (frtipid){
        if (frtipid.style.visibility){
            frtipid.style.visibility="hidden";
            frtipid.style.zIndex=0;
            }
        }
    return;
    }

// work out what number to trip on when approaching right margin
function width_trip(tip) {
    var room = (tipid.style.width)?(tipid.style.width):'300px';
    room = parseInt(room.replace(/[^0-9]+/g,''))+30;
    // trip for short text...
    room = (tip.length<30)?150:room;

    if (window.innerWidth) {
        return (window.innerWidth-room);
        }
    if (document.body && document.body.clientWidth){
        return (document.body.clientWidth-room);
        }
    var dwidth=900;
    return (dwidth - room);
    }


// ================================== Cookies ==============================

// retrieve cookie by name
function getCookie(name) {

    if (typeof name != 'string' ){
        return false;
        }

    var lookfor = name + "=";
    var cookiestext = document.cookie;

    if (typeof cookiestext != 'string' ){
        return false;
        }

    var i = 0;
    while (i < cookiestext.length) {
        var j = i + lookfor.length;
        if (cookiestext.substring(i, j) == lookfor) {
            var k = cookiestext.indexOf (";", j);
            if (k < 0) {
                k = cookiestext.length;
            }
        cookietext = cookiestext.substring(j, k);
        if (typeof cookietext != 'string' ){
            return false;
            }
        var clean_cookie = unescape(conditional_unenc_it(cookietext));
        if (typeof clean_cookie != 'string' ){
            return false;
            }
        //alert(name + '\n' + clean_cookie);
        return clean_cookie;
        }
        i = cookiestext.indexOf(" ", i) + 1;
        if (i == 0) return null;
    }
    return null;
}


// store cookie value for 1 yr, site wide.
function setCookie(name, value) {

    if (typeof name != 'string' ){
        return false;
        }
    if (typeof value != 'string' ){
        return false;
        }

    var expDate = new Date();
    expDate.setDate(expDate.getDate() + parseInt(365));
    var expires = expDate.toGMTString();
    document.cookie = name + "=" + escape (value) +
                    "; expires=" + expires +
                    "; path=" + "/" ;
    return true;
    }


// delete cookie value, site wide.
function deleteCookie(name) {

    if (typeof name != 'string' ){
        return false;
        }

    // Only delte when a cookie exists
    if (! getCookie(name)){
        return false;
        }

    var expDate = new Date();
    expDate.setDate(expDate.getDate() - parseInt(3)); // 3 days ago!!
    var expires = expDate.toGMTString();
    document.cookie = name + "=" +
                    "; expires=" + expires +
                    "; path=" + "/" ;
    return true;
    }

// ====================== Popup Preview Windows =========================
// for previews of pics, schedule rows etc...
function show_preview_window_of_online_pic (pic){
    if ((pic=='none')||(!pic)){
        return false;
        }
    var body_text = '<p class=c><IMG src='+ docs_base() + pic +'><br clear=all>' + pic +'</p>';
    show_preview_window ("Preview of file online", "File online", body_text);
    }

function show_preview_window_of_local_pic (pic){
    if ((pic=='none')||(!pic)){
        return false;
        }
    var body_text = '<p class=c><IMG src=file:///'+ pic +'><br clear=all>' + pic +'</p>';
    show_preview_window ("File on your PC - ready for upload", "File on your PC", body_text);
    }

function show_preview_window (title, head, body_text){
    var PreviewWindow = window.open('','preview','scrollbars=yes,resizable=yes,width=900,height=700');
    write_on_wdow('<HTML><HEAD><TITLE>'+title+'</TITLE>', PreviewWindow);
    include_style (docs_base(), PreviewWindow);
    write_on_wdow('<h1>'+head+'</h1>',PreviewWindow);
    write_on_wdow(body_text,PreviewWindow);
    page_end_credit(PreviewWindow);
    write_on_wdow('</BODY></html>',PreviewWindow);
    PreviewWindow.document.close();
    PreviewWindow.focus();
    }

// Work out host/target doc base from the referencing docs url
function docs_base (){
        return "../";
    }


// ======================== CGI linking & frame building ==============================

// Attach any relevant params to a cgi/uri - from parent, from doc, or from param string passed.
function cgilink (cgi, params){
    var baselink = cgibin+cgi;
    // used to have top.location.search in here, but problems with security if framed from outside
    try {
        if (window && window.location && window.location.search && (typeof window.location.search =='string') ){
            var sparams = window.location.search;
            baselink = add_srch_params (baselink, sparams);
            }
        }
    catch (e){
        }
    try {
        if (parent && parent.location && parent.location.search && (typeof parent.location.search =='string')){
            var sparams = parent.location.search;
            baselink = add_srch_params (baselink, sparams);
            }
        }
    catch (e){
        }
    try {
        if (document && document.location && document.location.search && (typeof document.location.search =='string')){
            var sparams = document.location.search;
            baselink = add_srch_params (baselink, sparams);
            }
        }
    catch (e){
        }

    if (params && (typeof params =='string')){
        baselink = add_srch_params (baselink, params);
        }
    return baselink;
    }

// Adds more ?& params nicely to the end of a path
function add_srch_params (srchstr, params) {

    var webstr=srchstr;
    if (params) {
        // cut anything unwanted inc '?' of the start of the params
        if (params.indexOf('?')>=0){
            params = params.substring(params.indexOf('?')+1);
            }
        if (srchstr.indexOf('?')>0){
            // extend params
            webstr= srchstr+'&'+params;
            }
        else {
            webstr= srchstr+'?'+params;
            }
        }
    webstr = remove_duplicate_params (webstr);
    return webstr;
    }

// Remove duplicate params from uri - the methods used above to
// make sure all params are collected can catch some twice!
function remove_duplicate_params (webstr){
    if (webstr.indexOf('?')<1) {
        return webstr;
        }
    var uri = webstr.split('?')[0];
    var paramlist = webstr.split('?')[1];

    if (! (paramlist.indexOf('&')>=0)){
        // only 1 parameter
        return webstr;
        }

    var paramparts = new Array();
    paramparts = paramlist.split ('&');
    paramparts = paramparts.each(function(param_part){
        if (contains_garbage(param_part)) {
            param_part=null;
            }
        }).uniq().compact();

    var outparams = '?'+paramparts.join('&');
    return uri + outparams;
    }


// Outputs a framed page with menu and specified cgi in frame
function make_framed_cgi (cgi, params){
    var page_link = cgilink (cgi, params);
    var menu_set =  '<frameset cols = "'
                    +vertical_menu_width
                    +',*" border=0 frameborder=0><frame name="menu" src="'
                    +path_prefix
                    +'sys_menu/menu.htm" marginwidth=0 marginheight=0 scrolling="auto" noresize>';

    var frame_intro = '<frame name="info" src="';
    var frame_end = '" marginwidth=10 marginheight=0 scrolling="auto"></frameset>';

    write_on_wdow (menu_set);
    write_on_wdow (frame_intro+page_link+frame_end);
    }

// Outputs a framed page with menu and specified doc in frame
function make_framed_htm (htm, params){
    var page_link = htm;
    try{
        if (top && top.location && top.location.search){
            page_link = add_srch_params (page_link, top.location.search);
            }
        }
    catch (e){
        }
    try {
        if (document && document.location && document.location.search){
            page_link = add_srch_params (page_link, document.location.search);
            }
        }
    catch (e){
        }
    if (params){
        page_link = add_srch_params (page_link, params);
        }

    var deepsea_menu_set = '<frameset cols = "210,*" border=0 frameborder=0><frame name="menu" src="'+path_prefix+'sys_menu/menu.htm" marginwidth=0 marginheight=0 scrolling="auto" noresize>';

    var frame_intro = ' <frameset border=0 frameborder=0><frame name="indiv" src="';
    var frame_end = '" marginwidth=10 marginheight=0 scrolling="auto"></frameset>';

    write_on_wdow (deepsea_menu_set);
    write_on_wdow (frame_intro+page_link+frame_end);
    }


// The path of the current document
function get_nice_path(){
    try {
        if (window && window.location && window.location.pathname) {
            return window.location.pathname;
            }
        if (window && window.location && window.location.href) {
            var pathstuff = window.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return pathstuff;
            }
        if (document && document.location && document.location.pathname) {
            return  document.location.pathname;
            }
        if (document && document.location && document.location.href) {
            var pathstuff = document.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return  pathstuff;
            }
        if (document && document.url && document.url.pathname) {
            return  document.location.url.pathname;
            }
        if (document && document.url && document.url.href) {
            var pathstuff = document.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return  pathstuff;
            }
        }
    catch (exception_obj){
        }
    return "";
    }


// The path of the current page (which contains the document)
function get_overall_path(){
    try {
        if (window && window.parent && window.parent.location && window.parent.location.pathname) {
            return window.parent.location.pathname;
            }
        if (window && window.parent && window.parent.location && window.parent.location.href) {
            var pathstuff = window.parent.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return pathstuff;
            }
        if (window && window.parent && window.parent.document.location && window.parent.document.location.pathname) {
            return  window.parent.document.location.pathname;
            }
        if (window && window.parent && window.parent.document && window.parent.document.location && window.parent.document.location.href) {
            var pathstuff = window.parent.document.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return  pathstuff;
            }
        if (window && window.parent && window.parent.document && window.parent.document.url &&  window.parent.document.url.pathname) {
            return   window.parent.document.location.pathname;
            }
        if (window && window.parent && window.parent.document && window.parent.document.url &&  window.parent.document.url.href) {
            var pathstuff = window.parent.document.location.href;
            pathstuff = pathstuff.replace (/\?.*/, ''); // kill all after ?....
            return  pathstuff;
            }
        }
    catch (exception_obj){
        }
    return "";
    }

// The address of the current page within the site
function get_current_page_id(){
    var overall_path = get_overall_path();
    // on local development system
    var re1 = new RegExp('^.*\/docs[\/]+', 'i'); // anything before docs/
    overall_path = overall_path.replace(re1, '');
    // online - co.uk/, .com/, .org/ etc..
    var re2 = new RegExp('^.*\.[\w]+[\/]+', 'i'); // anything with dots before text and /
    overall_path = overall_path.replace(re1, '');
    overall_path = overall_path.replace(re2, '');
    overall_path = overall_path.replace(/^[\/\\]+/, ''); // kill leading / or \
    return overall_path;
    }


// get absolute page address
function get_site_base_addr(){
    // options lower down the list carry progressively more risk of
    // failing later, but may be less likely to fail now!!
    var site ='document.location.href';

    try{
        if (document && document.location && document.location.hostname){
            site = document.location.hostname;
            }
        else if (parent && parent.location && parent.location.hostname){
            site = parent.location.hostname;
            }
        else if (top && top.location && top.location.hostname){
            site = top.location.hostname;
            }
        else if (window && window.location && window.location.hostname){
            site = window.location.hostname;
            }
        else if (parent && parent.location && parent.location.href){
            site = parent.location.href;
            }
        else if (top && top.location && top.location.href){
            site = top.location.href;
            }
        else if (window && window.location && window.location.href){
            site = window.location.href;
            }
        else {
            site = document.location.href;
            }
        }
    catch (exception_obj){

        }

    // trim any 'http://' from the start
    site = site.replace(/(^http:\/\/)/,'');
    // trim any other parameters from the end
    if (site.indexOf('/')>0){
        var s_result;
        // maybe in a local path, which means we have to keep up to &
        // including docs. eg http://localhost/psa/docs/.....
        if (
                (s_result = site.match(/(localhost\/.+\/docs)/))
                &&
                (s_result != null)
            ){
            site = s_result[1];
            }
        // maybe just have parameters on a real web address
        // so cut them off. eg http://www.psainternational.co.uk/info/...
        else {
            site = site.split('/')[0];
            }
        }

    // final catch for offline - should have been sorted earlier
    if (site == 'localhost'){
        var s_result;
        // maybe in a local path, which means we have to keep up to &
        // including docs. eg http://localhost/psa/docs/.....
        if (
                (s_result = document.location.href.match(/localhost(\/.+\/docs)/))
                &&
                (s_result != null)
            ){
            site += s_result[1];
            }
        // worst case assumption - within development environment
        else {
            site+='/deepsea/docs';
            }
        }
    return site;
    }


// === Error code diagnosis ======================================

var http_error_codes = {
    err400: "Bad Request:Our web server could not process the request due to a bad command or syntax.",
    err401: "Authorisation Required:Our web server could not process the request because you are not authorised to enter this restricted area of our site.",
    err403: "Forbidden:Our web server could not process the request because you have attempted to enter a forbidden area of our site.",
    err404: "File Not Found:Our web server could not process the request because the file or script could not be found.",
    err500: "Internal Server Error:Our web server has encountered an unexpected condition that prevented it from completing the request.",
    err501: "Not Implemented:Our web server does not support the functionality required to fulfill the submitted request.",
    err503: "Service Unavailable:Our web server is currently unable to handle the submitted request due to a temporary overloading or maintenance of the server.",
    err505: "HTTP Version Not Supported:Our web server does not support the protocol used in the request.",
    errunk: ""
}

// Retrieve error code from the table
function html_error_lookup (ecode){
    var msgtext;
    ecode = 'err'+ecode;
    msgtext = http_error_codes[ecode];
    if (msgtext) return msgtext;
    return ; // return empty string if nothing found.
    }

// Display hhtp error message associated with any current http error codes
function display_error_info(){
    var errors = new Array();
    var ecode ='';
    var emsg ='';
    var head ='';
    var body ='';
    //dummy will inherit the parameters passed
    var dummy_address = cgilink ('dummy','dummy');
    var params = dummy_address.split ('?')[1]||'errunk';
    //alert(params);
    if (params) {
        errors = params.split('&');
        //for (var i=0; i<errors.length; i++){
        //  ecode = errors[i].split('=')[1];
        errors.each(function(an_error){
            ecode = an_error.split('=')[1];
            if (ecode) {
                emsg = html_error_lookup (ecode);
                if (emsg) {
                    var head = emsg.split(':')[0];
                    var body = emsg.split(':')[1];
                    write_on_wdow ('<h3>Error: '+ecode);
                    if (head) write_on_wdow (' - '+head);
                    write_on_wdow ('</h3><p>'+body+'</p><br>');
                    //return;
                    }
                }
            });
        }
    return;
    }



// === Debug/diagnostic utilities ======================================
// used to switch debug on/off
function confirm_debug() {
    //return 1;
    // Debug only shown for webmaster
    if (
            (user_security_ok('Webmaster') == 'Webmaster')

            && (typeof debug_flag != 'undefined')

            && (debug_flag>0)

            ) {
        return debug_flag;
        }
    return 0;
    }

function debug (msg){
    if (confirm_debug()) {
        alert ('DEBUG\n\n'+msg);
        }
    // else - ignore
    }

// Only write on page if debug enabled
function write_debug_on_wdow(text,wdow){
    if (confirm_debug()) {
        write_on_wdow(text,wdow);
        }
    // else - ignore
    }

function diplay_rendered_html(wdow){
    if (confirm_debug()){
        var diagw = window.open("","","");

        var opstyle = '<style "TYPE=text/css">em{color:navy}; H1,H2,H3,H4{color:red}; pre{font-size:10pt}</style>';

        // doc uri, formatted to break on each parameter
        var d_title = unescape(document.location.href);
        d_title = d_title.replace (/\?/ig, "<br>?");
        d_title = d_title.replace (/\&/ig, "<br>&");
        diagw.document.write('<html><body><pre>'+opstyle+'<h3>'+d_title+'</h3></pre>');

        diagw.document.write('<pre>'+cookieDump()+'</pre>');



        // get the entire doc body
        var d_body = document.body.parentNode.innerHTML+"\n\n\n\n";

        // formatted to break on tags,
        d_body = d_body.replace ( />/ig, ">\n");
        // change the colour of tags and make them displayable
        d_body = d_body.replace ( /</ig, "&lt;");
        d_body = d_body.replace ( />/ig, "&gt;");
        d_body = d_body.replace ( /\&lt\;/ig, "<em>&lt;");
        d_body = d_body.replace ( /&gt\;/ig, "&gt;</em>");
        // write pre-formatted to follow \n in text
        diagw.document.write("<pre>"+d_body+"</pre><br><br></body></html>");
        }
    return false;
    // else - ignore
    }


function page_end_diag(wdow) {
    if (confirm_debug()){
        // show rendered html after js has executed ------
        write_debug_on_wdow ('<p class=fn>', wdow);
        write_debug_on_wdow ('<a href="'+path_prefix+'error.htm" onClick="return diplay_rendered_html()" target=_top>', wdow);
        write_debug_on_wdow ('View Rendered HTML</a></p>', wdow);

        // obj model browser------------------------------
        write_debug_on_wdow ('<p class=fn>', wdow);
        write_debug_on_wdow ('<a href="'+path_prefix+'sys_look/objbrowser.htm" target=debug>', wdow);
        write_debug_on_wdow ('Object Browser</a></p>', wdow);

        }
    }


// text of all cookie values
function page_end_cookie_diag(wdow) {
    if (confirm_debug()){
        // Cookie info
        write_debug_on_wdow ('<p class=fnl>', wdow);
        write_debug_on_wdow (cookieDump(), wdow);
        write_debug_on_wdow ('</p>', wdow);
        }
    }

function cookieDump(){
    var result_str;
    result_str = '';

    var result_arr = new Array();

    var cookiestext = document.cookie;
    var ck_size = cookiestext.length;
    var cookies = new Array();
    cookies = cookiestext.split(/;/);
    cookies.each(function(cookietext){

        var cnm;
        var cval;
        var nmval = new Array();
        nmval = cookietext.split('=',2);
        cnm = nmval[0]||'?name?';
        cval = nmval[1]||'?value?';
        var clean_cval = unescape(conditional_unenc_it(cval));
        result_arr.push(cnm + '<em class=em2> = </em><em class=em3>' + clean_cval+'</em>');

        });
    result_arr.sort();

    return 'LENGTH<em class=em2> = </em><em class=em3>'+ck_size+'</em><br>\n'+result_arr.join('<br>\n');
    }


function test_stuff(){
//  var ts='Hello John!';
//  var encts = enc_it(ts);
//  alert (ts+'\n'+encts+'\n'+conditional_unenc_it(encts) );
//alert (cookieDump());
    }

function old_cookie_cleanup(ck){
    deleteCookie(ck);
    ['deepsea', 'psa', 'hwhyde', 'weezle'].each(function(site){
        var st = site+'history';
        //deleteCookie(st);
        });
    }

//======= end disgnostic stuff ===========================================