$(document).ready(function() {
    // all initialisation functions are called on all pages, so they must first check for their relevant content, and only continue if it is found

    initMultipod();
    initNews();
    initWatchListen();
    initTabClicks();
    initNewsFeedPod();
    initNewsPage();


    keywordSearch = $("#ctl00_MenuBar1_txtGlossary");
    if (keywordSearch.length > 0) {
        $("#ctl00_MenuBar1_txtGlossary").autocomplete("GlossaryOutput.aspx", {
            width: 290,
            max: 100,
            highlight: false,
            multiple: true,
            multipleSeparator: "|",
            scroll: false,
            scrollHeight: 800,
            delay: 200
        });
    }

    $(".jargon-box").bind("focus", function() { this.value = ""; });

    $(".logos a").hover(
      function() {
          $(this).find("img").attr("src", $(this).find("img").attr("src").replace(".gif", "-over.gif"));
      },
      function() {
          $(this).find("img").attr("src", $(this).find("img").attr("src").replace("-over.gif", ".gif"));
      }
    );

    $("a[href*='.pdf']").click(
        function() {
            //window.location.href = "/file.aspx?d=" + $(this).attr("href");
            var fileName = $(this).attr("href");
            $('#ajaxhidden').load('UpdatePdf.aspx?pdf=' + ($(this).attr("href").replace(/ /g, '+')));

            //Now track it
            pageTracker._trackPageview($(this).attr('href'));
        }
    );


    jQuery.query = function() {
        var r = {};
        var q = location.search;
        q = q.replace(/^\?/, ''); // remove the leading ?        
        q = q.replace(/\&$/, ''); // remove the trailing &
        jQuery.each(q.split('&'), function() {
            var key = this.split('=')[0];
            var val = this.split('=')[1];
            // convert floats
            if (/^[0-9.]+$/.test(val))
                val = parseFloat(val);
            // ingnore empty values
            if (val)
                r[key] = val;
        });
        return r;

    };

});

function initNewsFeedPod()
{
    if($('.news'))
    {
     var myDate = new Date();
            $('#date-' + (parseInt(myDate.getMonth()) +1)).addClass('month-on');
           
            $(".date-selector").click(function () {
               $(".date-selector").removeClass("month-on");
               $(this).addClass("month-on");
               $('.scroll-items-holder .scroll-items').html("<img src='assets/images/ajax-loader.gif' alt='loader' /> ");
               $('.scroll-items-holder .scroll-items').load('newshomeoutput.aspx?month='+$(this).attr('rel')+'&year='+$('#year-field').text(),'',function() {initScroller();});
               
               return false;
            });
            
            $("#year-older").click(function () {
               
               $('#year-field').text(parseInt($('#year-field').text())-1);
                $('.scroll-items-holder .scroll-items').html("<img src='assets/images/ajax-loader.gif' alt='loader' /> ");
               $('.scroll-items-holder .scroll-items').load('newshomeoutput.aspx?month='+$('.month-on').attr('rel')+'&year='+$('#year-field').text(),'',function() {initScroller();  });
               
               return false;
            });
            
            $("#year-newer").click(function () {
                $('#year-field').text(parseInt($('#year-field').text())+1);
                $('.scroll-items-holder .scroll-items').html("<img src='assets/images/ajax-loader.gif' alt='loader' />");
                $('.scroll-items-holder .scroll-items').load('newshomeoutput.aspx?month='+$('.month-on').attr('rel')+'&year='+$('#year-field').text(),'',function() {initScroller();});
               
               return false;
            });
    }
}

function initNewsPage()
{
    if($('.tab-news')){
           var myDate = new Date();
            
            
            if(getQueryVariable("month")!=undefined)
            {
                var month = getQueryVariable("month");
                var year = getQueryVariable("year");
                $('#date-'+month).addClass('selected');
                $('#tabCategory .tab-middle').load('newsoutput.aspx?month='+month+'&year='+year);
                
            }else{
                $('#date-' + (parseInt(myDate.getMonth()) +1)).addClass('selected');
                $('#tabCategory .tab-middle').load('newsoutput.aspx');
            }
            
            $('#year-selector-less').click(function () {
                 var curDate = $(this).parent().find('#date-field').html();
                 $(this).parent().find('#date-field').html(curDate - 1);
                 
                 var curDate = $('#date-field').html();
                 $('.selected').attr('href','NewsOutput.aspx?month='+$('.selected').attr('rel')+'&year='+curDate);
                 $('#tabCategory .tab-middle .loader').show();
                 $('#tabCategory .tab-middle').load($('.selected').attr('href'));
                 $('#tabCategory .tab-middle .loader').hide();
                 return false;
            });
            
            $('#year-selector-more').click(function () {
                 var curDate = $(this).parent().find('#date-field').html();
                 $(this).parent().find('#date-field').html(parseInt(curDate)+parseInt(1))
                 
                 var curDate = $('#date-field').html();
                 $('.selected').attr('href','NewsOutput.aspx?month='+$('.selected').attr('rel')+'&year='+curDate);
                 $('#tabCategory .tab-middle .loader').show();
                 $('#tabCategory .tab-middle').load($('.selected').attr('href'));
                 $('#tabCategory .tab-middle .loader').hide();
                  
                 return false;
            });
            
            $(".month-selector").click(
                function () {
                    var curDate = $('#date-field').html();
                    $('.month-selector').attr('href','NewsOutput.aspx?month='+$(this).attr('rel')+'&year='+curDate);
                    $('#tabCategory .tab-middle .loader').show();
                    $('#tabCategory .tab-middle').load($(this).attr('href'));
                    $('#tabCategory .tab-middle .loader').hide();
                    
                    $(".month-selector").removeClass('selected');
                    $(this).addClass('selected');
                    
                    return false;
                }
            );
           }
}

function initTabClicks()
{
           $(".cat-more").click(function(event){
                 if($(this).css('background-image').indexOf("btn-hide.gif")>0)
                 {
                    $(this).css('background-image','url(assets/images/btn-reveal.gif)');
                    $(this).parent().find('.cat-head').addClass("section-closed");
                    $(this).parent().find('.cat-head').removeClass("section-open");
                    //$(this).parent().css('background-image','url(/assets/images/tab-top-dark.gif)');
                    $(this).parent().css('background-position','0px -100px');
                 }else{
                    $(this).css('background-image','url(assets/images/btn-hide.gif)');
                    $(this).parent().find('.cat-head').removeClass("section-closed");
                    $(this).parent().find('.cat-head').addClass("section-open");
                    //$(this).parent().css('background-image','url(/assets/images/tab-top.gif)');
                    $(this).parent().css('background-position','0px 0px');
                 }
                 $(this).parent().parent().find('.tab-middle').slideToggle("slow");
            
                 return false;
             });
             
             $(".tab-head").click(function(event){
                 if($(this).find(".cat-more").css('background-image').indexOf("btn-hide.gif")>0)
                 {
                    $(this).find(".cat-more").css('background-image','url(assets/images/btn-reveal.gif)');
                    $(this).find('.cat-head').addClass("section-closed");
                    $(this).find('.cat-head').removeClass("section-open");
                    //$(this).parent().css('background-image','url(/assets/images/tab-top-dark.gif)');
                    $(this).css('background-position','0px -100px');
                 }else{
                    $(this).find(".cat-more").css('background-image','url(assets/images/btn-hide.gif)');
                    $(this).find('.cat-head').removeClass("section-closed");
                    $(this).find('.cat-head').addClass("section-open");
                    //$(this).parent().css('background-image','url(/assets/images/tab-top.gif)');
                    $(this).css('background-position','0px 0px');
                 }
                 $(this).parent().find('.tab-middle').slideToggle("slow");
            
                 return false;
             });
}

var multipodCycles = [["multipod-bg-indian-sandstone.jpg", "publications/pdfs/indian_sandstone.pdf", "_blank"], ["multipod-bg-corporate-responsibility-report.jpg", "publications/pdfs/Corporate%20Responsibility%20Report%202009.pdf", "_blank"], ["multipod-bg-education-manifesto.jpg", "/select/PDF/brochures/edland.pdf", "_blank"], ["multipod-bg-walk-to-work.jpg", "publications/pdfs/Walk to Work.pdf", "_blank"], ["multipod-bg-carbon-labelling.jpg", "publications/pdfs/final-carbon-labelling-guide.pdf", "_blank"]]; // maximum of 7 'cycles'; use empty string url when no link is required; also set link target (pdfs & external sites open in new window)
var multipodNavs = [["multipod-bg-environmental.jpg", ""], ["multipod-bg-social.jpg", ""], ["multipod-bg-economic.jpg", ""], ["multipod-bg-responsible-business.jpg", ""]]; // always the same 4 'navs'
var multipodNavSections = ["environmental", "social", "economic", "responsible-business"];
var currentMultipod = ["cycle", 0, 0]; // cycle (numbered news banner which changes every few seconds) or nav (when user rolls over the multipod navigation links); last-displayed cycle; last-displayed nav
var multipodInterval;
var watchListenClips;
var currentWatchListenClip = 0;
var ccExpanded = false;

function initMultipod() { // large homepage pod containing many sub-pods

 multipod = $(".multipod"); // multipod navigation & anim
 if (multipod.length > 0) {
	 multipod.css("background-image", "url('assets/images/" + multipodCycles[0][0] + "')");
		navs = $(".multipod div.nav a.nav").length;
		for (navIndex=0; navIndex<navs; navIndex++) {
			navLink = $(".multipod .nav a.nav:eq(" + navIndex + ")");
			navLink.attr("id", "nav-" + navIndex);
			navLink.bind("mouseover", function() {clearInterval(multipodInterval); updateMultipod('nav', this.id); return false;});
			navLink.bind("mouseout", function() {multipodInterval = setInterval(cycleMultipod, 6000); return false;});
		}
		cycles = $(".multipod div.cycles a.cycle").length;
		for (cycleIndex=0; cycleIndex<cycles; cycleIndex++) {
			if (cycleIndex < multipodCycles.length) {
				cycleLink = $(".multipod div.cycles a.cycle:eq(" + cycleIndex + ")");
			 cycleLink.attr("id", "cycle-" + cycleIndex);
			 cycleLink.bind("mouseover", function() {clearInterval(multipodInterval); updateMultipod('cycle', this.id, true); return false;});
			 cycleLink.bind("mouseout", function() {updateMultipod('cycle', currentMultipod[1], false, true); return false;});
			 cycleLink.attr("href", multipodCycles[cycleIndex][1]);
			 cycleLink.attr("target", multipodCycles[cycleIndex][2]);
			} else {
	 	 $(".multipod div.cycles a.cycle:eq(" + cycleIndex + ")").css("display", "none");
				if (cycleIndex > 0) {$(".multipod div.cycles img.spacer:eq(" + cycleIndex + ")").css("display", "none");}
			}
		}
		margin = 160 - (multipodCycles.length * 15) - ((multipodCycles.length - 1) * 8);
		$(".multipod div.cycles img.spacer:eq(0)").attr("width", String(Math.floor(margin / 2)));
		$(".multipod div.cycles img.spacer:eq(7)").attr("width", String(Math.ceil(margin / 2)));
		updateMultipod("cycle", 0, false, true);
 }

 if ($(".watch-listen").length > 0) { // watch & listen pod (can also be used outside the multipod)
  $(".watch-listen .title:first").css("display", "block");
 	$(".watch-listen a.icon:eq(0) img").attr("src", "assets/images/multipod-watch-listen-icon-on.gif");
 	watchListenClips = $(".watch-listen a.icon").length;
		$(".watch-listen .thumbs").css("width", watchListenClips * 146 + "px");
  for (clipIndex=0; clipIndex<watchListenClips; clipIndex++) {
			iconLink = $(".watch-listen a.icon:eq(" + clipIndex + ")");
			iconLink.attr("id", "icon" + clipIndex);
			iconLink.bind("click", function() {updateWatchListen('absolute', this.id); return false;});
 	}
  $(".watch-listen a.scroll-left").bind("click", function() {updateWatchListen("relative", -1); return false;});
  $(".watch-listen a.scroll-right").bind("click", function() {updateWatchListen("relative", 1); return false;});
 }

 if ($(".carbon-calculator").length > 0) { // carbon calculator pod (can also be used in a static version outside the multipod, but this is a different include)
  $(".carbon-calculator a.expander").click(function() {
   updateCCExpander();
   return false;
  },
   function () {
    updateCCExpander();
   return false;
  });
 }

}

function updateMultipod(mode, index, lock, forced) { // lock = stay on this multipod banner; do not cycle even if it's a cycle banner; forced = forced update
	if (typeof(index) == "string") { // if a link id has been sent instead of an index number, reformat it
		 cycleIndex = index.indexOf("cycle-");
			if (cycleIndex == 0) {index = index.substring(6);}
		 navIndex = index.indexOf("nav-");
			if (navIndex == 0) {index = index.substring(4);}
			index = Number(index);
	}
 if ((mode != currentMultipod[0]) || (index != currentMultipod[(mode == "cycle" ? 1 : 2)]) || (forced)) { // ignore repeated clicks on same link
//alert(mode + " " + index);
	 currentMultipod[0] = mode;
	 currentMultipod[(mode == "cycle" ? 1 : 2)] = index;
	 displayMultipod();
	 clearInterval(multipodInterval);
		multipodInterval = undefined;
	 if ((mode == "cycle") && (! lock)) {
	 	multipodInterval = setInterval(cycleMultipod, 6000);
	 }
	}
}

function cycleMultipod() {
	switch(currentMultipod[0]) {
		case "cycle": // continue the cycle
			currentMultipod[1]++;
			break;
		case "nav": // revert to cycle mode
		 currentMultipod[0] = "cycle";
			break;
	}
	if (currentMultipod[1] >= multipodCycles.length) {currentMultipod[1] = 0;}
	displayMultipod();
}

function displayMultipod() {
	for (navIndex=0; navIndex<multipodNavs.length; navIndex++) { // redraw nav interface
		navSrc = "assets/images/multipod-nav-" + multipodNavSections[navIndex] + ".png";
		navStatus = ((currentMultipod[0] == "nav") && (navIndex == currentMultipod[2])) ? "on" : "up";
 	$(".multipod div.nav a.nav:eq(" + navIndex + ") img").attr("src", getImageFilename(navSrc, navStatus));
	}
	for (cycleIndex=0; cycleIndex<multipodCycles.length; cycleIndex++) { // redraw cycles interface
		cycleSrc = "assets/images/multipod-cycle-" + (cycleIndex + 1) + ".png";
		cycleStatus = ((currentMultipod[0] == "cycle") && (cycleIndex == currentMultipod[1])) ? "on" : "up";
 	$(".multipod div.cycles a.cycle:eq(" + cycleIndex + ") img").attr("src", getImageFilename(cycleSrc, cycleStatus));
	}
	$(".multipod div.overlay").css("display", "none"); // redraw multipod background & overlay content
 switch(currentMultipod[0]) {
		case "cycle":
   multipod.css("background-image", "url('assets/images/" + multipodCycles[currentMultipod[1]][0] + "')");
			if (multipodCycles[currentMultipod[1]][1].length > 0) {
			 $(".multipod div.cycle").css("display", "block");
			 $(".multipod div.cycle a").attr("href", multipodCycles[currentMultipod[1]][1]);
			 $(".multipod div.cycle a").attr("target", multipodCycles[currentMultipod[1]][2]);
			} else {
			 $(".multipod div.cycle").css("display", "none");
			}
			$(".multipod div.overlays div.overlay-margin").css("width", "0px");
			break;
		case "nav":
   multipod.css("background-image", "url('assets/images/" + multipodNavs[currentMultipod[2]][0] + "')");
			/*overlayDiv = $(".multipod div.overlays div.nav" + currentMultipod[2]);
			overlayDiv.css("display", "block");
			overlayDiv.css("top", "0px");
			//overlayDiv.animate({top: "0px"}, 750);
			$(".multipod div.overlays div.overlay-margin").css("width", (currentMultipod[2] == 1) ? "131px" : "61px");*/
			break;
	}
}

function getImageFilename(filename, rolloverStatus) { // a link can have separate images for the following 3 states: "up", "over" for rollover and the optional "on" for the current nav section.  "-over" or "-on" must appear in image filenames for those states
 if (rolloverStatus == undefined) {rolloverStatus = "up";}
 statusSubstring = "-" + rolloverStatus;
 overIndex = filename.indexOf("-over"); // strip any old statusSubstring from filename first
 if (overIndex > -1) {filename = filename.substring(0, overIndex) + filename.substring(overIndex + 5);}
	onIndex = filename.indexOf("-on");
 if (onIndex > -1) {filename = filename.substring(0, onIndex) + filename.substring(onIndex + 3);}
	gifIndex = filename.indexOf(".gif");
	jpgIndex = filename.indexOf(".jpg");
	pngIndex = filename.indexOf(".png");
	if (gifIndex > -1) {
  filename = filename.substring(0, gifIndex);
		if (statusSubstring != "-up") {filename += statusSubstring;}
		filename += ".gif";
	} else if (jpgIndex > -1) {
  filename = filename.substring(0, jpgIndex);
		if (statusSubstring != "-up") {filename += statusSubstring;}
		filename += ".jpg";
	} else if (pngIndex > -1) {
  filename = filename.substring(0, pngIndex);
		if (statusSubstring != "-up") {filename += statusSubstring;}
		filename += ".png";
	}
	return filename;
}



var scrollHolderHeight = 82;
var scrollItemHeight = 82;
var scrollerPages;
var currentScrollerPage;
var scrollerInitialized = false;

function initNews() { // load multipod news
	scrollItems = $(".scroll-items");
	if (scrollItems.length > 0) { // only proceed if this is a relevant page
  $('.scroll-items-holder .scroll-items').load('newshomeoutput.aspx', '', function() {initScroller();});
	}
}

function initScroller() { // scrolling articles - multipod news
	scrollItems = $(".scroll-items");
	if (scrollItems.length > 0) { // only proceed if this is a relevant page
  scrollerPage = $(".scroll-items .scroll-items-page");
  scrollerPage.css("height", scrollHolderHeight + "px");
  scrollerPages = $(".scroll-items .scroll-items-page").length;
  currentScrollerPage = 0;
  scrollItems.css("height", (scrollerPages * scrollHolderHeight) + "px");
  scrollItems.css("top", "0px");
  /*pagesDiv = $(".pages");
		htmlBuffer = "";
		for (pageIndex=0; pageIndex<scrollerPages; pageIndex++) {
			htmlBuffer += "<a href=\"#\" onclick=\"updateScroller('absolute', " + pageIndex + "); return false;\">" + (pageIndex + 1) + "</a>&nbsp;&nbsp;&nbsp;";
		}
		pagesDiv.html(htmlBuffer);
		$(".pages a").eq(currentScrollerPage).addClass("page-on");
			updateScrollerButton("up", false);
		if (scrollerPages > 1) {*/
 	 if (! scrollerInitialized) { // only set these the first time
    $("a#year-older").bind("click", function() {updateMonths(-1); return false;});
    $("a#year-newer").bind("click", function() {updateMonths(1); return false;});
    $(".scroll-up a").bind("click", function() {updateScroller("relative", -1); return false;});
		  $(".scroll-down a").bind("click", function() {updateScroller("relative", 1); return false;});
		 }
 	/*} else { // hide scroller interface if only one page
			pagesDiv.css("display", "none");
			updateScrollerButton("down", false);
	 }*/
		$(".scroll-down .scroll-page").html("1 of " + scrollerPages);
		scrollerInitialized = true;
	}
}

function updateMonths(scrollAmount) { // scroll the months
 months = $(".news .month .months");
	months.css("left", (scrollAmount > 0 ? 0 : -1002) + "px");
 months.stop();
 months.animate({left: "-501px"}, 450);
}

function updateScroller(mode, scrollAmount) { // scroll the articles
	scrollItems = $(".scroll-items");
	switch (mode) {
  case "absolute":
   targetScrollerPage = scrollAmount;
   break;
  case "relative":
   targetScrollerPage = currentScrollerPage + scrollAmount;
   break;
	}
	if (targetScrollerPage < 0) {targetScrollerPage = 0;}
	if (targetScrollerPage >= scrollerPages) {targetScrollerPage = scrollerPages - 1;}
	if (targetScrollerPage != currentScrollerPage) {
		currentPosition = scrollItems.css("top");
 	currentPosition = Number(currentPosition.substring(0, currentPosition.indexOf("px")));
 	targetPosition = - (targetScrollerPage * scrollHolderHeight);
 	animDuration = (Math.abs(targetPosition - currentPosition)) * (450 / scrollHolderHeight); // 450ms per page
  pagesDiv = $(".pages");
		$(".pages a").removeClass("page-on");
		$(".pages a").eq(targetScrollerPage).addClass("page-on");
		//updateScrollerButton("up", targetScrollerPage > 0);
		//updateScrollerButton("down", targetScrollerPage < scrollerPages - 1);
  scrollItems.stop();
  scrollItems.animate({top: (targetPosition + "px")}, animDuration);
		//thumbSrc = $(".news div.thumb-src:eq(" + targetScrollerPage + ") img.thumb-src").attr("src");
		//$(".news div.thumb img.thumb").attr("src", thumbSrc);
		$(".scroll-down .scroll-page").html((targetScrollerPage + 1) + " of " + scrollerPages);
	 currentScrollerPage = targetScrollerPage;
	}
}

function updateScrollerButton(direction, visible) { // show/hide the up/down scroller buttons
 if ((direction == "up") || (direction == "down")) {
  if (visible) {
	  $(".scroll-" + direction + " div.rollover-fade").css("background-image", "url('assets/images/scroll-" + direction + ".gif')");
	  $(".scroll-" + direction + " a").css("display", "block");
	 } else {
	  $(".scroll-" + direction + " div.rollover-fade").css("background-image", "none"); // set background image to one you can't see; keep the div displayed at all times so that its size keeps the floated content in the down place
	  $(".scroll-" + direction + " a").css("display", "none"); // hide the link, while preserving its mouse events for when it is shown again later
	 }
 }
}



function updateWatchListen(mode, scrollAmount) {
	if (typeof(scrollAmount) == "string") { // if a link id has been sent instead of a scrollAmount number, reformat it
		 iconIndex = scrollAmount.indexOf("icon");
			if (iconIndex == 0) {scrollAmount = scrollAmount.substring(4);}
			scrollAmount = Number(scrollAmount);
	}
 switch (mode) {
  case "absolute":
   targetClip = scrollAmount;
   break;
  case "relative":
   targetClip = currentWatchListenClip + scrollAmount;
   break;
	}
	if (targetClip < 0) {targetClip = 0;}
	if (targetClip >= watchListenClips) {targetClip = watchListenClips - 1;}
	if (targetClip != currentWatchListenClip) {
		$(".watch-listen a.icon:eq(" + currentWatchListenClip + ") img").attr("src", "assets/images/multipod-watch-listen-icon.gif");
		$(".watch-listen a.icon:eq(" + targetClip + ") img").attr("src", "assets/images/multipod-watch-listen-icon-on.gif");
		$(".watch-listen .title:eq(" + currentWatchListenClip + ")").css("display", "none");
		$(".watch-listen .title:eq(" + targetClip + ")").css("display", "block");
	 scrollItems = $(".watch-listen .thumbs");
  scrollItems.stop();
  scrollItems.animate({left: (((targetClip * -146) + 0) + "px")}, 450);
  currentWatchListenClip = targetClip;
	}
}

function updateCCExpander() {
	ccExpanded = ! ccExpanded;
	expandedDiv = $(".carbon-calculator .expanded");
	expandedDiv.stop(); // stop old anim
	browserOffset = (window.XMLHttpRequest ? 0 : 8); // ie6 workaround - move the expanded content 10 pixels lower
 expandedDiv.animate({top: ((ccExpanded ? 0 : -128) + browserOffset)}, 450);
}



var streamFileSTD = "";
var streamFileHD = "";
var showIPod = false;
var iPodURL = "";
var downloadURL = "";
var videoTitle = "";
var hd = false;
var showPodsTimeout;

function initWatchListen() { /* video player on watch & listen page */
 if ($(".video-holder").length > 0) {
		streamFileSTD = getQueryVariable("streamfilestd");
		streamFileHD = getQueryVariable("streamfilehd");
		downloadURL = getQueryVariable("downloadurl");
        videos = $("div.video-item");
        if ((streamFileSTD != "") || (streamFileHD != "")) { // look up title of video specified in queries, if any
            for (videoIndex = 0; videoIndex < videos.length; videoIndex++) {
                targetStreamFileSTD = $("div.video-item:eq(" + videoIndex + ") .video-data a.stream-file-std").attr("href");
                if (targetStreamFileSTD == streamFileSTD) {
                    videoTitle = $("div.video-item:eq(" + videoIndex + ") .title").html();
                    break;
                }
            }
            
           if (videoTitle != "") {
              // Update video title and refresh SIFR.
              $(".tv-header").html("Now playing: " + videoTitle).removeClass("sIFR-replaced");

              sIFR.replace(myriad, {
                  selector: '.tv-header',
                  css: '.SIFR-root {background-color: transparent; color:#000000; }'
              });
           }
       }

       if ((streamFileSTD != undefined) && (streamFileSTD != "")) {
            setTimeout(embedVideo, 100);
       }

        videos = $("div.video-item");
        for (videoIndex=0; videoIndex<videos.length; videoIndex++) {
 		    videoImgDiv = $("div.video-item:eq(" + videoIndex + ") .video-img");
 		    videoImgDiv.attr("id", "video-link-" + videoIndex);
 	        videoImgDiv.bind("mouseover", function() {updateVideoRollover(this.id, true);});
 	        videoImgDiv.bind("mouseout", function() {updateVideoRollover(this.id, false);});
 	        videoImgDiv.bind("click", function() {selectVideo(this.id); return false;});
 		    videoImgDiv.css("cursor", "pointer");
 		}
	}
}

function updateVideoRollover(videoID, rolloverStatus) {
	videoIndex = Number(videoID.substring(11));
	if (typeof(videoIndex) == "number") {
		videoDataDiv = $("div.video-item:eq(" + videoIndex + ") .video-data");
		videoDataDiv.css("display", (rolloverStatus ? "block" : "none"));
	}
}

function selectVideo(videoID) {
	videoIndex = Number(videoID.substring(11));
	if (typeof(videoIndex) == "number") {
		streamFileSTD = $("div.video-item:eq(" + videoIndex + ") .video-data a.stream-file-std").attr("href");
		streamFileHD = $("div.video-item:eq(" + videoIndex + ") .video-data a.stream-file-hd").attr("href");
		showIPod = false; // ipod download not used on this site
		iPodURL = "";
		downloadURL = escape($("div.video-item:eq(" + videoIndex + ") .video-data a.download-url").attr("href"));
		videoTitle = $("div.video-item:eq(" + videoIndex + ") .title").html();
		$(".tv-header").html("Now playing: " + videoTitle).removeClass("sIFR-replaced");

		sIFR.replace(myriad, {
		    selector: '.tv-header',
		    css: '.SIFR-root {background-color: transparent; color:#000000; }'
		});
		
		//track video
        pageTracker._trackPageview(streamFileSTD);
		
  window.scroll(0,140);
		if (hd && (streamFileHD == "")) { // if switching from an hd clip to another that doesn't have hd, animate the definition to standard.  this will then automatically reload the correct clip in std when finished
		 updateHD(true);
		} else {
			embedVideo();
		}
	}
}

function embedVideo() {
 $("#video-swf-std").css("display", (hd ? "none" : "block")); // show the correct swf div; hide the static html lookalike of the player
 $("#video-swf-hd").css("display", (hd ? "block" : "none"));
 $("#video-swf-placeholder").css("display", "none");
 $("#video-swf-placeholder .border-top").css("height", "1px"); // kicking ie6 into line
 videoFlashvars = new Object();
	videoFlashvars.streamFileSTD = streamFileSTD;
	videoFlashvars.streamFileHD = streamFileHD;
	videoFlashvars.showIPod = String(showIPod);
	videoFlashvars.iPodURL = escape(iPodURL);
	videoFlashvars.downloadURL = escape(downloadURL);
 videoParams = new Object();
	videoParams.wmode = "transparent";
	videoParams.allowFullScreen = "true";
 swfobject.embedSWF("assets/swf/player-" + (hd ? "hd" : "std") + ".swf", "embed-" + (hd ? "hd" : "std"), (hd ? "898" : "642"), (hd ? "537" : "393"), "9.0.115", "", videoFlashvars, videoParams);
}

function updateHD(animate) {
	if (animate) {
	 $(".video-holder").css("left", (hd ? "-43" : "0") + "px");
  $("#video-swf-std").css("display", "none"); // hide swf; show the static html lookalike of the player
  $("#video-swf-hd").css("display", "none");
	 $("#video-swf-placeholder .main-row").css("background-image", "none"); // hide marshalls tv logo during anim
  $("#video-swf-placeholder").css("display", "block");
  $("#video-swf-placeholder .border-top").css("width", (hd ? "898" : "642") + "px");
  $("#video-swf-placeholder .border-top").css("height", "1px"); // kicking ie6 into line
  $("#video-swf-placeholder .main-row").css("width", (hd ? "898" : "642") + "px");
  $("#video-swf-placeholder .border-left").css("height", (hd ? "505" : "361") + "px");
  $("#video-swf-placeholder .border-right").css("height", (hd ? "505" : "361") + "px");
  $("#video-swf-placeholder .controls").css("width", (hd ? "898" : "642") + "px");
  hd = ! hd; // set target definition and animate the html player lookalike to that size
	 $(".video-holder").animate({left: (hd ? "-43" : "0") + "px"}, 1500);
  $("#video-swf-placeholder .border-top").animate({width: (hd ? "898" : "642") + "px"}, 1500);
  $("#video-swf-placeholder .main-row").animate({width: (hd ? "898" : "642") + "px"}, 1500);
  $("#video-swf-placeholder .border-left").animate({height: (hd ? "505" : "361") + "px"}, 1500);
  $("#video-swf-placeholder .border-right").animate({height: (hd ? "505" : "361") + "px"}, 1500);
  $("#video-swf-placeholder .controls").animate({width: (hd ? "898" : "642") + "px"}, 1500);
  if (hd) { // hide pods before going to hd
	 	$(".watch-listen").fadeOut(350);
	 	$(".publications-library").fadeOut(350);
	 	$(".carbon-calculator").fadeOut(350);
	 } else { // show pods at end of anim
	  clearTimeout(showPodsTimeout);
	 	showPodsTimeout = setTimeout(showPods, 1150);
	 }
  setTimeout(embedVideo, 1600);
	} else {
  hd = ! hd; // set target definition
	 $(".video-holder").css("left", (hd ? "-43" : "0") + "px");
  $("#video-swf-std").css("display", "none");
  $("#video-swf-hd").css("display", "none");
  if (hd) { // hide pods before going to hd
	 	$(".watch-listen").hide();
	 	$(".publications-library").hide();
	 	$(".carbon-calculator").hide();
	 } else { // show pods before going to std
	 	$(".watch-listen").show();
	 	$(".publications-library").show();
	 	$(".carbon-calculator").show();
	 }
  embedVideo(); // swap the html player lookalike to that size
	}
}

function showPods() {
	$(".watch-listen").fadeIn(350);
	$(".publications-library").fadeIn(350);
	$(".carbon-calculator").fadeIn(350);
}

function getFileName(url){
  url = url.replace(' ',"_");
  var filename = url.substring(url.lastIndexOf('/')+1);
  return filename ? filename : "undefined";
}


function getQueryVariable(variable) {
 var query = window.location.search.substring(1);
 var vars = query.split("&");
 for (var i=0;i<vars.length;i++) {
  var pair = vars[i].split("=");
  if (pair[0] == variable) {
   return pair[1];
  }
 }
 //alert('Query Variable ' + variable + ' not found');
}
