// Design & Technology by Reading Room
// www.readingroom.com (020) 7173 2800
// Author: Lucy Kavanagh
// Date: June 2009
// Client: G4S

/*
 * IMPORTANT:
 * jQuery.noConflict is ON in jQuery source for sitecore page edit compatability.
 * Therefor all instances of '$' selectors must be replaced with 'jQuery'.
 */

jQuery(document).ready(function() {


    // *** Begin Custom code by Jason Smith *** //


    //custom code for adding classes to the current location of the user
    //coded by Jason Smith
    //G4S Australia
    //21/07/10	

    //this var gets the full location 
    var currentLocationClass = location.href;
    //this var gets the query area of the location
    var contentClass = location.search;


    if (currentLocationClass.search(/nz.g4s.com/i) != -1) {
        jQuery(".homePage .stage").css("background-image", "url(/images/content/978x370/Auckland-skyline2.jpg)");
        jQuery(".currentCountry, .leadBtn a").css("background-image", "url(/images/design/flags/nzl.png)");
        jQuery(".currentCountry").text("New Zealand");
    }
    else {
        jQuery(".homePage .stage").css("background-image", "url(/images/content/978x370/medicalservices.jpg)");
        jQuery(".currentCountry, .leadBtn a").css("background-image", "url(/images/design/flags/aus.png)");
        jQuery(".currentCountry").text("Australia");
    }


    if (currentLocationClass.search(/about/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('About')").parent("li").addClass("active");

        //display the active class on the dd based on the query string value
        switch (contentClass) {
            case "?content=health":
                jQuery("#subNav dl dd a:contains('Health')").parent("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/health.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/about/'>About</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>G4S Health Services</li>"); //breadcrumb leveler
                break;
            case "?content=customers":
                jQuery("#subNav dl dd a:contains('Our')").parent("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/motion.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/about/'>About</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Our Customers</li>"); //breadcrumb leveler
                break;                
            default: jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/health.jpg)"); //Image for that area
        }

    }
    else if (currentLocationClass.search(/services/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('Services')").parent("li").addClass("active");

        //display the active class on the dd based on the query string value
        switch (contentClass) {
            case "?content=stretcher":
                jQuery("#subNav dl dd a:contains('Stretcher')").parents("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/stretcher.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/services/'>Services</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Stretcher Patient Transport</li>"); //breadcrumb leveler
                break;
            case "?content=walker":
                jQuery("#subNav dl dd a:contains('Walking')").parents("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/wheelchair.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/services/'>Services</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Walking and Wheelchair Patient Transport</li>"); //breadcrumb leveler
                break;
            case "?content=paramedical":
                jQuery("#subNav dl dd a:contains('Paramedical')").parents("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/beacon.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/services/'>Services</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Paramedical Standby Services</li>"); //breadcrumb leveler
                break;
            case "?content=neonatal":
                jQuery("#subNav dl dd a:contains('Neonatal')").parents("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/neonatal.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/services/'>Services</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Neonatal Emergency Transport Services</li>"); //breadcrumb leveler
                break;                
            case "?content=communications":
                jQuery("#subNav dl dd a:contains('Communications')").parents("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/communications.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/services/'>Services</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Communications Centre</li>"); //breadcrumb leveler
                break;                                                                
            default: jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/medical.jpg)"); //Image for that area
        }
    }
    else if (currentLocationClass.search(/careers/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('Careers')").parent("li").addClass("active");

        //display the active class on the dd based on the query string value
        switch (contentClass) {
            case "?content=requirements":
                jQuery("#subNav dl dd a:contains('Position')").parent("dd").addClass("active"); //Active class for the left menu
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/medical.jpg)"); //Image for that area
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/careers/'>Careers</a></li>"); //Bread crumb leveler
                jQuery(".crumb").append("<li>Position Requirements</li>"); //breadcrumb leveler
                break;
            case "?content=training":
                jQuery("#subNav dl dd a:contains('Training Bodies')").parent("dd").addClass("active");
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/training.jpg)");
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/careers/'>Careers</a></li>");
                jQuery(".crumb").append("<li>Training Bodies</li>");
                break;
            case "?content=vacancies":
                jQuery("#subNav dl dd a:contains('Vacancies')").parent("dd").addClass("active");
                jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/worldMap.jpg)");
                jQuery(".crumb li:last-child").replaceWith("<li><a href='/careers/'>Careers</a></li>");
                jQuery(".crumb").append("<li>Vacancies</li>");
                break;
            default: jQuery(".evidenceBox").css("background-image", "url(/images/content/793x280/medical.jpg)"); //Image for that area
        }
    }
    else if (currentLocationClass.search(/Bookings/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('Bookings')").parent("li").addClass("active");


    }    
    else if (currentLocationClass.search(/Feedback/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('Feedback')").parent("li").addClass("active");


    }
    else if (currentLocationClass.search(/Contacts/i) != -1) {

        //if the the var contains  the specified text then add the class
        jQuery(".mainNav ul li a:contains('Contacts')").parent("li").addClass("active");


    }
    else if (currentLocationClass.search(/footer/i) != -1) {

        //Do nothing




    }
    else {
        //this sets the class on the home page
        jQuery(".mainNav ul li a:contains('Home')").parent("li").addClass("active");
    }


    // *** End Custom code by Jason Smith *** //


    // ****** TRANSLATIONS FOR JS TEXT ****** //

    // If there is a problem with the language's XML file, English defaults will be used
    var phBackMap = 'Back to world map';
    var phClose = 'Close this';
    var phLoadError = 'There has been an error loading the content you requested. Please try again, or, if the problem persists, contact us.';
    var phNewWin = 'This link opens in a new window';
    var phLoading = 'Loading';
    var phMyClippings = 'My Clippings';
    var phNext = 'Next';
    var phNextSl = 'Next slide';
    var phNoClip = 'You haven\'t selected any clippings';
    var phPrev = 'Prev';
    var phPrevSl = 'Prev slide';

    // Call sits outside the delay - as the variables need a chance to be loaded from XML before the rest of the script executes (essentially preventing asynchronous behaviour)
    jQuery.get(xmlURL, function(d) {
        jQuery(d).find('entry').each(function() {
            var phraseKey = jQuery(this).attr("key")
            if (phraseKey == 'Back') { phBack = jQuery(this).text(); }
            else if (phraseKey == 'Back to world map') { phBackMap = jQuery(this).text(); }
            else if (phraseKey == 'Close This') { phClose = jQuery(this).text(); }
            else if (phraseKey == 'Error loading content') { phLoadError = jQuery(this).text(); }
            else if (phraseKey == 'External link') { phNewWin = jQuery(this).text(); }
            else if (phraseKey == 'Loading') { phLoading = jQuery(this).text(); }
            else if (phraseKey == 'My Clippings') { phMyClippings = jQuery(this).text(); }
            else if (phraseKey == 'Next') { phNext = jQuery(this).text(); }
            else if (phraseKey == 'Next slide') { phNextSl = jQuery(this).text(); }
            else if (phraseKey == 'No clippings') { phNoClip = jQuery(this).text(); }
            else if (phraseKey == 'Prev') { phPrev = jQuery(this).text(); }
            else if (phraseKey == 'Prev slide') { phPrevSl = jQuery(this).text(); }
        });
    });

    jQuery(this).delay(200, function() { // delay needed for Firefox 3.0.x - content not syncing properly on refresh only


        // ****** MISC ENHANCEMENTS ****** //

        // Activate general functions for specified elements
        jQuery.preloadImages("/images/design/loading.gif"); // preload loading image
        jQuery('.linkBlock').equalHeights('twoLevels'); // equalize link blocks

        // Target="_blank" solution for external links in XHTML strict
        jQuery('a.new-window').click(function() { window.open(jQuery(this).attr('href')); return false; }).attr('title', phNewWin);

        // Back links
        var backLink = '<a href="#" class="back">Back</a>'
        jQuery('.back').click(function() { window.history.back() });

        // Form focus
        jQuery('input[type="text"]').focus(function() { jQuery(this).addClass('active'); });
        jQuery('input[type="text"]').blur(function() { jQuery(this).removeClass('active'); });

        // ****** GLOBAL CLOSE FUNCTIONS ****** //

        function closeCarousels() {
            jQuery('.toolTabs li').removeClass('active');
            jQuery('.evidenceBox .carousel').hide();
            jQuery('.evidenceBox').removeClass('hideImage');
            jQuery('.evidenceBox .strapLine, .evidenceBox shape').show();
        };

        function closeOverlays() {
            if (jQuery('#g4sPlayer').length == 1) { flowplayer().unload(); }
            jQuery('body').removeClass('activeOverlay');
            jQuery('.overlay').fadeOut(function() { jQuery(this).remove() });
            jQuery('.countryDropDown').fadeOut(function() { jQuery(this).remove() });
            jQuery('.evidenceBox .worldMap li .teaserBox').fadeOut(function() { jQuery(this).parent('li').removeClass('active') });
        };

        function closePDF() {
            jQuery('.pdfHelp').fadeOut(function() { jQuery(this).remove() });
            jQuery('.pdfCreator .pdfBasket').slideUp(function() { jQuery('.pdfCreator').removeClass('active').removeClass('activeHelp') });
        };

        function closeAll() {
            closeCarousels();
            closeOverlays();
            closePDF();
        };


        // ****** AJAX ****** //	

        // Create loading gif function
        function loadNotifier() { jQuery('body').append('<div class="loading" style="display:none;"><img src="/images/design/loading.gif" alt="' + phLoading + '" /></div>').children('.loading').fadeIn('medium'); };

        // Create generic AJAX function
        function loadContent(targetContent, targetLocation, manipulateContent) {
            jQuery.ajax({
                beforeSend: function(html) {
                    loadNotifier();
                },
                url: targetContent,
                error: function(html) {
                    jQuery('.loading').remove();
                    alert(phLoadError);
                },
                success: function(html) {
                    jQuery('.loading').fadeOut('fast');
                    jQuery(targetLocation).append(html)
                    manipulateContent();
                }
            });
        };


        // ****** CAROUSELS ****** //

        // Manipulate the DOM for the evidence box
        if (jQuery('.content ul').is('.cases') || jQuery('.content ul').is('.features')) {
            jQuery('.evidenceBox').prepend('<ul class="toolTabs"></ul>');
            jQuery('.content .features').prev('h2').wrap('<li class="toolFeatures"></li>');
            jQuery('.content .cases').prev('h2').wrap('<li class="toolCases"></li>');
            jQuery('.toolFeatures, .toolCases').appendTo('.toolTabs');
            jQuery('.features').prependTo(jQuery('.evidenceBox')).wrap('<div class="carousel features"></div>').wrap('<div class="carouselInner"></div>');
            jQuery('.cases').prependTo(jQuery('.evidenceBox')).wrap('<div class="carousel cases"></div>').wrap('<div class="carouselInner"></div>');
        };

        // Activate carousel
        if (jQuery('html').attr('dir') == 'rtl') {
            jQuery('.homePage .carousel ul').jcarousel({
                start: jQuery(".homePage .carousel li").length - 1,
                scroll: 1,
                buttonNextHTML: '<span class="roundBtn scrollPrev"><span><span><span><span>' + phPrev + '</span></span></span></span></span>',
                buttonPrevHTML: '<span class="roundBtn scrollNext"><span><span><span><span>' + phNext + '</span></span></span></span></span>'
            });
            jQuery('.evidenceBox .carousel ul').each(function() {
                jQuery(this).jcarousel({
                    start: jQuery(this).children('li').length - 1,
                    scroll: 1,
                    buttonNextHTML: '<img class="scrollNext" src="/images/design/btnScrollNext.gif" alt="Go to previous slide" />',
                    buttonPrevHTML: '<img class="scrollPrev" src="/images/design/btnScrollPrev.gif" alt="Go to next slide" />'
                });
            });
            // esc key closes
            jQuery().keyup(function(event) { if (event.keyCode == 27) { closeCarousels(); } });
        }
        else {
            jQuery('.homePage .carousel ul').jcarousel({
                scroll: 1,

                buttonNextHTML: '<span class="roundBtn scrollNext"><span><span><span><span>' + phNext + '</span></span></span></span></span>',
                buttonPrevHTML: '<span class="roundBtn scrollPrev"><span><span><span><span>' + phPrev + '</span></span></span></span></span>'
            });
            jQuery('.evidenceBox .carousel ul').each(function() {
                jQuery(this).jcarousel({
                    scroll: 1,
                    buttonNextHTML: '<img class="scrollNext" src="/images/design/btnScrollNext.gif" alt="Go to next slide" />',
                    buttonPrevHTML: '<img class="scrollPrev" src="/images/design/btnScrollPrev.gif" alt="Go to prev slide" />'
                });
            });
            jQuery('.carousel ul').css('left', '0');
            // esc key closes
            jQuery().keyup(function(event) { if (event.keyCode == 27) { closeCarousels(); } });
        };
        // Remove styling added by plugin
        jQuery('.jcarousel-next,.jcarousel-prev').removeAttr('style');


        // ****** OVERLAY ****** // 

        // If js is enabled, the view more link will call the content overlay from the target page via ajax, which will thus not exist in the XHTML on load
        //jQuery('.carousel .featureLink,.carousel .featureImage,.carousel .featureHeader,.worldMap .featureLink,.worldMap .featureImage,.worldMap .featureHeader').click(function() {
        jQuery('.worldMap .featureLink,.worldMap .featureImage,.worldMap .featureHeader').click(function() {

            // Close other interactive content
            closeOverlays();
            closePDF();

            // Define funtion to manipulate dom of overlay on successful load
            function manipulateContent() {

                // esc key closes panel and fades content back in
                jQuery().keyup(function(event) { if (event.keyCode == 27) { closeOverlays(); jQuery(dimItems).fadeTo("slow", 1); } });

                // Enable print styling
                jQuery('body').addClass('activeOverlay');

                // Create close option
                jQuery('#wrapper .overlay').addClass('active').fadeIn('slow').children('h1').append('<img class="closeTab" src="/images/design/btnCloseCross.gif" alt="' + phClose + '" />').children('.closeTab').click(function() {
                    if (jQuery('#wrapper .overlay').is('.active')) {
                        closeOverlays();
                        jQuery(dimItems).fadeTo("slow", 1);
                    };
                });

                // Manipuldate DOM and activate needed functions
                jQuery('.overlay').children('h1').siblings().wrapAll('<div class="overlayContent"></div>');
                jQuery('.overlay h1 .addPDF').appendTo('.overlay h1 span');
                var dimItems = '#subNav, .toolTabs, .crumb, .content, .contactUs, .schemeA, .schemeB, #footer';
                jQuery(dimItems).fadeTo("slow", 0.2);
                jQuery('.evidenceBox .strapLine').hide();
                initVid();
                toolTipItems = jQuery(".overlay .addPDF");
                pdfToolTip(toolTipItems);
                jQuery('.overlay a.addPDF').click(function() { return jQuery.addPDF(jQuery(this)); });
            };

            // Define AJAX variables
            var targetContent = jQuery(this).attr('href');
            targetContent = targetContent + '?mode=ajax';
            jQuery('#wrapper').prepend('<div class="overlay"></div>').children('.overlay').hide();
            var targetLocation = jQuery('#wrapper .overlay');

            // Call AJAX function
            loadContent(targetContent, targetLocation, manipulateContent);
            return false;

        });


        // ****** EVIDENCE BOX EVENTS ****** //

        // Create close function for carousels in the evidence box
        jQuery('.evidenceBox .carousel').hide().prepend('<img class="closeThis" src="/images/design/btnClose.gif" alt="' + phClose + '" />');
        jQuery('.evidenceBox .closeThis').click(function() { closeAll(); });

        // Create show/hide function for carousels in the evidence box
        function evidenceCarousel(carousel, tab) {
            closeAll();
            jQuery(carousel).show();
            jQuery(tab).addClass('active');
            jQuery('.evidenceBox').addClass('hideImage')
            jQuery('.evidenceBox .strapLine').hide();
        };

        // Trigger show/hide function for carousels in the evidence box
        jQuery('.toolCases').click(function() {
            var tab = this
            var carousel = '.carousel.cases'
            evidenceCarousel(carousel, tab);
        });
        jQuery('.toolFeatures').click(function() {
            var tab = this
            var carousel = '.carousel.features'
            evidenceCarousel(carousel, tab);
        });


        // ****** PDF CREATOR ****** // 

        // Tool tip for add to pdf buttons
        function pdfToolTip(toolTipItems) {
            var yOffset;
            if (jQuery('html').attr('dir') == 'rtl') { yOffset = -0; }
            else { yOffset = -189; };
            var xOffset = -21;
            toolTipItems.hover(
				function(e) { this.t = this.title; this.title = ""; jQuery("body").append("<span class='toolTip'>" + this.t + "</span>"); jQuery(".toolTip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px").fadeIn("fast"); },
				function() { this.title = this.t; jQuery(".toolTip").remove(); }
			);
            toolTipItems.mousemove(function(e) { jQuery(".toolTip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px"); });
        };

        var toolTipItems = jQuery(".stage .addPDF, .helpIcon");
        pdfToolTip(toolTipItems);

        // Open and populate help, then close it on toggle
        jQuery('.helpIcon').toggle(
			function() {

			    // Close other interactive content, grab basket url
			    closeCarousels();
			    closeOverlays();
			    var basketURL = jQuery('.helpIcon').attr('href');

			    // Create basket placeholder, load help
			    jQuery('.pdfCreator').addClass('activeHelp').append('<div class="pdfHelp"></div>').children('.pdfHelp').hide().load(basketURL.replace(/ /g, "%20") + " .pdfHelp", function() {

			        // Change inner class, show help
			        var classChange = jQuery('.pdfHelp').children('.pdfHelp');
			        classChange.replaceWith('<div class="inner">' + jQuery(classChange).html() + '</div>');

			        // Modify the help area
			        jQuery('.pdfHelp .inner').prepend('<img class="closeHelp" src="/images/design/btnCloseCross.gif" alt="' + phClose + '" />');

			        jQuery('.pdfHelp .closeHelp').click(function() {
			            jQuery('.pdfHelp').fadeOut(function() { jQuery(this).remove() });
			            jQuery('.pdfCreator').removeClass('activeHelp');
			        });

			        jQuery('.pdfHelp').fadeIn();

			    });

			    return false;
			},
			function() { closePDF(); return false; }
		); // end toggle

        // JS ON: Items will be added and removed from the basket via ajax when clicking the icons. The basket link will make it slide up in the page and it will be populated via AJAX. 
        // JS OFF: The add link will reload the page to add the item to the basket. The basket link will take user directly to standalone pdf basket page

        // Add onclick event
        jQuery('a.addPDF').click(function() { return jQuery.addPDF(jQuery(this)); });

        // Add clippings basket 
        jQuery('.pdfCreator').append('<div class="pdfBasket"></div>').children('.pdfBasket').hide();

        // Load ONLY if correct link available to grab basketURL from		
        if (jQuery('div').is('.pdfTab')) { loadBasket(); }

        // Remove onclick event for standalone PDF basket
        jQuery('.content .pdfBasket a').removeAttr('onclick');
        jQuery('.content .pdfBasket a').unbind('click');

        function getParameterByName(name, url) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(url);
            if (results == null)
                return "";
            else
                return results[1];
        }

        jQuery.addPDF = function(obj) {
            var href = jQuery(obj).attr('href');
            jQuery.get(href, { mode: "ajax" });
            jQuery(".pdfTab").animate({ paddingBottom: "10px" }).animate({ paddingBottom: "0" });
            if (jQuery('.pdfCreator .active')) { loadBasket(); }
            return false;
        };

        // Remove from basket
        jQuery.removePDF = function(obj) {
            var href = jQuery(obj).attr('href');
            jQuery.get(href, { mode: "ajax" });
            loadBasket();
            return false;
        };

        // Empty basket
        jQuery.removeAll = function(obj) {
            var href = jQuery(obj).attr('href');
            jQuery.get(href, { mode: "ajax" });
            loadBasket();
            return false;
        };

        // Load basket
        function loadBasket() {

            var basketURL = jQuery('.pdfTab a').attr('href') + "?mode=ajax";

            jQuery('.pdfCreator .pdfBasket').load(basketURL.replace(/ /g, "%20") + " .pdfBasket", function() {

                // Update counter
                var pdfItems = jQuery('.pdfBasket ol').children('li').length;
                jQuery('.basketLink').html(phMyClippings + ' (<strong class="pdfCount">' + pdfItems + '</strong>)');

                var basketVisible = false;
                if (jQuery('.pdfCreator .pdfBasket').is(':visible')) { basketVisible = true; }

                // Remove extrenuous mark up
                var excessWrapper = jQuery('.pdfCreator').children('.pdfBasket');
                excessWrapper.replaceWith("" + jQuery(excessWrapper).html() + "");

                // Activate functions for newly created DOM elements
                toolTipItems = jQuery(".removePDF, .createPDF a, .removeAll a");
                pdfToolTip(toolTipItems);

                jQuery('a.removePDF').click(function() {
                    jQuery(".toolTip").fadeOut('fast', function() { jQuery(this).remove(); })
                    jQuery(this).parents('li').fadeOut('slow', function() { jQuery(this).remove(); });
                    return jQuery.removePDF(jQuery(this));
                });

                jQuery('li.removeAll a').click(function() {
                    return jQuery.removeAll(jQuery(this));
                });

                // Create scrollbar
                if (jQuery('html').attr('dir') == 'rtl') { jQuery('.pdfBasket ol').jScrollPane({ scrollbarOnLeft: true, showArrows: true, scrollbarWidth: 15, arrowSize: 16 }); }
                else { jQuery('.pdfBasket ol').jScrollPane({ showArrows: true, scrollbarWidth: 15, arrowSize: 16 }); };

                if (!basketVisible) { jQuery('.pdfCreator .pdfBasket').hide(); }
            });
        }

        // Open and populate basket, then close it on toggle
        jQuery('.basketLink').toggle(
			function() {

			    // esc key closes pdf
			    jQuery().keyup(function(event) { if (event.keyCode == 27) { closePDF(); } });

			    // Close other interactive content, load basket
			    closeCarousels();
			    closeOverlays();

			    jQuery('.pdfBasket').children().fadeIn(900);
			    jQuery('.pdfCreator').addClass('active').children('.pdfBasket').slideDown();

			    return false;
			},
			function() {
			    jQuery('.pdfBasket').children().fadeOut(200);
			    jQuery('.pdfCreator .pdfBasket').slideUp(function() { jQuery('.pdfCreator').removeClass('active').removeClass('activeHelp') });
			    return false;
			}
		); // end toggle


        // ****** COUNTRY SELECTOR RE-USABLE FUNCTIONS ****** // 

        // Create dropdown structure
        function createCountryDrop(selectorContainer, dropContainer) {
            jQuery(selectorContainer).after('<div class="countryDropDown"><img src="/images/design/btnCloseCross.gif" alt="Close" class="close" /><dl class="selectYourCountry"></dl></div>');
            jQuery(dropContainer).fadeIn(function() { jQuery(this).addClass('active') });
            jQuery(dropContainer + ' .close').click(function() {
                if (jQuery(dropContainer).is('.active')) { closeOverlays(); };
            });
        };

        // Create encompassing loading function
        function loadLocations(locationsURL, regionsContainer, singleRegion, countriesContainer) {

            jQuery('.countrySelector .countryInner').append('<div class="loading" style=""><img src="/images/design/loading.gif" alt="' + phLoading + '" /></div>').children('.loading').fadeIn('medium');

            jQuery(regionsContainer).load(locationsURL.replace(/ /g, "%20") + " dt.tab", function() {

                // Set load countries function
                function loadCountries() {

                    // Remove extrenuous mark up
                    jQuery(countriesContainer).remove();

                    // Identify the active region, and find the region number from its class
                    var activeRegion = jQuery(regionsContainer).children('dt.active');
                    var activeRegionName = jQuery(activeRegion).attr("class");
                    var pos = activeRegionName.indexOf('Region');
                    activeRegionName = activeRegionName.substring(pos, pos + 7);

                    // Find and load the active region's countries from the standalone page
                    jQuery(activeRegion).after('<dd class="countries"></dd>').siblings('.countries').load(locationsURL.replace(/ /g, "%20") + " dd." + activeRegionName, function() {

                        // Remove extrenuous mark up
                        var excessWrapper = jQuery(countriesContainer).children('dd')
                        excessWrapper.replaceWith("" + jQuery(excessWrapper).html() + "");

                        // Create specific function if loading contact us details in page
                        if (jQuery('.countryContacts').is('.linkIn')) {
                            jQuery('.contactUs .countryDropDown .countries').children('dl').children('dd').hide(); // Hide loaded contact details
                            jQuery('.contactUs .countryDropDown .countries').children('dl').children('dt').children('a').click(function() {
                                // Remove existing details from contact box if showing new ones
                                if (jQuery('.contacts').children('li').is('.phone,.email')) { jQuery('.contacts').children('.phone,.email').remove(); }
                                // Show country details in contact box
                                jQuery(this).parents('dt').next('dd').children('ul').children('li').prependTo('.contacts');
                                closeAll();
                                return false;
                            });
                        }
                    });
                };

                loadCountries(); // Load active region's countries by default
                // Create click event for regions
                jQuery(regionsContainer).children('dt').removeClass('tab').addClass('region').wrapInner('<a href="#"></a>').click(function() {
                    jQuery(regionsContainer).children('dt').removeClass('active');
                    jQuery(this).addClass('active');
                    loadCountries();
                    return false
                });
                jQuery('.loading').fadeOut('fast', function() {
                    jQuery('.loading').remove();
                });
            }); // end load
        };


        // ****** COUNTRY SELECTOR - MAIN MENU ****** // 

        // JS ON: The country selector will drop down in the page and be populated via ajax via a manipulated url with query string
        // JS OFF: The country selector will link directly to a standalone page

        jQuery('.locationBar .countryOuter').click(function() {

            if (jQuery('.locationBar .countryDropDown').is('.active')) { }
            else {
                closeAll();

                // Set dropdown variables and activate create dropdown function
                var selectorContainer = '.locationBar .countryOuter';
                var dropContainer = '.locationBar .countryDropDown';
                createCountryDrop(selectorContainer, dropContainer);

                // Set location variables and activate load locations function
                var locationsURL = jQuery('.currentCountry').attr('href');
                locationsURL += '?mode=ajax';
                var regionsContainer = '.locationBar .selectYourCountry';
                var singleRegion = jQuery(regionsContainer).children('dt');
                var countriesContainer = '.locationBar .countries';
                loadLocations(locationsURL, regionsContainer, singleRegion, countriesContainer);

                // Add G4S corporate links
                jQuery(regionsContainer).after('<div class="linkPlaceholder"></div>').siblings('.linkPlaceholder').load(locationsURL.replace(/ /g, "%20") + " .corporateSites", function() {
                    // Remove extrenuous mark up
                    var linkPlaceholder = jQuery('.linkPlaceholder');
                    linkPlaceholder.replaceWith("" + jQuery(linkPlaceholder).html() + "");
                });
            } // end else
            return false;
        }); // end click


        // ****** COUNTRY SELECTOR - CONTACT BOX ****** // 

        // JS ON: The country selector will drop down in the page and be populated via ajax via a manipulated url with query string
        // JS OFF: The country selector will link directly to a standalone page

        jQuery('.contactUs .countryContacts').click(function() {
            if (jQuery('.contactUs .countryDropDown').is('.active')) { }
            else {
                closeAll();

                // Set dropdown variables and activate create dropdown function
                var selectorContainer = '.contactUs .countryContacts';
                var dropContainer = '.contactUs .countryDropDown';
                createCountryDrop(selectorContainer, dropContainer);

                // Set location variables and activate load locations function
                var locationsURL = jQuery('.countryContacts a:first').attr('href') + 'ajax'
                var regionsContainer = '.contactUs .countryDropDown .selectYourCountry';
                var singleRegion = jQuery(regionsContainer).children('dt');
                var countriesContainer = '.contactUs .countryDropDown .countries';
                loadLocations(locationsURL, regionsContainer, singleRegion, countriesContainer);
            } // end else
            return false;
        }); // end click


        // ****** MAIN NAV ****** //

        // Dropdown is pure css, but needs js fix to appear in IE6, and has fade/tab focus enhancement when JS on
        jQuery('.mainNav > li > ul').hide();
        jQuery('.mainNav > ul > li').hover(
			function() { jQuery(this).addClass('hover').children('ul').fadeIn(); },
			function() { jQuery(this).children('ul').hide().parent('li').removeClass('hover'); }
		);
        jQuery('.mainNav > ul > li > a').focus(
			function() { jQuery(this).parents('li').addClass('hover').siblings('ul').fadeIn(); }
		);
        jQuery('.mainNav > ul > li > a').blur(
			function() { jQuery(this).siblings('ul').hide().parent('li').removeClass('hover'); }
		);

        // ****** SUB NAV****** //

        // Slide for sectors and services faux headers (but not if there is only one)
        if (jQuery('.fauxHeader').length !== 1) {
            jQuery('.fauxHeader').addClass('navSlide');
            jQuery('#subNav dd.active').siblings('.navSlide').removeClass('navSlide').addClass('fauxActive');
            jQuery('.navSlide').siblings('dd').hide();
            jQuery('.navSlide').click(function() {
                if (jQuery(this).siblings('dd').is(':hidden')) {
                    jQuery(this).children('span').addClass('active').parents('.navSlide').siblings('dd').slideDown('slow');
                    jQuery(this).siblings('.navSlide').children('span').removeClass('active').parents('.navSlide').siblings('dd').slideUp();
                }
                else {
                    jQuery(this).children('span').removeClass('active').parents('.navSlide').siblings('dd').slideUp();
                }
            });
            jQuery('.fauxActive').toggle(
				function() { jQuery(this).children('span').addClass('off').parents('.fauxActive').siblings('dd').slideUp(); },
				function() {
				    jQuery(this).children('span').removeClass('off').parents('.fauxActive').siblings('dd').slideDown('slow');
				    jQuery(this).siblings('.fauxActive').children('span').removeClass('off').parents('.fauxActive').siblings('dd').slideUp();
				}
			);
        };

        // ****** SITE MAP ****** //
        jQuery('#sitemap h2').siblings('ul, a').hide();
        jQuery('#sitemap h2').toggle(
			function() { jQuery(this).addClass('active').siblings('ul, a').slideDown('fast'); return false; },
			function() { jQuery(this).removeClass('active').siblings('ul, a').slideUp('fast'); return false; }
		);


        // ****** SEARCH FILTER ****** //
        // Stay open if inputs populated from previous search
        if (jQuery('.searchfilter input.search').attr('value') !== '' || jQuery('.searchfilter input#startdate').attr('value') !== '' || jQuery('.searchfilter input#enddate').attr('value') !== '') {
            jQuery('.searchfilter').addClass('open');
            jQuery('.searchfilter legend').toggle(
				function() { jQuery('.searchfilter').addClass('closed').removeClass('open'); return false; },
				function() { jQuery('.searchfilter').removeClass('closed').addClass('open'); return false; }
			)
        }
        else {
            jQuery('.searchfilter').addClass('closed');
            jQuery('.searchfilter legend').toggle(
				function() { jQuery('.searchfilter').removeClass('closed').addClass('open'); return false; },
				function() { jQuery('.searchfilter').addClass('closed').removeClass('open'); return false; }
			)
        }

        // ****** DATE PICKER ****** // 

        //initialise all .datepickers on page
        jQuery('.datepicker').datepicker({ maxDate: 'D', dateFormat: 'dd/mm/yy' });
        //Date range (start date / end date)
        jQuery('#startdate').datepicker('option', {
            onSelect: function(dateText, inst) {
                //set after init, that enddate cannot start before startdate
                jQuery('#enddate').datepicker('option', { minDate: new Date(dateText) });
            }
        });


        // ****** WORLD MAP - WHAT WE DO ****** // 

        // If JS is on, what we do case studies content gets progressively enhanced into a map
        jQuery('.content .worldMap').appendTo('.evidenceBox');
        jQuery('.worldMap h2').addClass('hidden');
        jQuery('.evidenceBox .worldMap li').hover(function() {
            jQuery('.evidenceBox .worldMap li').removeClass('active');
            jQuery(this).children('.teaserBox').fadeIn();
            jQuery(this).addClass('active');
        }, function() {
            jQuery(this).children('.teaserBox').fadeOut('fast');
            jQuery(this).removeClass('active');
        });


        // ****** WORLD MAP - WHERE WE OPERATE ****** // 

        // If JS is on, where we operate lists get progressively enhanced into a map
        var wwo = jQuery('.countryList');
        if (wwo.length == 1) {
            wwo.appendTo('.evidenceBox');
            wwo.before('<ul class="regionPanel"></ul>');
            var wwoP = jQuery('.regionPanel');
            var wwoR = jQuery('.countryList h2'); /*regions*/
            var wwoC = jQuery('.countryList ul'); /*countries*/
            if (wwoR.length >= 0) {

                // Create function to identify chosen region and show/hide accordingly
                function wwoSelection(clickedReg) {
                    wwo.addClass('inRegion');
                    wwoR.parents('li').hide();
                    wwoC.hide();
                    // find chosen region class
                    var regClick = jQuery(clickedReg).parents('li').attr('class');
                    regClick = '.' + regClick;
                    // manipulate correct elements
                    wwo.children(regClick).show().children('ul').fadeIn('slow');
                    wwoP.children(regClick).addClass('active').siblings('li').removeClass('active');
                    return false;
                };

                // Assign bubble types to regions, clone to region panel
                wwoR.each(function(i) {
                    jQuery(this).parents('li').clone().appendTo(wwoP);
                    jQuery(this).removeClass('tab');
                    var regClass = jQuery(this).closest('li').attr('class');
                    if ((regClass == 'region01') || (regClass == 'region05') || (regClass == 'region06')) { jQuery(this).addClass('leftBubble'); }
                    else { jQuery(this).addClass('rightBubble'); };
                });

                // Clean up region panel
                jQuery('.regionPanel ul').remove();
                jQuery('.regionPanel h2').each(function(i) { jQuery(this).replaceWith('<a href="#">' + jQuery(this).html() + '</a>'); });
                wwoP.append('<li class="backToMap"><a href="#">' + phBackMap + '</a></li>');

                // Region marker clicks
                wwoR.children('span').wrapInner('<a href="#"></a>').children('a').click(function(e) {
                    wwoP.fadeIn('slow');
                    var clickedReg = jQuery(this);
                    wwoSelection(clickedReg);
                });

                // Region panel clicks
                jQuery('.regionPanel a').click(function() {
                    var clickedReg = jQuery(this);
                    wwoSelection(clickedReg);
                });
                jQuery('.regionPanel .backToMap a').click(function() {
                    wwo.removeClass('inRegion');
                    wwoP.fadeOut();
                    wwoR.parents('li').fadeIn();
                });

                // country rollovers
                wwoC.children('li').children('a').wrapInner('<span>', '</span>');
                wwoC.children('li').hover(
					function() { jQuery(this).addClass('on') },
					function() { jQuery(this).removeClass('on') }
				);
            }

            /* var country = ['left pos','top pos']; */

            // Europe coords
            var aut = ['378', '164']; var aze = ['632', '228']; var bel = ['316', '118']; var bgr = ['472', '210']; var cyp = ['460', '266']; var cze = ['375', '152']; var dnk = ['351', '75']; var est = ['460', '47']; var fin = ['460', '5']; var grc = ['443', '239']; var ggy = ['269', '146']; var hun = ['404', '170']; var irl = ['227', '102']; var imn = ['250', '97']; var jey = ['259', '140']; var lva = ['470', '65']; var ltu = ['444', '82']; var lux = ['327', '129']; var mlt = ['388', '261']; var nld = ['327', '107']; var nor = ['331', '18']; var pol = ['400', '100']; var rou = ['468', '195']; var rus = ['610', '10']; var srb = ['440', '209']; var svk = ['398', '156']; var svn = ['378', '176']; var swe = ['388', '58']; var tur = ['500', '234']; var gbr = ['270', '102']; var ukr = ['490', '140'];

            // Africa coords
            var dza = ['340', '35']; var ago = ['408', '197']; var bwa = ['436', '225']; var cmr = ['385', '125']; var cod = ['430', '150']; var dji = ['505', '98']; var egy = ['455', '37']; var gab = ['390', '147']; var gmb = ['290', '93']; var gha = ['338', '115']; var gin = ['300', '102']; var civ = ['319', '115']; var ken = ['489', '142']; var lib = ['420', '40']; var lso = ['450', '260']; var mdg = ['520', '220']; var mwi = ['474', '194']; var mli = ['324', '75']; var mrt = ['300', '70']; var mus = ['555', '225']; var mar = ['325', '15']; var moz = ['488', '200']; var nam = ['410', '245']; var nga = ['372', '110']; var rwa = ['455', '157']; var sle = ['301', '115']; var zaf = ['430', '262']; var sdn = ['455', '92']; var tza = ['475', '168']; var uga = ['466', '138']; var zmb = ['442', '199'];

            // Latin Am coords
            var arg = ['366', '225']; var brb = ['390', '40']; var bol = ['355', '150']; var col = ['325', '75']; var chl = ['346', '200']; var cri = ['293', '59']; var dom = ['342', '18']; var ecu = ['309', '100']; var slv = ['265', '40']; var grd = ['395', '22']; var gtm = ['255', '33']; var hnd = ['278', '35']; var jam = ['313', '22']; var mex = ['215', '10']; var nic = ['282', '45']; var pan = ['307', '59']; var pry = ['390', '190']; var per = ['315', '130']; var pri = ['357', '20']; var lca = ['399', '8']; var tto = ['375', '53']; var ury = ['394', '227']; var ven = ['360', '70'];

            // North Am coords
            var can = ['400', '100']; var usa = ['425', '200'];

            // Middle East coords		
            var bhr = ['430', '138']; var irq = ['365', '60']; var isr = ['278', '80']; var jor = ['296', '85']; var kwt = ['400', '10']; var lbn = ['284', '60']; var omn = ['480', '210']; var qat = ['437', '149']; var sau = ['360', '150']; var syr = ['320', '38']; var are = ['458', '162']; var yem = ['370', '250'];

            // Asia Pacific coords
            var afg = ['220', '30']; var aus = ['400', '230']; var bgd = ['285', '62']; var btn = ['284', '49']; var brn = ['374', '125']; var khm = ['335', '101']; var chn = ['330', '30']; var gum = ['480', '110']; var hkg = ['375', '65']; var ind = ['255', '90']; var idn = ['335', '155']; var jpn = ['455', '10']; var kaz = ['240', '1']; var mac = ['363', '67']; var mys = ['327', '125']; var npl = ['270', '50']; var nzl = ['536', '263']; var pak = ['220', '45']; var png = ['470', '162']; var phl = ['394', '89']; var sgp = ['334', '134']; var kor = ['415', '15']; var lka = ['261', '116']; var twn = ['394', '60']; var tha = ['330', '90']; var uzb = ['220', '10'];

            // assign co-ordinate styles based on iso class
            jQuery(wwoC).children('li').each(function(i) {
                var isoCode = jQuery(this).attr('class');
                var coords;
                try { coords = eval(isoCode); }
                catch (err) { };
                if (coords != undefined) {
                    var xp = coords[0] + 'px'; var yp = coords[1] + 'px';
                    jQuery(this).css({ 'left': xp, 'top': yp });
                }
            });
        };


        // ****** VIDEO PLAYER ****** // 

        function initVid() {
            if (jQuery('#g4sPlayer').length == 1) {

                // Set up structure	
                jQuery("#g4sPlayer").empty().addClass("FPenabledHolder");
                jQuery(".flowControls").addClass("FPenabledControls");

                // using v3.1.1 to negate bug in v3.1.4 with overlaid play button in flash
                var player = flowplayer("g4sPlayer", { src: "/flash/flowplayer-3.1.1.swf", wmode: "transparent" }, {
                    // don't start automcatically 
                    clip: { autoPlay: false, autoBuffering: true /*, captionUrl: '/flash/timedtext.xml'*/ },
                    // disable default controls 
                    plugins: { controls: null /*, captions: {url: '/flash/flowplayer.captions-3.1.5-dev.swf', captionTarget: 'content' }, content: {url:'/flash/flowplayer.content-3.1.0.swf'}*/ },
                    // set volume slider
                    onLoad: function() { this.setVolume(50); jQuery(".volumeSlider .vol").css("width", 25); }
                }).controls("flowControls", { duration: 0 });

                // Volume		
                jQuery(".flowControls").after("<div class='volumeSlider'><span class='vol'>volume: 50</span><a class='grab'>drag to change volume</a></div>");
                jQuery(".volumeSlider .grab").mousedown(function(e) {
                    jQuery(".volumeSlider").bind("mousemove", function(e) {
                        var x = Math.round(e.pageX - jQuery(this).offset().left);
                        x = x > 50 ? 50 : x;
                        x = x < 0 ? 0 : x;
                        jQuery(".volumeSlider .vol").css("width", x);
                        flowplayer("g4sPlayer").setVolume(x * 2);
                    });
                });
                jQuery(".volumeSlider .grab").click(function(e) {
                    var x = Math.round(e.pageX - jQuery(this).offset().left);
                    x = x > 50 ? 50 : x;
                    x = x < 0 ? 0 : x;
                    jQuery(".volumeSlider .vol").css("width", x);
                    flowplayer("g4sPlayer").setVolume(x * 2);
                });

                // Seeker
                var playheadActive = false;
                jQuery(".flowControls .playhead").focus(function() { playheadActive = true; });
                jQuery(".flowControls .playhead").blur(function() { playheadActive = false; });
                jQuery().keydown(function(e) {
                    var key = e.charCode || e.keyCode || 0;
                    if (playheadActive && key == 37) {
                        var currentTime = flowplayer("g4sPlayer").getTime();
                        var newTime = currentTime - 4 > 0 ? currentTime - 4 : 0;
                        flowplayer("g4sPlayer").seek(newTime);
                    }
                    if (playheadActive && key == 39) {
                        var currentTime = flowplayer("g4sPlayer").getTime();
                        var newTime = (currentTime + 3);
                        if (newTime > player.getClip().duration) { newTime = player.getClip().duration; }
                        flowplayer("g4sPlayer").seek(newTime);
                    }
                });

                // Volume
                jQuery().mouseup(function(e) { jQuery(".volumeSlider").unbind("mousemove"); });

                // Set overall height so IE6 plays nicely
                var vidHeight = jQuery('#g4sPlayer').height()
                jQuery('.video').css('height', vidHeight);

            };
            if (jQuery('.evidenceBox #g4sPlayer').length == 1) {
                // Remove imagery from evidence box
                jQuery('.evidenceBox').removeAttr('style').css('background-color', '#d7d7d7')
            };
        }
        initVid();

    }); // end delay
});     // end document ready

