﻿var isIE6 = false;
var isIE7 = false;

var fontSizeCookie = 'font-size';

$(document).ready(function () {
    $(".labelify").labelify({ labelledClass: "hasLabel" });
    $("#topBarMenu, #pageContainer, #contentSubNavContainer, #contentSubNavContainer div").cleanWhitespace();
    if (!checkPrint()) {
        checkIE();
        setNavRollovers();
        setRolloverSubchannels();
        highlightCurrentPage();
    }
    setInterstitials();
    setReferenceLinks();
    initGlossaryPopups();

    // set the font size based off of previous setting (if available)
    getFontSize();

    // Check to see if fontSizeCookie exist. If not Set med text button to active.
    checkCookieExist();


});


/*CHECK IF IE6*/
/**************/
//sets global var true if ie6 is detected
function checkIE(){
    if(String(navigator.appVersion).indexOf("MSIE 6") > -1){
        isIE6 = true;
        //alert("set true");
    }
    if (String(navigator.appVersion).indexOf("MSIE 7") > -1) {
        isIE7 = true;
        //alert("set true");
    }
}


/*ROLLOVER NAV STUFF*/
/********************/
//shows subnav when primary nav button is entered, keeps primary highlighted
//while the list is hovered, and removes all when mouse leaves
function setNavRollovers() {
    //bind rollover to primary nav button to show subnav on mouseover
    //stopping previous animation to make animation more intuitive
    $(".hasSubNav", "#mainNav").each(function() {
        $(this).children("a.rollover:first").bind("mouseenter", function() {
            $(this).parent().children("ul.subNav").stop(true, true).slideDown(400);
        });
        //hide subnav and remove primary nav highlight on mouse leave
        $(this).bind("mouseleave", function() {
            $(this).children("ul.subNav").slideUp(400);
            $(this).children("a:first").removeClass("activeNav");
        });
        //keep primary nav highlighted while on list but not on primary nav
        $(this).bind("mouseenter", function() {
            $(this).children("a:first").addClass("activeNav");
        });
    });
    //hide afterload so images are preloaded
    $(".subNav").css("display", "none");
}


/*RIGHT TOUT SETTER*/
/********************/
//looks for right touts, hides them, then brings back only those touts
//called as parameters in the function, placing them in the order they
//are called as args in the function call, then sets top one to correct class
function setRightTouts() {
    var targetList = $("#rightBodyContainer .textTout, #rightBodyContainer .graphicTout").css("display", "none");
    targetList.css("display", "none");

    for (var i = (arguments.length - 1); i >= 0; i--) {
        var currTarget = targetList.filter("[name=" + arguments[i] + "]");
        currTarget.css("display", "block");
        if (i > 0) currTarget.addClass("notFirst");
    }
    $(".toutContainer").show();
}


/*ROLLOVER SUBCHANNELS*/
/**********************/
//finds subchannels in content subnavs and applies rollover to the
//container, so offstate is the background image, and onstate is the
//contents, which are the rollover images for each link
function setRolloverSubchannels() {
    $("div.subChannel").each(function() {
        $(this).bind("mouseenter", function() { $(this).children().css("display", "block") });
        $(this).bind("mouseleave", function() { $(this).children().css("display", "none") });
        $(this).children().css("display", "none");
    });
}


/*SET ACTIVE LINKS FOR CURRENT PAGE*/
/***********************************/
//highlights the content subnav and the main nav according to
//the current page, as well as initializes the view
function highlightCurrentPage() {
    var pathName = window.location.pathname;
    var pattern = /[a-z_\-]*.aspx/i;
    var page = pathName.match(pattern);
    //check content subnav for the current page and gives it the
    //highlight class. if the page exists in a subchannel, then
    //make the subchannel in the overstate and remove its offstate
    //mouseover binds, as well as reset the page to the highest sibling
    //so the main nav can check against it, since subchannels aren't
    //in the main nav
    var anySubchannels = false;
    $("a[href$=" + page + "]", "#contentSubNavContainer").each(function() {
        $(this).addClass("currentPageHighlight");
        if ($(this).parent().hasClass("subChannel")) {
            anySubchannels = true;
            $(this).parent().children().css("display", "block");
            $(this).parent().unbind();
            page = String($(this).parent().children("a:first").attr("href"));
        }
    });
    //check the main nav for the current page (or subchannel main page)
    //and give its landing page link the highlight class
    $("a[href$=" + page + "]", "#mainNav").each(function() {
        if ($(this).parents("ul").hasClass("subNav")) {
            anySubchannels = true;
            $(this).parents("li.hasSubNav").each(function() { $(this).children("a").addClass("currentPageHighlight"); });
        }
        else {
            $(this).addClass("currentPageHighlight");
        }
    });
    //hide all subnavs, then refind the channel using the main navs
    //highlight, save a key url to search against in the subnav, and
    //when that is found, show that specific subnav. This is to get
    //around the fact that there is no link to the landing page of a
    //channel in the subnav
    $("#contentSubNavContainer > div").css("display", "none");
    var keyPage = $(".currentPageHighlight", "#mainNav").siblings("ul").find("a:first").attr("href");
    var keyElement = $("#contentSubNavContainer").find("a[href$=" + keyPage + "]");
    if (keyElement.length > 0) {
        keyElement.parents("div").css("display", "block");
        anySubchannels = true;
    }

    if (!anySubchannels) $("#contentSubNavContainer").css("display", "none");
}


/*PRINT THE CURRENT PAGE*/
/************************/
//opens the current page in a new window with modified view, basically
//just the page content, and prints the page
function printThisPage() {
    var modifiedHref = String(window.location) + ((String(window.location).indexOf("?") == -1) ? "?print=true" : "&print=true");
    window.open(modifiedHref, "printPage", "screenX=200, left=200, screenY=100, top=100, width=700, height=700, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no, status=no, menubar=yes, copyhistory=no");
}


/*CHECK IF PAGE IS A PRINT PAGE*/
/*******************************/
//checks if the page is being loaded as a print request and takes action
//accordingly
function checkPrint() {
    var href = String(window.location);
    if (href.indexOf("print=true") <= -1) {
        return false;
    }
    else {
        //send content to body to make hiding everything easier
        $('form#aspnetForm').append($('#leftBodyContainer'));
        $('form#aspnetForm').append($('#fullBodyContainer'));
        $('#leftBodyContainer,#fullBodyContainer').css("margin-left", "auto");
        $('#leftBodyContainer,#fullBodyContainer').css("margin-right", "auto");
        
        // rip out the former containers, to ensure that they don't get printed by inferior browsers *coughIEcough*
        $('#centeredContainer, #contentSubNavContainer, #pat-hcp-switchContainer').remove();

        // add the print stylesheet
        $('head').append('<link title="print" href="styles/print.css" rel="Stylesheet" type="text/css" />');

        window.print();
        return true;
    }
}


/* PURGE TEXT */
/********************/
// removes all text nodes from the matched tags.
// does not recurse into child nodes, so text deeper in the DOM tree is safe.
// intended primarily to remove whitespace between successive image elements.
jQuery.fn.cleanWhitespace = function() {
    textNodes = this.contents().filter(function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); })
        .remove();
};


/* INTERSTITIAL CONNECTION */
/********************/
// automatically links interstitial panels to appropriate links.
var alliedSitesArray = [ "peernetwork.net", "livingpah.com", "lungrx.com" ];
function setInterstitials() {
    var currHost = window.location.hostname;
    var outTargets = jQuery("a[href^='http://'], a[href^='https://']").not("[href*='://" + currHost + "'], [href$=.pdf]"); // should grab every outbound link on the page
    outTargets.filter('[href*="unither.com"]').addClass('outbound-ut');
    jQuery('#utInterstitial').jqm({ trigger: 'a.outbound-ut', onShow: outboundUtClicked });
    outTargets.not('[href*="unither.com"]').addClass('outbound-generic');
    jQuery('#genericInterstitial').jqm({ trigger: 'a.outbound-generic', onShow: outboundGenericClicked });

    jQuery('#utInterstitial .jqmContinue').click(function() {
        jQuery('#utInterstitial').jqmHide();
    });

    jQuery('#genericInterstitial .jqmContinue').click(function() {
        jQuery('#genericInterstitial').jqmHide();
    });

    jQuery('#hcpInterstitial .jqmContinue').click(function() {
        jQuery('#hcpInterstitial').jqmHide();
    });

    var inTargets = jQuery("a[href^='../']");
    inTargets.filter("[href^='../hcp/']").addClass('outbound-hcp');
    jQuery('#hcpInterstitial').jqm({ trigger: 'a.outbound-hcp', onShow: outboundHcpClicked });
}

function outboundUtClicked(hash) {
    jQuery('#utInterstitial').show();
    jQuery('#utInterstitial .jqmContinue').attr('href', jQuery(hash.t).attr('href'));
}

function outboundGenericClicked(hash) {
    jQuery('#genericInterstitial').show();
    jQuery('#genericInterstitial .jqmContinue').attr('href', jQuery(hash.t).attr('href'));
    try {
        nameMatcher = new RegExp("^https?://[a-zA-Z0-9_\.]*");
        matches = nameMatcher.exec(hash.t);
        httpsMatcher = new RegExp("^https?://(www\.)?");
        targetName = matches[0].replace(httpsMatcher, "");
        jQuery('#genericInterstitial .targetName').text(targetName);
        if (alliedSitesArray.join().indexOf(targetName) >= 0) jQuery("#genericInterstitial #interstitialDisclaimer").hide();
        else jQuery("#genericInterstitial #interstitialDisclaimer").show();
    }
    catch (err) {
        jQuery('#genericInterstitial .targetName').text("an unrelated site");
    }
}

function outboundHcpClicked(hash) {
    jQuery('#hcpInterstitial').show();
    jQuery('#hcpInterstitial .jqmContinue').attr('href', jQuery(hash.t).attr('href'));
}


/* REFERENCE CONNECTION */
/********************/
// automatically links interstitial panels to appropriate links.

function setReferenceLinks() {
    jQuery('.reference').each(function() {
        var linkId = jQuery(this).text();
        jQuery(this).wrapInner('<a href="references.aspx?refid=' + linkId + '" />');
    });
}
function initGlossaryPopups() {
    jQuery('a.glossary').click(function() {
        return false;
    });
    jQuery('#glossaryPopup').jqm({ ajax: '@href', trigger: 'a.glossary' });
}


/* FONT SIZING */
/********************/
// automatically links interstitial panels to appropriate links.

function setFontSize(size) {
    setFontSizeInternal(size);

    var pageSize
    if (size == 12) pageSize = "small";
    else if (size == 16) pageSize = "large";
    else pageSize = "medium";
    trackLink(this, document.URL + '~size-' + pageSize, 'o');
}

function setFontSizeInternal(size) {
    // set the font size
    jQuery('#contentBodyContainer').css('font-size', parseFloat(size));
    jQuery('#isiContainer').css('font-size', parseFloat(size));

    // store the size in a cookie
    jQuery.cookie(fontSizeCookie, parseFloat(size));

    // Reset active rollover state on refresh or when changing text size.
    $('#text-size-small, #text-size-med, #text-size-large').css('background-position', 'top left');

    // Find text size from cookie and set active rollover style to text size buttons
    if (size == 12) {
        $('#text-size-small').css('background-position', 'bottom left');
    } else if (size == 16) {
        $('#text-size-large').css('background-position', 'bottom left');
    } else {
        $('#text-size-med').css('background-position', 'bottom left');        
    }
}

function getFontSize() {
    // get the size from a cookie
    if (jQuery.cookie(fontSizeCookie)) {
        var size = jQuery.cookie(fontSizeCookie);
        
        // set the size
        setFontSizeInternal(size);
        
    }
}

function checkCookieExist() {
    // Check to see if fontSizeCookie exist. If not Set med text button to active.
    if (jQuery.cookie(fontSizeCookie) == null) {
        $('#text-size-med').css('background-position', 'bottom left');
    }       
}


