﻿
// page initialization sequence
windowOnLoad = function() {
    // pageId identifies document, for page-specific scripts;
    setBgPosition();    // irritating hack
    window.pageId = document.getElementsByTagName('body')[0].id;
    setRollovers();     // set rollover behaviours for images
    if (client.engine == 'msie' && parseInt(client.engRev) == 6) { ieSixPngSupport(); }
    //setSwf();           // set swf movies for site
    setAncWidth();      // top of page anchor section styling script (shrink to fit longest link)
    setLinkEvents();    // set link events by type
    setGlossary();      // hide anchorlinks in glossary for nonexistant sections
    setExitLink();      // sets exit link url based on querystring.
    setDropDowns();     // sets dropdown functionality for the main menu
    setPagintion(1500); // set pages to paginate at 1500 pixels depth of (pagination) content
    setListExpansion(document.getElementById('map'), ['contracted', 'expanded']);
    //setTopNavState();   // sets nav state.
}
window.onresize = function() { setBgPosition(); }    // irritating hack



// finds best method to detect window load event
if (/KHTML/i.test(navigator.userAgent)) {
    var checkLoad = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { clearInterval(checkLoad); windowOnLoad(); } }, 70);
    document.addEventListener('load', windowOnLoad, false);
}
if (typeof window.addEventListener != 'undefined') {
    document.addEventListener('DOMContentLoaded', windowOnLoad, false);
    document.addEventListener('load', windowOnLoad, false);
} else if (typeof window.attachEvent != 'undefined') {
    document.write('<script id=__ie_onload defer src=https:javascript:false></script>');
    document.getElementById('__ie_onload').onreadystatechange = function(evt) { if (this.readyState == 'complete') windowOnLoad(); };
    window.attachEvent('onbeforeunload', function() {
        __flash_unloadHandler = function() { };
        __flash_savedUnloadHandler = function() { };
    });
}




// set state of topNav by page location
var setTopNavState = function(override) {
    // reset all menu states to passive
    var mainNav = document.getElementById('navigation-main');
    if (mainNav) { //check to see if it exists
        mainNav.normalize();
        for (var i = 0; i < mainNav.childNodes.length; i++) {
            var thisItm = mainNav.childNodes[i];
            if (thisItm.nodeName != 'LI') {
                continue;
            } else {
                thisImg = thisItm.getElementsByTagName('img')[0];
                thisImg.out();
            }
        }
    }
    // restore previously nullifed mouseouts
    setRollovers();
    // get current button index
    if (/.+\/index.html$/.test(document.location.href) && !override) {
        var pBut = 0;
    } else {
        var pBut = override || document.qstr.page || null;
    }
    // set image state, and remove mouseout
    el = document.getElementById('topNav' + (parseInt(pBut) + 1));
    if (el) {
        var thisImg = el.getElementsByTagName('img')[0];
        thisImg.ovr();
        thisImg.onmouseout = null;
    }
}




// function sets custom link behaviors by attribute
var setLinkEvents = function() {
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        var l = links[i];
        // if type is defined, assign behaviour by it.
        if (l.getAttribute('linktype')) {
            switch (l.getAttribute('linktype')) {
                case 'poparticle':
                    l.onclick = function() {
                        popArticle(this.href);
                        return false;
                    }
                    break;
                case 'popinter':
                    l.onclick = function() {
                        popInter(this.href);
                        return false;
                    }
                    break;
                case 'closewin':
                    l.onclick = function() {
                        self.close();
                        return false;
                    }
                    break;
                case 'gopage':
                    l.onclick = function() {
                        var newwindow = window.open(this.href, '', 'height=600,width=900,location=1,menubar=0,resizable,scrollbars=1');
                        self.close();
                        newwindow.focus();
                        return false;
                    }
                    break;
                case 'printwin':
                    l.onclick = function() {
                        window.print();
                        return false;
                    }
                    break;
                case 'showoverlayimage':
                    l.onclick = function() {
                        // move href to custom attribute, and remove
                        if (!this.getAttribute('imgUrl')) {
                            this.setAttribute('imgUrl', this.href);
                            this.removeAttribute('href');
                        }
                        // show overlay
                        showOverlayImage(this.getAttribute('imgUrl'), this.getAttribute('mapto'));
                        return false;
                    }
                    break;
            }
        }
    }
}




// function gets page num from path
var getPageName = function() {
    var sPath = window.location.pathname;
    return sPath.substring(sPath.lastIndexOf('/') + 1);
}




// top of page anchor section styling script (shrink to fit longest link)
var setAncWidth = function() {
    var allLists = document.getElementsByTagName('ul');
    // for each list
    for (var i = 0; i < allLists.length; i++) { //<-- for i in allLists
        var thisList = allLists[i];
        // exclude all but lists .anchors
        if (thisList.className == 'anchors' || thisList.className == 'split-links' || thisList.className == 'peach-links') {
            // look at all linkes within each list
            var listLinks = thisList.getElementsByTagName('a');
            var longestLink = 0;
            for (var ii = 0; ii < listLinks.length; ii++) { //<-- for i in listLinks\
                var thisLink = listLinks[ii];
                // record width of longest link
                longestLink = Math.max(longestLink, thisLink.offsetWidth);
            }
            // set width of list to longest link's width
            thisList.style.width = longestLink / 10 + 'em';
        }
    }
}




// hide anchorlinks in glossary for nonexistant sections
var setGlossary = function() {
    var glossAnchors = document.getElementById('glossary-anchors')
    if (glossAnchors) {
        // determines if an anchor link leads anywhere on the page
        var hasSection = function(anchor) {
            // get all anchors and the name attbr to search for
            var allAnchors = document.getElementsByTagName('a');
            var anchor = anchor.href.split('#')[1];
            // if match found, return true, else return false
            for (var ii = 0; ii < allAnchors.length; ii++) { if (allAnchors[ii].name == anchor) { return true } }
            return false;
        }
        // go through all glossary anchors and hide the dead ones.
        glossAnchors = glossAnchors.getElementsByTagName('a');
        for (var i = 0; i < glossAnchors.length; i++) {
            var thisAnchor = glossAnchors[i];
            // hide or show anchor by availability of attached content
            thisAnchor.parentNode.style.display = (hasSection(thisAnchor)) ? 'inline' : 'none';
        }
        // return to anchor on page to assure page-length adjustments jive with anchors
        if (/#/.test(document.location.href)) { document.location.href = '#' + document.location.href.split('#')[1] }
        //				document.location.href = document.location.href;
    }
}




// set external link href (used in both popup, and interstitial behaviour)
function setExitLink(url) {
    var exitLink = document.getElementById('extLinkExitLink');
    var exitUrl = url || unescape(document.qstr.goTo) || false;
    if (exitLink) {
        if (exitUrl) {
            exitLink.href = exitUrl;
            exitLink.style.display = 'block';
        } else {
            throw ('setExitLink was not sent an argument and the querystring variable \'goTo\' is undefined: where do you want to go?');
        }
    }
}




// set swf movies for site
var setSwf = function() {
    // if flash support insuffient, hide links to flash content
    if (swf.rev < 7) {
        var allLinks = document.getElementsByTagName('*');
        for (var i = 0; i < allLinks.length; i++) {
            var thisLink = allLinks[i];
            if (thisLink.getAttribute('swfReq')) { thisLink.style.display = 'none'; }
        }
    }
    // set options for flash movies
    var flashOpts = {
        width: 980,
        height: 571,
        bgcolor: '#FFFFFF',
        wmode: 'transparent',
        revReq: 7,
        altCont: './1_1.html'
    }
    // set movie url if exists
    var swfUrl = false;
    switch (document.body.id) {
        case 'home':
            swfUrl = './allergan_site.swf';
            break;
        case 'experts':
            swfUrl = './allergan_site.swf';
            break;
    }
    // support for deeplinking via querystring
    if (typeof (document.qstr.page) != 'undefined') { swfUrl += '?page=' + document.qstr.page; }
    // embedding script for ask the experts
    if (swfUrl) {
        var movieParen = document.getElementById('body');
        window.exptsMovie = swf.movie(swfUrl, flashOpts);
        if (exptsMovie) {
            exptsMovie = movieParen.appendChild(exptsMovie);
            movieParen.style.width = '980px';
            movieParen.style.height = '571px';
        }
    }
}




// set list expansion
var setListExpansion = function(listRoot, toggle) {
    if (listRoot && toggle && toggle.length == 2) {
        var allItems = listRoot.getElementsByTagName('li');
        for (var i = 0; i < allItems.length; i++) {
            var thisItem = allItems[i];
            if ((thisItem.className == (toggle[0] || toggle[1])) && thisItem.getElementsByTagName('ul').length != 0) {
                var clickElement = thisItem.getElementsByTagName('*')[0];
                clickElement.onclick = function() { this.parentNode.className = (this.parentNode.className == toggle[0]) ? toggle[1] : toggle[0]; }
            }
        }
    }
}




// set dropdown menus ... got help anyone that ever has to maintain this ... 
var setDropDowns = function() {
    var navList = document.getElementById('navigation-main');
    if (navList) {
        navList.normalize();
        // get some element
        var allItems = navList.getElementsByTagName('li');
        var allLinks = navList.getElementsByTagName('a');
        // create global function for timeout passing
        window.hideLastOut = function() {
            if (typeof (window.navOutObj) != 'undefined' && window.navOutObj) {
                window.navOutObj.className = 'closed';
                if (window.navOutObj.getAttribute('istop')) { try { window.navOutObj.firstChild.firstChild.onmouseout(); } catch (e) { } } //<!-- ugly, I know ... no time ... 
            }
        }
        // loop through items and handle appearance
        for (var i = 0; i < allItems.length; i++) {
            var thisItem = allItems[i];
            // remove mouseover event from top-level menu graphics
            // as that behaviour will be set by in the li element
            if (thisItem.id.indexOf('topNav') != -1) { thisItem.setAttribute('istop', 'true'); }
            if (thisItem.getAttribute('istop')) {
                thisItem.onmouseover = function() {
                    window.navOutTimer = clearTimeout(window.navOutTimer);
                    window.navOutObj = false;
                    // hide previous menu
                    if (typeof (window.navOnObj) != 'undefined') {
                        if (this.getAttribute('istop')) {
                            window.navOnObj.className = 'closed';
                            try { window.navOnObj.firstChild.firstChild.onmouseout(); } catch (e) { } //<!-- ugly, I know ... no time ... 
                        }
                    }
                    // show this menu menu
                    if (this.getAttribute('istop')) {
                        this.className = 'opened';
                        this.firstChild.firstChild.onmouseover();
                    }
                    // set previous menu ref for future
                    window.navOnObj = this;
                }
                thisItem.onmouseout = function() {
                    window.navOutObj = this;
                    window.navOutTimer = setTimeout(window.hideLastOut, ((client.engine == 'msie') ? 500 : 5)); // <!-- ie needs extra help on the timer of course ...
                }
            } else {
                thisItem.onmouseover = function() { this.className = 'hover'; }
                thisItem.onmouseout = function() { this.className = ''; }
                if (thisItem.firstChild.nodeName == 'A' && thisItem.firstChild.href == document.location.href) {
                    thisItem.onmouseover();
                    thisItem.onmouseout = null;
                    var menuParent = thisItem.parentNode.parentNode;
                    menuParent.normalize()
                    var parentImg = menuParent.firstChild.firstChild;
                    parentImg.out = parentImg.ovr;
                    parentImg.ovr();
                } else {
                    thisItem.onmouseout();
                }
            }
        }
        // loop through links and set click behaviour for flash, if support available
        for (var i = 0; i < allLinks.length; i++) {
            var thisLink = allLinks[i];
            var flashIndex = thisLink.getAttribute('flashIndex');
            if (swf.rev >= 7 && flashIndex) {
                thisLink.onclick = function() {
                    if (typeof (exptsMovie) != 'undefined' && exptsMovie) {
                        // js-based linking when flash is present
                        exptsMovie.setVar('page', this.getAttribute('flashIndex'));
                        setTopNavState(this.getAttribute('flashIndex'));
                    } else {
                        // page-based linking when flash is not present
                        document.location.href = './index.html?page=' + this.getAttribute('flashIndex');
                    }
                }
                thisLink.removeAttribute('href')
            }
        }
    }
}




// set pagintation for long pages
var setPagintion = function(maxDepth, debug) {
    // will store blocks of html in sections of pages
    var pageBlocks = [[]];
    var currentPage = 0;
    // returns an array of elements designated for use as controls blocks
    var returnControls = function() {
        var controls = [];
        var allElements = document.getElementsByTagName('*');
        for (var i = 0; i < allElements.length; i++) {
            // find element and skip if not a pagination control
            var thisControl = allElements[i]
            if (thisControl.className != 'pagination') { continue; }
            // add control to array
            controls.push(thisControl);
        }
        return controls;
    }
    // finish styling the control blocks ..
    var styleControls = function() {
        var controls = returnControls();
        for (i in controls) {
            // get object refs
            var control = controls[i];
            var prevLink = control.getElementsByTagName('a')[0];
            var nextLink = control.getElementsByTagName('a')[1];
            var pageList = control.getElementsByTagName('ul')[0];
            var pageone = control.getElementsByTagName('li')[0];
            var pageDiv = pageList.parentNode;
            // set some styling properties
            control.style.width = ((prevLink.offsetWidth + nextLink.offsetWidth + pageList.offsetWidth) / 10) + 'em';
            pageDiv.style.marginLeft = (prevLink.offsetWidth / 10) + 'em';
            pageDiv.style.marginRight = (nextLink.offsetWidth / 10) + 'em';
            pageone.style.borderLeft = 'none';
            control.style.visibility = 'visible';
            // css bugfix ... only workaround for firefox bug ... irritating
            control.style.position = 'absolute';
            control.style.right = '0';
            control.style.top = '0';
        }
    }
    // create all controls ... pretty self explanatory
    var createControls = function() {
        var controls = returnControls();
        for (i in controls) {
            var control = controls[i];
            var prevLink = control.appendChild(document.createElement('a'));
            prevLink.className = 'prev';
            prevLink.innerHTML = 'Previous page';
            prevLink.onclick = function() { goToPage('prev'); }
            var nextLink = control.appendChild(document.createElement('a'));
            nextLink.className = 'next';
            nextLink.innerHTML = 'Next page';
            nextLink.onclick = function() { goToPage('next'); }
            var pagesDiv = control.appendChild(document.createElement('div'));
            pagesDiv.className = 'pages';
            var pagesList = pagesDiv.appendChild(document.createElement('ul'));
            for (ii in pageBlocks) {
                var thisPage = pagesList.appendChild(document.createElement('li'));
                var thisLink = thisPage.appendChild(document.createElement('a'));
                thisLink.innerHTML = (parseInt(ii) + 1);
                thisLink.onclick = function() { goToPage(parseInt(this.innerHTML) - 1); }
            }
        }
    }
    // function attached to anchor links to ensure content is visible.
    // need to add anchor link support ...
    var goToPage = function(dest) {
        // defaults
        var page = dest || 0;
        // keyword based navigation
        if (page == 'prev') { page = Math.max(currentPage - 1, 0); }
        if (page == 'next') { page = Math.min(currentPage + 1, pageBlocks.length - 1); }
        // show the target page
        for (i in pageBlocks) {
            var thisPage = pageBlocks[i];
            for (ii in thisPage) {
                thisPage[ii].style.display = (i == page) ? 'block' : 'none';
            }
        }
        // classify pagination controls
        var controls = returnControls();
        for (i in controls) {
            // get object refs
            var control = controls[i];
            var pageLinks = control.getElementsByTagName('li');
            // classify numbered controls
            for (var ii = 0; ii < pageLinks.length; ii++) {
                thisLink = pageLinks[ii];
                thisLink.className = (parseInt(thisLink.firstChild.innerHTML) - 1 == page) ? 'current' : '';
            }
            // classify named controls
            control.childNodes[0].className = (page == 0) ? 'prevOff' : 'prev';
            control.childNodes[1].className = (page + 1 == pageBlocks.length) ? 'nextOff' : 'next';
        }
        // back to the top.
        window.scrollTo(0, 0);
        // record current page
        currentPage = page;
    }
    // break up content blocks and display requested page
    // uses href to deeplink anchor linkage. Pretty smart!
    var setContBlocks = function(maxDepth, debug) {
        var thisPage = 0;
        var thisDepth = 0;
        var allElements = document.getElementsByTagName('*');
        for (var i = 0; i < allElements.length; i++) {
            // find element and skip if not a paginated block
            var block = allElements[i];
            if (!block.getAttribute('paginate') || block.getAttribute('paginate') != 'true') { continue; }
            var blockDepth = block.offsetHeight;
            var thisBlock = pageBlocks[thisPage];
            // pagination decision logic
            if (!thisBlock.length || (thisDepth + blockDepth <= maxDepth)) {   // <-- if empty or short enough to fit use current array node
                thisDepth += blockDepth;
            } else {                                                           // <-- set/create next array node when current block won't fit
                thisDepth = blockDepth; thisPage++;
                pageBlocks.push([]);
            }
            // push this block onto selected subarray
            pageBlocks[thisPage].push(block);                                  // <-- push block onto selected array node
        }
        // only display pagination if doc contains > 1 page
        if (pageBlocks.length > 1) {
            createControls(goToPage);
            styleControls();
            goToPage();
        }
    }
    // initialize
    setContBlocks(maxDepth, debug);
}




var setRollovers = function() {
    var bareUrl = function(string) {
        string = string.substring(string.lastIndexOf('#'));
        string = string.substring(string.lastIndexOf('?'));
        return string;
    }
    var allImages = document.getElementsByTagName('img');
    for (var i = 0; i < allImages.length; i++) {
        var thisImage = allImages[i];
        var thisPath = thisImage.src.substring(0, (thisImage.src.lastIndexOf('/') + 1));
        var thisFile = thisImage.src.substring(thisImage.src.lastIndexOf('/') + 1);
        var thisParent = thisImage.parentNode;
        if ((/_off$/.test(thisFile.split('.')[0])) || (/_on$/.test(thisFile.split('.')[0]))) {
            thisImage.setAttribute('imagpath', thisPath);
            thisImage.setAttribute('ovrstate', thisFile.split('_off.').join('_on.'));
            thisImage.setAttribute('offstate', thisFile);
            // create state-setting methods.
            thisImage.ovr = function() {
                this.src = this.getAttribute('imagpath') + this.getAttribute('ovrstate');
                if (client.engine == 'msie' && parseInt(client.engRev) == 6) { makePngIe6Friendly(this); }
            }
            thisImage.out = function() {
                this.src = this.getAttribute('imagpath') + this.getAttribute('offstate');
                if (client.engine == 'msie' && parseInt(client.engRev) == 6) { makePngIe6Friendly(this); }
            }
            // surface state-setting methods.
            thisImage.onmouseover = function() { this.ovr(); }
            thisImage.onmouseout = function() { this.out(); }
        }
    }
}




// support for graphic interstitial overlays
var showOverlayImage = function(imgUrl, mapto) {
    var thisImg = document.getElementById('site-wrapper').appendChild(document.createElement('img'));
    thisImg.id = 'overlayImageLayer';
    thisImg.style.visibility = 'hidden';


    thisImg.setAttribute('isMap', 'true');
    thisImg.setAttribute('useMap', '#' + mapto);
    thisImg.setAttribute('border', '0');

    thisImg.isMap = true;
    thisImg.useMap = '#' + mapto;

    // don't try and style image until it has has loaded ... 
    thisImg.onload = function() {
        this.style.left = (this.parentNode.offsetWidth - this.offsetWidth) / 2 + 'px';
        this.style.top = parseInt(Math.max((client.viewport()[1] - this.offsetHeight), 1) / 2) + parseInt(client.scrollCoords()[1]) + 'px';
        this.style.position = 'absolute';
        this.style.visibility = 'visible';
    }
    window.hideoverlay = function() {
        var destroyNode = document.getElementById('overlayImageLayer');
        destroyNode = document.getElementById('site-wrapper').removeChild(destroyNode);
        destroyNode = null;
    }
    // change src and wait for the onload event to fire.
    thisImg.src = imgUrl;
}




// handles daughter windows for articles
function popArticle(url) {
    var height = 500;
    var width = 996;
    newwindow = window.open(url, '', 'height=' + height + ',width=' + width + ',location=1,menubar=0,resizable,scrollbars=1');
    if (window.focus) { newwindow.focus() }
    return false;
}




// handles daughter windows for interstitials
function popInter(url) {
    var height = 275;
    var width = 350;
    newwindow = window.open(url, '', 'height=' + height + ',width=' + width + ',location=0,menubar=0,resizable,scrollbars=1');
    if (window.focus) { newwindow.focus() }
    return false;
}




// handles printing & tracking
function printPage(Pagename, channel, eVar2) {
    s = s_gi(s_account);
    s.Pagename = Pagename;
    s.channel = channel;
    s.eVar2 = eVar2;
    s.linkTrackVars = "eVar2";
    //s.tl(object,'o','PrintClick');
    window.print();
}




// hack to make sure positioning of background and wrapper match on both even and odd width viewports ... retarded.
var setBgPosition = function() {
    // get width and elements (limit to even numbers only)
    var viewWidth = Math.floor((client.viewport()[0] / 2)) * 2;
    var parent = document.getElementById('site-wrapper');
    var body = document.getElementsByTagName('body')[0];
    try {
        // calculate positioning
        var posLeft = parseInt(viewWidth - parent.offsetWidth) / 2;
        var posLeftBg = parseInt(posLeft - 789);
        // set positioning
        parent.style.marginLeft = posLeft + 'px';
        body.style.backgroundPosition = posLeftBg + 'px 0px';
        body.style.backgroundrepeat = 'no-repeat';
    } catch (e) { }

}





