// CAROUSEL IMG ASYNC LOAD

$(window).load(function () {
    var img1 = $(".carousel_slide input[type=hidden]").eq(1).val();
    var img2 = $(".carousel_slide input[type=hidden]").eq(2).val();
    var img3 = $(".carousel_slide input[type=hidden]").eq(3).val();
    $(".carousel_slide img").eq(1).attr('src', img1);
    $(".carousel_slide img").eq(2).attr('src', img2);
    $(".carousel_slide img").eq(3).attr('src', img3);
});
/*
$(window).load(function () {
var img1 = $(".carousel_slide input[type=hidden]").eq(0).val();
var img2 = $(".carousel_slide input[type=hidden]").eq(1).val();
var img3 = $(".carousel_slide input[type=hidden]").eq(2).val();
var img4 = $(".carousel_slide input[type=hidden]").eq(3).val();
if (img1.length > 0) {
$(".carousel_slide img").eq(0).attr('src', img1);
}
if (img2.length > 0) {
$(".carousel_slide img").eq(1).attr('src', img2);
}
if (img3.length > 0) {
$(".carousel_slide img").eq(2).attr('src', img3);
}
if (img4.length > 0) {
$(".carousel_slide img").eq(3).attr('src', img4);
}	
});
*/

// SUBPAGE PANEL / MAP HYPERLINK

$(document).ready(function () {
    $(".subpage_panel").css({ 'cursor': 'pointer' });
    $(".subpage_panel").click(function () {
        var hyperlink = $("a", this).attr('href');
        window.location = hyperlink;
        return false;
    });
    $("#csg_menu_container #locations").css({ 'cursor': 'pointer' });
    $("#csg_menu_container #locations").click(function () {
        var hyperlink = $("a", this).attr('href');
        window.location = hyperlink;
        return false;
    });
});

// TEXT-ONLY

(function ($) {
    var availableStylesheets = [];
    var activeStylesheetIndex = 0;
    $.stylesheetToggle = function () {
        activeStylesheetIndex++;
        activeStylesheetIndex %= availableStylesheets.length;
        $.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
    };
    $.stylesheetSwitch = function (styleName) {
        $('link[@rel*=style][title]').each(
			function (i) {
			    this.disabled = true;
			    if (this.getAttribute('title') == styleName) {
			        this.disabled = false;
			        activeStylesheetIndex = i;
			    }
			}
		);
        createCookie('style', styleName/*, 365*/);
    };
    $.stylesheetInit = function () {
        $('link[rel*=style][title]').each(
			function (i) {
			    availableStylesheets.push(this.getAttribute('title'));
			}
		);
        var c = readCookie('style');
        if (c) {
            $.stylesheetSwitch(c);
            Cufon.refresh();
        }
        if (c == 'styles2') {
            $("#utilities a:contains('Text-Only')").css({ 'color': '#E85100' });
            var carousel = $(".hero_carousel");
            carousel.removeClass("hero_carousel").addClass("hero_carousel_txt");
            $(".carousel_slide").eq(1).text("");
            $(".carousel_slide").eq(2).text("");
            $(".carousel_slide").eq(3).text("");
            $(".slide_paging").css({ 'display': 'none' });
            $("#links_container").css({ 'top': '340' });
            Cufon.refresh();
        }
    };
})(jQuery);

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

$(function () {
    try {
        $.stylesheetInit();
        $('#switch').bind(
			'click',
			function (e) {
			    $.stylesheetToggle();
			    location.reload();
			    dcsMultiTrack('WT.z_textonly', 'True', 'WT.dl', '600');
			    return false;
			}
		);

    } catch (e) { }
}
);

// FONT SIZE LARGER/SMALLER

$(document).ready(function () {
    var currentSize = readCookie('fontSize');
    if (currentSize == null) {
        createCookie('fontSize', '1', 1);
    } else {
        $('#body,.group_profile_divBody,.key_message_panel,.dynamic_divBody,.group_profile_std_divBody,.result,.item,#news_body').css('font-size', currentSize + 'em');
        Cufon.refresh();
    }
    $("#text_size_lg").click(function () {
        var currentSize = readCookie('fontSize');
        var increment = '0.1';
        newSize = parseFloat(currentSize) + parseFloat(increment);
        createCookie('fontSize', newSize, 1);
        $('#body,.group_profile_divBody,.key_message_panel,.dynamic_divBody,.group_profile_std_divBody,.result,.item,#news_body').css('font-size', newSize + 'em');
        Cufon.refresh();
        dcsMultiTrack('WT.z_fontsize', 'increase', 'WT.dl', '601');
        return false;
    });
    $("#text_size_sm").click(function () {
        var currentSize = readCookie('fontSize');
        var increment = '0.1';
        newSize = parseFloat(currentSize) - parseFloat(increment);
        createCookie('fontSize', newSize, 1);
        $('#body,.group_profile_divBody,.key_message_panel,.dynamic_divBody,.group_profile_std_divBody,.result,.item,#news_body').css('font-size', newSize + 'em');
        Cufon.refresh();
        dcsMultiTrack('WT.z_fontsize', 'decrease', 'WT.dl', '601');
        return false;
    });
});

// GLOBAL NAVIGATION

$(function () {
    $("ul.bhpb_menu_l1 li").hover(function () {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');
        var ulCols = $('ul:first', this);
        var listItems = $('ul:first', this).children("li");
        var liCount = listItems.size();
        if (liCount > 6) {
            $(listItems).css({ 'width': '50%', 'float': 'left' });
            $(ulCols).css('width', '506px');
		var temp = liCount % 2;            
            if (temp == 0) {
                $(listItems)[listItems.size()-2].style.borderBottomWidth = "0px";
            }

        }
    }, function () {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
        /*
        $('ul:first',this).hover(function(){
        $("ul.bhpb_menu_l1 li.active a:first").css('color', '#444744');
        }, function(){
        $("ul.bhpb_menu_l1 li.active a:first").css('color', '#FFFFFF');
        });
        */
    });
});

$(function () {
    $("ul.bhpb_menu_l1 li.active").hover(function () {
        $('a:first', this).css('color', '#444744');
    }, function () {
        $('a:first', this).css('color', '#FFFFFF');
    });
});

$(function () {
    $("ul.bhpb_menu_l1 li.active ul").hover(function () {
    }, function () {
        $(this).parents("li.active a:first").css('color', '#FFFFFF');
        Cufon.refresh();
    });
});

$(function () {
    $("ul.bhpb_menu_l1 li ul.bhpb_menu_l2 li:last-child").css("border-bottom", "none")
})

// GLOBAL NAVIGATION EXTENSION

$(window).load(function () {
    navWidth = $('.bhpb_menu_l1').width();
    extWidth = (1010 - navWidth);
    $("#nav_ext").css({ 'width': extWidth + 'px' });
});

// GLOBAL SEARCH

function globalSearch(url) {
    var keyword = $("#searchKeywords").val();
    var searchString = url + "?k=" + keyword + "&s=BHPBContent";
    if (keyword == "" || keyword == "Site Search") {
        showPopupMessage('No keyword(s) entered', 'Please ensure you enter a keyword and try searching again');
    } else {
        window.location = searchString;
    }
}

$(document).ready(function () {
    $("input#searchKeywords").keydown(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            var keyword = $("#searchKeywords").val();
            var URL = $("#global_search a").attr("href");
            URL = URL.replace("javascript:globalSearch('", "");
            URL = URL.replace("')", "");
            var searchString = URL + "?k=" + keyword + "&s=BHPBContent";
            if (keyword == "" || keyword == "Site Search") {
                showPopupMessage('No keyword(s) entered', 'Please ensure you enter a keyword and try searching again');
            } else {
                window.location = searchString;
            }
        }
    });
});

// GROUPED ITEM JUMP

$(document).ready(function () {
    //populate the filter dropdown list
    $('.groupHead_label').each(function (index) {

        var catName = $(this).text();
        var catLink = "#" + $(this).find("a").attr("name");

        $('#jump_values ul').append("<li><a href='" + catLink + "'>" + catName + "</a></li>");

    });

    $("#jump_values").hide();
    $("#jump_select").click(function () {
        $(this).next("#jump_values").slideToggle(300);
    });
    $("#jump_values ul li a").click(function () {
        $(this).parents("#jump_values").slideToggle(300);
    });
});

// FOOTER YEAR

function footerYear() {
    var theDate = new Date();
    document.write(theDate.getFullYear());
};

// EXPAND/COLLAPSE DIVS
var profileName;
var csgHeader;
var groupedItem;
$(document).ready(function () {
    $(".dynamic_divBody").hide();
    $(".dynamic_divBody:first").show();
    $('.dynamic_divHead:first').toggleClass('dynamic_divHeadOpen');
    $(".dynamic_divHead:first").click(function () {
        $(this).toggleClass('dynamic_divHead');
    });
    $(".dynamic_divHead").click(function () {
        csgHeader = $(this).find('h2').text();
        $(this).next(".dynamic_divBody").slideToggle(300, callbackFn);
        $(this).toggleClass('dynamic_divHead').toggleClass('dynamic_divHeadOpen');
    });
    $(".group_profile_divBody").hide();
    $(".group_profile_divHead").click(function () {
        profileName = $(this).find('h3').text();
        $(this).next(".group_profile_divBody").slideToggle(300, callbackFn);
        $(this).toggleClass('group_profile_divHead').toggleClass('group_profile_divHeadOpen');
    });
    $(".group_profile_std_divBody").hide();
    $(".group_profile_std_divHead").click(function () {
        groupedItem = $(this).find('h3').text();
        $(this).next(".group_profile_std_divBody").slideToggle(300, callbackFn);
        $(this).toggleClass('group_profile_std_divHead').toggleClass('group_profile_std_divHeadOpen');
    });
    $(".filter_metaValues").hide();
    $(".filter_metaHead").click(function () {
        $(this).next(".filter_metaValues").slideToggle(300);
        $(this).toggleClass('filter_metaHead').toggleClass('filter_metaHeadOpen');
    });

    //$(".sitemap_divBody").hide();
    $(".sitemap_divHead").click(function () {
        $(this).next(".sitemap_divBody").slideToggle(300);
        $(this).toggleClass('sitemap_divHeadOpen').toggleClass('sitemap_divHead');
    });

});

/* Profile page last child line */
/*
$(document).ready(function () {
$(".dynamic_divHead:last").css({'border-bottom':'solid 1px #DEDED9'});
$(".dynamic_divHead:last").click(function () {
$(this).css({'border-bottom':'none'});      
});
$(".dynamic_divBody:last").css({'border-bottom':'solid 1px #DEDED9'});
    	
});
*/
function callbackFn() {
    if ($(this).is(":visible")) {
        if (csgHeader != null) {
            var csgName = document.title.substring(document.title.indexOf('-') + 1);
            var csgUrlStr = window.location.pathname;
            csgUrlStr = csgUrlStr.replace(".aspx", csgHeader + ".aspx");

            dcsMultiTrack('DCS.dcsuri', csgUrlStr, 'WT.ti', csgName + ' ' + csgHeader, 'WT.cg_n', csgName);
        }
        else if (profileName != null) {
            var ldrUrlStr = window.location.pathname;
            ldrUrlStr = ldrUrlStr.replace(".aspx", profileName + ".aspx");

            dcsMultiTrack('DCS.dcsuri', ldrUrlStr, 'WT.ti', 'Leadership' + ' ' + profileName, 'WT.cg_n', 'Leadership');
        }
        else if (groupedItem != null) {
            var groupedItemPage = document.title.substring(document.title.indexOf('-') + 1);
            var grpUrlStr = window.location.pathname;
            grpUrlStr = grpUrlStr.replace(".aspx", groupedItem + ".aspx");

            dcsMultiTrack('DCS.dcsuri', window.location.pathname, 'WT.ti', groupedItemPage + ' ' + groupedItem, 'WT.cg_n', groupedItemPage);
        }
    }
}


// FILTER PANEL STATE

$(document).ready(function () {
    $(".filter_metaValues ul li.active a").each(function () {
        $(this).parents(".filter_metaValues").show();
        $(this).parents(".filter_metaValues").prev(".filter_metaHead").removeClass('filter_metaHead').addClass('filter_metaHeadOpen');
    });
});

// POPUP MESSAGE

function showPopupMessage(popUpLabel, popUpText) {
    $("#video_overlay").show();
    $("#popup_window").show();
    $("#popup_window .label").text(popUpLabel);
    $("#popup_window p").text(popUpText);
}

$(document).ready(function () {
    $("#popup_window #ok").click(function () {
        $("#video_overlay").hide();
        $("#popup_window").hide();
    });
});

// Helper functions
function validEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}
// QUICK LINKS UTILITY
// AMO fix INC700013920828 (IN631657) on 17-Aug-2011

$(document).ready(function () { 
     $("ul.generalList li a[href$=.pdf]").each(function(){        
        $(this).parent("li").css({ 'background': 'url("/style library/images/bhpb/icon_pdf.gif") no-repeat', 'background-position': '0 -4px' });
    });
    $("ul.generalList li a[href$=.PDF]").each(function(){        
        $(this).parent("li").css({ 'background': 'url("/style library/images/bhpb/icon_pdf.gif") no-repeat', 'background-position': '0 -4px' });
    });   
$("#home_QLink a[href$=.pdf],#home_VLink a[href$=.pdf],#hero_QLink a[href$=.pdf],#tile_QLink a[href$=.pdf],#home_QLink a[href$=.PDF],#home_VLink a[href$=.PDF],#hero_QLink a[href$=.PDF],#tile_QLink a[href$=.PDF]").addClass("icon_pdflink").css({ 'padding-left': '34px' });
    $("#hero_QLink_right a[href$=.pdf],#hero_QLink_right a[href$=.PDF]").addClass("icon_pdflink").css({ 'padding-left': '34px', 'width': '210px' });
    $("#home_QLink a[href*=PageUp],#home_VLink a[href*=PageUp],#hero_QLink a[href*=PageUp],#tile_QLink a[href*=PageUp]").addClass("icon_search").css({ 'padding-left': '34px' });
    $("#hero_QLink_right a[href*=PageUp]").addClass("icon_search").css({ 'padding-left': '34px', 'width': '210px' });
});

//CR- 239458 Open pdf in new window
$(document).ready(function () {
    $('a[href$=.pdf]').attr("target","_blank");
    $('a[href$=.PDF]').attr("target","_blank");
});

// GLOBAL RUN VIDEO FUNCTION
$(document).ready(function () {
    $("#video_overlay").hide();
    $("#video_container").hide();
    $("#close").hide();
    $("#close a").click(function () {
        $("#video_overlay").hide();
        $("#video_container").hide();
        $("#close").hide();
        jwplayer("media_player").remove();
	// AMO Update - Fix for INC700013464902
        return false;
    });
});

$(document).ready(function () {
   var links = document.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++) {
        if (/.mp4$/.test(links[i].href))
            links[i].href = "javascript:runVideo(\'" + links[i].href + "\')";
    }
});

//$(document).ready(function () {
//    $("a").each(function (index, domEle) {
//        if ($(this).parent().is('.bhpb-rteElement-5')) {
//            // e.preventDefault();  //stop the browser from following 
//            domEle.href = "javascript:RedirectVideoDownload(\'" + domEle.href + "\')";
//        }
//        else {
//            if (/.mp4$/.test(domEle.href))
//                domEle.href = "javascript:runVideo(\'" + domEle.href + "\')";
//        }
//    });
//});

//function RedirectVideoDownload(link) {
//    window.location.href = link;
//}


//Alert user if its a old flash player
function ChecknAlertflash() {

    if (!IsMobileDevice()) {
        var version = GetFlashVersion().split(',').shift();
        if (version < 9) {
            showPopupMessage('Adobe Flash Player', 'You need flash player version 9.0.115 or above \r\nto play video on this site. \r\nDownload the latest flash player here: \r\nhttp://get.adobe.com/flashplayer');
            return false;
        } else {
            //Do nothing.
        }
    }
    return true;
}

//Finding out if its a iDevice
function IsMobileDevice() {
    var ua = navigator.userAgent.toLowerCase();
    var isMobilenCromeBrwsr = /ipad/i.test(ua) || /iphone/i.test(ua) || /android/i.test(ua) || /blackberry/i.test(ua) || /windows ce/i.test(ua) || /windows phone/i.test(ua);
    if (isMobilenCromeBrwsr == true) {
        var isChrome = /Chrome/i.test(ua);
        if (isChrome == false) {
            return true;
        }
    }
    return false;
}

//Finding out flash player version on the browser
function GetFlashVersion() {
    try {
        try {
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch (e) { return '6,0,0'; }
        } catch (e) { }
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
        // other browsers
    } catch (e) {
        try {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch (e) { }
    }
    return '0,0,0';
}


// SEARCH FILTER OPEN

$(document).ready(function () {
    var urlQS = window.location.search.substring(1);
    var ref = urlQS.match(/3A%22(.*?)%22/gi);
    if (ref != null) {
        for (i = 0; i < ref.length; i++) {
            ref[i] = ref[i].replace("3A%22", "");
            ref[i] = ref[i].replace("%22", "");
            var active = $(".filter_metaValues a.ms-searchref-filterlink:contains(" + ref[i] + ")");
            active.parents("li").addClass('active');
            active.css("cssText", "color:#E85100 !important");
            active.parents(".filter_metaValues").show();
            active.parents(".filter_metaValues").prev(".filter_metaHead").removeClass('filter_metaHead').addClass('filter_metaHeadOpen');
        }
    }
    var cat = urlQS.match(/3D%22(.*?)%22/gi);
    if (cat != null) {
        for (i = 0; i < cat.length; i++) {
            cat[i] = cat[i].replace("3D%22", "");
            cat[i] = cat[i].replace("%22", "");
            var active = $(".filter_metaValues a.ms-searchref-filterlink:contains(" + cat[i] + ")");
            active.parents("li").addClass('active');
            active.css("cssText", "color:#E85100 !important");
            active.parents(".filter_metaValues").show();
            active.parents(".filter_metaValues").prev(".filter_metaHead").removeClass('filter_metaHead').addClass('filter_metaHeadOpen');
        }
    }
    var year = urlQS.match(/3B%23(.*?)%22/gi);
    if (year != null) {
        for (i = 0; i < year.length; i++) {
            year[i] = year[i].replace("3B%23", "");
            year[i] = year[i].replace("%22", "");
            var active = $(".filter_metaValues a:contains(" + year[i] + ")");
            active.parents("li").addClass('active');
            active.css("cssText", "color:#E85100 !important");
            active.parents(".filter_metaValues").show();
            active.parents(".filter_metaValues").prev(".filter_metaHead").removeClass('filter_metaHead').addClass('filter_metaHeadOpen');
        }
    }
});

// SEARCH FILTER FULL WIDTH AMPERSAND ISSUE

$(document).ready(function () {
    $('#search_filter_zone li a').each(function (index) {
        for (i = 0; i < $(this).text().length; i++) {
            if ($(this).text().charCodeAt(i) == 65286)
                $(this).text($(this).text().substring(0, i) + "&" + $(this).text().substring(i + 1));
        }
    });
});


// IMAGE GALLERY FILTER FULL WIDTH AMPERSAND ISSUE

$(document).ready(function () {
    $('#tertiary_nav li a').each(function (index) {
        for (i = 0; i < $(this).text().length; i++) {
            if ($(this).text().charCodeAt(i) == 65286)
                $(this).text($(this).text().substring(0, i) + "&" + $(this).text().substring(i + 1));
        }
    });
});

$(document).ready(function () {
    $('#search_results .result:first').css({ 'border-top': 'none', 'padding-top': '0' });
});

/* Breadcrumb GT symbol */
/*
$(document).ready(function () {
    var $gtChar = $('#breadcrumb');
    $gtChar.html($gtChar.text().replace('>', '<img src="/style library/images/bhpb/icon_breadcrumb_gt.gif" alt="" />'));
    Cufon.refresh();
});
*/

/* Search page Home inactive state */

$(document).ready(function () {
    if (/SearchResults.aspx/.test(self.location.href)) {
        $("ul.bhpb_menu_l1 li.active").removeClass("active");
    }
});

/* Home tab left align */

$(document).ready(function () {
    $("ul.bhpb_menu_l1 li:first a:first").css({ 'padding-left': '20px' });
});

/* Truncate I&M LP titles*/

$(window).load(function () {
    var i = 0;
    for (i = 0; i <= 2; i++) {
        var length = 90;
        var newsItem = $(".column .news_item h3 a").eq(i).text();
        if (newsItem.length > length) {
            var truncNews = newsItem.substring(0, length);
            truncNews = truncNews.replace(/\w+$/, '');
            var truncNews = truncNews + '...';
            $(".column .news_item h3 a").eq(i).text(truncNews);
        }
        var docItem = $(".column .document h3 a").eq(i).text();
        if (docItem.length > length) {
            var truncDoc = docItem.substring(0, length);
            truncDoc = truncDoc.replace(/\w+$/, '');
            var truncDoc = truncDoc + '...';
            $(".column .document h3 a").eq(i).text(truncDoc);
        }
    }
});

/* Conditional Footer Adjustments (Businesses/About Us) */

$(document).ready(function () {
    if ($("#hero_banner_operations").length > 0 || $("#info_columns_container").length > 0) {
        $("#global_footer").css("cssText", "margin-top:0px !important");
    }
});


/* Conditional style rectify on clicking on quickdeploy button */

$(document).ready(function () {
    $("#hero_title").each(function () {
        var value = $(this).html();
        if (value.indexOf('<DIV>') >= 0) {
            SolveQuickDeployStyle();
        }
    });
});

function SolveQuickDeployStyle() {
    $("#hero_title div").css({ 'top': '-20px', 'margin': '0', 'outline': '0 none', 'padding': '0', 'margin-bottom': '18px', 'left': '0px', 'position': 'relative', 'font-size': '1.2em', 'color': '#FFFFFF', 'float': 'left', 'width': '340px', 'line-height': '1.5em' });

    Cufon.replace('#hero_title p div', { fontFamily: 'arial', fontWeight: 'normal' });
}
