var agent;
var isMajor;
var isIe;
var isIe6;
var isIe7;
var isIe8;
var isFirefox;
var isWindows;
var flashMoviesOnPage = 0;
var silverlightPlayersOnPage = 0;
var debugLog = false;
var equalizeGrid = false;
var defaultButtonFired = false;
var slideshowImageDetails = [];
var websiteFeatures = [];
var globalObj = {};

var siteConfig = {
    equalize: {
        main: {
            active: true,
            offset: 6
        },
        committees: {
            active: true,
            offset: 6
        },
        mlo: {
            active: true,
            offset: 6
        },
        education: {
            active: false,
            offset: -9
        },
        popvox: {
            active: false
        },
        woa: {
            active: true,
            offset: 6
        },
        briefingPapers: {
            active: true,
            offset: 6
        },
        edm: {
            active: true,
            offset: 6
        },
        cpa: {
            active: true,
            offset: 6
        },
        popup: {
            active: false
        },
        rollinghansard: {
            active: true,
            offset: 6
        }
}
};

var subSiteJavaScript = {
    srcPath: '/assets/scripts/sub-sites/',
    sites: {
        committees: true,
        main: true,
        woa: true,
        education: true,
        mlo: false,
        popvox: true,
        briefingPapers: true,
        edm: true,
        cpa: true,
        rollinghansard: true

    }
};

var silverlightConfiguration = {
	localWebServiceUrl: 'http://dev.parliament.uk/AJAX/SilverlightEmbed.ashx'
};

var websiteFeaturesConfig = {
    defaultFlashVersion: '9.0.0',
    initialLoad: 1,
    rotationEnabled: false,
    rotationTime: 2000
};

var toggleConfig = {
    slideTime: 1000
};

var whatsOnConfig = {
    autoSelect: 'current'
};

var educationToggleConfig = {
    slideTime: 1000
};

var advancedSearchConfig = {
    autoFill: false,
    max: 30,
    scroll: true,
    scrollHeight: 150,
    width: 402,
    delay: 300
};

var popvoxToggleConfig = {
    slideTime: 500
};

var tracking = {
    accountID: 'UA-15845045-1',
    enabled: true
};

var flashTrackingProgress = {
    percentage: 0,
    viewed1To25Percent: false,
    viewed26To50Percent: false,
    viewed51To75Percent: false,
    viewed76To100Percent: false
};

//plugins
var calendarConfig = {
    cssFile: '/assets/css/datepicker.css',
    javascriptFiles: {
        file1: '/assets/scripts/jquery.date.js',
        file2: '/assets/scripts/jquery.datepicker.js'
    }
};

var shadowBoxConfig = {
    cssFile: '/assets/css/shadowbox.css',
    javascriptFiles: {
        file1: '/assets/scripts/shadowbox.js'
    }
};

var WoAZoomConfig = {
    javascriptFiles: {
        file1: '/assets/scripts/jquery.mousewheel.min.js'
    }
};

var educationPictureViewerConfig = {
    javascriptFiles: {
        file1: '/assets/scripts/jquery.imageviewer.js',
        file2: '/assets/scripts/jquery.scrollTo.js'
    },
    slideTime: 1000
};

var advancedSearchMembersConfig = {
    cssFile: '/assets/css/jquery.autocomplete.css',
    javascriptFiles: {
        file1: '/assets/scripts/jquery.autocomplete.js',
        file2: '/assets/scripts/jquery.bgiframe.js'
    }
};

parliamentUK = {
    init: function (obj) {
        //add .js class to html tag
        $('.noJS').removeClass('noJS').addClass('js');

        //handle page specific initializations
        $.extend(obj, { site: $(document.body).attr('class') });

        //extend init object to global scope
        $.extend(globalObj, obj);

        //check to see if colour debugging needs to be loaded
        top.location.href.indexOf('show-colours') != -1 ? $('BODY').addClass('show-colours') : $('BODY').attr('class', $(this).attr('class'));

        //check to see if debug logging needs to be loaded
        top.location.href.indexOf('debug') != -1 ? debugLog = true : debugLog = false;

        //prepare external document links
        $('.document').each(function () {
            $('<img />').attr({ 'class': 'new-window-icon', 'src': '/assets/images/new-window-icon.gif', 'alt': 'Opens in a new window' }).appendTo(this);
        });

        $('a.document').attr('rel', 'external');

        //assign _blank targets in order to meet Strict doctype markup restrictions
        $('A[rel="external"]').attr('target', '_blank');

        //run browser-sniffer for a rare case where custom JavaScript requires variance between browsers		
        parliamentUK.browserSniffer();

        //add alternate row colouring for <table>s (global site scope)
        $('.alternate-table TABLE TBODY').each(function () {
            parliamentUK.alternateHighlight({ wrapper: $(this), selector: 'TR', siblingShowHideSelector: 'TD' });
        });

        //initialize page specific functionality
        parliamentUK.page.init(obj);

        //equalize grid columns to ensure grey tramlines run consistently to full page depth (three-wide template only)
        if (obj.pageType != 'main-start' && obj.pageType != 'print') {
            setTimeout("parliamentUK.resetGrid()", 1);
        }
    },

    //dynamically load plugins into the DOM (use AJAX for the scripts, so as to save data bursting and to enforce browser caching)
    pluginLoader: function (obj) {
        switch (obj.pluginName) {
            case 'woaZoom':
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: WoAZoomConfig.javascriptFiles.file1 });

                break;
            case 'calendar':
                parliamentUK.createElement({ type: 'LINK', appendTo: $('HEAD'), other: { rel: 'stylesheet', type: 'text/css', media: 'projection,screen', href: calendarConfig.cssFile }, insertMode: 'insertAfter' });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: calendarConfig.javascriptFiles.file1 });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: calendarConfig.javascriptFiles.file2 });

                break;
            case 'advancedSearchMembers':
                parliamentUK.createElement({ type: 'LINK', appendTo: $('HEAD'), other: { rel: 'stylesheet', type: 'text/css', media: 'projection,screen', href: advancedSearchMembersConfig.cssFile }, insertMode: 'insertAfter' });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: advancedSearchMembersConfig.javascriptFiles.file1 });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: advancedSearchMembersConfig.javascriptFiles.file2 });

                break;
            case 'woaPictureViewer':
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: educationPictureViewerConfig.javascriptFiles.file1 });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: educationPictureViewerConfig.javascriptFiles.file2 });

                break;
            case 'shadowbox':
                parliamentUK.createElement({ type: 'LINK', appendTo: $('HEAD'), other: { rel: 'stylesheet', type: 'text/css', media: 'projection,screen', href: shadowBoxConfig.cssFile }, insertMode: 'insertAfter' });
                $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: shadowBoxConfig.javascriptFiles.file1 });

                //identify whether any callee was passed, in order to unique initialize shadowbox with different settings
                var initSettings;

                if (obj.shadowboxCallee) {
                    initSettings = {
                        onOpen: function (item) {
                            $('#sb-title-inner').css('display', 'none');
                            $('#sb-body').addClass('main-gallery-artwork');
                        }
                    }
                } else {
                    initSettings = {};
                }

                Shadowbox.init(initSettings);

                if (isIe6) { DD_belatedPNG.fix('#sb-nav-close'); }

                break;
        }
    },

    //load any sub-site JavaScript files (if required)
    loadSubSiteJavaScript: function (site) {
        if (subSiteJavaScript.sites[site]) {
            //add sub-site JavaScript file to the DOM
            $.ajax({ async: false, cache: true, dataType: 'script', type: 'get', url: subSiteJavaScript.srcPath + site + '.js' });
        }
    },

    //initialize all Flash movies
    flashMovieInit: function (obj) {
        if (debugLog) { parliamentUK.logEvent('[FLASH MOVIE]: initialize'); }

        //iterate global counter for movies on current page
        flashMoviesOnPage++;

        var flashParent = $('.flash:eq(' + (flashMoviesOnPage - 1) + ')');
        $(flashParent).attr('id', 'flash-container-' + flashMoviesOnPage);

        //assign an id to the original no-flash <div>
        $('.no-flash', $(flashParent)).attr('id', 'inner-' + flashMoviesOnPage + '-swfobject');

        //apply any CSS individual alterations here
        if (obj.additionalSettings != undefined) {
            $('#inner-' + flashMoviesOnPage + '-swfobject').parent().css(obj.additionalSettings.css);
        }

        swfobject.embedSWF(obj.configuration.src, 'inner-' + flashMoviesOnPage + '-swfobject', obj.configuration.width, obj.configuration.height, obj.configuration.version != undefined ? obj.configuration.version : websiteFeaturesConfig.defaultFlashVersion, obj.configuration.expressInstallSrc, obj.flashvars, obj.params);

        var flashvarsDebug = '';
        var paramsDebug = '';

        for (x in obj.flashvars) { flashvarsDebug += x + '=' + obj.flashvars[x] + ', '; }
        for (x in obj.params) { paramsDebug += x + '=' + obj.params[x] + ', '; }

        flashvarsDebug = flashvarsDebug.substr(0, flashvarsDebug.length - 2);
        paramsDebug = paramsDebug.substr(0, paramsDebug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[FLASH MOVIE (settings)]: src=' + obj.configuration.src + ', div=' + 'inner-' + flashMoviesOnPage + '-swfobject' + ', width=' + obj.configuration.width + ', height=' + obj.configuration.height + ', flashvars={' + flashvarsDebug + '} params={' + paramsDebug + '}'); }

        if (obj.buildWoAControls) {
            //ensure mousewheel JavaScript library is dynamically loaded
            parliamentUK.pluginLoader({ 'pluginName': 'woaZoom' });

            //initialize mousewheel handler to ensure scrolling of page content doesn't occur whilst scrolling inside flash (artwork) swf
            $('.flash').mousewheel(function (event, delta) {
                return false;
            });

            $('<ul />').appendTo($(flashParent))
				.append($('<li />').attr({ 'id': 'pan-left' }).append($('<a />').html('Pan left').attr({ 'href': '#' })))
				.append($('<li />').attr({ 'id': 'pan-right' }).append($('<a />').html('Pan right').attr({ 'href': '#' })))
				.append($('<li />').attr({ 'id': 'pan-up' }).append($('<a />').html('Pan up').attr({ 'href': '#' })))
				.append($('<li />').attr({ 'id': 'pan-down' }).append($('<a />').html('Pan down').attr({ 'href': '#' })))
				.append($('<li />').attr({ 'id': 'zoom-in' }).append($('<a />').html('Zoom in').attr({ 'href': '#' })))
				.append($('<li />').attr({ 'id': 'zoom-out' }).append($('<a />').html('zoom-out').attr({ 'href': '#' })))

            $('#pan-left').bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('moveLeft'); return false; })
				.next().bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('moveRight'); return false; })
				.next().bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('moveUp'); return false; })
				.next().bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('moveDown'); return false; })
				.next().bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('zoomIn'); return false; })
				.next().bind('click', function () { $('#inner-' + flashMoviesOnPage + '-swfobject')[0].executeExternalCall('zoomOut'); return false; })

        }
    },

    //equalize grid columns to ensure grey tramlines run consistently to full page depth (three-wide template only)
    equalizeGrid: function () {
        //only equalize if the specific site has been configured to
        if (siteConfig.equalize[$('BODY').attr('class')].active) {
            if (debugLog) { parliamentUK.logEvent('[EQUALIZE GRID]: initialize'); }

            //ensure only the grid elements which exist are equalled
            var equalizeElements = '';
            if ($('#secondary-navigation').size() == 1) { equalizeElements += '#secondary-navigation,'; }
            if ($('#content-small').size() == 1) { equalizeElements += '#content-small,'; }
            if ($('#panel').size() == 1) { equalizeElements += '#panel,'; }
            equalizeElements = equalizeElements.substr(0, equalizeElements.length - 1);

            if ($(document.body).attr('id') != 'grid' && globalObj.pageType != 'education-education-home' && globalObj.pageType != 'main-start' && equalizeElements != '') {
                $(equalizeElements).equalHeight({ objectToAppend: $('#content-small'), height: siteConfig.equalize[$('BODY').attr('class')].offset });

                if (debugLog) { parliamentUK.logEvent('[EQUALIZE GRID]: #secondary-navigation (height=' + (isIe6 ? $('#secondary-navigation').height() : $('#secondary-navigation').css('minHeight')) + '), #content-small (height=' + (isIe6 ? $('#content-small').height() : $('#content-small').css('minHeight')) + '), #panel (height=' + (isIe6 ? $('#panel').height() : $('#panel').css('minHeight')) + ')'); }
            }
        }
    },

    //run a reset before initializing (tabs-specific)
    resetGrid: function () {
        if (debugLog) { parliamentUK.logEvent('[RESIZE GRID]: #secondary-navigation (height=' + (isIe6 ? $('#secondary-navigation').height() : $('#secondary-navigation').css('minHeight')) + '), #content-small (height=' + (isIe6 ? $('#content-small').height() : $('#content-small').css('minHeight')) + '), #panel (height=' + (isIe6 ? $('#content-small').height() : $('#content-small').css('minHeight')) + ')'); }

        $('#secondary-navigation').css(isIe6 ? { 'height': '1px'} : { 'min-height': '1px' });
        $('#content-small').css(isIe6 ? { 'height': '1px'} : { 'min-height': '1px' });
        $('#panel').css(isIe6 ? { 'height': '1px'} : { 'min-height': '1px' });

        parliamentUK.equalizeGrid();
    },

    //append an 'alternate' class for alternate elements	
    alternateHighlight: function (obj) {
        var debug = '';
        for (x in obj) { debug += x + '=' + obj[x] + ', '; }
        debug = debug.substr(0, debug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[ALTERNANTE HIGHLIGHT]: ' + debug); }

        $(obj.selector, $(obj.wrapper)).each(function (index) {          
            if (obj.initialShow != undefined) {
                if (index >= (obj.initialShow)) {
                    $(obj.siblingShowHideSelector, $(this)).css('display', 'none');
                    $(obj.selector, $(this)).css('display', 'none');
                }
            }

            //handle any exceptions here, such as sibling highlights/ignoring initial elements etc
            if (obj.ignoreInitial == undefined || (obj.ignoreInitial != undefined) && ((index) > obj.ignoreInitial)) {
                if (obj.siblingShowHideSelector != undefined) {
                    $(obj.siblingShowHideSelector, $(this)).addClass((index % 2 == 0) ? '' : 'alternate');
                }
                else {
                    $(this).addClass((index % 2 == 0) ? '' : 'alternate');
                }
            }
        });
    },

    //initialize all sliding toggle groups
    initToggleSlides: function (obj) {
        var debug = '';
        for (x in obj) { debug += x + '=' + obj[x] + ', '; }
        debug = debug.substr(0, debug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[INIT TOGGLE SLIDES]: ' + debug); }

        //before initalizing any animations, inject all relevant triggers
        switch (obj.reference) {
            case 'news-listing':
                $('<h4 />').insertAfter($('.thumbnail-image-list', $(obj.wrapper)))
					.append($('<a />').attr({ 'href': '#' })
							.append($('<img />').attr({ 'alt': '', 'src': '/assets/images/plus-blue.gif' }))
							.append($('<span />').html('View all'))
					);

                break;
            case 'toggle-before-news-listing':
                $('<h4 />').insertBefore($('.thumbnail-image-list', $(obj.wrapper)).prev())
					.append($('<a />').attr({ 'href': '#' })
							.append($('<img />').attr({ 'alt': '', 'src': '/assets/images/plus-blue.gif' }))
							.append($('<span />').html('View all'))
					);
                break;
        }

        obj.wrapper.each(function () {
            $(obj.trigger, $(this)).each(function () {
                //create and bind event handlers
                $('A', $(this)).bind('click', function () {
                    //recurse to the correct parent whilst at the correct scope level
                    switch (obj.reference) {
                        case '':
                            var toggleChild = '';
                            break;
                        default:
                            var toggleChild = $(this).parent().next();
                            break;
                    }

                    $(toggleChild).css('display') == 'block' ? $(toggleChild).slideUp(toggleConfig.slideTime, parliamentUK.completedToggle({ obj: this, reference: obj.reference })) : $(toggleChild).slideDown(toggleConfig.slideTime, parliamentUK.completedToggle({ obj: this, reference: obj.reference }));
                    return false;
                });

                $(this).next().css('display', 'none');
            });
        });
    },

    //onComplete trigger for completed toggle animation
    completedToggle: function (obj) {
        if (debugLog) { parliamentUK.logEvent('[COMPLETED TOGGLE]: ' + obj.obj + ', ' + obj.reference); }

        switch (obj.reference) {
            case 'news-listing':
                $('SPAN', $(obj.obj)).html($(obj.obj).parent().next().css('display') == 'block' ? 'View all' : 'Hide all');
                $('IMG', $(obj.obj)).attr('src', $(obj.obj).parent().next().css('display') == 'block' ? '/assets/images/plus-blue.gif' : '/assets/images/minus-blue.gif');
                break;
            case 'toggle-before-news-listing':
                $('SPAN', $(obj.obj)).html($(obj.obj).parent().prev().css('display') == 'block' ? 'View all' : 'Hide all');
                $('IMG', $(obj.obj)).attr('src', $(obj.obj).parent().prev().css('display') == 'block' ? '/assets/images/plus-blue.gif' : '/assets/images/minus-blue.gif');
                break;
            case 'education-sub-landing':
            case 'education-tabbed-content':
            case 'education-main-generic-content':
                obj.toggleMode == 'show' ? $(obj.obj).parent().addClass('expanded') : $(obj.obj).parent().removeClass('expanded');
                break;
        }
    },

    //initialize tab group(s)
    tabsInit: function (obj) {
        if ($('.tabs-wrapper.parent').length > 0) {
            parliamentUK.initTabGroups(obj);
        }
    },

    //manipulate the original code to be non-semantically ordered (for toggling purposes)
    initTabGroups: function (obj) {
        if (debugLog) { parliamentUK.logEvent('[TAB GROUP]: initialize'); }

        //run generic site functionality
        $('TABLE.alternate TR:odd TD').addClass('alternate');

        var runningOnHomepage = ($('#content').hasClass('homepage') ? true : false);
        var firstLevel = runningOnHomepage ? 1 : 2;
        var secondLevel = runningOnHomepage ? 2 : 3;
        var thirdLevel = runningOnHomepage ? 3 : 0;
        var firstLevelActiveClass = false;
        var firstLevelActiveIndex = 0;
        var secondLevelActiveClass = false;
        var secondLevelActiveIndex = 0;
        var thirdLevelActiveClass = false;
        var thirdLevelActiveIndex = 0;

        //for each identified tab group, manipulate the DOM to convert HTML markup into post DOM-ready structure
        $('.tabs-wrapper.parent').each(function (index) {
            $('<div />').attr({ 'id': 'tabs-container-' + (index + 1), 'class': 'tabs-wrapper tabs-injected' }).insertBefore($(this));

            //level 1 tabs
            $('<div />').attr({ 'class': 'triggers level-' + firstLevel }).appendTo($('#tabs-container-' + (index + 1)));
            $('<div />').attr({ 'class': 'inner level-' + firstLevel }).appendTo($('#tabs-container-' + (index + 1)));

            var parentWrapperId = '#tabs-container-' + (index + 1);

            $(this).children('H4').appendTo($('.triggers:eq(0)', $(parentWrapperId)));
            $(this).children('DIV').appendTo($('.inner:eq(0)', $(parentWrapperId)));

            $('.inner:eq(0)', $(parentWrapperId)).children('DIV').each(function (level1Index) {
                //check for active class index
                if ($(this).hasClass('active')) {
                    firstLevelActiveClass = true;
                    firstLevelActiveIndex = level1Index;
                }

                //level 2 tabs
                if ($('DIV.tabs-wrapper', $(this)).length > 0) {
                    var suffixListLevel1 = $('> .list-suffix', $(this));
                    var suffixListExistsLevel1 = $(suffixListLevel1).length > 0 ? true : false;
                    var positionInjectionLevel1 = suffixListExistsLevel1 ? 'injectBefore' : 'insertAfter';
                    var appendElementLevel1 = suffixListExistsLevel1 ? $('> .list-suffix', $(this)) : $(this);

                    switch (positionInjectionLevel1) {
                        case 'injectBefore':
                            $('<div />').attr({ 'class': 'triggers level-' + secondLevel }).insertBefore(appendElementLevel1);
                            break;
                        case 'insertAfter':
                            $('<div />').attr({ 'class': 'triggers level-' + secondLevel }).appendTo(appendElementLevel1);
                            break;
                    }

                    //clone headings
                    $('.tabs-wrapper:eq(0)', $(this)).children('H4').appendTo($('.triggers.level-' + secondLevel, $(this)));

                    $('<div />').attr({ 'class': 'inner level-' + secondLevel }).insertAfter($('.triggers.level-' + secondLevel, $(this)));

                    //clone content <div>s
                    $('.tabs-wrapper:eq(0)', $(this)).children('DIV').appendTo($('.inner:eq(0)', $(this)));

                    $('.level-' + secondLevel + '.inner', $(this)).children('DIV').each(function (level2Index) {
                        if ($(this).hasClass('active')) {
                            secondLevelActiveClass = true;
                            secondLevelActiveIndex = level2Index;
                        }
                    });

                    //ensure the first tab is selected for level 2 (if not active state was supplied)
                    if (!secondLevelActiveClass) { $('.level-' + secondLevel + '.inner', $(this)).children('DIV:eq(0)').addClass('active').parent().prev().children('H4:eq(0)').addClass('active'); }

                    //reset auto-selection states for tabs where an active state has not been pre-supplied in the markup
                    secondLevelActiveClass = false;
                    secondLevelActiveIndex = 0;

                    //level 3 tabs
                    $('.inner:eq(0)', $(this)).children('div').each(function (level3Index) {
                        if ($('DIV.tabs-wrapper', $(this)).length > 0) {
                            var suffixListLevel2 = $('> .list-suffix', $(this));
                            var suffixListExistsLevel2 = $(suffixListLevel2).length > 0 ? true : false;
                            var positionInjectionLevel2 = suffixListExistsLevel2 ? 'injectBefore' : 'insertAfter';
                            var appendElementLevel2 = suffixListExistsLevel2 ? $('> .list-suffix', $(this)) : $(this);

                            switch (positionInjectionLevel2) {
                                case 'injectBefore':
                                    $('<div />').attr({ 'class': 'triggers level-' + thirdLevel }).insertBefore(appendElementLevel2);
                                    break;
                                case 'insertAfter':
                                    $('<div />').attr({ 'class': 'triggers level-' + thirdLevel }).appendTo(appendElementLevel2);
                                    break;
                            }

                            //clone headings
                            $('.tabs-wrapper:eq(0)', $(this)).children('H4').appendTo($('.triggers:eq(0)', $(this)));

                            $('<div />').attr({ 'class': 'inner level-' + thirdLevel }).insertAfter($('.triggers.level-' + thirdLevel, $(this)));

                            //clone content <div>s
                            $('.tabs-wrapper:eq(0)', $(this)).children('DIV').appendTo($('.inner:eq(0)', $(this)));

                            $('.level-' + thirdLevel + '.inner', $(this)).children('DIV').each(function (level3Index) {
                                if ($(this).hasClass('active')) {
                                    thirdLevelActiveClass = true;
                                    thirdLevelActiveIndex = level3Index;
                                }
                            });

                            //ensure the first tab is selected for level 3 (if not active state was supplied)
                            if (!thirdLevelActiveClass) { $('.level-' + thirdLevel + '.inner', $(this)).children('DIV:eq(0)').addClass('active').parent().prev().children('H4:eq(0)').addClass('active'); }

                            //reset auto-selection states for tabs where an active state has not been pre-supplied in the markup
                            thirdLevelActiveClass = false;
                            thirdLevelActiveIndex = 0;
                        }
                    });
                }
            });

            //ensure the first tab is selected for level 1 (if not active state was supplied)
            if (!firstLevelActiveClass) { $('.level-' + firstLevel + '.inner', $(parentWrapperId)).children('DIV:eq(0)').addClass('active').parent().prev().children('H4:eq(0)').addClass('active'); }

            //reset auto-selection states for tabs where an active state has not been pre-supplied in the markup
            firstLevelActiveClass = false;
            firstLevelActiveIndex = 0;

            //assign last class to all last trigger elements, at levels 1, 2 and 3
            $('.triggers').each(function () {
                $('H4:last', $(this)).addClass('last');
            });

            //assign necesary event handlers and run initial toggle state
            var tabEventConfigObj = { tabsWrapper: $(parentWrapperId) };

            //add additional binding to tab triggers if running an education sub-site tabbed group
            if (typeof (obj) == 'object') {
                $.extend(tabEventConfigObj, obj);
            }

            parliamentUK.tabEventHandlers(tabEventConfigObj);
        }).remove();
    },

    //handle eventHandlers for toggle tab switching
    toggleTabs: function (tabsObj) {
        var debug = '';
        for (x in tabsObj) { debug += x + '=' + tabsObj[x] + ', '; }
        debug = debug.substr(0, debug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[TOGGLE TABS]: ' + debug); }

        //re-assign "active" class to the newly selected h4 tab heading		
        $('H4', tabsObj.triggerObj.parent().parent()).each(function (index) {
            $(this).toggleClass('active', tabsObj.toggleId == index);
        });

        //re-assign "display" types to the newly selected sub-tab content block
        tabsObj.triggerObj.parent().parent().next().children('DIV').each(function (index) {
            $(this).toggleClass('active', tabsObj.toggleId == index);

            if (tabsObj.toggleId == index) {
                // restore hidden silverlight elements
                $(this).find('.silverlight').each(function () {
                    $(this).append($(this).data('_sl'));
                    $(this).removeData('_sl');
                })
            }
            else {
                // remove any silverlight elements from dom when hidden to avoid playing in background
                $(this).find('.silverlight').each(function () {
                    if ($(this).children().length && !$(this).data('_sl')) {
                        $(this).data('_sl', $(this).children()).empty();
                    }
                })
            }
        });
    },

    tabEventHandlers: function (tabsObj) {
        var debug = '';
        for (x in tabsObj) { debug += x + '=' + tabsObj[x] + ', '; }
        debug = debug.substr(0, debug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[TAB EVENT HANDLERS]: ' + debug); }

        //initialize all nevessary eventHandlers for tab headings (irrespective of tab depth
        $('.triggers', tabsObj.tabsWrapper).each(function () {
            $('H4 A', $(this)).each(function (index) {
                $(this).bind('click', function (e) {
                    e.preventDefault();
                    parliamentUK.toggleTabs({ toggleId: index, triggerObj: $(this) });

                    //reset and re-initialize page grid after each tab toggle
                    parliamentUK.resetGrid();

                    //add additional binding to tab triggers if running an education sub-site tabbed group
                    if (tabsObj.bindImageWraparound) {
                        //handle left floated images, in order to force the widths of the floated <div>s
                        parliamentUK.floatedImageWrapInit({ floatWrapperClass: '.left', wrapperObj: $(this).parent().next() });
                    }
                    return false;
                });
            });
        });
    },

    //handle events sent out from Flash movies
    //TODO:
    //	- subtitles (identify between subtitles-on and subtitles-off)
    flashTracking: function (playerID, playerType, eventType, params) {
        switch (eventType) {
            case 'play':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID: ' + playerID + ', playerType:' + playerType); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'play', playerID); }

                break;
            case 'pause':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID: ' + playerID + ', playerType: ' + playerType); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'pause', playerID); }

                break;
            case 'subtitles on':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType); }

                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'subtitles (on)', playerID); }
                break;
            case 'subtitles off':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'subtitles (off)', playerID); }

                break;
            case 'fullscreen':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'fullscreen', playerID); }

                break;
            case 'duration':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType + ', position=' + params.position); }

                if (!flashTrackingProgress.viewed1To25Percent) {
                    flashTrackingProgress.viewed1To25Percent = true;
                    if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: 1% - 25% (event sent to external tracking provider)'); }
                    if (tracking.enabled) { pageTracker._trackEvent(playerType, 'duration (1% - 25%)', playerID); }
                }
                if (params.position >= 26 && params.position <= 50 && !flashTrackingProgress.viewed26To50Percent) {
                    flashTrackingProgress.viewed26To50Percent = true;
                    if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: 26% - 50% (event sent to external tracking provider)'); }
                    if (tracking.enabled) { pageTracker._trackEvent(playerType, 'duration (26% - 50%)', playerID); }
                }
                if (params.position >= 51 && params.position <= 75 && !flashTrackingProgress.viewed51To75Percent) {
                    flashTrackingProgress.viewed51To75Percent = true;
                    if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: 51% - 75% (event sent to external tracking provider)'); }
                    if (tracking.enabled) { pageTracker._trackEvent(playerType, 'duration (51% - 75%)', playerID); }
                }
                if (params.position >= 76 && params.position <= 100 && !flashTrackingProgress.viewed76To100Percent) {
                    flashTrackingProgress.viewed76To100Percent = true;
                    if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: 76% - 100% (event sent to external tracking provider)'); }
                    if (tracking.enabled) { pageTracker._trackEvent(playerType, 'duration (76% - 100%)', playerID); }
                }

                break;
            case 'quality':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType + ', quality=' + params.quality); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'quality (' + params.quality + ')', playerID); }

                flashTrackingProgress.viewed1To25Percent = false;
                flashTrackingProgress.viewed26To50Percent = false;
                flashTrackingProgress.viewed51To75Percent = false;
                flashTrackingProgress.viewed76To100Percent = false;

                break;
            case 'info':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'info', playerID); }

                break;
            case 'volume':
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ', playerID=' + playerID + ', playerType=' + playerType + ', volume=' + params.volume); }
                if (tracking.enabled) { pageTracker._trackEvent(playerType, 'volume (' + params.volume + ')', playerID); }

                break;
            default:
                if (debugLog) { parliamentUK.logEvent('[FLASH TRACKING]: Event type=' + eventType + ' not recognised'); }
                break;
        }
    },

    //handle left floated images, in order to force the widths of the floated <div>s
    floatedImageWrapInit: function (obj) {
        //if obj.wrapperObj has been passed, this is specific to filtering a <div> content block within a toggled tab (primarily Education sub-site)
        var wrapperToFix = $(obj.floatWrapperClass);
        if (obj.wrapperObj == 'object') {
            wrapperToFix = $(obj.floatWrapperClass, $(obj.wrapperObj));
        }

        if (isIe6 || isIe7) {
            $(wrapperToFix).each(function () {
                var currentFloat = $(this);

                //set left floated width dimension
                var embeddedImage = $('IMG', $(this));

                if ($(embeddedImage).size() == 1) {
                    $(this).css('width', $(embeddedImage).width());
                }

                //update the parent anchor tag
                var parentAnchor = $(this).parent().is('A');
                if (parentAnchor) {
                    $(embeddedImage)
						.css({ 'cursor': 'pointer' })
						.bind('click', function () {
						    top.location.href = $(currentFloat).parent().attr('href');
						});
                }
            });
        }
    },

    toggleElementsWithShowAll: function (obj) {
        $('ul.square-bullets').each(function () {
            var liItems = $(this);
            if (liItems.children('li').length > 3) {
                liItems.children('li:gt(2)').hide();
                liItems.after('<div id=\'showButton\'><img src=\'/assets/images/plus-blue.gif\' class=\'imgClass\' /> <a href="javascript:void(0)" class="showhideul" id="hlShowMoreLess">Show all...</a></div>');
                liItems.addClass('hasshowhide'); // new class
            }
            else if (liItems.children('li').length == 2) {
                liItems.after('<div id=\'showButton\'>&nbsp;</div>');
                liItems.after('<div id=\'showButton\'>&nbsp;</div>');
            }
            else {
                liItems.after('<div id=\'showButton\'>&nbsp;</div>');
            }
        });

        $('.showhideul').click(function (e) {
            //e.preventDefault(); alert("dfdf");
            var liItemInWord = $(this);
            //hide/show items
            liItemInWord.prev().parent().prev().children('li:gt(2)').toggle(); //.slideToggle();  //.stop(true,true).slideToggle();  //'li:hidden:lt(3)'
            //$('#showAllClass').prev().prev().children('li:gt(2)').toggle();
            if (liItemInWord.prev().parent().prev().children('li:hidden').length == 0) {
                // text and image should be show more
                liItemInWord.text('Show less...');
                liItemInWord.prev().attr('src', '/assets/images/minus-blue.gif');
            } else {
                // text and image should be show less
                liItemInWord.text('Show all...').prev().attr('src', '/assets/images/plus-blue.gif');
            }
            //also need to add different image "minus  sign(-)"
            $('ul.hasshowhide').not(liItemInWord.prev().parent().prev()).each(function () { // md line
                var liClickedItem = $(this);
                liClickedItem.next().children().attr('src', '/assets/images/plus-blue.gif').next().text('Show all...');
                liClickedItem.children('li:gt(2)').slideUp(); //hide();
            });

            return false;
        });
    },

    //equalize heights for all 'highlights-images' modules
    highlightImageEqualize: function (obj) {
        debugLog = true;
        if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE]: init()'); }

        var layoutMode;
        var negativeOffset = 0;

        $(obj.wrapper).each(function (groupIndex) {
            switch (obj.pageType) {
                case 'main-gallery-artwork-listing':
                    layoutMode = 3;
                    negativeOffset = -10;
                    break;
                case 'woa-start':
                    layoutMode = 2;
                    negativeOffset = -20;
                    break;
                case 'woa-collection-highlights':
                    layoutMode = 4;
                    break;
                case 'woa-compare-contrast-detail':
                    layoutMode = 2;
                    negativeOffset = -20;
                    break;
                case 'imagegallery-gallery-set':
                    layoutMode = 4;
                    break;
                case 'imagegallery-gallery-sub-set':
                    layoutMode = 4;
                    negativeOffset = -20;
                    break;
            }

            var equalHeightObj = '';
            var elementRowPosition = 1;
            var totalElements = $(obj.iterator, $(this)).size();
            var completeRows = Math.floor(totalElements / layoutMode);
            var totalRows = Math.ceil(totalElements / layoutMode);

            if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE (equalizeObj)]: ' + obj.equalizeObj); }
            if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE (pageType)]: ' + obj.pageType); }
            if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE (totalElements)]: ' + totalElements); }
            if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE (completeRows)]: ' + completeRows); }
            if (debugLog) { parliamentUK.logEvent('[HIGHLIGHT IMAGE EQUALIZE (totalRows)]: ' + totalRows); }

            $(obj.iterator, $(this)).each(function (elementIndex) {
                //position image vertically aligned to the centre for all landscape thumbnails
                var thumbnailImage = $('IMG', $(this));
                var landscapeOrientation = ($(thumbnailImage).height() < +$(thumbnailImage).width()) ? true : false;

                if (landscapeOrientation && layoutMode != 2) {
                    thumbnailImage.css({ 'paddingTop': ((140 - $(thumbnailImage).height()) / 2) });
                }

                var activeElement = obj.wrapper + ':eq(' + groupIndex + ') ' + obj.iterator + ':eq(' + elementIndex + ') ' + obj.equalizeObj
                equalHeightObj += activeElement + ',';

                if ((elementIndex + 1) % layoutMode == 0) {
                    equalHeightObj = equalHeightObj.substr(0, equalHeightObj.length - 1);

                    $(equalHeightObj).equalHeight({ objectToAppend: $(equalHeightObj), height: negativeOffset });

                    equalHeightObj = '';
                    elementRowPosition++;
                }
                else if ((elementIndex + 1) == totalElements) {
                    $(equalHeightObj).equalHeight({ objectToAppend: $(equalHeightObj), height: negativeOffset });

                    equalHeightObj = '';
                }
            });
        });
    },

    //dynamic DOM element creation
    createElement: function (obj) {
        //obj.type
        //obj.id
        //obj.className
        //obj.appendTo
        //obj.innerHTML
        //obj.other
        //obj.insertMode
        //parliamentUK.createElement({type:'',id:'',className:'',appendTo:'',innerHTML:'',other:'',insertMode:''});	

        var debug = '';
        for (x in obj) { debug += x + '=' + obj[x] + ', '; }
        debug = debug.substr(0, debug.length - 2);

        if (debugLog) { parliamentUK.logEvent('[CREATE ELEMENT]: ' + debug); }

        //due to IE6 not supporting DOM manipulation for CSS files at runtime, use native Javascript code to append to the document head
        if (isIe && obj.type == 'LINK') {
            var objCSS = document.createElement('link');
            objCSS.type = 'text/css';
            objCSS.href = obj.other.href;
            objCSS.rel = 'stylesheet';
            objCSS.media = 'screen';
            document.getElementsByTagName('HEAD')[0].appendChild(objCSS);

            return;
        }

        $newDOMElement = $('<' + obj.type + '>');
        if (obj.id != undefined) { $newDOMElement.attr('id', obj.id); }
        if (obj.className != undefined) { $newDOMElement.attr('class', obj.className); }
        if (obj.innerHTML != undefined) { $newDOMElement.html(obj.innerHTML); }

        //loop through additional properties of object for dynamically adding via dot notation
        if (obj.other != undefined) {
            if (typeof (obj.other) == "object") {
                for (property in obj.other) {
                    $newDOMElement.attr(property, obj.other[property]);
                }
            }
        }

        switch (obj.insertMode) {
            case "insertAfter":
                $(obj.appendTo).append($newDOMElement);
                break;
            case "injectBefore":
                $newDOMElement.insertBefore($(obj.appendTo));
                break;
            case "injectAfter":
                $newDOMElement.insertAfter($(obj.appendTo));
                break;
            case "insertBefore":
                $(obj.appendTo).prepend($newDOMElement);
                break;
        }
    },

    //global mechanism for tracking events to the console	
    logEvent: function (event) {
        if (window.console && window.console.log) {
            console.log(event);
        }
    },

    //required browser sniffer for XmlHttp() Rss retrieval
    browserSniffer: function () {
        agent = navigator.userAgent.toLowerCase();
        isMajor = parseInt(navigator.appVersion);

        isIe = (agent.indexOf('msie') != -1);
        isIe6 = (isIe && (isMajor == 4) && agent.indexOf("msie 6.") != -1);
        isIe7 = (isIe && (isMajor == 4) && agent.indexOf("msie 7.") != -1);
        isIe8 = (isIe && (isMajor == 4) && agent.indexOf("msie 8.") != -1);
        isFirefox = ((agent.indexOf('firefox') != -1));
        isOpera = ((agent.indexOf('opera') != -1));
        isWindows = ((agent.indexOf('win') != -1) || (agent.indexOf('16bit') != -1));

        if (debugLog) { parliamentUK.logEvent('[BROWSER DETAILS]: agent=' + agent + ', IE=' + isIe + ', IE6=' + isIe6 + ', IE7=' + isIe7 + ', IE8=' + isIe8 + ', Firefox=' + isFirefox, Opera = ' + isOpera'); }
    },

    //.net keyboard enter key functionality for submission of multiple forms
    WebFormFireDefaultButton: function (event, target) {
        if (!defaultButtonFired && event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase() == "textarea"))) {
            var defaultButton = $('#' + target);

            if (defaultButton && typeof (defaultButton.click) != 'undefined') {
                defaultButtonFired = true;
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
        return true;
    },

    //adds tooltip toggling functionality to the page
    TooltipToggle: function (obj) {
        //get current context
        var options = {
            obj: null,
            currentOffset: null,
            parentOffset: null,
            currentTooltip: null
        };

        $(obj).each(function (i) {
            //get unique object data to pass to events
            options.obj = $(obj[i]);
            options.currentOffset = options.obj.offset();
            options.parentOffset = options.obj.offsetParent().offset();
            //add close button to tooltipInfo box
            options.currentTooltip = options.obj.parent().find('.tooltipInfo');

            var closeButton = $('<a />')
						                .addClass('close')
						                .attr('href', '#')
						                .attr('tabindex', '-1')
						                .html('Close')
				                        .bind('click.closeTooltip', {
				                            obj: options.currentTooltip
				                        },
				                            function (triggerEvent) {
				                                triggerEvent.preventDefault();
				                                triggerEvent.stopPropagation();
				                                var options = {
				                                    obj: triggerEvent.data.obj
				                                };
				                                $(options.obj).css({ 'left': '-9999em', 'top': '0' }).removeClass('displayed');
				                            }
				                        );
            options.currentTooltip.wrapInner('<div class="inner" />').prepend(closeButton);

            //bind click & focus events passing through unique object data
            options.obj.bind('focus.TooltipToggle click.TooltipToggle', {
                obj: options.obj,
                objOffset: options.currentOffset,
                objParentOffset: options.parentOffset,
                objTooltip: options.currentTooltip
            }, function (triggerEvent) {
                triggerEvent.preventDefault();
                triggerEvent.stopPropagation();
                var options = {
                    obj: triggerEvent.data.obj,
                    objOffset: triggerEvent.data.objOffset,
                    objParentOffset: triggerEvent.data.objParentOffset,
                    objTooltip: triggerEvent.data.objTooltip
                }
					                        ;
                if (!options.objTooltip.hasClass('displayed')) {
                    //close any other open tooltips before showing current one
                    $('.displayed').css({ 'left': '-9999em', 'top': '0' }).removeClass('displayed');
                    //get positioning using current context before showing tooltip 
                    var tooltipPosX, tooltipPosY; //currentOffset, parentOffset;
                    tooltipPosX = options.objOffset.left - options.objParentOffset.left + options.obj.outerWidth();
                    tooltipPosY = options.objOffset.top - options.objParentOffset.top - options.objTooltip.height() / 2;
                    options.objTooltip.css({
                        'display': 'none',
                        'left': tooltipPosX,
                        'top': tooltipPosY
                    }).fadeIn(300, "linear").addClass('displayed');
                    //highlight current field
                    //first remove active class from all other fields
                    $('.inputFieldContainer').removeClass('active');
                    //then apply active class to specific field
                    options.obj.parent('.inputFieldContainer').addClass('active');
                }
                //$(options.objTooltip).focus(); //set focus to tooltip
                return false;
            });
        });
    }
};

//handle page specific init() on a site AND page-by-page basis for any non-global init() routines
parliamentUK.page = {
    //obj.site == '' OR 'committees' OR 'mlo' OR 'woa'
    //obj.pageId
    init: function (obj) {
        //run an global site functionality
        //add alternate row colouring for <table>s within the inquiries module (committees landing page)
        parliamentUK.alternateHighlight({ wrapper: '.rte TBODY', selector: 'TR', siblingShowHideSelector: 'TD' });

        switch (obj.site) {
            //Committees site: page specific init()                
            case 'committees':
                switch (obj.pageType) {
                    case 'committee-landing':
                        //add alternate row colouring for <table>s within the inquiries module (committees landing page)
                        parliamentUK.alternateHighlight({ wrapper: '.inquiries-a-to-z TBODY', selector: 'TR', siblingShowHideSelector: 'TD' });

                        //initialize tab group(s)
                        parliamentUK.tabsInit();

                        break;
                    case 'committees-previous-inquiry':
                        //create alternate row colouring for "previous enquiry" table
                        parliamentUK.alternateHighlight({ wrapper: 'TABLE.publications-records TBODY', selector: 'TR', siblingShowHideSelector: 'TD' });

                        break;
                    case 'committee-inquiry-detail':
                        //initialize all sliding toggle groups
                        parliamentUK.initToggleSlides({ wrapper: $('.toggle-before-news-listing.toggle'), trigger: 'H4', reference: 'toggle-before-news-listing' });

                        //create toggle triggers for 'What's on' events <table>                        
                        var hdnEventsToShow = $("input[id$='_hdnNumberOfEventsToDisplay']");
                        var numberEventsToShow = parseInt(hdnEventsToShow.val());
                        parliamentUK.committees.whatsOnEventsTriggerInit(numberEventsToShow);

                        //create toggle triggers for News listing on Committee Inquiry pages
                        var hdnNewsEventsToShow = $("input[id$='_hdnNumberOfNewsItemsToDisplay']");
                        var numberNewsEventsToShow = parseInt(hdnNewsEventsToShow.val());


                        parliamentUK.committees.newsListingTriggerInit(numberNewsEventsToShow);
                        //create alternate row colouring as well as toggling event handlers for 'Publications and records' <table>
                        parliamentUK.committees.publicationsAndRecordsInit(obj.main.publicationsAndRecordsInitialShow);

                        //create toggle triggers for 'Publications and Records' events <table>
                        parliamentUK.committees.publicationsAndRecordsTriggerInit(3);

                        //create toggle triggers for 'News' events <table>
                        parliamentUK.committees.newsTriggerInit(1);
                        break;

                    case 'committee-other-committee-work-detail':
                        //initialize all sliding toggle groups
                        parliamentUK.initToggleSlides({ wrapper: $('.toggle-before-news-listing.toggle'), trigger: 'H4', reference: 'toggle-before-news-listing' });

                        //create toggle triggers for 'What's on' events <table>                        
                        var hdnEventsToShow = $("input[id$='_hdnNumberOfEventsToDisplay']");
                        var numberEventsToShow = parseInt(hdnEventsToShow.val());
                        parliamentUK.committees.whatsOnEventsTriggerInit(numberEventsToShow);

                        //create toggle triggers for News listing on Committee Inquiry pages
                        var hdnNewsEventsToShow = $("input[id$='_hdnNumberOfNewsItemsToDisplay']");
                        var numberNewsEventsToShow = parseInt(hdnNewsEventsToShow.val());                      

                        parliamentUK.committees.newsListingTriggerInit(numberNewsEventsToShow);
                        //create alternate row colouring as well as toggling event handlers for 'Publications and records' <table>
                        parliamentUK.committees.publicationsAndRecordsInit(obj.main.publicationsAndRecordsInitialShow);

                        //create toggle triggers for 'Publications and Records' events <table>
                        parliamentUK.committees.publicationsAndRecordsTriggerInit(3);

                        //create toggle triggers for 'News' events <table>
                        parliamentUK.committees.newsTriggerInit(1);
                        break;

                    case 'committee-detail':
                        //initialize all sliding toggle groups
                        parliamentUK.initToggleSlides({ wrapper: $('.news-listing.toggle'), trigger: 'H4', reference: 'news-listing' });

                        //create toggle triggers for 'What's on' events <table>                        
                        var hdnEventsToShow = $("input[id$='_hdnNumberOfEventsToDisplay']");
                        var numberEventsToShow = parseInt(hdnEventsToShow.val());
                        parliamentUK.committees.whatsOnEventsTriggerInit(numberEventsToShow);
                        parliamentUK.committees.committeesTriggerInit();

                        //create alternate row colouring as well as toggling event handlers for 'Publications and records' <table>
                        parliamentUK.committees.publicationsAndRecordsInit(obj.main.publicationsAndRecordsInitialShow);

                        break;
                }
                break;
            //MLO site: page specific init()                
            case 'mlo':
                switch (obj.pageType) {
                    case 'mlo-members-filter-listing':
                    case 'complete-ssi-template':
                        //add alternate	row colouring for all <table>s within members filter list (results page)
                        $('#members-filter-listing TBODY').each(function () {
                            parliamentUK.alternateHighlight({ wrapper: $(this), selector: 'TR', siblingShowHideSelector: 'TD' });
                        });
                        break;
                }
                break;
            //EDM site: page specific init()                           
            case 'edm':
                var currentObjAjaxUrl = obj.main.edmMembersAjaxUrl;
                switch (obj.pageType) {
                    case 'edm-detail':
                    case 'edm-filter-listing':
                    case 'edm-number-listings':
                        //add alternate	row colouring for all <table>s within members filter list (results page)
                        parliamentUK.TooltipToggle($('a.tooltip', $('#edm-filter-listing')));
                        parliamentUK.EDM.init();
                        break;
                    default:
                        parliamentUK.TooltipToggle($('a.tooltip', $('#edm-filter-listing')));
                        parliamentUK.pluginLoader({ 'pluginName': 'advancedSearchMembers' });
                        //add autofill functionality when "member" category is selected 
                        //please read http://stackoverflow[dot]com/questions/208471/getting-jquery-to-recognise-change-in-ie
                        $('.searchKeyword').bind('focus.autoFill',
                                        { objAjaxUrl: currentObjAjaxUrl }
                                        , function (triggerEvent) {
                                            //triggerEvent.preventDefault();
                                            if ($('.search-category').val() == "1") { //edm member search
                                                $('.searchKeyword').autocomplete(
                                                        triggerEvent.data.objAjaxUrl,
										                {
										                    autoFill: advancedSearchConfig.autoFill,
										                    max: advancedSearchConfig.max,
										                    scroll: advancedSearchConfig.scroll,
										                    scrollHeight: advancedSearchConfig.scrollHeight,
										                    delay: advancedSearchConfig.delayTime,
										                    width: advancedSearchConfig.width,
										                    parse: $.parseMemberSearchXML,
										                    formatItem: function (data) {
										                        return data.text;
										                    }
										                }
									                ).result(function (event, data) {
									                    //write the member id value to a hidden .net control
									                    //with the class of "cloneSelectedMemberId"
									                    //for backend to load information from webservice using 
									                    //the member's unique id
									                    //try catch created for ie6 which needs a timeout to update the selected
									                    //drop-down (http://csharperimage[dot]jeremylikness.com/2009/05/jquery-ie6-and-could-not-set-selected.html)
									                    try {
									                        $('.cloneSelectedMemberId').val(data.value);
									                    }
									                    catch (ex) {
									                        setTimeout("$('.cloneSelectedMemberId').val('" + data.value + "')", 200);
									                    }
									                });


                                            } else {
                                                //disable the autocomplete event handlers 
                                                $('.searchKeyword').unautocomplete();
                                                // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
                                                $('.searchKeyword').unbind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete");
                                            };
                                        }
                                    );
                        parliamentUK.EDM.init();
                        break;
                }
                break;
            //WoA site: page specific init()                
            case 'woa':
                //re-define page heading depths
                var pageHeading = $('#page-heading');
                if ($(pageHeading).length == 1) {
                    var additionalSpacing = $('H1', $(pageHeading)).height() > $('FIELDSET', $(pageHeading)).height() ? 0 : 10;
                    $(pageHeading).css('height', ($('H1', $(pageHeading)).height() + additionalSpacing) + 'px');
                }

                switch (obj.pageType) {
                    case 'woa-start':
                        //fire this event on window load rather than DOM ready as images need to exist and be downloaded before calculating offsets
                        $(window).load(function () {
                            parliamentUK.highlightImageEqualize({ wrapper: '.highlights-images', iterator: 'P', pageType: 'woa-start', equalizeObj: 'EM A' });
                        });

                        break;
                    case 'woa-image-unpack':
                        //assign event handlers to trigger points for all 'in-the-picture' pages						
                        parliamentUK.woa.inThePictureInit();

                        break;
                    case 'woa-email-a-friend':
                        //add alternate row colouring for <li>s within the 'Send a Friend' page
                        parliamentUK.alternateHighlight({ wrapper: '#send-a-friend FIELDSET:eq(0) OL', selector: 'LI' });
                        parliamentUK.alternateHighlight({ wrapper: '#send-a-friend FIELDSET:eq(1) OL', selector: 'LI' });

                        break;
                    case 'woa-compare-contrast-detail':
                        //fire this event on window load rather than DOM ready as images need to exist and be downloaded before calculating offsets
                        $(window).load(function () {
                            parliamentUK.highlightImageEqualize({ wrapper: '.highlights-images', iterator: 'P', pageType: 'woa-compare-contrast-detail', equalizeObj: 'EM' });
                        });

                        break;
                    case 'woa-search-listings':
                        parliamentUK.alternateHighlight({ wrapper: $('#search-results UL:first'), selector: '>LI' });

                        break;
                    case 'woa-collection-highlights':
                        //fire this event on window load rather than DOM ready as images need to exist and be downloaded before calculating offsets
                        $(window).load(function () {
                            parliamentUK.highlightImageEqualize({ wrapper: '.highlights-images', iterator: 'P', pageType: 'woa-collection-highlights', equalizeObj: 'EM A' });
                        });

                        break;
                    case 'woa-artwork':
                        //remove 'zoom' option from markup as JavaScript will handle the zooming feature
                        if ($('#artwork-options LI#zoom').size() == 1) {
                            $('#artwork-options LI#zoom').remove();
                        }

                        //add alternate row colouring for artwork overview table rows
                        parliamentUK.alternateHighlight({ wrapper: $('.alternate-rows'), selector: '>LI' });

                        break;
                    case 'woa-advanced-search':
                        parliamentUK.alternateHighlight({ wrapper: $('#advanced-search OL'), selector: '>LI' });

                        //initialize advanced search form
                        parliamentUK.woa.advancedSearchInit();

                        break;
                }

                break;
            case 'popvox':
                //create and assign event handlers for theme switcher
                $('#theme-switcher #default').unbind('click').bind('click', function () { $('#wrapper').attr('class', ''); return false; });
                $('#theme-switcher #green').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'green'); return false; });
                $('#theme-switcher #orange').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'orange'); return false; });
                $('#theme-switcher #pink').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'pink'); return false; });

                switch (obj.pageType) {
                    case 'popvox-generic-content':
                        //initialize 'more/less' toggle elements (in panel)
                        parliamentUK.popvox.panelToggleInit();

                        break;
                }

                break;

            case 'education':
                //create and assign event handlers for theme switcher
                $('#theme-switcher #default').unbind('click').bind('click', function () { $('#wrapper').attr('class', ''); return false; });
                $('#theme-switcher #green').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'green'); return false; });
                $('#theme-switcher #orange').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'orange'); return false; });
                $('#theme-switcher #pink').unbind('click').bind('click', function () { $('#wrapper').attr('class', 'pink'); return false; });

                switch (obj.pageType) {
                    case 'education-education-home':
                        //equalize the heights of the homepage secondary navigation groups
                        $('#secondary-navigation UL').equalHeight({ objectToAppend: $('#secondary-navigation UL'), height: -50 });
                        $('#secondary-navigation UL H4').equalHeight({ objectToAppend: $('#secondary-navigation UL H4'), height: -20 });

                        break;
                    case 'education-picture-viewer':
                        //load in the required JavaScript plugin for the image viewer
                        parliamentUK.pluginLoader({ 'pluginName': 'woaPictureViewer' });

                        //run init for image viewer, creating all animation
                        $('#picture-viewer').imageViewer({ slideTime: educationPictureViewerConfig.slideTime });

                        break;
                    case 'education-sub-landing':
                    case 'education-tabbed-content':
                    case 'education-tabbed-content-item':
                        if (obj.pageType == 'education-tabbed-content' || obj.pageType == 'education-tabbed-content-item') {
                            //initialize tab group(s)
                            parliamentUK.tabsInit({ bindImageWraparound: true });
                        }

                        //handle left floated images, in order to force the widths of the floated <div>s
                        parliamentUK.floatedImageWrapInit({ floatWrapperClass: '.left' });

                        //initialize resource toggle groups (inside and outside of tab groups)
                        $.extend(obj, { 'trigger': '.resource H3 A', 'reference': obj.pageType });

                        parliamentUK.education.resourceToggleInit(obj);

                        //initialize Shadowbox/Lightbox functionality for interactive layer "popups"
                        parliamentUK.pluginLoader({ 'pluginName': 'shadowbox' });

                        //launch education popup
                        $('a[rel=external].launch').each(function () {
                            $(this).attr({ target: 'blank', alt: 'Opens in a new window' }).click(function () {
                                window.open(this.href, 'newWindow', 'fullscreen=no,location=no,resizable=no,status=no,scrollbars=no,toolbar=no,directories=no,menubar=no,width=840,height=680');
                                return false;
                            });
                        });

                        break;
                    case 'main-generic-content':
                        //handle left floated images, in order to force the widths of the floated <div>s
                        parliamentUK.floatedImageWrapInit({ floatWrapperClass: '.left' });

                        //initialize resource toggle groups (inside and outside of tab groups)
                        $.extend(obj, { 'trigger': '.toggle A', 'reference': 'education-' + obj.pageType });

                        parliamentUK.education.resourceToggleInit(obj);

                        break;
                }
                break;
            case 'briefingPapers':
                //add js functionality specific page types

                switch (obj.pageType) {
                    case 'landing':
                        parliamentUK.briefingPapers.activateAccordions($('.accordianParentContainer .accordianParent'));
                        break;
                    case 'bp-listing':
                        parliamentUK.TooltipToggle($('a.tooltip', $('#listings')));
                        parliamentUK.briefingPapers.init();
                        break;
                }
                break;
            case 'cpa':
                //add js functionality specific page types

                switch (obj.pageType) {
                    case 'conference':
                        parliamentUK.TooltipToggle($('a.tooltip', $('.conferenceForm')));
                        parliamentUK.CPA.init();
                        break;
                }
                break;
            case 'rollinghansard':
                //add js functionality specific page types
                parliamentUK.ROLLINGHANSARD.init();
                /* switch (obj.pageType) {
                case 'landing':
                // parliamentUK.ROLLINGHANSARD.init();
                break;
                    
                }*/
                break;
            default:
                switch (obj.pageType) {
                    case 'main-start':
                    case 'lords-media-notices-listing':
                        //initialize tab group(s)
                        parliamentUK.tabsInit();

                        break;
                    case 'main-gallery-artwork':
                        //add alternate row colouring for gallery details
                        parliamentUK.alternateHighlight({ wrapper: $('.alternate-rows'), selector: '>LI' });

                        if ($('#artwork-transcript').size() == 1) {
                            //initialize Shadowbox/Lightbox functionality for interactive layer "popups"
                            parliamentUK.pluginLoader({ 'pluginName': 'shadowbox', 'shadowboxCallee': 'main-gallery-artwork' });

                            $('#artwork-options LI#transcript A').bind('click', function () {
                                Shadowbox.open({
                                    content: $('#artwork-transcript DIV').html(),
                                    height: 300,
                                    player: 'html',
                                    title: 'Transcript',
                                    width: 500
                                });

                                return false;
                            });
                        }

                        break;
                    case 'main-gallery-artwork-listing':
                        //fire this event on window load rather than DOM ready as images need to exist and be downloaded before calculating offsets
                        $(window).load(function () {
                            parliamentUK.highlightImageEqualize({ wrapper: '.collections-thumbnails', iterator: 'LI', pageType: 'main-gallery-artwork-listing', equalizeObj: 'P' });
                        });

                        break;
                    case 'main-news-landing':
                    case 'main-news-topic':
                        //add alternate row colouring for <table>s within the 'News Topic' page (which uses the news-listing uid)
                        parliamentUK.alternateHighlight({ wrapper: $('#news-landing TABLE TBODY'), selector: 'TR', siblingShowHideSelector: 'TD' });

                        break;
                    case 'main-publications-calendar-listing':
                        //initialize events calendars
                        parliamentUK.main.calendarInit({ ajaxUrl: obj.main.calendarListingAjaxUrl, pageInstanceId: obj.pageInstanceId });

                        //despite asynchronous setings, IE6 requires a grid reset once the calendar has been initialized
                        if (isIe6) { setTimeout("parliamentUK.resetGrid()", 1); }

                        break;
                    case 'main-send-a-friend':
                        //add alternate row colouring for <li>s within the 'Send a Friend' page
                        parliamentUK.alternateHighlight({ wrapper: '#send-a-friend FIELDSET:eq(0) OL', selector: 'LI' });
                        parliamentUK.alternateHighlight({ wrapper: '#send-a-friend FIELDSET:eq(1) OL', selector: 'LI' });

                        break;
                    case 'main-advanced-search':
                    case 'main-search-results':
                        //initialize advanced search form
                        parliamentUK.main.advancedSearchInit(obj);

                        break;
                    case 'main-landing-advanced':
                    case 'mainmodule-whats-on-calendar':
                    case 'mainmodule-calendar-feed-set':
                    case 'mainmodule-calendar-feed':
                        //initialize tab group(s)
                        parliamentUK.tabsInit();

                        break;
                    case 'main-generic-content':
                        //handle left floated images, in order to force the widths of the floated <div>s
                        parliamentUK.floatedImageWrapInit({ floatWrapperClass: '.left' });

                        break;
                    case 'main-topical-issues-landing':
                        parliamentUK.toggleElementsWithShowAll();

                        break;
                    case 'complete-rte':
                        //handle left floated images, in order to force the widths of the floated <div>s
                        parliamentUK.floatedImageWrapInit({ floatWrapperClass: '.left' });

                        break;
                    case 'imagegallery-gallery-set':
                        parliamentUK.highlightImageEqualize({ wrapper: '#content-small .inner UL', iterator: 'LI', pageType: obj.pageType, equalizeObj: 'H4 A' });

                        break;
                    case 'imagegallery-gallery-sub-set':
                        //create 'View slideshow' trigger within secondary navigation since JavaScript is available
                        /*$('<ul />').attr('class','slideshow overlay')
                        .append(
                        $('<li />')
                        .append(
                        $('<a />').attr({'class':'view ' + $('#secondary-navigation DIV:first').attr('class'),href:'#'}).html('View slideshow')
                        )
                        )
                        .appendTo($('#secondary-navigation DIV:first'));
                        */
                        //get aspx control, wrap in .slideshow and .overlay class						
                        //$('#secondary-navigation DIV:first a').addClass('view'); //temporary
                        $('#secondary-navigation DIV:first a').addClass($('#secondary-navigation DIV:first').attr('class'));
                        $('#secondary-navigation DIV:first a').wrap('<div class=\"slideshow overlay\" />');

                        parliamentUK.highlightImageEqualize({ wrapper: '#content-small .inner UL', iterator: 'LI', pageType: obj.pageType, equalizeObj: 'H4 A' });

                        break;
                }
                break;
        }
    }
};

$.extend({
    //return in concatenated string format the supplied JSON object (for debugging/logging purposes)
    logJSONObj: function (obj) {
        var debugJSON = '';

        for (x in obj) {
            debugJSON += x + '=' + obj[x] + ', ';
        }

        return debugJSON.substr(0, debugJSON.length - 2);
    },
    /* this function will parse xml and return a json string with the results for a member search
    the key/value pair being used from the xml is member id and member name fields (please refer to the xml 
    result from the webservice call for a reference of this data)
    */
    parseMemberSearchXML: function (xml) {
        var results = [];
        $(xml).find('PickListItem').each(function (i, val) {
            var text = $.trim($(val).text());
            var value = $.trim($(val).attr("id"));
            results[results.length] = { 'data': { 'text': text, 'value': value },
                'result': text, 'value': text
            };
        });
        return results;
    }
});

