﻿/* Global vars */
var CurrentImg = 0;
var CarouselSetUp = false;
var ScrollingBlocked = false;
var IsMobile = (window.screen && window.screen.width && window.screen.width <= 640);

if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(err) {}
}

$(document).ready(function() {        
    $(".topbanners .FadingImage").css("position", "absolute");
    $(".topbanners .FadingImage:first").nextAll().hide();
    window.setTimeout("fadeHeroBanners()", 7000);
    $(".sch-fld").val("Search").focus(function() {
        this.value = "";
    });
    $("li:last-child").addClass("last");

    /* Commenting functionality */
    $("a[href *= /utilities/]").fancybox({
        'autoScale': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'iframe'
    });

    $("a span:empty").remove();

    DoCarouselSetUp();
    SetupChemAndYouThumbHover();
    TwitterCarousel();

    /* GA tracking for AddThis */
    if (pageTracker) {
        addthis_config = {
            data_ga_tracker: pageTracker
        }
    }

    /* File tracking */
    $("a[href$=.pdf],a[href$=.doc],a[href$=.docx],a[href$=.xls],a[href$=.xlsx],a[href$=.ppt],a[href$=.pptx],a[href$=.mp3],a[href$=.swf],a[href$=.jpg],a[href$=.jpeg],a[href$=.gif],a[href$=.png],a[href$=.mov],a[href$=.wav],a[href$=.flv]").click(function(e) {
        if ($(this).attr("href").indexOf('?', 0) >= 0) return false;
        var Matches = $(this).attr("href").match(/^(.+)\.([a-zA-Z0-9]{2,4})$/);
        if (pageTracker && Matches.length > 0) {
            if (this.href.indexOf("/documents/", 0) >= 0) {
                pageTracker._setCustomVar(5, "visit_type", "doc_download", 1);
            }
            pageTracker._trackPageview("/files/" + Matches[2] + Matches[1]);
        }
    });

    /* External link tracking */
    $("a[href^=http://],a[href^=https://]").click(function() {
        if (pageTracker) {
            pageTracker._trackPageview("/outbound/" + this.href.replace(/https?:\/\//gi, ""));
        }
    });

    /* Email link tracking */
    $("a[href^=mailto:]").click(function() {
        if (pageTracker) {
            pageTracker._trackPageview("/email/" + this.href.replace("mailto:", ""));
        }
    });

    /* RSS feed tracking */
    $("a.rss, a.rss-rgt, li.rss a").click(function() {
        var Matches = $(this).attr("href").match(/([^\/]*)\/?$/);
        if (pageTracker && Matches) {
            pageTracker._trackPageview("/rss/" + Matches[1]);
        }
    });

    /* Print */
    $("a.print, li.print a").click(function() {
        if (pageTracker) {
            pageTracker._trackPageview("/print" + location.pathname);
        }
    });

    /* Comment form tracking */
    $(".CommentForm :submit").click(function() {
        if (pageTracker && $("#tk").size() > 0) {
            pageTracker._trackPageview($("#tk").attr("value"));
        }
    });

    /* LHS Nav expanded-bug-fix */
    $("#lhsnav ul li.expanded").each(function() {
        var parent = this;
        if ($("ul", parent).size() == 0) {
            $(parent).removeClass("expanded");
        }

    });

    //Setup change handler for document search dropdowns
    $("#banner-overlay .document-search .category select").change(function() {
        var thmDD = $("#banner-overlay .document-search .theme select").get(0);
        $("#banner-overlay .document-search .theme select option").remove();
        for (i = 0; i < themes[this.selectedIndex].length; i++) {
            var objOption = document.createElement("option");
            objOption.text = themes[this.selectedIndex][i].toString();
            objOption.value = themes[this.selectedIndex][i].toString();
            thmDD.options.add(objOption);
        }
    });

    $("#banner-overlay .document-search .category select").change();


    //RC tools
    $(".tool-detail").hover(function() {
        if ($(this).children(".tool-detail-full:visible").size() == 0)
            $(this).addClass("rc-tool-hover");
    }, function() {
        $(this).removeClass("rc-tool-hover");
    }).click(function() {
        if ($(this).children(".tool-detail-full:visible").size() == 0) {
            $(this).removeClass("rc-tool-hover");
            $(this).children(".tool-detail-full").slideDown("normal");
            $(this).children(".tool-intro").slideUp("fast");
            RegisterToolHit(this.id);
        }
    }).each(function() {
        $(this).children("img").after('<div class="tool-intro"><p>' + GetTruncatedElementContent(("#" + this.id + " .tool-desc"), 200) + '</p><p><a onclick="return false;" href="#' + this.id + '" class="rc-more">Read more</a></p></div>');
        $(this).children(".tool-detail-full").append('<p><a onclick="return false;" href="#' + this.id + '" class="rc-less">Read less</a></p>');
    });
    $(".rc-less").click(function() {
        $(this).closest(".tool-detail").removeClass("rc-tool-hover");
        $(this).closest(".tool-detail").children(".tool-detail-full").slideUp("normal");
        $(this).closest(".tool-detail").children(".tool-intro").slideDown("fast");
    });
    $(".tool-detail-full").hide();
    $(".tool-detail:last-child").addClass("tool-detail-last");

    $(".th-spotlight-full:first").after('<div class="th-spotlight-intro"><p>' + GetTruncatedElementContent((".th-spotlight-full:first"), 200) + '</p><p><a onclick="return false;" href="#" class="th-spotlight-more">Read more</a></p></div>');
    $(".th-spotlight-full:first").append('<p><a onclick="return false;" href="#' + this.id + '" class="th-spotlight-less">Read less</a></p>');
    $(".th-spotlight-full:first").hide();
    $(".th-spotlight-less").click(function() {
        $(".th-spotlight-full:first").slideUp("normal");
        $(".th-spotlight-intro:first").slideDown("fast");
    });
    $(".th-spotlight-more").click(function() {
        $(".th-spotlight-intro:first").slideUp("normal");
        $(".th-spotlight-full:first").slideDown("fast");
    });


    //Setup change handler for docs & tools dropdowns
    $("#doc-tools-filters .category select").change(function() {
        DoSubThemeChange(this);
    });
    if ($("#doc-tools-filters .theme select").size() > 0) {
        selVal = $("#doc-tools-filters .theme select").get(0).options[$("#doc-tools-filters .theme select").get(0).selectedIndex].value;
        DoSubThemeChange($("#doc-tools-filters .category select").get(0));
        for (i = 0; i < $("#doc-tools-filters .theme select").get(0).options.length; i++) {
            if ($("#doc-tools-filters .theme select").get(0).options[i].value == selVal)
                $("#doc-tools-filters .theme select").get(0).selectedIndex = i;
        }
    }
    //RC tools home
    $(".tool-home-detail").hover(function() {
        if ($(this).children(".tool-detail-full:visible").size() == 0)
            $(this).addClass("rc-tool-hover");
    }, function() {
        $(this).removeClass("rc-tool-hover");
    }).click(function() {
        if ($(this).children(".tool-detail-full:visible").size() == 0) {
            $(this).removeClass("rc-tool-hover");
            $(this).children(".tool-detail-full").slideDown("normal");
            $(this).children(".tool-intro").slideUp("fast");
        }
    }).each(function() {
        $(this).children("p").after('<div class="tool-intro"><p>' + GetTruncatedElementContent(("#" + this.id + " .tool-desc"), 200) + '</p><p><a onclick="return false;" href="#' + this.id + '" class="rc-more">Read more</a></p></div>');
        $(this).children(".tool-detail-full").append('<p><a onclick="return false;" href="#' + this.id + '" class="rc-less">Read less</a></p>');
    });
    $(".rc-less").click(function() {
        $(this).closest(".tool-home-detail").removeClass("rc-tool-hover");
        $(this).closest(".tool-home-detail").children(".tool-detail-full").slideUp("normal");
        $(this).closest(".tool-home-detail").children(".tool-intro").slideDown("fast");
    });
    $(".tool-detail-full").hide();
    
    //COTF
    if (!IsMobile) {
        $("#cotf-boxes li a.yt[href*='youtu.be'], #cotf-boxes li a.yt[href*='www.youtube.com']").click(function(e){
            e.preventDefault();
	        $.fancybox(
		        {
		            width: 560,
		            height: 315,
			        'transitionIn'		: 'elastic',
			        'transitionOut'		: 'elastic',
			        href: this.href.replace("youtu.be","www.youtube.com/embed"),
			        type: 'iframe'
		        }
	        );
        });
        $("#cotf-boxes li a[href$=.jpg], #cotf-boxes li a[href$=.jpeg], #cotf-boxes li a[href$=.gif], #cotf-boxes li a[href$=.png]").fancybox();
        $("#cotf-boxes li a[href$=.flv], #cotf-boxes li a[href$=.f4v], #cotf-boxes li a[href$=.m4v], #cotf-boxes li a[href$=.mov], #cotf-boxes li a[href$=.mp4]").click(function(e){
            e.preventDefault();
            popVideoLightbox($(this).attr("href"));
        });
    }
    
    $(".Future_Chemistry_Page .main").each(function(){
        introHeight = $(this).attr("class").replace(/[^0-9]/gi,"");
        originalHeight = $(this).find(".freeform").height();
        $(this).find(".freeform").data("crop",introHeight);
        $(this).find(".freeform").data("height",originalHeight);
        if (originalHeight > introHeight) {
            $(this).find(".freeform").css({height: introHeight + "px", overflow: "hidden"}).after('<div class="freeform"><p class="more-less"><a onclick="return false;" href="#" class="rc-more">Read more</a></p></div>');
        }
    });
    
    $(".Future_Chemistry_Page .rc-more").live("click",function(e){
        e.preventDefault();
        originalEl = $(this);
        targetEl = $(this).parent().parent().prev();
        targetEl.stop().animate({height: targetEl.data("height")},1000,function(){
            originalEl.toggleClass("rc-more rc-less").html(originalEl.html().replace("more","less"));
        });
    });
    $(".Future_Chemistry_Page .rc-less").live("click",function(e){
        e.preventDefault();
        originalEl = $(this);
        targetEl = $(this).parent().parent().prev();
        targetEl.stop().animate({height: targetEl.data("crop")},1000,function(){
            originalEl.toggleClass("rc-more rc-less").html(originalEl.html().replace("less","more"));
        });
    });

});

function DoSubThemeChange(el){
        var sthmDD = $("#doc-tools-filters .theme select").get(0);
        $("#doc-tools-filters .theme select option").remove();
        selIndex = el.selectedIndex;
        if (subthemes[el.selectedIndex] == null)
            selIndex = 0;
        for (i = 0; i<subthemes[selIndex].length; i++)
        {
           var objOption = document.createElement("option");
           objOption.text = subthemes[selIndex][i].toString();
           objOption.value = subthemes[selIndex][i].toString();
           sthmDD.options.add(objOption);
        }

}

function DoCarouselSetUp(){
	/* Media library carousel */
	if (CarouselSetUp || $("#carousel-hldr").size() == 0) return;
	CarouselSetUp = true;
	CurrentImg = Math.floor($(".c-img-wrap img").size()/2);
    $(".c-img-wrap img").each(function(){
        $(this).attr("id",this.parentNode.id).appendTo("#carousel-hldr");
    });
    $(".c-img-wrap").remove();
    $(".file-summary").hide();
    $("#carousel-hldr").waterwheelCarousel("horizontal",{
                    startingItem: CurrentImg+1,
                    startingItemSeparation: 110,
                    opacityDecreaseFactor: 1,
                    movedToCenter: ItemCentered,
                    clickedCenter: CenterItemClicked,
                    flankingItems: 3,
                    startingWaveSeparation: 0,
                    centerOffset: 0
    }); 
    
    $("#c-btn-prv").show().click(function(e){
        e.preventDefault();
        if (ScrollingBlocked) return false;
        if ($("#img-" + (parseInt(CurrentImg)-1).toString()).size() == 0) return false;
        $("#img-" + (parseInt(CurrentImg)-1).toString()).click();
        ScrollingBlocked = true;
    });
    
    $("#c-btn-nxt").show().click(function(e){
        e.preventDefault();
        if (ScrollingBlocked) return false;
        if ($("#img-" + (parseInt(CurrentImg)+1).toString()).size() == 0) return false;
        $("#img-" + (parseInt(CurrentImg)+1).toString()).click();
        ScrollingBlocked = true;
    });
    
    ItemCentered($("#img-" + CurrentImg));
}

function fadeHeroBanners() {
		if ($(".topbanners .FadingImage:visible").next().length > 0) {
			$(".topbanners .FadingImage:visible").fadeOut(2000).next().fadeIn(2000);
		} else {
				$(".topbanners .FadingImage:visible").fadeOut(2000);
				$(".topbanners .FadingImage:first").fadeIn(2000);
		}
		window.setTimeout("fadeHeroBanners()",7000);
}

function ItemCentered(itm){
    CurrentImg = itm.attr("id").replace("img-","");
    $(".file-summary").hide();
    $("#info-" + CurrentImg).show();
    ScrollingBlocked = false;
}

function CenterItemClicked(itm){
    itmURL = $("#info-" + CurrentImg + " a.download").attr("href");
    if (itmURL.match(/(.jpg$|.gif$|.png|.swf$)/gi)) {
        popLightbox(itmURL);
        return false;
    }
    if (itmURL.match(/(.flv$|.f4v$|.m4v$|.mov$|.mp4$)/gi)) {
        popVideoLightbox(itmURL);
        return false;
    }
    if (itmURL.match(/(.mp3$)/gi)) {
        popAudioLightbox(itmURL);
        return false;
    }
    window.open(itmURL);
}

function popLightbox(url) {
	$.fancybox(
		{
        	'autoDimensions'	: true,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			href: url
		}
	);
}


function popVideoLightbox(url) {
    $("#util-hldr").html('<div id="vid-pop" style="width: 800px; height: 450px"><a href="'+url+'" id="vid-pop-lnk" style="width: 400px; height: 225px"></a></div>');
    flowplayer("vid-pop-lnk", { src: '/Templates/Cefic/Swfs/flowplayer-3.1.5.swf', wmode: 'opaque' }, {
        key: "#$b6bd2d46bc8c9bf16cf",
        clip: {
            autoPlay: false,
            autoBuffering: true,
            scaling: 'orig'
        },
        plugins: {
            controls: {
                sliderColor: '#cccccc',
                borderRadius: '0px',
                backgroundColor: '#888888',
                progressGradient: 'medium',
                timeBgColor: '#666666',
                buttonOverColor: '#666666',
                bufferGradient: 'none',
                backgroundGradient: [0.6, 0.3, 0, 0, 0],
                bufferColor: '#666666',
                tooltipTextColor: '#ffffff',
                timeColor: '#000000',
                volumeSliderColor: '#000000',
                buttonColor: '#333333',
                sliderGradient: 'none',
                volumeSliderGradient: 'none',
                durationColor: '#ffffff',
                progressColor: '#111111',
                tooltipColor: '#666666',
                height: 24,
                opacity: 1.0
            },
		    gatracker: {
			    url: "/Templates/Cefic/Swfs/flowplayer.analytics-3.2.0.swf",
			    trackingMode: "Bridge",
			    bridgeObject: "pageTracker"
		    }
        }
    });
    popLightbox("#vid-pop");
}

function popAudioLightbox(url) {
    $("#util-hldr").html('<div id="pop-snd" style="width: 250px; height: 25px;"><div id="pop_audioplayer"><a href="' + url + '">Download audio file</a></div></div>');
    AudioPlayer.embed("pop_audioplayer", { soundFile: url });   
	
    popLightbox("#pop-snd");
}


function SetupChemAndYouThumbHover() { 
	$("body.Chemisty_and_You_Page div.summary a.thumbnail, #homer1 div.grid_6 a.thumbnail").hover(function() {
	
		$(this).find("span").stop(true,true).animate({bottom: "0"}, "normal");}, 
	    
	    function() {
		el = $(this).find("span");
		el.stop().animate({bottom: 0-(el.height() + 28)}, "normal");
		
	}).find("span").each(function(){
	    $(this).css("bottom",0-($(this).height() + 28));
	});

} 

function TwitterCarousel() {

    $('#slider-code').tinycarousel({ 
    
        axis: 'y',
        interval: true,
        intervaltime: 8000
    
    });

}

function GetTruncatedElementContent(selector,chars){
    var content = $(selector).text();
    if (content.length > chars)
    {
        return content.substring(0,chars) + '...';
    }
    return content;
}

function RegisterToolHit(tool){
    $.get('/Templates/Cefic/handlers/ToolHitHandler.ashx?tool=' + tool);
}

