﻿<!--
/*
* ## CONFIG ##
*/
// Log to Firebug Console, set to false for Live!
var _debug = true;
var $j = jQuery.noConflict();
/*
* ## END CONFIG ##
*/

/* General functions
----------------------------------------------- */

// log to firebug console - remove for production environment
function debug(message) {
    if (_debug) if (window.console) console.log(message);
}

// addtion to find control from .Net client ID
$j.extend({
	clientID: function(id) {
		return $j("[id$='" + id + "']");
	}
});
// -->


/*
* open windows in external window
*/ 
function setLinkRel()
{
  $j('a[rel="external"]').click( function() {
      window.open( $j(this).attr('href') );
      return false;
  });
}

function setExternalLinks()
{
    $j.expr[':'].external = function(obj){
        return !obj.href.match(/^mailto\:/)
                //&& !obj.href.endsWith("javascript:")
                //&& !obj.href.endsWith("#")
                && !obj.href.startsWith("javascript:")
                && !obj.href.startsWith("#")
                && (obj.hostname != location.hostname)
                && !obj.href.startsWith("/")
                || (obj.pathname.match(/.pdf$/));
        
    };

    // Opens link in new window
    $j('a:external').click( function(){
        window.open( $j(this).attr('href'))
        return false
    });    
}

function attachKeypressToSearchBox()
{
    $j("#ctl00_ctl00_ctl00_Content_HeaderLayout_0_LanguageSelector_MagusSearch1_SiteSearch").keyup(function(event){
        if(event.keyCode == 13)
        {
             $j("#ctl00_ctl00_ctl00_Content_HeaderLayout_0_LanguageSelector_MagusSearch1_SiteSearchSubmit").click();       
        }
    });
}


/*
* display error message
*/ 
function alertError(err)
{
    txt="Sorry, there was an error on this page.\n\n";
    txt+="Error description: " + err + "\n\n";
    txt+="Click OK to continue.\n\nThen refresh your page.";
    alert(txt);
}

/* Homepage Banner
----------------------------------------------- */
function ftnScaleUp($clickedElement, intIndex) {
    $clickedElement.addClass("ani").animate({
        fontSize: "3em"
    },
    {
        duration: 400,
        complete: function() {
            $clickedElement.removeAttr("style").parent().addClass("selected");
            aniActive = false;
            
            // show respective panels
            $j(".home_banner .mb div").hide();
            $j(".home_banner .mf div").hide();
            $j(".home_banner .mb div").eq(intIndex).show();
            $j(".home_banner .mf div").eq(intIndex).show();
        }
    });
}

function ftnScaleDown($element) {
    $element.animate({
        fontSize: "2em"
    },
    {
        duration: 400,
        complete: function() {
            $element.removeAttr("style").parent().removeClass("selected");
        }
    });
}


// fixes HTML encoded items in a dropdown list
function FixHtmlEncodedSelectOptions()
{    
    $j("select option").each(function(){
        $j(this).html($j(this).text());                
    });
}

function setupHomepageBanner()
{
    $j(".home_banner").each(function(index){
        var thisHomeBanner = $j(this);
        $j(".mh li a",thisHomeBanner).unbind().click(function() {
            var $clickedElement = $j(this);           
            var $selectedElement = $j(".mh li.selected a",thisHomeBanner);
            var intIndex = $clickedElement.parent().index();
            if (!$clickedElement.parent().hasClass("selected")) {                
                $j(".mb div",thisHomeBanner).hide();
                $j(".mf div",thisHomeBanner).hide();
                $j(".mb div",thisHomeBanner).eq(intIndex).show();
                $j(".mf div",thisHomeBanner).eq(intIndex).show();                                
                $j(".mf div img", thisHomeBanner).eq(intIndex).show();       
                $j(".mh li.selected",thisHomeBanner).removeClass("selected")
                $clickedElement.removeAttr("style").parent().addClass("selected");                                
            }                                    
            return false;
        });
        $j(".mh li:last-child",thisHomeBanner).addClass("last");
        // for each mb with drop down then use label text as first option
        $j(".mb div select",thisHomeBanner).each(function(index) {
            $option = $j('<option/>').text($j(this).parent().find('label').text());
            $option.attr("value","select").attr("selected","true");
            $j(this).prepend($option);
        });
        // setup interface
        $j(".mh",thisHomeBanner).show();
        $j(".mb div",thisHomeBanner).eq(0).show();
        $j(".mf div",thisHomeBanner).eq(0).show().parent().show();
    });        
}
/* Tabbed List
----------------------------------------------- */
function setupTabbedList()
{
    
    $j('.tabbed_list').not('.stl_processed').each(function(listIndex){
       $tabbedList = $j(this); 
       
       $tabs = $j('<ul/>').addClass('tabs');
       $tabbedList.prepend($j('<div/>').addClass('mh').append($tabs));
       $j('> .mb > h2', $tabbedList).each(function(intIndex) {
            // create and append tabs
            $j(this).html('<span>'+ $j(this).text() +'</span');
            $li = $j('<li/>').append($j(this));
            if(intIndex == 0) $li.addClass('selected');
            $tabs.append($li);
            //if(intIndex > 0) $j('.mb > ul', $tabbedList).eq(intIndex).hide();
            $j(this).click(function() {
                $j('> .mb > ul',$tabbedList).hide();
                $j('> .mb > ul',$tabbedList).eq(intIndex).show();
                $j('> .mf',$tabbedList).eq(intIndex).show();
                $j('li', $j(this).parent().parent()).removeClass('selected');
                $j(this).parent().addClass('selected');
                return false;
            });
            $j('> .mb > ul', $tabbedList).hide();
            $j('> .mb > ul', $tabbedList).eq(0).show();
        }); 
        $tabbedList.addClass('stl_processed');
    });  
}

/* Shares
----------------------------------------------- */
function setupShares()
{
    $shares = $j('.shares');

    $j('.mf li', $shares).each(function(intIndex) {
        $j(this).click(function() {
          $j('.mb div', $shares).hide();
          $j('.mb div', $shares).eq(intIndex).show();
          $j('a',$j(this).parent()).removeClass('selected');
          $j('a',this).addClass('selected');
          return false;
        });
    });
    if ($shares)
    {
        var instance = Sys.WebForms.PageRequestManager.getInstance();
        if (!(instance)) return;
        instance.add_endRequest(function(s, e){
            setupShares();
        });
    }

}

/* Correct the static nav classes
----------------------------------------------- */
function selectCorrectNavOption()
{
    var url = window.location.pathname;
    $j(".static_navigation li a").each(function(index) {
	    var href = $j(this).attr("href");
	    if(url.toLowerCase().indexOf(href.toLowerCase()) > -1)
        {
		    $j(this).parent().attr("class", "selected");
	    }
	    else
	    {
		    $j(this).parent().attr("class", "");
	    }
    });
}

/* Setup countries drop down
----------------------------------------------- */
function setupCountriesDropDown() {
if (typeof(countries) === undefined || typeof(countries)=='undefined') return;
try
  {
    $countriesContainer = $j('<div/>').addClass('countries_container').hide();
    $countries = $j('<ul/>');    
    var url = window.location.pathname;
    var currentlySelected = false;
    for(var i in countries)
    {
        if(countries[i].Brand == _currentBrand && (url.toLowerCase().indexOf(countries[i].Uri.toLowerCase()) > -1))
        {
            currentlySelected = true;
        }
        
            //if(countries[i].Name == "Brazil") debug("test");
            $flagImg = $j('<img/>').attr('src',countries[i].Image).attr('alt','').attr('width','26').attr('height','26');
            $countryLink = $j('<a/>').attr('href',countries[i].Uri).text(countries[i].Name).prepend($flagImg);
            $li = $j('<li/>').append($countryLink);
            $countries.append($li);
        
    }
    $countriesContainer.append($countries);
    $j("#navigation").append($countriesContainer); 

    $countriesLink = $j('<a/>').addClass('country_selector').attr('href','#');
    
    /*var pathsplit = window.location.pathname.split("/");        
               
    if(pathsplit[1].length > 0)
    {      */     
    var bIsCountryThere = false;    
        for(var j in countries)
        {            
            if(countries[j].Brand == _currentBrand && (url.toLowerCase().indexOf(countries[j].Uri.toLowerCase()) > -1))
            {   
                $countriesLink.text(countries[j].Name);
                bIsCountryThere = true;                
            }
        } 
        if(bIsCountryThere == false)
        {
            $countriesLink.text($j('.countries_label').text());
        }      
    /*}  
   else{
       $countriesLink.text($j('.countries_label').text());
   }  */    
        
    $countriesLink.toggle(function() {
      $countriesContainer.show();
      $j(this).addClass("selected");
      if(currentlySelected)
      {
          $countriesLink.addClass("selected");
      }
    }, function() {
      $countriesContainer.hide();
      $j(this).removeClass("selected");
      if(currentlySelected)
      {
          $countriesLink.addClass("selected");
      }
    });
    
    if(currentlySelected)
      {
          $countriesLink.addClass("selected");
      }
      
    $arrowImg = $j('<img/>').attr('src',_ImageFolder + 'modules/arrow_down.gif').attr('alt','');
    $countriesLink.append($arrowImg);

    $j('.country_navigation').replaceWith($countriesLink);

  }
catch(err)
  {
    debug(err);
  }

}

/* Hide and show flash when a lightbox is opened and closed
------------------------------------------------------------*/
function hideAndShowFlashOnLightBoxDisplay()
{
    $j("a.cboxElement").click(function() {
        $j("iframe#player").parent().hide();
    });

    $j("div#cboxClose").click(function() {
        $j("iframe#player").parent().show();
    });
}

/* Setup print button
----------------------------------------------- */
function setupPrintButton()
{
    $printButton = $j('.page_tools a[href="#"]');
    $printButton.unbind().click(function() {
          window.print();
          return false;
        });
    if (!window.print) {$printButton.parent().hide();}
}

/* Reload banner flash after postback
----------------------------------------------- */
function reloadFlash(selector)
{
    var script = "<script type='text/javascript'>" + 
                    $j(selector).html() + 
                 "</script>";

    $j(script).replaceAll(selector);
    
    if(isIE)
    {
        $j.each($j("div.home_banner .mf script"), function(){
            script = "<script type='text/javascript'>" + 
                        $j(this).html() + 
                     "</script>";

            $j(script).replaceAll($j(this));
        });
    }
}

// Test for IE
function isIE() {
    if($j.browser.msie) {
        return true;
    }
    else {
        return false;
    }
}

/* On Page Load
----------------------------------------------- */

//ASP.NET pageload event for full and partial postbacks
function pageLoad() {
    setupHomepageBanner();
    attachKeypressToSearchBox();
    // reload banner flash
    var selector = "div.home_banner .mf div[style='display: block;'] script";
    reloadFlash(selector);
    $j("div.home_banner .mh a").click(function(event){
        reloadFlash(selector);
    });
    initSlidingFeatureGallery();
    initVerticalTabbedFeatureGallery();
    expandRootNode();
}
  
$j(document).ready(function () {
  setExternalLinks();
  
  hideAndShowFlashOnLightBoxDisplay();
  initLoopedSlider();
  setVideoBoxLinks();

  setupTableRowAlts();
  formElements(); 
  
  cleanPowerhidePrimaryNavigationHomeLink();
  cleanPowerGalleryModules(); 
  
  foundationLightboxPagination();
  foundationMediaSignpostGallery(); 
  
  webtvMediaSignpostAccordian(); 
  webtvSearchBox();
  webtvDropdown();
  webtvSignpostSlider();
  webtvMediaTeaserGallery();
  webtvFilters();
  webtvEmbedLink();
});
$j(function() {
    
    //set script enabled hook
    $j('body').addClass("jse");
    
    // set site search box text
    $j('.site_search').example(function() {
        return $j(this).attr('title');
    });
    
     // set site search box text
    $j('.keyword_search').example(function() {
        return $j(this).attr('title');
    });
    
    //A little temp style fix for a signpost
    $j.each($j(".type5").parents("div.PBViewing"), function() {
        $j(this).css("width", "319px");
    });
    $j(".shares").parents("div.PBViewing").css("width", "");

    setupCountriesDropDown();    
    setLinkRel();
    selectCorrectNavOption();
    hideAndShowFlashOnLightBoxDisplay();
    
    FixHtmlEncodedSelectOptions();
    EnsureTitleSurvivesAsyncCall()
    //setExternalLinks() Moved further up the page to hopefully avoid issues; 
    
    //if elements and corresponding functions exist then apply
    if ($j('.home_banner')[0] && $j.isFunction(setupHomepageBanner())) setupHomepageBanner();
    if ($j('.shares')[0] && $j.isFunction(setupShares())) setupShares();
    if ($j('.tabbed_list')[0] && $j.isFunction(setupTabbedList())) setupTabbedList();
    if ($j('.page_tools')[0] && $j.isFunction(setupPrintButton())) setupPrintButton();
 
    // qTip stuff
      $j.fn.qtip.styles.alstom = { // Last part is the name of the style
          width: 200,
          background: '#6790d0',
          color: '#ffffff',
          padding: 0,
          textAlign: 'left',
          border: {
              width: 1,
              radius: 2,
              color: '#6790d0'
          },
          tip: true
      }
      // Match all link elements with href attributes within the content div
      $selected = $j('.banner_with_nav .selected > a');

      $selected.qtip({
        content: $j('ul', $selected.parent()),
        show: 'mouseover',
        hide: { fixed: true, delay: 1000 },
        position: {
          corner: {
              tooltip: 'leftMiddle', // Use the corner...
              target: 'rightMiddle' // ...and opposite corner
          }
        },
        style: {
          name: 'alstom' // Style it according to the preset 'cream' style
        }
      });
 
});


/* Looped Slider
----------------------------------------------- */

function initLoopedSlider(){
    var loopedSlider = $j('.loopedSlider');
    if(loopedSlider.length > 0){
        var slides = $j('.slides > div', loopedSlider);
        checkLoopedSliderMediaTypes(slides);
        loopedSlider.append(buildLoopedSliderPagination(slides.length));
        $j('.loopedSlider').loopedSlider();
    }
}

function checkLoopedSliderMediaTypes(slides){
    slides.each(function(index){
        if($j(this).find('div').size() > 0)
            $j(this).addClass('videoSlide');
    });
}

function buildLoopedSliderPagination(slideCount){
    var output='<a href="#" class="previous">previous</a><a href="#" class="next">next</a><ul class="pagination">';
    for(var i = 1; i<=slideCount; i++){
        output += '<li><a href="#"></a></li>';
    }
    output += '</ul>';
    return output;  
}

/* Feature Galleries
----------------------------------------------- */

var loopInterval; 
var tabbedLoopInterval;

function initSlidingFeatureGallery(){
    var slidingFeatureGallery = $j('.slidingFeatureBanner');
    if(slidingFeatureGallery.length > 0){
        // Initial vars
        var totalWidth = 0;
        var slideSpeed = 500;
        var fadeSpeed = 300;
        var distance = 0;
        var slideContainer = $j('.mf',slidingFeatureGallery);
        var totalSlides = $j('.mf',slidingFeatureGallery).children().length;
        var width = parseInt($j('.mf',slidingFeatureGallery).children(":eq(0)").css('width'),10);
        var contentBoxes = $j('.mb div',slidingFeatureGallery);
        var loopIntervalTime = 12000; // 8 seconds
        var clickEnabled = true;
        
        // Add appends
        slidingFeatureGallery.append('<a href="javascript:" class="scrollers scrollLeft"></a><a href="javascript:" class="scrollers scrollRight"></a>');
        var paginationOutput = '<ul class="pagination">';
        for(var i = 0; i<totalSlides; i++){
            paginationOutput += '<li><a href="javascript:" rel="'+(i+1)+'"></a></li>' ;
        }
        paginationOutput += '</ul>';
        slidingFeatureGallery.append(paginationOutput);
        
        // Initial set up
        var currentSlide = 1;
        $j('.mf div',slidingFeatureGallery).each(function(index){
            var slideWidth = parseInt($j(this).css('width'),10);
            $j(this).css('left',(slideWidth * index)+'px');
            totalWidth += slideWidth;
        });        
        slideContainer.css('width', totalWidth+'px');
        slideContainer.css('left', 0);
        var pagination =  $j('ul.pagination li a',slidingFeatureGallery);
        pagination.eq(0).addClass('selected');
        contentBoxes.hide();
        contentBoxes.eq(0).show();
        loopInterval = setInterval(function(){
            $j('a.scrollRight',slidingFeatureGallery).click();
        },loopIntervalTime);
                
        // Setup scroll left click
        $j('a.scrollLeft',slidingFeatureGallery).unbind().click(function(){
             if(clickEnabled){
                 window.clearInterval(loopInterval);
                 clickEnabled = false;
                 hideVideoBox(); // if required
                 currentSlide -= 1;
                 distance = (-(currentSlide*width-width));
                 if (totalSlides<3){
                    if(currentSlide===0){slideContainer.children(':eq('+(totalSlides-1)+')').css({position:'absolute',left:(-width)});}
                    if(currentSlide===1){slideContainer.children(':eq(0)').css({position:'absolute',left:0});}
                 }
                 contentBoxes.hide();
                 slideContainer.animate({left: distance}, slideSpeed,function(){
                    if(currentSlide === 0 ){
                        currentSlide = totalSlides;
                        slideContainer.children(':eq('+(totalSlides-1)+')').css({position:'absolute',left:(totalSlides*width-width)});
                        slideContainer.css({left: -(totalSlides*width-width)});
                        slideContainer.children(':eq(0)').css({left:(totalSlides*width)});
                    }
                    if (currentSlide===2 ) slideContainer.children(':eq(0)').css({position:'absolute',left:0});
                    if (currentSlide===1) slideContainer.children(':eq('+ (totalSlides-1) +')').css({position:'absolute',left:-width});
                    pagination.removeClass('selected');
                    pagination.eq(currentSlide-1).addClass('selected');
                    contentBoxes.eq(currentSlide-1).fadeIn(200,function(){
                        clickEnabled = true;
                    });
                 });
             }
        });
        
        // Set up scroll right click
        $j('a.scrollRight',slidingFeatureGallery).unbind().click(function(){
            if(clickEnabled){
                //window.clearInterval(loopInterval);
                clickEnabled = false;
                hideVideoBox(); // if required
                currentSlide += 1;
                distance = (-(currentSlide*width-width));
                if(totalSlides<3){
                    if (currentSlide===3){slideContainer.children(':eq(0)').css({left:(totalSlides*width)});}
                    if (currentSlide===2){slideContainer.children(':eq('+(totalSlides-1)+')').css({position:'absolute',left:width});}
                }
                contentBoxes.hide();
                slideContainer.animate({left: distance}, slideSpeed, function(){
                    if(currentSlide === totalSlides+1){
                        currentSlide = 1;
                        slideContainer.css({left:0},function(){slideContainer.animate({left:distance})});
                        slideContainer.children(':eq(0)').css({left:0});
                        slideContainer.children(':eq('+(totalSlides-1)+')').css({ position:'absolute',left:-width}); 
                    }
                    if (currentSlide===totalSlides) slideContainer.children(':eq(0)').css({left:(totalSlides*width)});
                    if (currentSlide===totalSlides-1) slideContainer.children(':eq('+(totalSlides-1)+')').css({left:(totalSlides*width-width)});
                    pagination.removeClass('selected');
                    pagination.eq(currentSlide-1).addClass('selected');
                    contentBoxes.hide();
                    contentBoxes.eq(currentSlide-1).fadeIn(fadeSpeed,function(){
                        clickEnabled = true;
                    });
                });
            }
        });
        
        // Set up pagination click
        pagination.unbind().click(function(){
            if(clickEnabled){
                window.clearInterval(loopInterval);
                clickEnabled = false;
                hideVideoBox(); // if required
                currentSlide = parseInt($j(this).attr("rel"),10);
                distance = (-(currentSlide*width-width));
                contentBoxes.hide();
                slideContainer.children().fadeOut(fadeSpeed, function(){
                    slideContainer.css({left: distance});
                    slideContainer.children(':eq('+(totalSlides-1)+')').css({left:totalSlides*width-width});
                    slideContainer.children(':eq(0)').css({left:0});
                    if(currentSlide===totalSlides){slideContainer.children(':eq(0)').css({left:(totalSlides*width)});}
                    if(currentSlide===1){slideContainer.children(':eq('+(totalSlides-1)+')').css({ position:'absolute',left:-width});}
                    pagination.removeClass('selected');
                    pagination.eq(currentSlide-1).addClass('selected');
                    contentBoxes.eq(currentSlide-1).show();
                    slideContainer.children().fadeIn(fadeSpeed, function() {
                        //removing filter from IE
                        if(jQuery.browser.msie) {
                            $j(this).get(0).style.removeAttribute('filter');
                        }
                        clickEnabled = true;
                    });
                });
            }
        });
              
        /* Special case where there is only 1 banner */
        if(totalSlides == 1){
            window.clearInterval(loopInterval);
            $j('a.scrollers, ul.pagination',slidingFeatureGallery).hide();
        }
    }
}

function initVerticalTabbedFeatureGallery(){
    /* Based on setupHomepageBanner() */    
    var verticalFeatureBanner = $j('.verticalFeatureBanner');
    if(verticalFeatureBanner.length > 0){
        // Initial vars
        var clickEnabled  = true;
        var currentTab = 0;
        // Initial setup
        $j('.mb div',verticalFeatureBanner).hide().eq(currentTab).show();
        $j('.mf div',verticalFeatureBanner).hide().eq(currentTab).show();
        var verticalBannerTrigger = $j('.mh ul li a',verticalFeatureBanner); 
        verticalBannerTrigger.attr("href", "javascript:");  // take off actual link, and replace with # (stops popups from opening when scrolling through items)
        // Loop
        clearInterval(tabbedLoopInterval);
        tabbedLoopInterval = setTimeout(function(){
            currentTab++;
            if(currentTab == verticalBannerTrigger.length)
                currentTab = 0;
            verticalBannerTrigger.eq(currentTab).click();
        },12000);        
        // Set up tab click
        verticalBannerTrigger.unbind().click(function(){
            if(clickEnabled){
                clickEnabled = false;
                hideVideoBox(); // if required
                var $clickedElement = $j(this);           
                var $selectedElement = $j('.mh li.selected a',verticalFeatureBanner);
                var intIndex = $clickedElement.parent().index();
                currentTab = intIndex;
                if (!$clickedElement.parent().hasClass('selected')) {                              
                    $j('.mh li.selected',verticalFeatureBanner).removeAttr('style').removeClass('selected')
                    $clickedElement.removeAttr('style').parent().addClass('selected');
                    $j('.mb div',verticalFeatureBanner).hide().eq(intIndex).show();
                    $j('.mf div',verticalFeatureBanner).fadeOut('slow').eq(intIndex).fadeIn('slow', function(){
                        clickEnabled = true;
                    });                               
                }
                else
                    clickEnabled = true;
                clearInterval(tabbedLoopInterval);
                tabbedLoopInterval = setTimeout(function(){
                    currentTab++;
                    if(currentTab == verticalBannerTrigger.length)
                        currentTab = 0;
                    verticalBannerTrigger.eq(currentTab).click();
                },12000);                               
            }
            return false;
        });
        // Add class last (may be useful)
        $j('.mh li:last-child',verticalFeatureBanner).addClass('last');
        // For each mb with drop down then use label text as first option
        $j('.mb div select',verticalFeatureBanner).each(function(index) {
            $option = $j('<option/>').text($j(this).parent().find('label').text());
            $option.attr('value','select').attr('selected','true');
            $j(this).prepend($option);
        });
    }
}

function setVideoBoxLinks(){
    $j('.featureBanner .mb a').each(function(index){
    if ($j(this).attr('target') != '_blank') {
            $j(this).unbind().click(function(ev){
                slideVideoBox($j(this), ev);
                window.clearInterval(loopInterval);
                window.clearInterval(tabbedLoopInterval);
            });
        }
    });
}

function slideVideoBox(link,ev){
    if(link.attr('class') != 'cboxElement'){ // ignore colourbox links
        window.clearInterval(loopInterval);
        var linkHref = link.attr('href');
        if(linkHref.indexOf('http://cdn.streamlike.com') > -1){ 
            ev.preventDefault();
            var linkParent = link.parents('.mb');
            linkParent.animate({width: linkParent.parent().css('width')},1000, function(){
                var params = initGetUrlVar(linkHref);
                linkParent.addClass('videoBoxActive');
                if($j('#videoFrame').length > 0){
                    $j('#videoFrame').attr('src','http://cdn.streamlike.com/player/getEmbedFive?med_id='+params['med_id']+'&width=350&height=200&maintain_ar=true&chapter=true&autoStart=true&screencolor=000000&streamlike_mp.server=http://cdn.streamlike.com&autoStart=true');
                }
                else{
                    linkParent.append('<iframe id="videoFrame" name="videoFrame" src="http://cdn.streamlike.com/player/getEmbedFive?med_id='+params['med_id']+'&width=350&height=200&maintain_ar=true&chapter=true&autoStart=true&screencolor=000000&streamlike_mp.server=http://cdn.streamlike.com&autoStart=true" style="border:0px black solid;"" name="media-'+params['med_id']+'" marginheight="0" marginwidth="0" scrolling="no" frameborder="0" align="top" width="350" height="200"></iframe>');
                }
            });
        }
    }
}

function hideVideoBox(){
    var videoBox = $j('#videoFrame');
    if(videoBox.length >0){
        videoBox.remove();
        if($j('.mb.videoBoxActive').length > 0){
            $j('.mb.videoBoxActive').removeAttr('style').removeClass('videoBoxActive');
        }
    }
}

function initGetUrlVar(url){
    var vars = [], hash;
    var hashes = url.slice(window.location.href.indexOf('?') + 1).split('?')[1].split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function formElements(){
    $j('input[type="text"]').addClass('textbox');
    $j('input[type="submit"]').addClass('sbmt');
    $j('input[type="button"]').addClass('btn');
    $j('select').addClass('dropdownList');
}

// CSV Driven Table
function setupFilterTablePopup(tableId, h, w) {
    $ft = $ektron('#' + tableId);
    $ektron('.linkColumn', $ft).hide();
    $ft.click(function(event){
        var $row, $tgt = $ektron(event.target);
        if($tgt.is('tr'))        {
            $row=$tgt;
        } else if ($tgt.parents('tr').length){
            $row=$tgt.parents('tr:first');
        }
        $links = $ektron('.linkColumn a', $row);
        if ($links.length > 0) {
            $j.colorbox({ width: w, height: h, iframe: true, href: $links[0].href })
        };
    });
}

function setupTableRowAlts(){
    var filteredTables = $j('.filteredTable table');
    if(filteredTables.length > 0){
        $j('tr:even',filteredTables).addClass('alt');     
    }    
}
  
function EnsureTitleSurvivesAsyncCall()
{
    var instance = Sys.WebForms.PageRequestManager.getInstance();
    if (!(instance)) return;
    document.orginalTitle=document.title;
    instance.add_endRequest(function(s, e){
        if (document.title.replace(/\s/g,"").length==0)
            document.title=document.orginalTitle;
    });
}

/* Clean Power Specific
----------------------------------------------- */

function cleanPowerhidePrimaryNavigationHomeLink(){
    var homeLink = $j('body.CleanPower #primary_navigation li:first');
    if(homeLink.length > 0){
        homeLink.hide();
    }
}

function cleanPowerGalleryModules(){
    var galleryModules = $j('body.CleanPower .signpostGallery .mb');
    if(galleryModules.length >0){
        galleryModules.each(function(index){
            $j('.type1:nth-child(4n)', this).addClass('last');
        });
    }
}

/* Foundation Specific
----------------------------------------------- */
  
// set globals
var mediaSignpostGallery;
var mediaPagingItems;
var mediaPagingIndex;
var mediaGalleryTitle;
var paginationMediaHelper;

function foundationMediaSignpostGallery(){
    mediaSignpostGallery = $j('body.Foundation .mediagallery');
    if(mediaSignpostGallery.length > 0){
        var pagingSize = 1;
        mediaSignpostGallery.addClass('active');
        mediaPagingItems = $j('.mb > div', mediaSignpostGallery);
        mediaPagingIndex = 0;
        // Build pagination
        var pagination = '<span class="newMediaImageTitle"></span><div class="pagination"><ul>';
        pagination += '<li><a style="visibility: hidden;" class="paginators previous" href="javascript:" onclick="foundationPageDirection(-1)"></a></li>';
        pagination += '<li><a class="paginators next" href="javascript:" onclick="foundationPageDirection(1)"></a></li>';
        pagination += '</ul></div><span class="paginationMediaHelper"></span>';
        $j('.mf', mediaSignpostGallery).append(pagination);
        mediaGalleryTitle = $j('span.newMediaImageTitle');
        paginationMediaHelper = $j('span.paginationMediaHelper');
        mediaPagingItems.hide().eq(mediaPagingIndex).show().addClass('current'); // initial set up
        mediaGalleryTitle.html(mediaPagingItems.eq(mediaPagingIndex).find('p').html());
        paginationMediaHelper.html(''+(mediaPagingIndex+1)+' of '+ mediaPagingItems.length  + '');
    }
}

function foundationPageDirection(direction){
    mediaPagingIndex += direction;
    mediaPagingItems.hide().eq(mediaPagingIndex).show();
    foundationUpdatePagination(mediaPagingIndex);
    mediaGalleryTitle.html(mediaPagingItems.eq(mediaPagingIndex).find('p').html());
    paginationMediaHelper.html(''+(mediaPagingIndex+1)+' of '+ mediaPagingItems.length  + '');
}

function foundationUpdatePagination(index){
    $j('.pagination ul li a[longdesc="' + (index+1) + '"]',mediaSignpostGallery).parent().addClass('current').siblings('.current').removeClass('current');
    if(mediaPagingIndex == 0){
        $j('.pagination ul li a.previous ',mediaSignpostGallery).css({visibility: 'hidden'});
    }else{
        $j('.pagination ul li a.previous ',mediaSignpostGallery).css({visibility: 'visible'});
    }if(mediaPagingIndex == mediaPagingItems.length-1){
        $j('.pagination ul li a.next',mediaSignpostGallery).css({visibility: 'hidden'});
    }else{
        $j('.pagination ul li a.next ',mediaSignpostGallery).css({visibility: 'visible'});
    }
} 

function foundationLightboxPagination(){  
    var addRel = $j('body.Foundation .x4 .signpostGallery .mf a');
    if(addRel.length > 0){
        addRel.each(function(){
            $j(this).attr('rel','gallery');
        }) 
        //$ektron(function(){$ektron(addRel).colorbox({ width: "709px", height: "555px", iframe: true, scrolling: false, opacity: .6 });});
    }
    var addRel2 = $j("body.Foundation div.signpost.mediagallery div.mb div > a"); 
    if(addRel2.length > 0){
        addRel2.each(function(){
            $j(this).attr('class', 'cboxElement').attr('rel','gallery');
        })
        $ektron(function(){$ektron(addRel2).colorbox({ width: "709px", height: "555px", iframe: true, scrolling: false, opacity: .6 });});
    }
}   


/* Web TV Specific
----------------------------------------------- */

function webtvDropdown(){
    var webtvDropdown = $j('body.WebTv #navigation ul li ul');
    if(webtvDropdown.length > 0){
        var ddlTrigger = webtvDropdown.parent('li');
        ddlTrigger.addClass('active').mouseenter(function(){
            webtvDropdown.slideDown('fast');
        }).mouseleave(function(){
            webtvDropdown.slideUp('fast');
        });
    }
}

function webtvSearchBox(){
    var webtvSearchBox = $j('body.WebTv #search_language input.site_search'); 
    var webtvSearchBtn = $j('body.WebTv #search_language input.sbmt');
    if(webtvSearchBox.length > 0){
        var strDefault = 'Enter search here';
        webtvSearchBox.val(strDefault).attr('title',strDefault).click(function(){
            clickClear($j(this).attr('id'),strDefault);
        }).blur(function(){
            clickRecall($j(this).attr('id'),strDefault);
        });
        webtvSearchBtn.click(function(){
            if(webtvSearchBox.val() == strDefault || webtvSearchBox.val() == 'Search')
                return false;
        });
    }
}

//Search filters
function webtvFilters(){
    var filterTriggers = $j('body.WebTv .sort_filter > li > span');
    if(filterTriggers.length > 0){
        filterTriggers.each(function(index){
            var filterUl = $j(this).next('ul');
            $j(this).click(function(){
                filterUl.slideToggle();
                $j(this).parent().toggleClass('filterActive');
            });
        });
    }
}

function clickClear(thisfield, defaulttext) {
    if ($j('#'+thisfield).val() == defaulttext) {
        $j('#'+thisfield).val("");
    }
}

function clickRecall(thisfield, defaulttext) {
    if ($j('#'+thisfield).val() == "") {
        $j('#'+thisfield).val(defaulttext);
    }
}

function webtvMediaSignpostAccordian(){
    var accordianContainer = $j('body.WebTv .media_signpost_banner');
    if(accordianContainer.length > 0){
        var blocks = $j('> .mb > div', accordianContainer);
        var allMedia = $j('> .mf > div',accordianContainer);
        var allContent = $j('.wysiwyg',accordianContainer);
        var allTriggers = $j('h1, h2, h3',accordianContainer);
        if(blocks.length > 1){
            accordianContainer.addClass('active');
            blocks.each(function(index){
                var thisTrigger = $j('> h1,> h2,> h3',this);
                var thisContent = $j('.wysiwyg',this);
                thisTrigger.click(function(){
                    var thisMedia = $j('.mf > div').eq(index);
                    if(thisContent.is(':visible')){
                        thisTrigger.removeClass('open');
                        thisContent.slideUp('fast');
                    }
                    else{
                        allTriggers.removeClass('open');
                        thisTrigger.addClass('open');
                        allContent.slideUp('fast');
                        thisContent.slideDown('fast', function(){
                            if(thisMedia.children().length != 0){
                                allMedia.hide();
                                thisMedia.show();
                            }
                        });                    
                    }               
                });
            });
            allContent.hide();
            allMedia.hide();
            $j('>.mb > div > h1, >.mb > div > h2, >.mb > div > h3',accordianContainer).eq(0).click();
        }
    }
}

function webtvSignpostSlider(){
    var signpostSlider = $j('body.WebTv .signpost_slider > .mb');
    if(signpostSlider.length > 0){
        signpostSlider.after('<a class="prev browse left" href="javascript:"></a><a class="next browse right" href="javascript:"></a>');
        var scrollables = signpostSlider.scrollable({circular:true}).autoscroll({interval: 5000});
        scrollables.each(function() {
	        var itemsToClone = $j(this).scrollable().getItems().slice(1);
	        var wrap = $j(this).scrollable().getItemWrap();
	        var clonedClass = $j(this).scrollable().getConf().clonedClass;
	        itemsToClone.each(function() {
		        $j(this).clone(true).appendTo(wrap)
			        .addClass(clonedClass + ' hacked-' + clonedClass);
	        })
        })
    }
}

// set globals
var pagingSize = "";
var mediaTeaserGallery = "";
var pagingItems = "";
var currentPagingIndex = "";

function webtvMediaTeaserGallery(){
    mediaTeaserGallery = $j('body.WebTv .media_teaser_gallery');
    if(mediaTeaserGallery.length > 0){
        if($j('body.WebTv .sidebar .media_teaser_gallery').length > 0)
            pagingSize = 4;
        else
            pagingSize = 10;
        
        mediaTeaserGallery.addClass('active');
        var items = $j('.mb > .media_teaser', mediaTeaserGallery);
        for(var i = 0; i < items.length; i+=pagingSize) {
          items.slice(i, i+pagingSize).wrapAll('<div></div>');
        }
        pagingItems = $j('> .mb > div', mediaTeaserGallery);
        currentPagingIndex = 0;
        pagingItems.hide().eq(currentPagingIndex).show().addClass('current'); // initial set up
        // Build pagination
        var pagination = '<div class="pagination">';
        if(pagingItems.length > 1){
            pagination += '<span class="pageIndicator">Page: </span><ul><li><a class="paginators previous" href="javascript:" onclick="pageDirection(-1)"></a></li>';
            for(var i = 1; i <= pagingItems.length; i++){
                pagination += '<li><a href="javascript:" onclick="pageTo('+ i +')" longdesc="'+i+'">'+ i +'</a></li>';
            }
            pagination += '<li><a class="paginators next" href="javascript:" onclick="pageDirection(1)"></a></li></ul>';
        }
        pagination += '</div>';
        $j('.mf', mediaTeaserGallery).append(pagination);
        updatePagination(0);
        webtvTooltips();
    }
}

function pageTo(index){
    currentPagingIndex = index-1;
    pagingItems.hide().eq(currentPagingIndex).show();
    updatePagination(currentPagingIndex);
}

function pageDirection(direction){
    currentPagingIndex += direction;
    pagingItems.hide().eq(currentPagingIndex).show();
    updatePagination(currentPagingIndex);
}

function updatePagination(index){
    $j('.pagination ul li a[longdesc="' + (index+1) + '"]',mediaTeaserGallery).parent().addClass('current').siblings('.current').removeClass('current');
    if(currentPagingIndex == 0){
        $j('.pagination ul li a.previous ',mediaTeaserGallery).css({visibility: 'hidden'});
    }else{
        $j('.pagination ul li a.previous ',mediaTeaserGallery).css({visibility: 'visible'});
    }if(currentPagingIndex == pagingItems.length-1){
        $j('.pagination ul li a.next',mediaTeaserGallery).css({visibility: 'hidden'});
    }else{
        $j('.pagination ul li a.next ',mediaTeaserGallery).css({visibility: 'visible'});
    }
}

function webtvTooltips(){
    var items = $j('.media_teaser', mediaTeaserGallery);
    if(items.length > 0){
        items.each(function(){
            var tooltip = $j(this).find('.tooltip');
            if($j('.tooltipTop',tooltip).html() != ""){
                $j('> .mb',this).mouseenter(function(){
                    tooltip.parents('.media_teaser').addClass('currentMediaItem');
                    tooltip.show();
                }).mouseleave(function(){
                    tooltip.parents('.media_teaser').removeClass('currentMediaItem');
                    tooltip.hide();
                });
            }
        });
    }
}

function webtvEmbedLink(){
    var pageTools = $j('body.WebTv .x2 ul.page_tools');
    var iframeSrc = $j('.featureMedia iframe');
    if(pageTools.length > 0 & iframeSrc.length > 0){
        pageTools.prepend('<li class="embedCode"><img src="/Corporate/ui/base/images/webtv/btn-embed-video.gif" alt="Embed this video" onclick="hideShowEmbedTooltip()" /><div id="embedTooltip" class="tooltip" style="display:none;"><div class="tooltipTop"><a href="javascript:" onclick="hideShowEmbedTooltip()" class="closeTooltip">x</a><p><strong>Please copy this code to embed the video:</strong></p><textarea id="embedTooltipTextArea">'+ iframeSrc.attr('src') +'</textarea></div><div class="tooltipBtm"></div></div></li>');
        pageTools.addClass('embedAdded');
    }
}

function hideShowEmbedTooltip(){
    if($j('#embedTooltip').is(':hidden')){
        $j('#embedTooltip').show();
        $j('#embedTooltipTextArea').focus().select();
    }else
        $j('#embedTooltip').hide();
}

//Sitemap
function expandRootNode(){
    $j("div#content .expandedSitemap ul.treeview > li > ul").show();
}
//Sitemap end
