/***************************************************
Design & Technology by Reading Room
www.readingroom.com (020) 7173 2800
* Author: Lucy Kavanagh
* Created: June 2009
* Updated: July 2010
***************************************************/

/*
 * 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() {

    jQuery(this).delay(200, function() { // delay needed for Firefox 3.0.x - content not syncing properly on refresh only

        // ****** MISC ENHANCEMENTS ****** //
		
		var phNewWin = "Nueva Ventana";
		var phNext = "Sig";
		var phPrev = "Ant";
		var phClose = "Cerrar";
		var phMyClippings = "Mis Apuntes";
		var phLoading = "Cargando";
		var phMore = "";
		var phBackMap = "Volver al mapa";

        // 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'); });
        
        // All media links open in a new window
        jQuery('a[href*="/media/Files/"]').each(function() {
            // Only add new window class if not already set to target = _blank
            if (jQuery(this).attr("target") == "" && !jQuery(this).hasClass('mp3') && !jQuery(this).hasClass('vid')) {
                jQuery(this).addClass("new-window");
                jQuery(this).attr('title', phNewWin);
            }
        });

        // ****** 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').append('<span class="more">' + phMore + '</span>');
            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() {

            // 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').children('.strapLine').hide();
            var crsItems = jQuery(carousel + ' li');
            var crsBtns = jQuery(carousel + ' .scrollPrev, ' + carousel + ' .scrollNext');
            if (crsItems.length < 4) { crsBtns.remove(); }
        };

        // Trigger show/hide function for carousels in the evidence box
        jQuery('.toolCases').click(function() { evidenceCarousel('.carousel.cases', this); });
        jQuery('.toolFeatures').click(function() { evidenceCarousel('.carousel.features', this); });


        // ****** 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') + '?mode=ajax'

			    // 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(selectorContainer).append('<img class="loading" src="/images/design/loading.gif" alt="' + phLoading + '" />').children('.loading').fadeIn('medium');
            jQuery(dropContainer).fadeIn(function() { jQuery(this).addClass('opened') });
            jQuery(dropContainer + ' .close').click(function() {
                if (jQuery(dropContainer).is('.opened')) { closeOverlays(); };
            });
        };

        // Create encompassing loading function
        function loadLocations(locationsURL, regionsContainer, dropContainer) {

            jQuery(regionsContainer).load(locationsURL.replace(/ /g, "%20") + " .countrycontainer", function() {

                // Remove extrenuous mark up
                var excess1 = jQuery(regionsContainer).children('.countrycontainer')
                excess1.replaceWith("" + jQuery(excess1).html() + "");

                // Remove extrenuous mark up
                var excess2 = jQuery(regionsContainer).children('.selectYourCountry')
                excess2.replaceWith("" + jQuery(excess2).html() + "");

                // Highlight active region			
                jQuery(regionsContainer).children('dd').hide().addClass('countries');
                jQuery(regionsContainer).children('dt.active').next('dd').show();

                // Add G4S corporate links if in main country selector
                jQuery(regionsContainer).children('.corporateSites').appendTo(dropContainer);

                // 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;
                    });
                }

                // 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(regionsContainer).children('dd').hide();
                    jQuery(this).addClass('active').next('dd').show();
                    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('.opened')) { }
            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') + '?mode=ajax';
                var regionsContainer = '.locationBar .selectYourCountry';
                loadLocations(locationsURL, regionsContainer, dropContainer);
            } // 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('.opened')) { }
            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';
                loadLocations(locationsURL, regionsContainer, dropContainer);
            } // 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']; */
    

            // Latin Am coords
            var arg_1 = ['336', '225']; 
			var arg_2 = ['366', '170']; var arg_3 = ['374', '113']; var arg_4 = ['434', '113']; var arg_5 = ['474', '116'];
			var arg_6 = ['472', '94']; var arg_7 = ['481', '92']; var arg_8 = ['475', '86']; 
			var arg_9 = ['456', '73']; var arg_10 = ['382', '70'];
			var arg_11 = ['386', '56']; var arg_12 = ['430', '60'];
			var arg_13 = ['405', '48']; var arg_14 = ['425', '33'];
			var arg_15 = ['434', '15']; var arg_16 = ['446', '13'];
            var arg_17 = ['482', '43']; var arg_18 = ['518', '48'];

            // 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) {

                jQuery('.g4sPlayer').empty().addClass("FPenabledHolder");
                jQuery(".flowControls").addClass("FPenabledControls");
                jQuery('.g4sPlayer.mp3').siblings('.flowControls').addClass('controls-mp3');
                jQuery('.g4sPlayer.vid').siblings('.flowControls').addClass('controls-vid');

                // Set up each player one by one
                jQuery('.g4sPlayer').each(function(i) {

                    var id = jQuery(this).attr('id');

                    // Set up mp3s
                    if (jQuery(this).hasClass('.mp3')) {
                        var href = jQuery(this).attr('href') + "?ext=.mp3";
                        jQuery(this).attr('href', href);
                        flowplayer(id, { src: "/flash/flowplayer-3.2.2.swf", wmode: "transparent" }, {
                            clip: { autoPlay: false, autoBuffering: true },
							plugins: { audio: { url: "/flash/flowplayer.audio-3.2.0.swf"} },
                            onLoad: function() { this.setVolume(50); jQuery(".volumeSlider .vol").css("width", 25); }
                        });
                        flowplayer(id).controls(jQuery(".controls-mp3").get(i), { duration: 0 });
                    }

                    // Set up videos
                    else {
                        flowplayer(id, { src: "/flash/flowplayer-3.2.2.swf", wmode: "transparent" }, {
                            clip: { autoPlay: false, autoBuffering: true },
                            plugins: { controls: null },
                            onLoad: function() { this.setVolume(50); jQuery(".volumeSlider .vol").css("width", 25); }
                        });
                        flowplayer(id).controls(jQuery(".controls-vid").get(i), { duration: 0 });
                        var vidHeight = jQuery(this).height();
                        jQuery(this).parents('.video').css('height', vidHeight);
                    }

                });

                // Set 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) {
                    var id = jQuery(this).parents('.video').children('.g4sPlayer').attr('id');
                    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(id).setVolume(x * 2);
                    });
                });
                jQuery(".volumeSlider .grab").click(function(e) {
                    var id = jQuery(this).parents('.video').children('.g4sPlayer').attr('id');
                    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(id).setVolume(x * 2);
                });
                jQuery().mouseup(function(e) { jQuery(".volumeSlider").unbind("mousemove"); });

                // Set seeker
                var playheadActive = false;
                jQuery(".flowControls .playhead").focus(function() { playheadActive = true; });
                jQuery(".flowControls .playhead").blur(function() { playheadActive = false; });
                jQuery().keydown(function(e) {
                    var id = jQuery(this).parents('.video').children('.g4sPlayer').attr('id');
                    var key = e.charCode || e.keyCode || 0;
                    if (playheadActive && key == 37) {
                        var currentTime = flowplayer(id).getTime();
                        var newTime = currentTime - 4 > 0 ? currentTime - 4 : 0;
                        flowplayer(id).seek(newTime);
                    }
                    if (playheadActive && key == 39) {
                        var currentTime = flowplayer(id).getTime();
                        var newTime = (currentTime + 3);
                        if (newTime > player.getClip().duration) { newTime = player.getClip().duration; }
                        flowplayer(id).seek(newTime);
                    }
                });

                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
