jQuery(function($) {
    // jQuery is passed as the first arg $
    $('.img-right img,.img-left img').bind('load', function() {
      var $img = $(this), imgWidth = $img.width();
      $img.siblings('p').width(imgWidth);
    }).each(function() {
    // we need to force the "load" event to fire if it was already complete:
    // technique taken from https://gist.github.com/268257
    if (this.complete || this.complete === undefined){
      var src = this.src;
      // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
      // data uri bypasses webkit log warning (thx doug jones)
      this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      this.src = src;
    }
  });
});

var MGHTools = {
    init: function() {
        this.rollOver();
        this.openCloseLinks();
        this.printPage();
        if ($E('.sN')) {
            this.setSubNavHover();
        }
        if ($E('.wSubs')) {
            $$('.tN').hoverIntent({
                over: this.mainNavOn,
                out: this.mainNavOff
            });
        }
        if ($E('.noSubs')) {
            this.setMainNavHover();
        }
        if ($E('.tabNav')) {
            this.tabNavigation();
        }
        
        /* BEGIN awb9 9.16.2008 added for DL Paging Feature 
           jlp8: function no longer needed during initialization.*/
        if ($E('.pgnTop')) {       
            this.pageNavigation();
        }
        
        /* END awb9 9.16.2008 added for DL Paging Feature */
        /* BEGIN awb9 9.16.2008 added for DL AZ Feature */
        if ($E('.a2zNav')) {
            this.azNavigation();
        }
        /* END awb9 9.16.2008 added for DL AZ Feature */
        if ($E('.toTop')) {
            this.pageScroll();
        }
        if ($E('.recNLink')) {
            this.setRecedingNav();
        }
        /*tool tips rollover functionality disabled
        if ( $E('.toolTip') ) {
        this.toolTips();
        }*/
        if ($E('.pageTools')) {
            /*
            this.txtCookieCheck();            
            this.textSize();*/
            /* awb9 12.8.2008 this.bookMarkThis(); */
            /*any link that calls an overlay needs to be added to the LightBox.Add object parameters below. 
            Example: { LinkId: 'toolEmail', LightBoxId: 'LightBoxTest }  LinkId: is the id of the <a> tag, LightBoxId: is the id of the light box window
            The links below call the same light box, to call seperate light boxes for each, give each LightBoxId: an individual name.
            The light box window should be contained inside the html page that's calling it, at the bottom of the page before the </body> tag.
            */
            /*
            LightBox.Add([
            {    
            LinkId: 'toolEmail',     
            LightBoxId: 'LightBoxTest'            
            },                
            {
            LinkId: 'toolShare',
            LightBoxId: 'LightBoxShareThisPage'
            }
            ]);
            LightBox.formHints();    
            */
        }
    },
    setRecedingNav: function() {
        var recNav = $E('.dropNav');
        recNav.hide();
        var slideNav = new Fx.Slide(recNav, {
            onComplete: function() {
                if (this.closeMe) {
                    this.slideOut();
                    recLk.removeClass('recNOn');
                }
                if (this.openMe) {
                    this.slideIn();
                }
                this.closeMe = false;
                this.openMe = false;
            }
        });
        slideNav.slideOut();
        var recLk = $E('.recNLink').addEvents({
            'mouseenter': function() {
                if (slideNav.timer) {
                    slideNav.openMe = true;
                    slideNav.closeMe = false;
                } else {
                    slideNav.openMe = false;
                    this.addClass('recNOn');
                    recNav.show();
                    slideNav.slideIn();
                }
            },
            'mouseleave': function() {
                if (slideNav.timer) {
                    slideNav.closeMe = true;
                    slideNav.openMe = false;
                } else {
                    slideNav.closeMe = false;
                    this.removeClass('recNOn');
                    slideNav.slideOut();
                }
            }
        });
    },
    mainNavOn: function() {
        this.addClass('hover');
    },
    mainNavOff: function() {
        this.removeClass('hover');
    },
    setMainNavHover: function() {
        $$('.tN').addEvents({
            'mouseenter': function() {
                this.addClass('hover');
            },
            'mouseleave': function() {
                this.removeClass('hover');
            }
        });
    },
    setSubNavHover: function() {
        $$('.sN').addEvents({
            'mouseenter': function() {
                this.addClass('active');
            },
            'mouseleave': function() {
                this.removeClass('active');
            }
        });
    },
    // any image with the class name "rollOver" will have an image roll over. There must be a roll over image with the same name 
    // plus the additional "_over" at the end of the image name. Example button.gif and button_over.gif    
    rollOver: function() {
        var oPreLoad = new Array();
        var oTempSrc;
        var imageEles = $$('.rollOver');
        imageEles.each(function(image, index) {
            var srcName = image.getProperty('src');
            var xSrc = srcName.substring(0, srcName.indexOf('.gif'));
            var newSrc = xSrc + '_over.gif';
            image.setProperty('newSrc', newSrc);

            // preload 'on' state images
            oPreLoad[index] = new Image();
            oPreLoad[index].src = newSrc;

            image.addEvents({
                'mouseover': function() {
                    oTempSrc = this.getProperty('src');
                    this.setProperty('src', this.getProperty('newSrc'));
                },
                'mouseout': function() {
                    if (!oTempSrc) oTempSrc = this.getAttribute('src').replace(/_over/i, '');
                    this.setProperty('src', oTempSrc);
                }
            });
        });
    },
    tabNavigation: function() {
        var allTabs = $$('.tabNav li');
        var infoDivs = $$('.tabInfo');
        var currTab = $E('.tabNav .active');
        var currHref = currTab.getElement('a').getProperty('href');
        var tabIndex = currHref.substring(currHref.indexOf('tab') + 3) - 1;
        var currTabContent = infoDivs[tabIndex];

        // hide all divs EXCEPT the one specified in tabIndex - displayed by default.
        infoDivs.each(function(div) {
            if (div != currTabContent) {
                div.hide();
            }
        });
        /* 
        When the tab <li> is clicked, add the class 'active', and remove active class from current tab.
        Get the href value of the link inside the <li>.
        Extract the id value from the href and display the corresponding tabInfo <div> with the same id.
        The href value of the tab link MUST equal the id of its corresponding content <div>.
        Hide all other tabInfo divs.
        */
        allTabs.each(function(ele) {
            ele.addEvent('click', function(evt) {
                new Event(evt).stop();
                if (currTab != this) {
                    currTab.removeClass('active');
                }
                var href = this.getElement('a').getProperty('href');
                var divID = href.substring(href.indexOf('#') + 1);

                try {
                    var pageID = divID + "_page1";
                    var pageResultsID = pageID + "_results";
                    var pageResultsBottomID = pageID + "_results_bottom";

                    $(pageID).show();
                    $(pageResultsID).show();
                    if ($(pageResultsBottomID))
                        $(pageResultsBottomID).show();

                }
                catch (err) {
                    //'tabNavigation: function() => ele.addEvent(\'click\', function(evt) => Error: ' + err.description; 
                }


                if (currTabContent != $(divID)) {
                    currTabContent.hide();
                }

                this.addClass('active');
                $(divID).show();
                currTab = this;
                currTabContent = $(divID);

                /* if there is paging results, go back to hide correct pages on tab change */
                if ($E('.pgnTop')) {
                    var resultDivs = $$('.resultPageNumbers');
                    // hide all divs EXCEPT the one specified in tabIndex - displayed by default.
                    resultDivs.each(function(div) {
                        //if(div.id != "tab1_page1_results"){
                        if (div.id == divID + "_page1_results" || div.id == divID + "_page1_results_bottom") { div.show(); }
                        else { div.hide(); }
                    });
                }

            });
        });
    },
    /* BEGIN awb9 9.16.2008 added for DL, Media Coverages, Paging Feature */
    // jlp8 function no longer needed or invoked. The new functionality resides now in the 
    // goToMediaCoveragePage(page) function.
    pageNavigation: function() {
        try {
            var allTabs = $$('.pgnTop li');
            var infoDivs = $$('.pageInfo');
            var resultDivs = $$('.resultPageNumbers');
            /*Note ... had to change this class .resultPageNumbers for paging formatting*/
            var currTab = $E('.pgnTop .active');
            var currHref = currTab.getElement('a').getProperty('href');
            var tabIndex = currHref.substring(currHref.indexOf('page') + 4) - 1;
            var currTabContent = infoDivs[tabIndex];

            // hide all divs EXCEPT the one specified in tabIndex - displayed by default.    
            infoDivs.each(function(div) {
                if (div != currTabContent) {
                    div.hide();
                }
            });
            

            // hide all divs EXCEPT the one specified in tabIndex - displayed by default.        
            resultDivs.each(function(div) {
                if (div.id == "tab1_page1_results" || div.id == "tab1_page1_results_bottom") { div.show(); }
                else { div.hide(); }
            });
            
            
            /* 
            When the tab <li> is clicked, add the class 'active', and remove active class from current page.
            Get the href value of the link inside the <li>.
            Extract the id value from the href and display the corresponding pageInfo <div> with the same id.
            The href value of the tab link MUST equal the id of its corresponding content <div>.
            Hide all other pageInfo divs.
            */
            
            allTabs.each(function(ele) {
                ele.addEvent('click', function(evt) {
                    new Event(evt).stop();
                    console.log(this);
                    if (currTab != this) {
                        currTab.removeClass('active');
                        currTab.removeClass('current');
                    }
                    var href = this.getElement('a').getProperty('href');
                    var divID = href.substring(href.indexOf('#') + 1);
                    console.log(divID);
                    var divResultsID = divID + "_results";
                    var divResultsBottomID = divID + "_results_bottom";
                    //alert(divResultsID);    

                    if (currTabContent != $(divID)) {
                        console.log("hide:  " + currTabContent);
                        currTabContent.hide();
                    }
                    else {
                        console.log("do not hide:  " + currTabContent);
                    }
                    
                    infoDivs.each(function(div) {
                        div.hide();
                    });

                    resultDivs.each(function(div) {
                        div.hide();
                    });
                    
                    this.addClass('active');
                    this.addClass('current');
                    $(divID).show();
                    $(divResultsID).show();
                    if ($(divResultsBottomID))
                        $(divResultsBottomID).show();
                    currTab = this;
                    currTabContent = $(divID);

                });
            });
        }
        catch (err) {
            //'pageNavigation: function() => ele.addEvent(\'click\', function(evt) => Error: ' + err.description; 
        }
    },
    /* END awb9 9.16.2008 added for DL Paging Feature */

    /* BEGIN awb9 9.16.2008 added for DL AZ Paging Feature */
    azNavigation: function() {
        try {
            var allTabs = $$('.a2zNav li');
            var infoDivs = $$('.azInfo');
            var resultDivs = $$('.resultNumber');
            var currTab = $E('.a2zNav .active');
            var currHref = currTab.getElement('a').getProperty('href');
            var tabIndex = currHref.substring(currHref.indexOf('page') + 5) - 1;
            var currTabContent = infoDivs[tabIndex];

            // hide all divs EXCEPT the one specified in tabIndex - displayed by default.
            infoDivs.each(function(div) {
                if (div != currTabContent && tabIndex != 0) {
                    div.hide();
                }
            });

            // hide all divs EXCEPT the one specified in tabIndex - displayed by default.
            resultDivs.each(function(div) {
                if (div.id == "pages1_results" || div.id == "pages1_results_bottom") { div.show(); }
                else { div.hide(); }
            });

            /* 
            When the tab <li> is clicked, add the class 'active', and remove active class from current page.
            Get the href value of the link inside the <li>.
            Extract the id value from the href and display the corresponding pageInfo <div> with the same id.
            The href value of the tab link MUST equal the id of its corresponding content <div>.
            Hide all other pageInfo divs.
            */
            allTabs.each(function(ele) {
                ele.addEvent('click', function(evt) {
                    new Event(evt).stop();
                    if (currTab != this) {
                        currTab.removeClass('active');
                    }
                    var href = this.getElement('a').getProperty('href');

                    var divID = href.substring(href.indexOf('#') + 1);
                    var divResultsID = divID + "_results";
                    var divResultsBottomID = divID + "_results_bottom";

                    infoDivs.each(function(div) {
                        if (href == "#pages1") {
                            infoDivs.each(function(div) {
                                div.show();
                            });
                        }
                        else {
                            div.hide();
                        }
                    });

                    resultDivs.each(function(div) {
                        if (href == "#pages1" && (div.id == "pages1_results" || div.id == "pages1_results_bottom")) { div.show(); }
                        else { div.hide(); }
                    });

                    this.addClass('active');
                    $(divID).show();
                    $(divResultsID).show();
                    if ($(divResultsBottomID))
                        $(divResultsBottomID).show();
                    currTab = this;
                    currTabContent = $(divID);
                });
            });
        }
        catch (err) {
            //'azNavigation: function() => ele.addEvent(\'click\', function(evt) => Error: ' + err.description;
        }
    },
    /* END awb9 9.16.2008 added for DL AZ Paging Feature */
    pageScroll: function() {
        var scroll = new Fx.Scroll(window, {
            duration: 1000,
            transition: Fx.Transitions.Quad.easeInOut
        });
        $$('.toTop').each(function(el) {
            el.addEvent('click', function(event) {
                event = new Event(event).stop();
                scroll.toTop();
            });
        });
    },
    toolTips: function() {
        var tipArrow = new Element('div', {
            'class': 'tipArrow'
        });
        var myTips = new Tips($$('.toolTip'), {
            maxTitleChars: 50,
            offsets: { 'x': -27, 'y': -30 },
            fixed: true,
            initialize: function() {
                this.fx = new Fx.Style(this.toolTip, 'opacity', { duration: 200, wait: false }).set(0);
            },
            onShow: function(toolTip) {
                this.fx.start(1);
                var tipBox = $E('.tool-tip');
                if (tipBox) {
                    tipArrow.inject(tipBox);
                }
            },
            onHide: function(toolTip) {
                this.fx.start(0);
            }
        });
    },
    createTextStyle: function(ss) {
        largeStyle = new Element('link', {
            'href': '../assets/css/font_' + ss + '.css',
            'rel': 'stylesheet',
            'media': 'screen',
            'type': 'text/css'
        });
        largeStyle.inject($E('head'));
    },
    txtCookieCheck: function() {
        if (Cookie.get('textSize') != null) {
            var textLink = $('toolText');
            var size = Cookie.get('textSize');
            MGHTools.createTextStyle(size);

            if (Cookie.get('textSize') == 'large') {
                textLink.setText('Smaller Text');
                textLink.setProperty('rel', 'default');
            } else {
                textLink.setText('Larger Text');
                textLink.setProperty('rel', 'large');
            }

        } else {
            Cookie.set('textSize', 'default', { path: '/' });
            MGHTools.createTextStyle('default');
        }
    },
    textSize: function() {
        $('toolText').addEvent('click', function() {
            var size = this.getProperty('rel');

            Cookie.set('textSize', size, { path: '/' });
            MGHTools.createTextStyle(size);

            if (document.all) {
                window.location.reload();
            } else {
                location = document.URL;
            }
            return false;
        });
    },
    printPage: function() {
        if ($('toolPrint')) {
            $('toolPrint').addEvent('click', function() {
                window.print();
                return false;
            });
        }
    },
    closeLink: function() {
        this.hide();
    },
    openLink: function() {
        this.show();
    },
    openCloseLinks: function() {
        if ($E('.openLink')) {
            var ol = $E('.openLink');
            var th = $E('.toggleHide');
            var cl = $E('.closeLink');
            boundOpenLink = MGHTools.openLink.bind(th);
            ol.addEvent('click', boundOpenLink);
            boundCloseLink = MGHTools.closeLink.bind(th);
            cl.addEvent('click', boundCloseLink);
        }
    },
    bookMarkThis: function() {
        var urlAddress = location.href;
        var pageTitle = document.title;
        $('toolBmark').addEvent('click', function() {
            if (window.sidebar) {
                window.sidebar.addPanel(pageTitle, urlAddress, "");
            } else if (window.external) {
                window.external.AddFavorite(urlAddress, pageTitle);
            }
            else {
                return;
            }
            return false;
        });
    }
}

Element.extend({
    show : function() {
        this.removeClass('hidden');
    },                    
    hide : function() {
        this.addClass('hidden');
    },
    isHidden: function() {
        return this.hasClass('hidden');
    },

    hoverIntent: function(f,g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $extend(cfg, g ? { over: f, out: g } : f );

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            if(!ev.pageX) {
                ev.pageX = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
                ev.pageY = event.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
            }
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
                $(ob).removeEvent("mousemove",track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob,[ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev,ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob,[ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
            if ( p == this ) { return false; }

            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = $extend({},e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // else e.type == "onmouseover"
            if (e.type == "mouseover") {
                if(!ev.pageX) {
                    ev.pageX = event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
                    ev.pageY = event.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
                }
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                ob.addEvent("mousemove",track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

            // else e.type == "onmouseout"
            } else {
                // unbind expensive mousemove event
                ob.removeEvent("mousemove",track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
            }
        };

        // bind the function to the two event listeners
        return this.addEvents({'mouseover': handleHover,'mouseout': handleHover});
    }
});            

//jlp8. New function showing and hiding paging navigation
function goToMediaCoveragePage(page) {
    var pageName = window.location.pathname.toLowerCase();
    if(pageName.indexOf("mediacoverage.aspx") != -1) {                    
        var divID = "#" + page;                    
        var divResultsID = divID + "_results";
        var divResultsBottomID = divResultsID + "_bottom";
        
        jQuery('.pageInfo').each(function(){
            if(!(jQuery(this).hasClass('hidden'))){
                jQuery(this).addClass('hidden');
            }
        });
        
        jQuery('.resultPageNumbers').each(function(){
            if(!(jQuery(this).hasClass('hidden'))){
                jQuery(this).addClass('hidden');
            }
        });        

        jQuery(divID).removeClass('hidden');
        jQuery(divResultsID).removeClass('hidden');
        jQuery(divResultsBottomID).removeClass('hidden');
    }
}

window.onDomReady(function(){
 MGHTools.init();

 var pageUrl = window.location.href.split('?')[0];
 pageUrl = pageUrl.toLowerCase();
 
    if (pageUrl.indexOf('heartcenter') != -1 ||
        pageUrl.indexOf('vascularcenter') != -1 ||
        pageUrl.indexOf('digestive') != -1 ||
        pageUrl.indexOf('cancer') != -1 ||
        pageUrl.indexOf('transplant') != -1)
    {
       //no SAYT for centers
    }
    else
    {
        searchAsYouType.initialize(document.getElementById('searchBox'), false);
    }

});


function textResize(size)
{
    MGHTools.createTextStyle(size);
}

