/*=========================================*/
/* Source:  z-resources/JLscripts/jlplugins/jquery.jl.list_utils.js */
/* Updated: 13/06/2010 20:01:36 */
/*=========================================*/
//
// z-resources/JLscripts/plugins/jquery.jl.list_utils.js
//
// Starter generated by http://starter.pixelgraphics.us/
// http://dougneiner.com/post/231472372/starter
// c 2009 Douglas Neiner and Pixel Graphic Design Studio.
//

jQuery.noConflict();

//----------------------------------------------------------------------------------------------
// A bit like Perl's List::Utils and List::MoreUtils
//----------------------------------------------------------------------------------------------

(function(jQuery){

    if(!jQuery.jl){
        jQuery.jl = new Object();
        }

    // first index in array
    jQuery.jl.list_firstidx = function(of_array, this_value){

        /*
        Checks whether an array contains some value and returns its index
        of_array - an array in which we search for a value
        this_value - the value we search for
        returns {integer} location if the array contains the value, otherwise -1
        */
        for (var i = 0, len = of_array.length; i < len; ++i) {
            if (of_array[i] == this_value) {
                return i;
                }
            }
        return -1;
        };


    // ucfirst of string
    jQuery.jl.uc_first = function(text){
        return text.substr(0,1).toUpperCase() + text.substr(1,text.length);
        };



    })(jQuery);




/*=========================================*/
/* Source:  z-resources/JLscripts/jlplugins/jquery.jl.logging.js */
/* Updated: 15/06/2010 13:42:40 */
/*=========================================*/
//
// z-resources/JLscripts/plugins/jquery.jl.logging.js
//
// Starter generated by http://starter.pixelgraphics.us/
// http://dougneiner.com/post/231472372/starter
//

jQuery.noConflict();

//----------------------------------------------------------------------------------------------
// A general purpose logging thing
//----------------------------------------------------------------------------------------------

(function(jQuery){

    if(!jQuery.jl){
        jQuery.jl = new Object();
        }

    jQuery.jl.logger = function(el, options){
        // To avoid scope issues, use 'this_base' instead of 'this'
        // to reference this class from internal events and functions.
        var this_base = this;

        // Access to jQuery and DOM versions of element
        // note that we only want one logger attached to any particular
        // dom element - we can't affort for it to be initialised
        // twice or it will crap on its own data!!

        // the logger already exists so simply return it;
        if (this_base.jl_logging && this_base.jl_logging.log){
            this_base.jl_logging.log.gap(jQuery(el));
            return this_base.jl_logging.log;
            }

        this_base.jl_logging = new Object();

        this_base.jl_logging.jQueryel = jQuery(el);
        this_base.jl_logging.el = el;

        // Add a reverse reference to the DOM object
        this_base.jl_logging.jQueryel.data("jl_logging", this_base);

         // init function, should only be called once for a logging area
        this_base.jl_logging.init = function(){

            this_base.jl_logging.options = jQuery.extend({},jQuery.jl.logger.defaultOptions, options);

            // Put your initialization code here
            //--------------------------------------------------

            this_base.jl_logging.startTime = new Date();
            this_base.jl_logging.options.hostParams.base_time = this_base.jl_logging.options.page_time||(this_base.jl_logging.startTime/1000);

            this_base.jl_logging.msgQueue = [];
            this_base.jl_logging.ajaxLogUploadEnabled = 0;
            this_base.jl_logging.msgCount = 0;
            this_base.jl_logging.log=[];


            var log_level_check = function(level1, level2){
                var v1 = jQuery.jl.list_firstidx(this_base.jl_logging.options.log_levels, level1);
                var v2 = jQuery.jl.list_firstidx(this_base.jl_logging.options.log_levels, level2);
                return v1 >= v2;
                };

            // log by level function, not used directly, but
            // forms the basis of all the logging level functions
            this_base.jl_logging.log_by_level = function(msg, logLevel){

                try {

                    // Object = exception or other object coming in
                    if (typeof msg == 'object'){
                        msg = 'Object: ' + jQuery.toJSON(msg);
                        }

                    // tidy up new line & empty values
                    if (msg ==='' || msg ==='newline' || msg ==='\n') {
                        msg = '';
                        }

                    // Tweak logLevel
                    logLevel = logLevel.toLowerCase();
                    if (logLevel == 'note') {
                        logLevel ='notice';
                        }


                    // Make time stamp
                    var nowTime = new Date();
                    var elapsedTime = nowTime-this_base.jl_logging.startTime;

                    //-----------------------------------------
                    // DESTINATION option 1: Append to web page
                    //-----------------------------------------
                    if (    log_level_check(logLevel, this_base.jl_logging.options.localFilter) &&
                            this_base.jl_logging.el  ){

                        //for local display append the message
                        this_base.jl_logging.jQueryel.find('code').
                            append(    '<li>[+' + elapsedTime + 'ms]' +
                                        '<span class=\"jl-dev-log-' +logLevel +
                                        '\">' +
                                        logLevel +
                                        '</span>: ' +
                                        msg +
                                        '</li>\n' );

                        // Maybe auto show the messages
                        if (    this_base.jl_logging.options.dev_mode &&
                                log_level_check(logLevel, this_base.jl_logging.options.localTrigger) ){
                            this_base.jl_logging.jQueryel.find('div').show();
                            }
                        }

                    //-----------------------------------------
                    // DESTINATION option 2: Log console (firebug) or an alert (ie)
                    //-----------------------------------------
                    else if (   this_base.jl_logging.options.dev_mode &&
                           log_level_check(logLevel, this_base.jl_logging.options.localFilter) &&
                           jQuery.log   ){
                        jQuery.log(logLevel+': '+msg);
                        }

                    //-----------------------------------------
                    // DESTINATION option 3: by AJAX to the server
                    // (can also be triggered by user adding an alert to the queue)
                    //-----------------------------------------
                    if (    log_level_check(logLevel, this_base.jl_logging.options.hostFilter)   ){
                        // add msg to upload queue
                        this_base.jl_logging.msgQueue.push({Index:this_base.jl_logging.msgCount, Time:elapsedTime, Level:logLevel, Message:msg});
                        this_base.jl_logging.msgCount++;
                        }
                    // check to see if ajax upload is triggered
                    if (    this_base.jl_logging.ajaxLogUploadEnabled > -1  &&
                            log_level_check(logLevel, this_base.jl_logging.options.hostTrigger)  ){
                        this_base.jl_logging.ajaxLogUploadEnabled = 1;
                        }
                    // flush the upload queue. This should do a big json transfer for the first triggered level, then
                    // message by message after that
                    if (    this_base.jl_logging.ajaxLogUploadEnabled > 0 &&
                            this_base.jl_logging.options.hostLogPath    ){
                        // disable further upload to prevent race
                        ajaxLogUploadEnabled = 0;

                        // flush the queue to JSON format
                        var entriesToUpload = jQuery.toJSON(this_base.jl_logging.msgQueue);
                        this_base.jl_logging.msgQueue=[];

                        var upload_params = jQuery.extend({},this_base.jl_logging.options.hostParams, {log_entries:entriesToUpload});

                        // send it
                        var uploadURL = this_base.jl_logging.options.root_rel_baseaddr + this_base.jl_logging.options.hostLogPath;
                        jQuery.ajax({
                            url     :   uploadURL,
                            type    :   'POST',
                            data    :   upload_params,
                            dataType:   'text',
                            success :   function(returned_text){
                                            // re-enable further upload - only when this one is finished (prevent race)
                                            this_base.jl_logging.ajaxLogUploadEnabled = 1;
                                            },
                            error   :   function(returned_text){
                                            // permanently disable further upload as we have an error
                                            this_base.jl_logging.ajaxLogUploadEnabled = -10;
                                            // local log entry (as upload now turned off!)
                                            jQuery.log('Log Upload Fail\n'+jQuery.toJSON(upload_params)+'\n'+returned_text);
                                            }
                            });

                        }
                    //-----------------------------------------
                    // End of log destination options
                    //-----------------------------------------

                    }

                catch (e) {
                    if (jQuery.log){
                        jQuery.log('critical: EXCEPTION IN LOGGING SYSTEM\n'+jQuery.toJSON(e) );
                        }
                    else {
                        alert('critical: EXCEPTION IN LOGGING SYSTEM\n'+jQuery.toJSON(e) );
                        }
                    }

                }; // end of log_by_level function


            //-----------------------------------------
            // create a displayable version that conforms to ui theme
            //-----------------------------------------
            this_base.jl_logging.log_msg_display = function (logLevel, msg){
                var uc_level = jQuery.jl.uc_first(logLevel);

                // Info
                var msg_class = 'ui-state-highlight';
                var msg_icon = 'ui-icon-comment';

                // >= Notice
                if (log_level_check(logLevel, 'info')){
                    msg_icon = 'ui-icon-info';
                    }
                // >= Notice
                if (log_level_check(logLevel, 'notice')){
                    msg_icon = 'ui-icon-notice';
                    }
                // >= Error
                // at error and above, switches to vivid class
                if (log_level_check(logLevel, 'error')){
                    msg_class = 'ui-state-error';
                    }
                // >= Alert
                if (log_level_check(logLevel, 'alert')){
                    msg_icon = 'ui-icon-alert';
                   }

                var op =
                        '<div class="ui-widget">' +
                            '<div class="'+msg_class+' ui-corner-all" style="padding: 0 .7em;">' +
                                '<p><span class="ui-icon '+msg_icon+'" style="float: left; margin-right: .3em;"></span>' +
                                '<strong>'+uc_level+':</strong> '+msg+'.</p>' +
                            '</div>' +
                        '</div>';

                return op;
                };

            //-----------------------------------------
            // Define magic fns in jl.logger space for each level: debug, info etc....
            //-----------------------------------------
            jQuery.each(this_base.jl_logging.options.log_levels, function(i,logLevel){
                //alert(logLevel);
                this_base.jl_logging.log[logLevel] = function(msg){
                    this_base.jl_logging.log_by_level(msg,logLevel);
                    // the level function returns an appropriately formatted message for diaplay
                    return this_base.jl_logging.log_msg_display(logLevel, msg);
                    };
                });



            //-----------------------------------------
            // insert a blank like in the output
            //-----------------------------------------
            this_base.jl_logging.log.gap = function(jqel){
                if (    log_level_check('debug', this_base.jl_logging.options.localFilter) &&
                        jqel  ){

                    //for local display append the message
                    jqel.find('code').append('<br>----------------------------<br>\n' );
                    }
                };

            //-----------------------------------------


            };

        // Run initializer
        this_base.jl_logging.init();

        // return the log object, with all the logging level functions
        this_base.jl_logging.log.info('Logging System Setup OK');
        return this_base.jl_logging.log;
        };

    jQuery.jl.logger.defaultOptions = {
        page_time       : '',   // default to false, so will be overridden by actual time unless set
        dev_mode        : 1,    // On by default
        source          : "jl_metadata",
        log_levels      : ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'],
        localFilter     : "debug",
        localTrigger    : "error",
        hostFilter      : "debug",
        hostTrigger     : "error",
        hostLogPath     : "z-resources/cgi-bin/jlappmanager.cgi",
        root_rel_baseaddr     : "/",

        hostParams  :   {
                            rm          :   'ajax_log',
                            base_time   :   ''
                        }

        };

    })(jQuery);




/*=========================================*/
/* Source:  z-resources/JLscripts/jlplugins/jquery.jl.pageinfo.js */
/* Updated: 13/06/2010 20:01:37 */
/*=========================================*/
//
// z-resources/JLscripts/plugins/jquery.jl.pageinfo.js
//
// Starter generated by http://starter.pixelgraphics.us/
//

jQuery.noConflict();

//----------------------------------------------------------------------------------------------
// pageinfo extension to jQuery - gets information about the web page
//----------------------------------------------------------------------------------------------

(function(jQuery){

    if(!jQuery.jl){
        jQuery.jl = new Object();
        }

    var log;

    try {

        var local_meta = jQuery('#DevelopmentMode').metadata('jl_metadata');

        log = jQuery.jl.logger('#DevelopmentMode', {    dev_mode    : local_meta.dev_mode,
                                                        page_time   : local_meta.page_time,
                                                        root_rel_baseaddr   : local_meta.root_rel_baseaddr
                                                    });

        log.info('Pageinfo Setup Begin');

        // eg. el = "#mblock"
        jQuery.jl.pageinfo = function(el, options){
            // To avoid scope issues, use 'this_base' instead of 'this'
            // to reference this class from internal events and functions.
            var this_base = this;

            // a pageinfo object already exists for the element, so simply return it;
            if (this_base.jl_pageinfo ){
                 return this_base.jl_pageinfo;
                }

            try {

                log.info('Pageinfo Constructor Begin');

                // we need a unique namespace within 'this';
                this_base.jl_pageinfo = new Object();

                // Access to jQuery and DOM versions of element
                this_base.jl_pageinfo.jQueryel = jQuery(el);
                this_base.jl_pageinfo.el = el;

                // Add a reverse reference to the DOM object
                this_base.jl_pageinfo.jQueryel.data("jl_pageinfo", this_base);

                this_base.jl_pageinfo.init = function(){

                    this_base.jl_pageinfo.options = jQuery.extend({},jQuery.jl.pageinfo.defaultOptions, options);

                    // Put your initialization code here
                    //--------------------------------------------------

                    var local_meta = this_base.jl_pageinfo.jQueryel.metadata(this_base.jl_pageinfo.options.source);

                    // General parameters set when template is filled in, metadata
                    var root_rel_baseaddr = local_meta.root_rel_baseaddr;

                    // The heading/title of the page
                    var page_title = jQuery(this_base.jl_pageinfo.options.title_at).text();

                    if (!page_title) {
                        page_title = cleanUp(top.document.title);

                        // the rest is really legacy code
                        var history_unwanted_text_re = /The Deep Sea Directory -[\s]*|[\s]*- the UK directory of professional angling, diving and commercial charter boats/gi;
                        page_title =  page_title.replace(history_unwanted_text_re, ''); // remove any others;
                         // if it is long and there is a dash, then truncate before the dash.
                        if (page_title && page_title.length > 20 && page_title.indexOf('-') >= 0){
                            page_title = page_title.split('-')[1];
                            }
                       }
                    page_title = cleanUp(page_title);

                    // The page address, used to build link URL
                    var this_page_id = local_meta.this_page;
                    var short_page_link_path = this_page_id.split('.')[0];
                    var page_link_ext = this_page_id.split('.')[1];

                    // again legacy code to cope with old site
                    if (!short_page_link_path){
                        var page_link_path = top.location.pathname.split('.')[0];
                        page_link_ext = top.location.pathname.split('.')[1];
                        var rrexp_pattern = new RegExp ('^'+root_rel_baseaddr);
                        short_page_link_path = page_link_path.replace (rrexp_pattern, '');
                        }

                    // The client can call obj.get_info to get at these
                    this_base.jl_pageinfo.jlinfo = {
                        title       :   page_title,
                        path        :   short_page_link_path+'.'+page_link_ext,
                        ext         :   page_link_ext,
                        path_noext  :   short_page_link_path
                        };
                    };

                // Local fn to Clean up a title - remove spaces, tags etc
                function cleanUp (clean_me){
                    clean_me = clean_me.replace(/<[^>]+>/gi, ' '); // remove any formatting tags
                    clean_me = clean_me.replace(/\([^\)]+\)/gi, ' '); // remove any parenthesis
                    clean_me = clean_me.replace(/[^\ -\~]+/gi, ' '); // any unusual characters, most likely a copyright symbol?
                    clean_me = jQuery.trim(clean_me).replace(/[\s]+/g,' ');
                    return clean_me;
                    }

                //-----------------------------------------------------------

                // function to return
                this_base.jl_pageinfo.get_info = function(part){
                    if (part){
                        return this_base.jl_pageinfo.jlinfo[part];
                        }
                    // else, retur the obj
                    return this_base.jl_pageinfo.jlinfo;
                    };

                // Run initializer
                this_base.jl_pageinfo.init();

                log.info('Pageinfo Constructor End');

                return this_base.jl_pageinfo;
                }
            catch (e) {
                log.info('Pageinfo Constructor Exception');
                log.critical(e);
                return this_base.jl_pageinfo;
                }
            };

        jQuery.jl.pageinfo.defaultOptions = {
            source: "jl_metadata",
            title_at: "#jl-header h1"
            };

        log.info('Pageinfo Setup End');
        }
    catch (e) {
        log.info('Pageinfo Setup Exception');
        log.critical(e);
        }

    })(jQuery);



/*=========================================*/
/* Source:  z-resources/JLscripts/utilities/development_mode.js */
/* Updated: 13/06/2010 20:01:53 */
/*=========================================*/
//
// z-resources/JLscripts/menu/development_mode.js
//

jQuery.noConflict();


//----------------------------------------------------------------------------------------------
// Log some useful info to the Development mode section
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {

    // set up later, but keep it outside the scope of the exception block
    var log;

    try {

        var local_meta = jQuery('#DevelopmentMode').metadata('jl_metadata');

        log = jQuery.jl.logger('#DevelopmentMode', {    dev_mode    : local_meta.dev_mode,
                                                        page_time   : local_meta.page_time,
                                                        root_rel_baseaddr   : local_meta.root_rel_baseaddr
                                                    });

        log.info('Development info Begin');

        // General parameters set when template is filled in, metadata

        if (local_meta.dev_mode > 0){

            // Setup the development mode area and the click handler for it
            jQuery('#DevelopmentMode').removeClass('jl-initial-hidden').
                                       find('ol').
                                       parent().
                                       hide();
            jQuery("#DevelopmentMode a.onoff").bind("click",function(e){
                e.preventDefault();
                jQuery(this).parents('#DevelopmentMode').find('div').toggle();
                return false;
                });
            jQuery("#DevelopmentMode a.savelog").bind("click",function(e){
                e.preventDefault();
                log.alert('Log saved by user action');
                jQuery(this).hide();
                return false;
                });

            }

        log.info('Development mode flag:'+local_meta.dev_mode);


        //--------------------
        // Log useful info
        //--------------------

        // Browser identification - not that accurate, but may be helpful
        log.info('Browser');
        log.debug(jQuery.browser);

        // Document info
        log.debug('Path: '+top.location.pathname);
        log.debug('Doc: '+document.location.pathname);

        // Cookies
        // filter could be more general eg /[a-z]+/
        log.info('Cookies');
        jQuery.each(jQuery.cookies.filter(local_meta.site_id),function(cookie_name, cookie_value){
            log.debug(cookie_name+'= '+cookie_value);
            });

        // List Metadata
        jQuery('[class*=_metadata]').each(function(){
            log.info('Metadata for '+jQuery(this).attr('id'));
            log.debug(jQuery(this).metadata('jl_metadata'));
            });

        // List Styles
        log.info('Style Sheets');
        // styles have attributes type and href
        jQuery('link[type][href]').each(function(){
            log.debug(jQuery(this).attr('type')+': '+jQuery(this).attr('href'));
            });

        // List Scripts
        log.info('Scripts');
        // scripts have attributes type and src
        jQuery('script[type][src]').each(function(){
            log.debug(jQuery(this).attr('type')+': '+jQuery(this).attr('src'));
            });

        // more?

         log.info('Development mode info End');
        }
    catch (e) {
        log.info('Development mode info Exception');
        log.critical(e);
        }

    }); // End development mode general heading stuff


//----------------------------------------------------------------------------------------------
// Testing
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {


   // SKIP - no tests
   return;

   var log = jQuery.jl.logger('#DevelopmentMode');


   try {

        log.info('TESTS Begin');


        log.info('TESTS End');

        }
    catch (e) {
        log.info('TESTS Exception');
        log.critical(e);
        }

    }); // End development mode general heading stuff



/*=========================================*/
/* Source:  z-resources/JLscripts/page_ui/jl-ui-assist.js */
/* Updated: 17/06/2010 15:59:41 */
/*=========================================*/
//
// z-resources/JLscripts/page_ui/jl-ui-assist.js
//
// scripts that make general ui features work buttons
//
// - Buttons
//
// Prerequisites - development_mode.js for logging
//
//

jQuery.noConflict();

// CHEAT SHEET - UI Styles
//.ui-state-hover
//.ui-state-active
//.ui-state-default
//.ui-state-highlight
//.ui-state-error

//----------------------------------------------------------------------------------------------
// BUTTONS
// makes any and every button work with a ui theme
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {


        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded buttons');
            }
        else {

             log.info('Buttons Setup Begin');

            // anywhere on the page that has class pseudo-button gets turned into a button
            jQuery(".pseudo-button").button();

            // anywhere on the page that has class pseudo-buttonset gets turned into a buttonset
            jQuery(".pseudo-buttonset").buttonset();

            // Covers up for a jquery problem where for some reason the button text colours
            // won't toggle reliably for all buttons (backgrounds do).
            var btn_col = jQuery("#jl_reference_ui-state-default").css('color');
            var btn_hov_col = jQuery("#jl_reference_ui-state-hover").css('color');

            jQuery(".ui-button").hover(
                                function(){
                                    // set
                                    jQuery(this).css('color',btn_hov_col);
                                    return true;
                                    },
                                function(){
                                    // reset
                                    jQuery(this).css('color',btn_col);
                                    return true;
                                    }
                    );



            } // End All Browsers (IE6 else) part

        log.info('Buttons Setup End');

        }
    catch (e) {
        log.notice('Buttons Setup Exception');
        log.critical(e);
        }

    }); // end doc ready fn - button special processing


//----------------------------------------------------------------------------------------------
// SUPPLEMENTARY PANEL
// Makes the supplementary panel never grow wider than xx pixels
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded panels');
            }
        else {

            log.info('Supplementary Width Begin');

            // skip if no #mblock
            if (! jQuery('#jl-complementary').length ){
                log.notice('Skipped - no #jl-complementary');
                return;
                }

            // config, maybe pass in metadata
            var sup_ulim = 300; // pixels
            var sup_llim = 200;
            var sup_timout = 1000; //ms


            var timeoutID;

            // can we limit the max width of the supplementary/complementary panel
            var panel_widths = function (){

                // starting split is 2:1

                // work out the gap/margin between the main and nav sections
                var main_margin = parseInt(jQuery('#yui-main').children('div:first').css('margin-left'), 10);
                var nav_width = parseInt(jQuery('#jl-navigation').parent('div').outerWidth(), 10);
                var standard_margin = main_margin - nav_width;

                //log.debug('Panels margins:'+main_margin+'-'+nav_width+'='+standard_margin);

                var jqOverall = jQuery('#jl-content').parent('div').parent('div');
                var jqMain = jQuery('#jl-content').parent('div');
                var jqSupp = jQuery('#jl-complementary').parent('div');

                var swidth = parseInt(jqSupp.width(),10);
                var mwidth = parseInt(jqMain.width(),10);
                var tot_width = parseInt(jqOverall.outerWidth(),10);

                //log.debug('Panels initial:'+mwidth+'+'+swidth+'='+tot_width);

                // width of supp is 1/3 or 300 (sup_ulim), whichever is smaller
                var new_swidth = parseInt((tot_width)/3, 10);
                if (new_swidth>sup_ulim) {
                    new_swidth = sup_ulim;
                    }
                var new_mwidth;

                // supp panel >=200 (sup_llim) wide, so worth showing it
                if (new_swidth>=sup_llim){
                    new_mwidth = tot_width - new_swidth - standard_margin;

                    jqSupp.width(new_swidth);
                    jqSupp.css('margin-left', '0px');
                    jqMain.width(new_mwidth);
                    //log.debug('Panels new:'+new_mwidth+'/'+new_swidth+'='+tot_width);
                    }

                // supp panel <200 wide, so move it below the main panel
                else {
                    new_swidth = tot_width;
                    new_mwidth = tot_width;
                    jqSupp.width(new_swidth);
                    jqMain.width(new_mwidth);

                    //log.debug('Panels new:'+new_mwidth+'/'+new_swidth+'='+tot_width);
                    }

                // call repeatedly every 1s
                timeoutID = window.setTimeout(panel_widths, sup_timout);

                }; // end panel widths function

            panel_widths();


            jQuery(window).resize(function() {
                window.clearTimeout(timeoutID);
                panel_widths();
                });

            // a safari glitch on shrinking, works out again when enlarging!!!
            // I think the resize event is not happening correctly?

            // also a glitch on windo growing to include scroll bars,
            // no resize event when teh scroll bars appear?
            // Safari glitch could als be this sort of thing?

            // See the timouts above - a cludge to catch any failed resizing events

            // See http://benalman.com/projects/jquery/ for better resize plugin

            } // End All Browsers (IE6 else) part

        log.info('Supplementary Width End');

        }
    catch (e) {
        log.notice('Supplementary Width Exception');
        log.critical(e);
        }

    }); // end doc ready fn - panels processing


//----------------------------------------------------------------------------------------------
// GALLERY - of type gal-widget-base
// sort out the popup of a window in a picture gallery and other gallery behaviours
//----------------------------------------------------------------------------------------------

// See also http://www.bennadel.com/blog/1871-Translating-Global-jQuery-Event-Coordinates-To-A-Local-Context.htm

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {


        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded gallery');
            }
        else {

            log.info('Gallery Setup Begin');

            // Only set it up if a gallery exists
             if (! jQuery("div.gal-widget-base").length ){
                 log.notice('Skipped - no div.gal-widget-base');
                 return;
                 }

            // The overall gallery area
            var jQ_gallery_area = jQuery("div.gal-widget-base[id$=_begin]");

            // a list of href's in the gallery (links to pics
            var jQ_gallery_hrefs = jQ_gallery_area.find('a.gal-widget-base');


            // The region used for popup dialog
            var jQ_dialog_body = jQuery("div.gal-widget-base[id$=_dialog_body]").removeClass('jl-initial-hidden');

            // -----------------------------------------------
            // pre-load the next image after the one specified
            // -----------------------------------------------
            var preloadNextJpegImage = function (){

                var cur_src = jQ_dialog_body.find('img').attr('src');
                jQ_gallery_hrefs.filter('[href='+cur_src+']').data('jl-loaded', 'loaded');

                var length = jQ_gallery_hrefs.length;
                var cur_offset = jQ_gallery_hrefs.index( jQ_gallery_hrefs.filter('[href='+cur_src+']') );

                // prev, with length wrap
                var p_offset = (cur_offset - 1 + length) % length;
                if (p_offset >=0 && jQ_gallery_hrefs.eq(p_offset).data('jl-loaded') != 'loaded'){
                    // preload
                    var image_obj_p = new Image();
                    image_obj_p.src = jQ_gallery_hrefs.eq(p_offset).attr('href');
                    jQ_gallery_hrefs.eq(p_offset).data('jl-loaded', 'loaded');
                    log.debug("Preload prev image:"+image_obj_p.src);
                    }

                // next, with length wrap
                var n_offset = (cur_offset + 1) % length;
                if (n_offset < length && jQ_gallery_hrefs.eq(n_offset).data('jl-loaded') != 'loaded'){
                    // preload
                    var image_obj_n = new Image();
                    image_obj_n.src = jQ_gallery_hrefs.eq(n_offset).attr('href');
                    jQ_gallery_hrefs.eq(n_offset).data('jl-loaded', 'loaded');
                    log.debug("Preload next image:"+image_obj_n.src);
                    }

                };

            // -----------------------------
            // Play jQobj.data('jl-playing', 'play')
            // -----------------------------
            var intervalID;

            var doPlay = function (e) {
                if (jQ_gallery_area.data('jl-playing') == 'play'){
                    // exit play mode
                    doStop();
                    }
                else {
                    // enter play mode
                    jQ_gallery_area.data('jl-playing', 'play');

                    // call repeatedly every 1s
                    clearInterval ( intervalID );
                    intervalID = window.setInterval(  function(){
                                                         // The current image in the dialog area
                                                        var cur_src = jQ_dialog_body.find('img').attr('src');
                                                        // handle the wrap round
                                                        if (cur_src == jQ_gallery_hrefs.last().attr('href')){
                                                            jQ_gallery_hrefs.first().click();
                                                            return false;
                                                            }
                                                        // or after in the sequence
                                                        jQ_gallery_hrefs.eq(jQ_gallery_hrefs.index( jQ_gallery_hrefs.filter('[href='+cur_src+']') )+1).click();
                                                        return false;
                                                        },
                                                        3000);
                    }

                // click the current pic, to refreh and sort out icons etc
                doCurrent();
                return false;
                }; // End doPlay

            // -----------------------------
            // Current
            // -----------------------------
            var doCurrent = function (e) {
                // click the current pic, mainly used to refreh and sort out icons etc
                var cur_src = jQ_dialog_body.find('img').attr('src');
                jQ_gallery_hrefs.filter('[href='+cur_src+']').click();
                 return false;
               }; // End doStop

            // -----------------------------
            // Stop
            // -----------------------------
            var doStop = function (e) {
                clearInterval ( intervalID );
                jQ_gallery_area.data('jl-playing', 'stop');
                return false;
               }; // End doStop

            // -----------------------------
            // First
            // -----------------------------
            var doFirst = function (e) {
                doStop();
                jQ_gallery_hrefs.first().click();
                return false;
                }; // End doFirst

            // -----------------------------
            // Last
            // -----------------------------
            var doLast = function (e) {
                doStop();
                jQ_gallery_hrefs.last().click();
                return false;
                }; // End doLast

            // -----------------------------
            // Previous
            // -----------------------------
            var doPrev = function (e) {
                doStop();
                // The current image in the dialog area
                var cur_src = jQ_dialog_body.find('img').attr('src');
                // handle the wrap round
                if (cur_src == jQ_gallery_hrefs.first().attr('href')){
                    jQ_gallery_hrefs.last().click();
                    return false;
                    }
                // or before in the sequence
                jQ_gallery_hrefs.eq(jQ_gallery_hrefs.index( jQ_gallery_hrefs.filter('[href='+cur_src+']') )-1).click();
                 return false;
                }; // End doPrev

            // -----------------------------
            // Next
            // -----------------------------
            var doNext = function (e) {
                doStop();
                // The current image in the dialog area
                var cur_src = jQ_dialog_body.find('img').attr('src');
                // handle the wrap round
                if (cur_src == jQ_gallery_hrefs.last().attr('href')){
                    jQ_gallery_hrefs.first().click();
                    return false;
                    }
                // or after in the sequence
                jQ_gallery_hrefs.eq(jQ_gallery_hrefs.index( jQ_gallery_hrefs.filter('[href='+cur_src+']') )+1).click();
                return false;
                }; // End doNext

            // -----------------------------
            // Previous or Next
            // Decided on location of click
            // -----------------------------
            var doPrevOrNext = function (e) {

                // if playing, simply stop here
                if (jQ_gallery_area.data('jl-playing') == 'play'){
                    // exit play mode
                    doStop();
                    // click the current pic, to refreh and sort out icons etc
                    return doCurrent();
                    }
                // left half = prev,
                else if (Math.floor( e.pageX - jQ_dialog_body.offset().left ) < Math.floor(jQ_dialog_body.width()/2)){
                    return doPrev(e);
                    }
                // right half = next
                else {
                    return doNext(e);
                    }
                }; // End doPrevNext

            // -----------------------------
            // General click handler for all
            // thumbnails
            // -----------------------------

            jQ_gallery_area.live('click',function(e){

                var jQthumb_item = jQuery(e.target).closest('a');

                // something else got clicked
                if (! jQthumb_item.attr('href')){
                    return true;
                    }

                // now processing a proper click on a thumbnail
                e.preventDefault();

                // the actual pic linked to, and mark it as loaded now we are loading it
                // (stop it from being preloaded later)
                var pic = jQthumb_item.data('jl-loaded', 'loaded').attr('href');

                log.info("Gallery view:"+pic);

                // for n of m in heading
                var total_pics = jQ_gallery_hrefs.length;
                var pic_index = jQ_gallery_hrefs.index(jQthumb_item)+1;

                // associated caption text
                var head = pic_index+' of '+total_pics+'. '+(jQthumb_item.siblings(':header').html()||'');
                // stored in 'alt' and escaped to pass it all through.
                //var text = unescape(jQthumb_item.attr('alt'));

                // content already rendered in a hidden section
                var content_obj = jQthumb_item.closest('div').find('.jl-initial-hidden').clone();

                // do this outside the open, so we update it later
                jQ_dialog_body.
                    attr('title', head).
                    html(   '<a href="#prev_next">' +
                            '<img src="' + pic + '" class="clear center" title="click for Previous/Next">' +
                            '</a>').
                    append(content_obj);


                // calculate a width for the dialogue
                var browser_width = jQuery(window).width();
                var dlg_w = 600;
                if (dlg_w>browser_width){
                    dlg_w = browser_width - 10;
                    }

                // calculate a height for the dialogue
                var browser_height = jQuery(window).height();
                var dlg_h = dlg_w * 1.2;
                if (dlg_h>browser_height){
                    dlg_h = browser_height - 10;
                    }

                // Configure options for dialog
                var dialogOpts = {
                    modal       :   false,

                    // something funny about the sequence, but it works!
                    buttons     :   {   'Last'  :   doLast,
                                        'Next'  :   doNext,
                                        'Play'  :   doPlay,
                                        'First' :   doFirst,
                                        'Prev'  :   doPrev
                                    },
                    height      :   dlg_h,
                    width       :   dlg_w,
                    title       :   head,

                    // Content function in the dialog when it opens/closes
                    open        :   function () {
                                        null;
                                        },
                    close       :   function () {
                                        doStop();
                                        }
                    };

                // Set the above options
                jQ_dialog_body.dialog(dialogOpts);

                // open the dialog if it is not already open
                if (! jQ_dialog_body.dialog('isOpen') ){
                    jQ_dialog_body.dialog("open");
                    } //end unless 'isOpen'


                // Remove any hidden class in the body of the popup
                jQ_dialog_body.addClass('page_sections').find('.jl-initial-hidden').removeClass('jl-initial-hidden');

                // assign doPrevNext to the picture link
                jQ_dialog_body.find('a').first().
                    bind("click", doPrevOrNext);

                // Add a title to the close button
                jQ_dialog_body.prev('div').find('a:contains("close")').attr('title','Close');

                //-------------------------------
                // Sort out the button bar controls at the bottom of the dialog
                //-------------------------------

                // turn the buttons into icons
                var jQbutton_area =  jQ_dialog_body.siblings(':last');

                // move the Prev button to the left and change to an icon
                jQbutton_area.
                    find('button:contains("Prev")').
                        attr('title','Previous').
                        css('float', 'left').
                        //css('margin-left', '10px').
                        find('span').
                        replaceWith('<span style="float:left;" class="ui-icon ui-icon-triangle-1-w"></span>');

                // move the First button to the left and change to an icon
                jQbutton_area.
                    find('button:contains("First")').
                        attr('title','First').
                        css('float', 'left').
                        css('margin-left', '10px').
                        find('span').
                        replaceWith('<span style="float:left;" class="ui-icon ui-icon-seek-first"></span>');

                // play/stop icons in the middle
                if (jQ_gallery_area.data('jl-playing') != 'play'){
                    // Stop mode, ready to play
                    jQbutton_area.
                        find('button:contains("Play")').
                            removeClass('ui-state-active').
                            attr('title','Play').
                            css('margin-right', '20px').
                            find('span').
                            replaceWith('<span style="float:Right;" class="ui-icon ui-icon-clock"></span>'+
                                        '<span style="float:Right;" class="ui-icon ui-icon-play"></span>');
                    }
                else {
                    jQbutton_area.
                    // Play mode, button contains stop
                       find('button:contains("Play")').
                            addClass('ui-state-active').
                            attr('title','Stop').
                            css('margin-right', '20px').
                            find('span').
                            replaceWith('<span style="float:Right;" class="ui-icon ui-icon-clock"></span>'+
                                        '<span style="float:Right;" class="ui-icon ui-icon-stop"></span>');
                    }

                // Leave the Next button to the right and change to an icon
                jQbutton_area.
                    find('button:contains("Next")').
                        attr('title','Next').
                        find('span').
                        replaceWith('<span style="float:Right;" class="ui-icon ui-icon-triangle-1-e"></span>');


                // Leave the Last button to the right and change to an icon
                jQbutton_area.
                    find('button:contains("Last")').
                        attr('title','Last').
                        find('span').
                        replaceWith('<span style="float:Right;" class="ui-icon ui-icon-seek-end"></span>');

                //-------------------------------
                // All buttons done
                //-------------------------------

                // next image gets preloaded ready for later
                preloadNextJpegImage();

                return false;
                }); // end of gallery click function;

            // all fns defined and run
            } // End All Browsers (IE6 else) part
        log.info('Gallery Setup End');

        }
    catch (e) {
        log.notice('Gallery Setup Exception');
        log.critical(e);
        }

    }); // end doc ready fn - gallery processing



//----------------------------------------------------------------------------------------------
// LOG ANALYSIS
// handles log analysis via ajax requests
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {


        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded No Log Analysis');
            }
        else {

             log.info('Log Analysis Setup Begin');

            // Only set it up if a single loganalysis form exists
             if (jQuery("form.iloganalysis").length != 1){
                 log.notice('Skipped - no form.iloganalysis');
                 return;
                 }

            //-------------------------------------------
            // Identifies the element in the page we will update with the server response.
            //-------------------------------------------
            var response_section =
                jQuery("form.iloganalysis").            // the form
                    parents('div.section').             // div for the section
                    next();                             // div of the next section (containing the table to fill)

            //-------------------------------------------
            // a div to collect results in - this will soon be hidden
            //-------------------------------------------
            jQuery(response_section).
                append('<div id="response_area" class="section_content"><div id="response_area_content"></div></div>');

            // where the response can be put
            var response_target = jQuery('#response_area');

            log.debug('Action: '+ jQuery("form.iloganalysis").attr('action') );


            //-------------------------------------------
            // When form submitted
            //-------------------------------------------
            var submitRequest = function(formData, jqForm, these_options) {
                // formData is an array; jQuery.param converts it to a string to display
                // but the form plugin does this automatically when it submits the data

                var loading_msg;

                // If it was a search, need to clear out the existing table
                var cmd = jQuery(jqForm).find(':submit').fieldValue();
                if (cmd[0] == 'Search'){
                    // new search
                    log.debug('New Search');
                    jQuery(response_section).find('tbody:first').replaceWith('<tbody></tbody>');
                    loading_msg = log.info('Loading new search .......');
                    }
                else {
                    loading_msg = log.info('Loading more .......');
                    }

                //log.debug('Log Analysis - submit form: ' + jQuery.param(formData));

                jQuery(response_target).find('div').replaceWith('<div><p class=\"center\">'+loading_msg+'</p></div>');

                // delete any existing more button
                jQuery('#more_button_goes_here').remove();

                // allow the form submit to continue
                return true;
                };

            //-------------------------------------------
            // success callback
            //-------------------------------------------
            var responseSuccess = function(responseText, statusText, xhr, form)  {

                // delete any existing more button
                jQuery('#more_button_goes_here').remove();

                // TBD - may need to modify response DOM if it was short and illegal, turn
                // it into a error message

                // Look for 'Continue Searching' button in last row, convert it into a new form and associated div
                var complete_msg;
                last_row = jQuery(response_target).find('tr:last');
                if (jQuery(last_row).find('form').length) {
                    log.debug('Log Analysis - Success - More available');

                    jQuery(response_section).
                        // a new div in the section
                        append('<div id="more_button_goes_here" class="section_content ajax_pseudotag_expansion iloganalysis"></div>').
                        // move to the new div just inserted
                        children().last().
                        // move the form & button into it
                        append('<br>').
                        append(jQuery(last_row).find('form')).
                        // style the button
                        find(".pseudo-button").button();

                    // remove the empty row at the end of the table
                    jQuery(last_row).remove();

                    // make the form ajax
                    jQuery(response_section).find("form.iloganalysis_more").ajaxForm(options);

                    }
                else {
                    complete_msg = log.info('Search completed');
                    }

                // move rows from response_target to response_section.
                if (jQuery(response_target).find('tbody:first').find('tr').length) {
                    // append new search results to end of table response_section
                    jQuery(response_section).find('tbody:first').
                        append( jQuery(response_target).
                                    find('tbody:first').
                                    find('tr')              );

                    // style the buttons for trace etc.
                    jQuery(response_section).find('tbody:first').find(".pseudo-button.trace").button({text:false, icons:{primary:'ui-icon-wrench'}});
                    jQuery(response_section).find('tbody:first').find(".pseudo-button.more").button({text:false, icons:{primary:'ui-icon-info'}});

                    // add click handler to popup trace info
                    var trace_head_row;
                    jQuery(response_section).bind('click', function(e){

                        var jQLogItemButton = jQuery(e.target).closest('a');

                        // no click found or something else got clicked

                        if (! jQuery(jQLogItemButton).length || ! jQuery(jQLogItemButton).attr('href') ){
                            return true;
                            }

                        // confirm a stack trace was clicked
                        if ( jQuery(jQLogItemButton).attr('href') == '#view_stack_trace') {
                            // now processing a proper click on a button in the log info
                            e.preventDefault();

                            // calculate a width for the dialogue
                            var browser_width = jQuery(window).width();
                            var dlg_w = 700;
                            if (dlg_w>browser_width){
                                dlg_w = browser_width - 10;
                                }

                            // clear out any previous highlight
                            jQuery(trace_head_row).removeClass('ui-state-active');
                            // highlight the current row and note the text of the first colum for use as a heading
                            trace_head_row = jQuery(jQLogItemButton).parents('tr');
                            var trace_heading = jQuery(trace_head_row).addClass('ui-state-active').css('font-weight','normal').find('td:first').text();

                            var dialogOpts = {
                                // not modal, so can read other stuff and look about
                                modal       :   false,
                                width       :   dlg_w,
                                // note which row it comes from
                                title       :   'Trace for: '+trace_heading,
                                // so it looks like any other page content
                                dialogClass :   'jl-content page_sections',
                                // clear out highlight
                                close       :   function () {jQuery(trace_head_row).removeClass('ui-state-active');}
                                };

                            // clone the trace info and hack the stles
                            var content_obj = jQuery(jQLogItemButton).next().clone();
                            jQuery(content_obj).
                                removeClass('jl-initial-hidden').
                                removeClass('ui-hidden').
                                addClass('section_content');

                            // The region used for popup dialog
                            jQuery("#iloganalysis_trace_dialog_body").
                                   // Clean it out and prepare for display
                                   removeClass('jl-initial-hidden').
                                   removeClass('ui-hidden').
                                   empty().
                                   // insert theb trace
                                   append(content_obj).
                                   // and pop it up
                                   dialog(dialogOpts);

                            jQuery("#iloganalysis_trace_dialog_body").dialog( "option", "position", 'center');
                            return false;
                            }

                        // confirm a stack trace was clicked
                        if ( jQuery(jQLogItemButton).attr('href') == '#view_more_message') {
                            // now processing a proper click on a button in the log info
                            e.preventDefault();

                            // locate the cell and the less & more sections
                            var cell = jQuery(jQLogItemButton).parents('td');
                            var vis_content = jQuery(cell).find('.less-content');
                            var hid_content = jQuery(cell).find('.more-content');
                            // Toggle more/less
                            if (jQuery(jQLogItemButton).button('option','label') == 'More'){
                                jQuery(jQLogItemButton).button('option','label','Less');
                                jQuery(jQLogItemButton).button('option', 'icons',{primary:'ui-icon-circle-triangle-n'});
                                //jQuery(jQLogItemButton).addClass('ui-state-active');
                               }
                            else {
                                jQuery(jQLogItemButton).button('option','label','More');
                                jQuery(jQLogItemButton).button('option', 'icons',{primary:'ui-icon-info'});
                                //jQuery(jQLogItemButton).removeClass('ui-state-active ui-state-hover');
                               }
                            // Swap More <-> Less - tried to do simples with the swap plugin, but no nodes inside, and it didn't work with just test or html!!
                            var c1 = jQuery(vis_content).html();
                            jQuery(vis_content).html(jQuery(hid_content).html());
                            jQuery(hid_content).html(c1);

                            return false;
                            }

                        return true;
                        }); // End response click handler



                    } // end of moving rows

                // over-ride msg if no results found
                if(complete_msg && ! jQuery(response_section).find('tbody:first').find('tr').length) {
                    complete_msg = log.notice('No matching results');
                    }
                // over-ride msg if no results found
                if(! complete_msg && ! jQuery(response_section).find('tbody:first').find('tr').length) {
                    complete_msg = log.info('No results so far, but there are more log files to search.');
                    }
                // over-ride msg if no results found
                if(! complete_msg && jQuery(response_section).find('tbody:first').find('tr').length) {
                    complete_msg = log.info('There are more log files to search.');
                    }


                // clean up response area
                if (complete_msg){
                    jQuery(response_target).
                        find('div').
                        replaceWith('<div><p class=\"center\">'+complete_msg+'</p></div>');
                    }
                else {
                    jQuery(response_target).
                        find('div').
                        replaceWith('<div id="response_area_content"></div>');
                    }

                };

            //-------------------------------------------
            // error callback
            //-------------------------------------------
            var responseError = function(XMLHttpRequest, statusText, errorThrown){
                // It has all gone wrong, so show an error msg in the tbody last row
                var emsg = log.error('Log Analysis - ajax response - ' + statusText);

                jQuery(response_target).find('div').replaceWith('<div><p class=\"center\">'+emsg+'</p></div>');

                //jQuery(response_section).find('tbody:first').find('tr:last').replaceWith('<tr><td colspan=\"10\">'+emsg+'</td></tr>');
                // Log any errors thrown by exceptions
                if (errorThrown){
                    log.error(errorThrown);
                    }
                };

            // Set up using jquery forms package
            var options = {
                cache           :   false,              // Browser must not cache responses
                target          :   response_target,    // target element to be updated with server response
                beforeSubmit    :   submitRequest,      // pre-submit callback
                success         :   responseSuccess,    // post-submit callback - ok
                error           :   responseError,      // post-submit callback - error
                timeout         :   120000              // 120 second timout
                };

            // bind form using 'ajaxForm'
            jQuery("form.iloganalysis").ajaxForm(options);

            } // End All Browsers (IE6 else) part

        log.info('Log Analysis Setup End');

        }
    catch (e) {
        log.notice('Log Analysis Setup Exception');
        log.critical(e);
        }

    }); // end doc ready fn - button special processing




//----------------------------------------------------------------------------------------------
// THEMES SECTION OF SUPPLEMENTARY PANEL
// traps themes links and adds an appropriate cookie
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded Themes');
            }
        else {

            log.info('Themes Begin');

            // skip if no #mblock
            if (! jQuery('#section_content_supp_plugin_themes').length ){
                log.notice('Skipped - no #section_content_supp_plugin_themes');
                return true;
                }

            // bind to the whole panel, then on click look for the closest theme
            jQuery('#section_content_supp_plugin_themes').bind('click', function(e){

                // Identify the theme selected
                var theme = jQuery(e.target).closest('a').text();
                log.debug('text='+theme);

                // name the cookie?

                // General parameters set when template is filled in, metadata
                var local_meta = jQuery('#sblock').metadata('jl_metadata');

                // Save the revised history cookie
                jQuery.cookies.set (local_meta.site_id+'theme' , theme, {hoursToLive: 24*366 }); // 1 leap year

                // now processing a proper click on a link - let it go ahead as the page needs to refresh
                //e.preventDefault();
                return true;
                });

            } // End All Browsers (IE6 else) part

        log.info('Themes End');

        }
    catch (e) {
        log.notice('Themes Exception');
        log.critical(e);
        }

    }); // end doc ready fn - themes processing



































//----------------------------------------------------------------------------------------------
// READY - simple log entry
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {
        log.info('UI-Assist System Ready');

        }
    catch (e) {
        log.notice('UI-Assist Ready Exception');
        log.critical(e);
        }

    }); // End 'ready' doc ready ready fn




//----------------------------------------------------------------------------------------------


/*=========================================*/
/* Source:  z-resources/JLscripts/menu/old-site-compatibility.js */
/* Updated: 13/06/2010 20:01:45 */
/*=========================================*/
//
// z-resources/JLscripts/menu/old-site-compatibility.js
//


//----------------------------------------------------------------------------------------------
// Old site compatibility stuff
//----------------------------------------------------------------------------------------------
jQuery.noConflict();

jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        log.info('Old site compatibility Begin');

        // skip if no #mblock
        if (! jQuery('#mblock').length ){
            log.notice('Skipped - no #mblock');
            return;
            }

        // adjust and maintain width of menu frame, parameter set by template
        var vertical_menu_width  = jQuery('#mblock').metadata('jl_metadata').vertical_menu_width || 310;
        if (    vertical_menu_width &&
                window &&
                window.parent &&
                window.parent.document){
            var fset = window.parent.document.getElementsByTagName("frameset")[0];
            if (fset){
                fset.cols = vertical_menu_width+",*";
                }
            }

        // Other compatibility stuff?

        // CJ cookie
        var site_id  = jQuery('#mblock').metadata('jl_metadata').site_id;

        if (jQuery.cookies.get( '__CJ_' + site_id + 'history' )){
            var ck_val = unescape(jQuery.cookies.get( '__CJ_' + site_id + 'history' ));
            jQuery.cookies.set (site_id + 'history' , ck_val, {hoursToLive: 24*366 }); // 1 leap year
            jQuery.cookies.del( '__CJ_' + site_id + 'history' );
            log.debug('Obsolete __CJ_ cookie replaced');
            }

        log.info('Old site compatibility End');

        }
    catch (e) {
        log.info('Old site compatibility Exception');
        log.critical(e);
        }

    }); // End Old site compatibility stuff


//----------------------------------------------------------------------------------------------
// Switch Old/New sites
//----------------------------------------------------------------------------------------------

jQuery(document).ready(function()   {


   var log = jQuery.jl.logger('#DevelopmentMode');

   try {

        log.info('Switch Sites Begin');

        // skip if no #mblock
        if (! jQuery('#OldSiteCompatibility').length ){
            log.notice('Skipped - no #OldSiteCompatibility');
            return;
            }


         // Setup the old site compatibility area

        var site_id  = jQuery('#OldSiteCompatibility').metadata('jl_metadata').site_id;
        var dev_mode  = jQuery('#OldSiteCompatibility').metadata('jl_metadata').dev_mode;

        //Only pay attention to it if in dev mode
        if (dev_mode && dev_mode > 0){

            log.debug('Switch Sites Mechanism Active');

            jQuery('#OldSiteCompatibility').
                    removeClass('jl-initial-hidden').
                    addClass('ui-helper-reset ui-widget ui-clearfix ui-component').
                    find('input').
                    click(function(){
                        if (this.checked){
                            jQuery.cookies.set (site_id + 'ss', 'development', {hoursToLive: 24*366 }); // 1 leap year
                            log.notice('Development site enabled');
                            }
                        else {
                            jQuery.cookies.del (site_id + 'ss'); // deleted
                            log.notice('Development site disbled');
                            }
                    });

            if (jQuery.cookies.get(site_id + 'ss') && jQuery.cookies.get(site_id + 'ss') == 'development') {
                // We are in the new site,  then initially enable the devel flag
                jQuery('#OldSiteCompatibility input').attr('checked', true);
                jQuery.cookies.set (site_id + 'ss', 'development', {hoursToLive: 24*7 }); // 1 week
                log.debug('New site initially enabled');
                }
            else {
                // Menu.htm implies We are in the old site, then initially disable the devel flag
                jQuery('#OldSiteCompatibility input').attr('checked', false);
                jQuery.cookies.del (site_id + 'ss'); // deleted
                log.debug('New site initially disabled');
                }
            }
        else {
            // We are in the old site by default,  then disable the devel flag
            jQuery.cookies.del (site_id + 'ss'); // deleted
            }

        log.info('Switch Sites End');
        }
    catch (e) {
        log.info('Switch Sites Exception');
        log.critical(e);
        }

    }); // End Switch Sites stuff




/*=========================================*/
/* Source:  z-resources/JLscripts/menu/jlmenu.js */
/* Updated: 16/06/2010 14:04:18 */
/*=========================================*/
//
// z-resources/JLscripts/menu/jlmenu.js
//
// scripts that make the menu work
//
// - Accordion - opening, closing and style for current page etc
// - User's Menu
// - History
//
// Prerequisites - development_mode.js for logging
//
// This used to depend on old site compatibility switching the menu.
// Now, that only widens the menu if it is in a frame and the
// menu could quite happily work without it
//

jQuery.noConflict();


//----------------------------------------------------------------------------------------------
// ACCORDION
// sets the accordion going and shows the outer block/div in #mblock
// the menu itself is identified by #am
// Also selects which section is open and adds a menu-selected class to
// sections that match the current page
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        // IE version 5.5 or less
        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 6){
            // no accordion if ie version < 6
            log.notice('IE5.5 Or less extreme Degraded menu ');
            jQuery('#am div').removeClass();
            jQuery('#mblock').removeClass();
            jQuery('#mblock_loading').remove();
            }

        // IE version 6
        else if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded menu styling');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            var degAccOpts = {
                autoHeight  :   false,
                icons       :   { 'header': 'ui-icon-folder-collapsed', 'headerSelected': 'ui-icon-folder-open' }
                };

            jQuery('#am').accordion(degAccOpts);

            // get rid of all styling of the div as that is what ie6 does not render
            jQuery('#am div').removeClass();
            jQuery('#mblock').removeClass();
            jQuery('#mblock_loading').remove();
            }


        // Normal operation, IE 7 or greater and all others
        else {

            //-- Now all the styling for the menu items
            log.info('Accordion Menu Setup Begin');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            // General parameters set when template is filled in, metadata
            var local_meta = jQuery('#mblock').metadata('jl_metadata');
            var root_rel_baseaddr = local_meta.root_rel_baseaddr;
            var site_id  = local_meta.site_id;


            //-------------------------------------
            // Make changes and modifications to the
            // default jQuery ui accordion styling
            //-------------------------------------
             // Styling for the individual menu items
            jQuery('#am ul').addClass('ui-helper-reset ui-clearfix ui-component').
                             parent().
                             addClass('ui-state-active ui-corner-bottom');

            // Add hover event to all menu items using jquery theme
            jQuery('#am li').prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>').
                             addClass('ui-helper-reset ui-state-default').
                             hover(
                                function(){
                                    jQuery(this).addClass('ui-state-hover');
                                    },
                                function(){
                                    jQuery(this).removeClass('ui-state-hover');
                                    }
                    );

            // The div above the ul is normally ui-state-active and this inherits
            // to give all sorts of crap side effects in the links in the menu
            // so by replacing it with pseudo-active, we still get the colour
            // but without the crap!
            jQuery('#am ul').parent().removeClass('ui-state-active').addClass('ui-state-pseudo-active');

            // Add rounded corners at the bottom of each panel
            jQuery('#am ul').each(function (i){
                                jQuery(this).find('li:last').addClass('ui-corner-bottom').end().find('li:first').addClass('border-top-on');
                                });

            //-------------------------------------
            // Mark all links that match the current page as active
            //-------------------------------------

            // extract path and page info, from metadata or browser
            // properties: 'title' 'path' 'ext' 'path_noext'
            var p1 = jQuery.jl.pageinfo('#mblock');
            var pinfo = p1.get_info();
            log.debug(pinfo);

            // Mark menu items as active if they match the current page
            // simple - only regular address to consider
            var page_link_path = top.location.pathname;
            jQuery('#am a[href='+page_link_path+']').parent().removeClass('ui-state-default').addClass('ui-state-active');
            log.debug('P1:'+page_link_path);
            // complex - need to consider index.htm and home_page.htm
            if (page_link_path.match(/\/index\.htm$/)){
                var hp_link_path = page_link_path.replace(/\index\.htm$/, "/home_page.htm");
                jQuery('#am a[href='+hp_link_path+']').parent().removeClass('ui-state-default').addClass('ui-state-active');
                log.debug('P2:'+hp_link_path);
                }
            // and also, any page defined from metadata
            jQuery('#am a[href='+root_rel_baseaddr+pinfo.path+']').parent().removeClass('ui-state-default').addClass('ui-state-active');
            log.debug('P3:'+root_rel_baseaddr+pinfo.path);

            //-------------------------------------
            // Now ready to set the accordion going
            //-------------------------------------
            jQuery('#am').accordion( {
                //event       :   "click",
                autoHeight  :   false,
                collapsible :   true,
                //animated    :   'slide',
                icons       :   { 'header': 'ui-icon-folder-collapsed', 'headerSelected': 'ui-icon-folder-open' },
                active      :   false
                });

            // A function to track the current accordion folder
            jQuery('#am').bind('accordionchange', function(ev, ui){

                // May result in a srollbar appearing, which
                // then changes the window inside size, so
                // need to trigger resize to compensate
                jQuery(window).resize();

                var curDrawer = jQuery(ui.newHeader).find('a').attr('id');
                //DEBUG alert('CHANGE2 '+curDrawer);
                // not interested if we are closed
                if (! curDrawer) {
                    return;
                    }
                // save the current drawer,
                jQuery.cookies.set( site_id + 'accordion', curDrawer, {hoursToLive: 24*366 });
                log.debug('Open Drawer '+jQuery.cookies.get( site_id + 'accordion'));
                });

            //-----------------------------------------------------
            // Work out which drawer of the accordion to initially open
            //-----------------------------------------------------
            var best_drawer_id;
            var top_drawer_id;
            var last_drawer_id = jQuery.cookies.get( site_id + 'accordion');
            // list all drawers with a link to the current page - by looking for an active style in a list/link
            // while making a note as to which one matches the current drawer
            jQuery('#am li.ui-state-active').parents('div.ui-accordion-content').prev('h3').find('a').each(
                function (i){
                    // try and match the current drawer
                    var id = jQuery(this).attr('id');
                    // log.debug ('ActiveLinks '+id+'\nLast '+last_drawer_id);
                    if (i<1) {
                        top_drawer_id = id;
                        }
                    // starting point is first drawer that matches
                    if (!best_drawer_id){
                        best_drawer_id = id;
                        }
                    // but can be overridden by the last drawer having an appropriate link
                    if (id == last_drawer_id) {
                        best_drawer_id = last_drawer_id;
                        }
                    }
                );
            // If last open drawer does not have a link to the current page, open
            // any matched drawer, or open the last drawer anyway
            if (!best_drawer_id) {
                best_drawer_id = last_drawer_id || top_drawer_id || 0;
                }

            // Open whatever is selected from the above by simulating a click on the
            // link in the header of a section
            jQuery('#'+best_drawer_id).trigger('click');
            log.debug('Initial Drawer '+best_drawer_id);

            } // End all good browsers part

        // Clear out any hidden issues and cancel the loading message
        // applies to all browser code
        jQuery('#mblock').removeClass();
        jQuery('#mblock_loading').remove();

        log.info('Accordion Menu Setup End');
        }
    catch (e) {
        log.notice('Accordion Menu Setup Exception');
        log.critical(e);
        jQuery('#mblock').removeClass();
        }

    }); // End doc redy fn - accordion


//----------------------------------------------------------------------------------------------
// USERS MENU
// user's menu special processing - using a dialogue in #umenudblock
// saves user menu links in the user menu cookie
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.info('IE6 Degraded User\'s Menu');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            // Section not used with IE6 version
            jQuery("#am [id^=UsersMenu]").parent().remove().next().remove();
            }
        else {

            log.info('User\'s Menu Setup Begin');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            // Clean up the title - spaces etc
            var cleanUp = function (clean_me){
                clean_me = clean_me.replace(/<[^>]+>/gi, ' '); // remove any formatting tags
                clean_me = clean_me.replace(/\([^\)]+\)/gi, ' '); // remove any parenthesis
                clean_me = clean_me.replace(/[^\ -\~]+/gi, ' '); // any unusual characters, most likely a copyright symbol?
                clean_me = jQuery.trim(clean_me).replace(/[\s]+/g,' ');
                return clean_me;
                };

            // These need to be outside the handler or it gets optimised into a constant ### SEE NOTE AT TOP
            // and sticks at the first button used
            var uc_id;  var uc_short_id;

            // General parameters set when template is filled in, metadata
            var local_meta = jQuery('#mblock').metadata('jl_metadata');
            var root_rel_baseaddr = local_meta.root_rel_baseaddr;
            var site_id  = local_meta.site_id;

            // extract path and page info, from metadata or browser
            // properties: 'title' 'path' 'ext' 'path_noext'
            var p1 = jQuery.jl.pageinfo('#mblock');
            var pinfo = p1.get_info();
            log.debug(pinfo);


            var w_short_page_link_path = pinfo.path_noext.replace (/[\/]{1}/g, '/<wbr>');

            // Define context menu fuction,
            // this is long and fills most of the rest of this section
            jQuery("#am [id^=UserConfig]").bind("contextmenu",function(e){
                e.preventDefault();

                // The current menu item
                uc_id = e.target.id;
                // The simple numeric part of the id
                uc_short_id = parseInt(uc_id.replace(/[^0-9]+/gi,''), 10);

                // the critical stuff
                // Configure some buttons for the dialogue and their actions

                // -----------------------------
                // CANCEL
                // -----------------------------
                var doCancel = function () {
                    jQuery('#umenudblock').dialog("close");
                    log.debug('User\'s Menu Dialog Cancel');
                    }; // End doCancel

                // -----------------------------
                // CLEAR
                // -----------------------------
                var doClear = function () {
                    // empty the text box where the title is entered
                    jQuery('#um_new_title').attr("value","");
                    log.debug('User\'s Menu Dialog Clear');
                    }; // END doClear

                // -----------------------------
                // SAVE
                // -----------------------------
                var doSave = function () {
                    jQuery('#umenudblock').dialog("close");

                    // The value in the dialogue
                    var ed_title = cleanUp( jQuery('#um_new_title').attr("value") );

                    // set the BUTTON now !
                    if (ed_title) {
                        // Note [U] is appended to the title
                        jQuery('#'+uc_id).text(ed_title + ' [U]').attr('href', root_rel_baseaddr + pinfo.path);
                        }
                    else {
                        // Saving an empty button clears it back to 'User Config'
                        jQuery('#'+uc_id).text('User Config').attr('href', root_rel_baseaddr + pinfo.path);
                        }

                    // The settings need to be saved in a COOKIE.
                    // Format of cookie =
                    // 42::Tiger Lily New Software [U]::boats/tiger_lily/boat.htm||45::Audit Last Month [U]::members/audit_reports/audit_last_month.htm'

                    // See if it is already in the cookie, by searching for id number
                    var ub_cookie = jQuery.cookies.get( site_id + 'umenu' );
                    var saved_user_buttons = [];
                    if (ub_cookie) {
                        saved_user_buttons = ub_cookie.split('||');
                        }
                    var foundit = 0;
                    var new_user_buttons = ''; // string to accumulate
                    if (saved_user_buttons.length>0){
                        jQuery.each( saved_user_buttons, function(i, val) {
                            // look for matching numbers - the short id of the item
                            var ck_short_id = val.split('::')[0];
                            if (uc_short_id == ck_short_id) {

                                // If there is a value, then set the button to it
                                if (ed_title && (ed_title != '[U]')) {
                                    // have found the id we are setting, so accumulate revised text with [U] appended to the title
                                    if (new_user_buttons.length >0) {
                                        new_user_buttons += '||';
                                        }
                                    new_user_buttons += uc_short_id+'::'+ed_title + ' [U]::'+ pinfo.path;
                                    foundit ++;
                                    }
                                else {
                                    // Saving an empty button clears it back to 'User Config'
                                    // erase the line from the cookie by simply leaving it out
                                    foundit ++;
                                    }
                                } // endif
                            else {
                                if (new_user_buttons.indexOf(ck_short_id+'::')>=0){
                                    // A duplicate, this only happens when the data is corrupted by a software bug
                                    // No need to keep it, but the cookie has to be corrected later
                                    foundit ++;
                                    }
                                else {
                                    // Not a duplicate
                                    if (new_user_buttons.length >0) {
                                        new_user_buttons += '||';
                                        }
                                    new_user_buttons += val;
                                    } // endif
                                } // endif
                            }); //end each loop
                        } // endif

                    // If not already in the cookie then append it
                    // Note [U] is appended to the title
                    if (! foundit) {
                        if (new_user_buttons.length >0) {
                            new_user_buttons += '||';
                            }
                        new_user_buttons += uc_short_id+'::'+ed_title + ' [U]::'+pinfo.path;
                        foundit ++;
                        }

                    // Now save the cookie again
                    if (foundit) {
                        if (new_user_buttons.length>0){
                            jQuery.cookies.set (site_id + 'umenu', new_user_buttons, {hoursToLive: 24*366 }); // 1 leap year
                            }
                        else {
                            // no entries left, so kill the cookie
                            jQuery.cookies.del (site_id + 'umenu'); // Delete
                            }
                        }

                    log.debug('User\'s Menu Dialog Save \'' + uc_short_id+'::'+ed_title + ' [U]::'+pinfo.path +'\'');
                    }; // End doSave

                //--------------------------------------------
                // Now the Dialog that uses the above buttons
                //--------------------------------------------

                // adjust width of dialog popup and text area inside
                var dialog_pop_width = (jQuery('#mblock').metadata('jl_metadata').dialog_pop_width);
                var page_width = jQuery('body').width()||jQuery(document).width();
                log.debug('Dialog page width: '+ page_width);
                if (dialog_pop_width > (page_width - 25)){
                    log.debug('Dialog width reduced from: '+ dialog_pop_width);
                    dialog_pop_width = page_width - 25;
                    }
                var dialog_text_cols = Math.round(dialog_pop_width * 0.141781 - 13.3014);
                jQuery('#um_new_title').attr('cols',dialog_text_cols);
                log.debug('Dialog width: '+ dialog_pop_width);
                log.debug('Dialog cols: '+ dialog_text_cols);

                var dialogOpts = {
                    bgiframe    :   true,
                    modal       :   true,
                    overlay     :   'jl-modal-bg',

                    buttons     :   {   'Cancel'        :   doCancel,
                                        'Save'          :   doSave,
                                        'Clear'         :   doClear
                                    },
                    width       :   dialog_pop_width-1,
                    // Set some text & options in the dialog when it opens
                    open        :   function () {
                                        jQuery('#um_short_new_link_path').html(w_short_page_link_path);
                                        jQuery('#um_new_title').attr('value', pinfo.title);
                                        }
                    }; // End dialogOpts


                // And set the dialog going
                jQuery('#umenudblock').dialog(dialogOpts).removeClass('ui-helper-hidden').dialog("open");
                log.debug('User\'s Menu Dialog Open');

                //--------------------------------------------


                e.preventDefault();
                }); // end contextmenu fn

            } // End All Browsers (IE6 else) part

        log.info('User\'s Menu Setup End');

        }
    catch (e) {
        log.notice('User\'s Menu Setup Exception');
        log.critical(e);
        }



    }); // end doc ready fn - user's menu special processing

//----------------------------------------------------------------------------------------------
// HISTORY
// page history special processing - all in the background
// Extends/updates the page history cookie
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');


    try {


        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.info('IE6 Degraded Visited Pages');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            // Section not used with IE6 version
            jQuery("#am [id^=VisitedPages]").parent().remove().next().remove();
            }
        else {

            log.info('Visited Pages Setup Begin');

            // skip if no #mblock
            if (! jQuery('#mblock').length ){
                log.notice('Skipped - no #mblock');
                return;
                }

            // General parameters set when template is filled in, metadata
            var local_meta = jQuery('#mblock').metadata('jl_metadata');
            var root_rel_baseaddr = local_meta.root_rel_baseaddr;
            var site_id  = local_meta.site_id;
            var hist_length  = local_meta.history_length||10;

            // extract path and page info, from metadata or browser
            // properties: 'title' 'path' 'ext' 'path_noext'
            var p1 = jQuery.jl.pageinfo('#mblock');
            var pinfo = p1.get_info();
            log.debug(pinfo);

            // don't do anything with error pages
            if (pinfo.title.match(/error/) || pinfo.path.match(/error/)){
                log.warning('Error found in path='+pinfo.path+' or title:'+pinfo.title);
                }

            // we have a path and a title, so can work on the history
            else if (pinfo.path_noext && pinfo.title){

               var history_obj = {};

                // Existing history is in a cookie as JSON
                var ck_string = unescape(jQuery.cookies.get( site_id + 'history' ));
                if (ck_string) {

                    // Sanitise if necessary - could contain unusual characters that break the rules for JSON
                    var bc = [];
                    bc = ck_string.match(/[^\ -\~]+/gi);
                    if (bc && bc.length>0 ){
                        // remove any unusual characters, most likely copyright symbol
                        ck_string = ck_string.replace(/[^\ -\~]+/gi, '');
                        // log the removal
                        log.debug(bc.join('.'));
                        }

                    // can now eval the JSON without risk of errors from illegal chars
                    history_obj = jQuery.secureEvalJSON(ck_string)||{};

                    // Add/amend a record for the page in the history object
                    // delete any existing variations
                    if (history_obj && history_obj.hasOwnProperty(pinfo.path_noext)){
                        delete history_obj[pinfo.path_noext];
                        }
                    if (history_obj && history_obj.hasOwnProperty(pinfo.path)){
                        delete history_obj[pinfo.path];
                        }

                    } // End if ck_string

                // Add new variation
                var sys_time = new Date();
                history_obj[pinfo.path] = { p_title: pinfo.title, p_time: parseInt(sys_time.getTime()/1000, 10)};
                log.debug('History add \''+pinfo.title+'\' link to '+pinfo.path);

                // Make a list of paths in the history
                var hist_page_keys = [];
                jQuery.each( history_obj, function(hp_path, hp_obj) {
                    hist_page_keys.push(hp_path);
                    });

                // Get the history in time order, we can now delete the oldest history if it is too big
                // reverse sort, newest first
                var hist_order = function (a,b) {
                    return history_obj[b].p_time - history_obj[a].p_time;
                    };
                var sorted_hist_page_keys = hist_page_keys.sort(hist_order);

                // Shorten if the history is too big
                if (sorted_hist_page_keys.length > hist_length){
                    var dkey = sorted_hist_page_keys.pop();
                    delete history_obj[dkey];
                    log.debug('--'+dkey);
                    }

                // Save the revised history cookie
                jQuery.cookies.set (site_id + 'history' , jQuery.toJSON(history_obj), {hoursToLive: 24*366 }); // 1 leap year
                }
            else {
                log.info('no path='+pinfo.path+' or no title:'+pinfo.title);

                }

            } // End IE6 else part

        log.info('Visited Pages Setup End');

        }
    catch (e) {
        log.notice('Visited Pages Setup Exception');
        log.critical(e);
        }



    }); // End page history doc ready ready fn


//----------------------------------------------------------------------------------------------
// READY - simple log entry
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {
        log.info('Menu System Ready');

        }
    catch (e) {
        log.notice('Ready Exception');
        log.critical(e);
        }

    }); // End 'ready' doc ready ready fn




//----------------------------------------------------------------------------------------------


/*=========================================*/
/* Source:  z-resources/JLscripts/menu/jlsupportmenu.js */
/* Updated: 16/06/2010 13:33:35 */
/*=========================================*/
//
// z-resources/JLscripts/menu/jlsupportmenu.js
//
// scripts that make the support menu work
//
// - Accordion - opening, closing and style for current page etc
// - User's Menu
// - History
//
// Prerequisites - development_mode.js for logging
//
// This used to depend on old site compatibility switching the menu.
// Now, that only widens the menu if it is in a frame and the
// menu could quite happily work without it
//

jQuery.noConflict();


//----------------------------------------------------------------------------------------------
// SUPPORT ACCORDION
// sets the accordion going and shows the outer block/div in #sblock
// the menu itself is identified by #sa
// Also selects which section is open and adds a menu-selected class to
// the open section
//----------------------------------------------------------------------------------------------
jQuery(document).ready(function()   {

    var log = jQuery.jl.logger('#DevelopmentMode');

    try {

        // IE version 5.5 or less
        if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 6){
            // no accordion if ie version < 6
            log.notice('IE5.5 Or less No Supporting Panel');
            jQuery('#sa div').removeClass();
            jQuery('#sblock').removeClass();
            jQuery('#sblock_loading').remove();
            }

        // IE version 6
        else if (jQuery.browser && jQuery.browser.msie && jQuery.browser.versionX && jQuery.browser.versionX < 7){
            // IE6, so no styling
            log.notice('IE6 Degraded Supporting Panel styling');

            var degAccOpts = {
                autoHeight  :   false,
                icons       :   { 'header': 'ui-icon-folder-collapsed', 'headerSelected': 'ui-icon-folder-open' }
                };

            jQuery('#sa').accordion(degAccOpts);

            // get rid of all styling of the div as that is what ie6 does not render
            jQuery('#sa div').removeClass();
            jQuery('#sblock').removeClass();
            jQuery('#sblock_loading').remove();
            }


        // Normal operation, IE 7 or greater and all others
        else {

            //-- Now all the styling for the menu items
            log.info('Supporting Panel Setup Begin');

            //-------------------------------------
            // Now ready to set the accordion going
            //-------------------------------------
            jQuery('#sa').accordion( {
                autoHeight      :   false,
                collapsible     :   true,
                clearStyle      :   true,
                //fillSpace       :   true,
                icons           :   {  'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-triangle-1-s' }
                });

             // May result in a srollbar appearing, which then changes the window inside size, so
             // need to trigger resize to compensate
             jQuery('#sa').bind('accordionchange', function(ev, ui){
                 jQuery(window).resize();
                 });

            } // End all good browsers part

        // Clear out any hidden issues and cancel the loading message
        // applies to all browser code
        jQuery('#sblock').removeClass();
        jQuery('#sblock_loading').remove();

        log.info('Supporting Panel Setup End');
        }
    catch (e) {
        log.notice('Supporting Panel Setup Exception');
        log.critical(e);
        jQuery('#sblock').removeClass();
        }

    }); // End doc redy fn - supporting accordion




//----------------------------------------------------------------------------------------------


