var slider = null, daFlow = null;

function onLoadFinish(container, opts) {
    var $nav = $j('#homeSliderNav ul'), startSlide = 0, $homeTalker = $j('#homeTalker'), $current = $j('#homeSlider').children('div.active');
    $homeTalker.html($current.find('.contents').html());
    $nav.children('li:eq(' + startSlide + ')').addClass('active');
}

function beforeSlide(container, itemsToDisplay, opts, direction) {
    if ($j('#movieBox:visible').size() > 0)
        $j('#movieBox').hide().empty();
    var currSlide = slider.CurrentPage() - 1, $homeTalker = $j('#homeTalker');
    $homeTalker.fadeOut(500, function () { $homeTalker.empty() });
}

function afterSlide(container, itemsToDisplay, opts, direction) {
    if ($j('#movieBox:visible').size() > 0)
        $j('#movieBox').hide().empty();
    var $nav = $j('#homeSliderNav ul'), $current = $j('#homeSlider').children('div.active'), currSlide = slider.CurrentPage() - 1, $homeTalker = $j('#homeTalker');
    $homeTalker.html($current.find('.contents').html()).fadeIn(500);
    $nav.children('li:eq(' + currSlide + ')').addClass('active').siblings('.active').removeClass('active');
}

function beforeSlideStateInfo() {
    $j('.slideshow-state').fadeOut();
}
function afterSlideStateInfo() {
    $j('.slideshow-state').fadeIn();
}

function tabLoadyThing($container, $start, opts) {
    $container.children().each(function () {
        tabloadMore($j(this).children('ul'));
    })

}

// get lists
// loop through lists
// check for kids
// if more than (count)
// hide
// add button
// on click
// if more kids than (count)
// show (count) kids
// else 
// show kids
// hide button

function tabloadMore($list) {
    var items = 3, fadeTime = 500;
    if (null != $list && $list.size() > 0) {
        if ($list.children().length > items) {
            $list.children(':gt(' + items + ')').hide();

            $j('a.show-more').click(function (e) {
                var $this = $j(this), $hidden = $list.children(':hidden');
                e.preventDefault();
                if ($hidden.size() > items)
                    $hidden.filter(':lt(' + (items + 1) + ')').fadeIn(fadeTime);
                    
                else {
                    $hidden.fadeIn(fadeTime);
                    $this.fadeOut(fadeTime);
                    
                }
                 
            });
        }
    }
} //End of function

$j(document).ready(function () {

    if ($j('#homeSlider').size() > 0)
        slider = $j('#homeSlider').ryslider({ speed: 1000, autoPlay: true, enablePlayStop: true, wrapSlider: true, renderPageButtons: false, renderNextButton: false, renderPrevButton: false, renderPlayButton: false, renderStopButton: false, renderStateInfo: true, stateSelector: '#stats', autoPlayInterval: 7000, beforeSlideFunction: beforeSlide, afterSlideFunction: afterSlide, afterCreateFunction: onLoadFinish, prevSelector: '#prevButton', nextSelector: '#nextButton' });
    if ($j('.slideshowrapper').size() > 0)
        slider = $j('.slideshowrapper').ryslider({ wrapperClass: 'fullSlider', speed: 1000, autoPlay: true, enablePlayStop: false, wrapSlider: true, renderPageButtons: false, renderNextButton: true, renderPrevButton: true, renderPlayButton: false, renderStopButton: false, renderStateInfo: true, stateContainerClass: 'slideshow-state', beforeSlideFunction: beforeSlideStateInfo, afterSlideFunction: afterSlideStateInfo });

    if ($j('.tabbox').size() > 0) {
        $j('.tabbox').rytabs({ afterCreateFunction: tabLoadyThing });
    }

    $j('.calendarIcon').hover(function () { $j(this).addClass('hover'); }, function () { $j(this).removeClass('hover'); });
    $j('#featureButton').parent().css({ top: "355px" });
    $j('#featureButton').click(function (e) {
        var $me = $j(this);
        $nextPrev = $j('.next_button ,.previous_button');
        if ($me.parent().hasClass('open')) {
            $nextPrev.fadeIn(250);
            $me.parent().animate({ top: "355px" }, 500, "easeInOutQuad", function () {
                $me.removeClass('active');
                $j(this).removeClass('open');
                if (daFlow != null)
                    daFlow.play();
                else
                    slider.Play();
            });
        }
        else {
            $nextPrev.fadeOut(250);
            $me.parent().animate({ top: "-1px" }, 500, "easeInOutQuad", function () {
                $me.addClass('active');
                $j(this).addClass('open');
            });
            if (daFlow != null)
                daFlow.pause();
            slider.Stop();
        }
        e.preventDefault();
    });
    $j('#homeSliderNav').find('li').each(function (index) {
        var $me = $j(this);
        $me.click(function () {
            slider.GotoPage(index + 1);
        });
        $me.hover(function () { $me.addClass('hover'); }, function () { $me.removeClass('hover'); });
    });
    $j('#homeSlider').children('.slider_content').children('p.playButton').children('a').click(function (e) {
        var $me = $j(this);
        slider.Stop();
        $j('#homeTalker > p.playButton > a').addClass('active').html('Stop video').addClass('playing');
        $j('#movieBox').show();
        daFlow = flowplayer(
            "movieBox",
            { src: "/assets/flowplayer/flowplayer/flowplayer.commercial-3.2.7b.swf", wmode: 'opaque' },
            {
                key: '#@dedb5e1de3dd3f8418e',
                play: {
                    url: '/assets/images/presentation/career-play.gif',
                    width: 136,
                    height: 83
                },
                clip: { url: $me.attr('href'), autoPlay: true }
            });
        e.preventDefault();
    });



    //$j(document).pngFix();

    // 'if' statments prevent plugsin being loaded if not used on page
    // plugins are separate to allow for different variable to be set

    if ($j('#navWrapper').length) {
        $j('#navWrapper').RYnavDropdown();
    };

    // ACCORDIANS #######################################################################################   
    // home page accordian
    //if ($j('#home-slider').length) {
    //  $j('#home-slider').RYaccordian({listClick: 'h2'});
    //};

    // country page accordian
    if ($j('#countryAccordian').length) {
        $j('#countryAccordian').RYaccordian({ listClick: 'h2', startIndex: 0 }); //
    };

    // services group with hidden services links
    if ($j('#primaryAccordian').length) {
        $j('#primaryAccordian').RYaccordian({ startIndex: 1, colapseOthers: 'no' });
    };

    // right col, related info accordian
    if ($j('#relatedInfo #relatedAccordian').length) {
        $j('#relatedAccordian').RYaccordian({ listClick: 'h3', duration: 400 });
        $j('#relatedAccordian li.relatedlinks p:last').css("padding-bottom", "10px");
    };

    if ($j('#relatedStuff #relatedAccordian').length) {
        $j('#relatedAccordian').RYaccordian({ listClick: 'h3', duration: 400, startIndex: '' });
        $j('#relatedAccordian li.relatedlinks p:last').css("padding-bottom", "10px");
    };

    if ($j('#contactUs #relatedAccordian').length) {
        $j('#relatedAccordian').RYaccordian({ listClick: 'h2', startIndex: '', autoStartIndex: 'yes', autoScrollTo: 'yes', duration: 1000 }); //
    };

    if ($j('#relatedMedia #relatedAccordian').length) {
        $j('#relatedAccordian').RYaccordian({ listClick: 'h3', startIndex: 0, autoStartIndex: 'yes', autoScrollTo: 'no', duration: 300 }); //
    };


    if ($j('#relatedMedia #infoAccordian').length) {
        $j('#infoAccordian').RYaccordian({ listClick: 'h3', startIndex: 0, autoStartIndex: 'yes', autoScrollTo: 'no', duration: 300 }); //
    };

    // projects advanced search
    if ($j('#advFilter .accordian').length) {
        $j('.accordian').RYaccordian({ listClick: 'h4', startIndex: '' }); //
    };

    // sitemap
    /*if ($j('#sitemap').length) {
    $j('#sitemap').RYaccordian({listClick: 'h2', startIndex: 0,autoStartIndex: 'yes', autoScrollTo: 'yes', duration:1000}); //
    };*/


    // CAROUSEL ####################################################################################### 
    // homepage carousel
    if ($j('#home-slider .carousel').length) {
        $j('.carousel').RYcarousel();
    };

    // project browse + banner carousel
    if ($j('#browseProjects .carousel, .banner .carousel').length) {
        $j('.carousel').RYcarousel();
    };

    // image gallery carousel (lightbox imagegallery is called from RYlightbox.js)
    if ($j('#innerHTML .carousel').length) {
        $j('.carousel').RYcarousel({ variableWidth: 'false', switchHeaders: 'true', autoPlay: 'true' });
    };

    // LIGHTBOXES #######################################################################################   
    if ($j('.lightbox').length) {
        if ($j('ul#services .lightbox').length) {
            $j('.lightbox').each(function () {
                var href = $j(this).attr("href");
                $j(this).attr("href", href + '?show-accordian-list=true');
                $j(this).RYlightbox({ innerContent: ' .serviceList' });
            });
        } else {
            $j('.lightbox').RYlightbox({ innerContent: ' #innerHTML' });
        }
    };

    // NAVIGATION #######################################################################################   
    // add "curent" class to selected top navigation (done via javascript so can cache rendering without varying by data)
    var selectedPath = window.location.pathname;
    $j('#navigation-primary > ul > li > a').each(function () {
        var navPath = $j(this).attr("href");
        navPath = navPath.substring(0, navPath.indexOf(".aspx")); //Remove extention

        if (navPath.lastIndexOf("/") > 0) {
            navPath = navPath.substring(0, navPath.lastIndexOf("/")); //Only return first level path componant of tree
        }

        if (selectedPath.indexOf(navPath) == 0) {
            $j(this).parent().addClass("current");
            return false;
        }
    })


    // OTHER RANDOM SCRIPTS ####################################################################################### 





    // emptys search box when selected
    $j('input[type=text]:not(#keywordSearch input[type=text])').each(function () {
        var text;
        $j(this).focus(function () {
            text = $j(this).attr('value');
            if ($j(this).attr('value') === 'Search' || 'Enter...') {
                $j(this).attr('value', '')
            }
        });
        $j(this).blur(function () {
            if ($j(this).attr('value') === '') {
                $j(this).attr('value', text)
            }
        })
    })

    // checks URL for # and opens lightbox if exists
    function autoOpenLb() {
        var url = new String(document.location)
        var hash = (url.indexOf('#'));
        if (hash > 0 && hash + 1 != url.length) {
            var href = (url.slice(hash, url.length));
            var start = (href.indexOf(':'))
            href = (href.slice(start + 1, href.length))
            $j('a[href^=' + href + ']').click();
        }
    }
    autoOpenLb()

    // Drop down radio buttons in news section
    if ($j('fieldset.news').length) {
        countrySelect();
    }
    function countrySelect() {
        var speed = 200;
        $j('fieldset.news div .checkbox:checked').each(function () {
            speed = 0;
            show(this);
        });
        $j('fieldset.news div .checkbox').click(function () {
            speed = 500;
            if ($j(this).is(':checked')) {
                show(this)
            } else {
                hide(this)
            }
        })
        var siblings;

        function show(checkbox) {
            siblings = $j(checkbox).parent().siblings().length;
            var newHeight = (siblings + 1) * 1.5;
            $j(checkbox).parent().css('backgroundColor', '#f5f5f5')
            if (siblings != 0) {
                $j(checkbox).parent().parent().animate({ height: newHeight + 'em' }, speed);
            }
        }
        function hide(checkbox) {
            if (siblings != 0) {
                $j(checkbox).parent().parent().animate({ height: '1.5em' }, speed);
            } else {
                speed = 0;
            }
            $j(checkbox).parent().animate({ opacity: 1 }, speed, function () {
                $j(this).css('backgroundColor', '#fff')
            })
        }
    }

    // Advanced search options
    if ($j('#advFilter').length) {
        $j('#advFilter').fn_RYadvSearch();
    };


    // FLASH #######################################################################################    
    // flash experience arup player
    // this is now inserted programtically in layouts/Arup.aspx.cs only in anoymous mode
    //  if ($j('#experience').length) {
    //      loadExperiencePlayer();
    //  };

    // flash video player
    if ($j('.VPcontainer').length) {
        loadVideoPlayer();
    }
    if ($j('#alternativeOfficeMap').length) {
        loadMap()
    }

    // IE Hover #####################################################################################   
    $j('.submitImage, a.lightboxLink').hover(function () {
        $j(this).addClass('hover')//.css('border','1px solid #000')
    }, function () {
        $j(this).removeClass('hover')//.css('border','none')
    })


    // search form button rollover ##################################################################

    $j("input.submitb").hover(function () {
        $j(this).attr("src", "/assets/images/presentation/search_roll.jpg");
    }, function () {
        $j(this).attr("src", "/assets/images/presentation/search.jpg");
    });

    $j("#what-we-do-button a").click(openExp);

    $j(".frameText").wrap("<div class='frameContainer'/>")




});   // end document.ready 
// #############################
// #############################
// #############################
// #############################



// used to switch path for local vs live
// var flashExpPath is set in header of HTML in local
var local;
var flashExpPath;

if (local == 'true') {
    flashExpPath = "assets/flash/experience/build/";
    flashMapPath = "assets/flash/officeMap/build/";
} else {
    flashExpPath = "/assets/flash/experience/build/";
    flashMapPath = "/assets/flash/officeMap/build/";
}

// needs to be outside of "document.ready" to work
// set globally because they are called by other plugins
var swfName = "experienceFlash";
var containerName = "experience";


function openExp() {
    movieById(swfName).openExperience();
}

function closeExp() {
    movieById(swfName).closeExperience();
}

function onExperienceOpened() {
    movieById(swfName).height = "100%";
    document.getElementById(containerName).style.height = "100%";
}

function onExperienceClosed() {
    movieById(swfName).height = "1";
    document.getElementById(containerName).style.height = "1px";
}

function movieById(id) {

    return (navigator.appName.indexOf("Microsoft") != -1) ? document.getElementById(id) : document[id];
}

var flashvars = { xmlUrl: "/System/ExperienceArupXml.aspx" };

var params = {};
params.play = "false";
params.loop = "false";
params.menu = "false";
params.quality = "best";
params.scale = "noscale";
params.salign = "tl";
params.wmode = "transparent";
params.bgcolor = "#FFFFFF";
params.devicefont = "false";
params.seamlesstabbing = "true";
params.swliveconnect = "false";
params.allowfullscreen = "true";
params.allowscriptaccess = "always";
params.allownetworking = "all";

var attributes = {};
attributes.id = swfName;
attributes.name = swfName;
attributes.align = "middle";

//swfobject.embedSWF(flashExpPath+"swfs/Experience.swf", "expContainer", "100%", "100%", "9.0.115", flashExpPath+"js/expressInstall.swf", flashvars, params, attributes);

//stayTop()

/**********************************************************************/
/**********************************************************************/

/* most of this is no longer being used. I've left it in just in case */

/**********************************************************************/
/**********************************************************************/
/*
function openExperience(){
var windowHeight = $j(window).height()
movieById(swfName).height = windowHeight;
$j('#'+containerName).css('height', windowHeight);      //.css('height','100%');

if ($j('#lightboxBg').length){
} else {    
$j('body').append('<div id="experienceBg"></div>');
$j('#experienceBg').css({'width':$j(window).width(), 'height': $j(document).height()-$j(window).height(), 'top': $j(window).height(), 'opacity':.95})
}
pauseVideo();
}
function closeExperience(){
movieById(swfName).height = "26";
$j('#'+containerName).css('height','26px');
$j('#experienceBg').remove()
}
*/
function pauseVideo() {
    if ('#videoPlayer') {
        movieById("videoPlayer").pauseVideo();
    }
}

/*function movieById(id){
return (navigator.appName.indexOf("Microsoft") != -1)? document.getElementById(id) : document[id];
}*/


// sigh
var isIDevice = {
    isIPod: navigator.userAgent.match(/iPhone/i) != null,
    isIPhone: navigator.userAgent.match(/iPod/i) != null,
    isIPad: navigator.userAgent.match(/iPad/i) != null
}

// sets video size in lightbox
var ARUP_videoWidth = 642, ARUP_videoHeight = 382;

function loadVideoPlayer() {
    $j('.VPcontainer').each(function () {

        var $input = $j(this).children('input[type=hidden]'),
    thisURL = $input.attr('value');

        if ($input.attr('id') == "embedscript"){
            if (isIDevice.isIPad || isIDevice.isIPhone || isIDevice.isIPod)
                $j('.VPcontainer').prepend("<script type='text/javascript' src='" + thisURL + "'></script>");
        }
        else {
            if (!(thisURL === undefined)) {
                var VP_flashvars = {}
                VP_flashvars.smilPath = thisURL;
                
                $j('.VPcontainer').flash(
                    {
                        src: flashExpPath + 'swfs/VideoPlayer.swf',
                        width: ARUP_videoWidth,
                        height: ARUP_videoHeight,
                        id: "videoPlayer",
                        name: "videoPlayer",
                        flashvars: VP_flashvars
                    },
                    {
                        expressInstall: true,
                        version: '9.0.115'
                    });
            }
        }
    });
}
/*
function loadExperiencePlayer(){
var EX_flashvars = {xmlUrl:"/System/ExperienceArupXml.aspx"};
$j('#experience').flash(
{ 
src: flashExpPath+'swfs/Experience.swf',
width: '100%',
height: '100%',
id: swfName,
name: swfName,
flashvars: EX_flashvars
},
{
expressInstall: true,
version: '9.0.115'
}
);
}
*/
// global locations settings
function resizeMap(height) {
    movieById('OfficeMap').height = height;
}

/*function movieById(id){
return (navigator.appName.indexOf("Microsoft") != -1)? document.getElementById(id) : document[id];
}*/

function loadMap() {
    $j('#alternativeOfficeMap').flash(
        {
            src: flashMapPath + 'swfs/Loader.swf',
            base: MAP_base,
            width: MAP_size.width,
            height: MAP_size.height,
            id: "OfficeMap",
            name: "OfficeMap",
            flashvars: MAP_flashvars
        },
        {
            expressInstall: true,
            version: '9.0.115'
        }
    )
    //if(swfmacmousewheel) swfmacmousewheel.registerObject(attributes.id);
};

// control videos


