var contextPath;

// text zoom control

textzoom = {};
textzoom.LEVELS = [55, 62.5, 77, 85];
textzoom.DEFAULT_INDEX = 1;
textzoom.index = Number(getCookie('zoom') || textzoom.DEFAULT_INDEX);
textzoom.zoom = function(n) {
    switch (n) {
        case +1: textzoom.index = Math.min(textzoom.index+1, textzoom.LEVELS.length-1); break;
        case -1: textzoom.index = Math.max(textzoom.index-1, 0); break;
        default: textzoom.index = textzoom.DEFAULT_INDEX; break;
    }
    document.body.style.fontSize = textzoom.LEVELS[textzoom.index] + '%';
    setCookie('zoom', textzoom.index, 365, '/');
};

/* patient callout */

document.write('<style type="text/css" media="screen">body { font-size: ' + textzoom.LEVELS[textzoom.index] + '%; }</style>');var contextPath;

function button_on(bgcolor,filename) {
  document.getElementById('callout-bg').style.backgroundColor='#'+bgcolor;
  document.getElementById('footer-on').src= getContextPath()+'/images/'+filename;
}

function button_off(bgcolor,filename) {
  document.getElementById('callout-bg').style.backgroundColor='#'+bgcolor;
  document.getElementById('footer-on').src= getContextPath()+'/images/'+filename;
}

/* css browser specific targeting */

var css_browser_selector = function() {
  var 
    ua=navigator.userAgent.toLowerCase(),
    is=function(t){ return ua.indexOf(t) != -1; },
    h=document.getElementsByTagName('html')[0],
    b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
    os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
  var c=b+os+' js';
  h.className += h.className?' '+c:c;
}();

function externalLinks() { 
  if (!document.getElementsByTagName) return; 
  var anchors = document.getElementsByTagName("a"); 
  for (var i=0; i<anchors.length; i++) { 
    var anchor = anchors[i]; 
    if (anchor.getAttribute("href") && anchor.getAttribute("class") == "external")anchor.target = "_blank"; 
  }
}

function nonFlashHeaderInit(){
  var tabContsIds = ['cll','dlbcl','marcus','e1496','relapsed'];
  var tabs = YAHOO.util.Dom.getElementsByClassName('splash-header-nav', 'ul')[0].getElementsByTagName('a');
  
  function tabClick(e){
    var el = getTarget(e);
    if(!(el.parentNode.className.match(/-active/))){
    
      for(var k=0;k<tabs.length;k++){
        var tgClass = tabs[k].parentNode.className;  
        if(tgClass.match(/active/)){
            if(document.all)tabs[k].style.backgroundImage = "url('../images/btn-hcp-header-off"+(k+1)+".png')";
            tabs[k].parentNode.className = tgClass.replace(/-active/,'');   
        }else if(tabs[k]==el){
           switchTab(tabContsIds[k]);
           if(document.all)el.style.backgroundImage =  "url('../images/btn-hcp-header-on"+(k+1)+".png')";
           el.parentNode.className += "-active";
        }
      }
     
    }
  }
  
    var tabs = YAHOO.util.Dom.getElementsByClassName('splash-header-nav', 'ul')[0].getElementsByTagName('a');
    for(var i=0;i<tabs.length;i++){
      addEvent(tabs[i],'mousedown',tabClick);
    }
  
}

function onLoadEvent(){
  externalLinks();
  initializeLinks();
  if(window.location.href.match(/hcp\/index.m/))nonFlashHeaderInit();
  if(window.location.href.match(/patient\/resources\/living\/index.m/))window.onunload = onUnloadFunc;
}

// special case link initialization

RituxanLymphoma_WARNING = '<div class="warning">The information contained in this section of the site is intended for U.S. healthcare professionals only. Click "OK" if you are a healthcare professional.</div>';
LINK_DISCLAIMER = '<div class="warning">The link you have selected will take you away from this site to one that is not owned or controlled by Genentech, Inc. Genentech, Inc. makes no representation as to the accuracy of the information contained on sites we do not own or control.\n\n Genentech does not recommend and does not endorse the content on any third-party websites. Your use of third-party websites is at your own risk and subject to the terms and conditions of use for such sites.</div>';
WINDOWS_DISCLAIMER = '<div class="warning">Windows only!</div>';

function initializeLinks() {
    var anchor, i = 0;
    while ((anchor = document.getElementsByTagName('a')[i++]) != null) {
        if (hasClass(anchor, 'external'))
            anchor.setAttribute('target', '_blank');
        if (hasClass(anchor, 'third-party'))
            addEvent(anchor, 'click', disclaimLink);
        if (hasClass(anchor, 'windows-only'))
            addEvent(anchor, 'click', windowsLink);
        if (hasClass(anchor.parentNode, 'hcp-link'))
            addEvent(anchor, 'click', warnApop);
        if (hasClass(anchor, 'windows-span-hover')){
            addEvent(anchor, 'mouseover', showSpan);
            addEvent(anchor, 'mouseout', hideSpan); 
        }
        
        if (anchor.href.match(".pdf")) 
            addEvent(anchor,"click",downloadPi);
          
    }      
}

function windowsLink(e) {
    confirmRedirect(e, WINDOWS_DISCLAIMER);
}

function disclaimLink(e) {
    confirmRedirect(e, LINK_DISCLAIMER);
}

function showSpan(e){
  var tg = getTarget(e);
  if(tg.tagName!='A') tg = tg.parentNode;
  var tgSpan = tg.getElementsByTagName('span')[0];
  if(tgSpan!=undefined){
    addClass(tgSpan,'show');
    addEvent(tgSpan, 'mousemove', function(e){
      removeClass(tgSpan,'show');
    });
    addEvent(tg, 'mouseout', function(e){
      removeClass(tgSpan,'show');
    });
  }
}

function hideSpan(e){
    var tg = getTarget(e);
    if(tg.tagName!='A') tg = tg.parentNode;
    var tgSpan = tg.getElementsByTagName('span')[0];
    if(tgSpan!=undefined)removeClass(tgSpan,'show');
}

function warnApop(e) {
    if (!location.pathname.match(/\/apop\//)) {
        var target = getTarget(e);
        target.href = rewriteHref(target.href);
        confirmRedirect(e, RituxanLymphoma_WARNING);
    }
}

function goPat(e) {
    var target = getTarget(e);
    location = rewriteHref(target.href);
    cancelEvent(e);
}

function rewriteHref(href) {
    var m;
    if (m = location.href.match(/\/(apop)\/([^\/]+)\//)) {
        href = href.replace(/\/(apop)\/.*/, '/' + '$1' + '/' + m[2] + '/');
    }
    return href;
}

function confirmRedirect(e, disclaimer) {
    var target = getTarget(e);
    if(target.tagName == "IMG" || target.tagName == "STRONG" || target.tagName == "SPAN") target = target.parentNode;
    var href = target.href;
    cancelEvent(e);

    function handleOK() {
        dialog.hide();
        if (hasClass(target, 'external'))
            window.open(href);
        else
            location = href;
    }

    function handleCancel() {
        dialog.hide();
        dialog.destroy();
    }

    var dialog = new YAHOO.widget.SimpleDialog('dialog',
                                              {
                                                  buttons: [ { text: 'OK', handler: handleOK },
                                                             { text: 'Cancel',  handler: handleCancel } ],
                                                  close: false,
                                                  constraintoviewport: true,
                                                  draggable: false,
                                                  fixedcenter: true,
                                                  modal: true,
                                                  icon: YAHOO.widget.SimpleDialog.ICON_WARN,
                                                  text: disclaimer,
                                                  underlay: 'none',
                                                  visible: false,
                                                  width: '315px'
                                              });
    dialog.setHeader('Rituxan.com/lymphoma');
    dialog.render(document.body);
    dialog.show();
}

//addEvent(window, 'load', initializeLinks);

// utility functions

function getCookie(name) {
    var pattern = new RegExp('(^|; )' + name + '=([^;]*)');
    var m = document.cookie.match(pattern);
    return m && unescape(m[2]);
}

function setCookie(name, value, days, path, domain, secure) {
    var c = name + '=' + escape(value);
    var expires = null;
    if (days)
        expires = new Date(new Date().getTime() + (days * 24 * 60 * 60 * 1000));
    if (expires)
        c += '; expires=' + expires.toUTCString();
    if (path)
        c += '; path=' + path;
    if (domain)
        c += '; domain=' + domain;
    if (secure)
        c += '; secure';
    document.cookie = c;
}

function getClasses(element) {
    return element.className.trim().split(/\s+/);
}

function hasClass(element, c) {
    return getClasses(element).indexOf(c) != -1;
}

function addClass(element,newCs){
  if(!(hasClass(element,newCs))) element.className += (" "+newCs);
}

function removeClass(element, rmCs){
    if(hasClass(element,rmCs)){
     var cs=element.className.match(' '+rmCs)?' '+rmCs:rmCs;
     element.className = element.className.replace(cs,""); 
    }
}

function addEvent(obj, type, fn) {
    if (obj.addEventListener)
        obj.addEventListener(type, fn, false);
    else if (obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function() { obj['e' + type + fn](window.event); }
        obj.attachEvent('on' + type, obj[type + fn]);
    }
}

function removeEvent(obj, type, fn) {
    if (obj.removeEventListener)
        obj.removeEventListener(type, fn, false);
    else if (obj.detachEvent) {
        obj.detachEvent('on' + type, obj[type + fn]);
        obj[type + fn] = null;
        obj['e' + type + fn] = null;
    }
}

function cancelEvent(e) {
    var e = e || window.event;
    e.cancelBubble = true;
    if (typeof e.stopPropagation == 'function')
        e.stopPropagation();
    e.returnValue = false;
    if (typeof e.preventDefault == 'function')
        e.preventDefault();
}

function getTarget(e) {
    var e = e || window.event;
    return e.target || e.srcElement;
}

function getTransport() {
    if (typeof window.XMLHttpRequest != 'undefined')
        return new XMLHttpRequest();
    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (ex) {}
    try { return new ActiveXObject('MSXML2.XMLHTTP'); } catch (ex) {}
    return null;
}

function onUnloadFunc(){ 
  checkTimeOnUnload();
}

function getMatchingTextNodes(node, pattern) {
    if (node == null || node.nodeType != 1)
        return;
    var nodes = [];
    var root = node;
    while (node != null) {
        if (node.hasChildNodes())
            node = node.firstChild;
        else if (node != root && null != (next = node.nextSibling))
            node = next;
        else {
            next = null;
            for ( ; node != root; node = node.parentNode) {
                next = node.nextSibling;
                if (next != null) break;
            }
            node = next;
        }
        if (node != null && node.nodeType == 3) {
            while ((match = pattern.exec(node.data)) != null)
                nodes.push([node, match]);
        }
    }
    return nodes;
}

function urlencode(str) {
    var encode = (typeof encodeURIComponent == 'function')
        ? encodeURIComponent
        : escape;
    return encode(str).replace(/%20/g,'+');
}

Array.prototype.indexOf = function(item, start) {
    for (var i = (start || 0); i < this.length; i++) {
        if (this[i] == item) return i;
    }
    return -1;
}

String.prototype.trim = function() {
    return this.replace(/^\s+/,'').replace(/\s+$/,'');
}


function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
    thefield.value = "";
}

function setContextPath(path) {
  contextPath = path;
}

function switchTab(_id){
  var container = document.getElementById('splash-feature');
  var child = container.firstChild;
 while (child){ 
    if (child.innerHTML != undefined) {
      if (child.id == _id) {
        child.style.display = 'block';
      } else {
        child.style.display = 'none';
      };
    }
    child = child.nextSibling;
  }
}

function smoothSwap(flag){ 
  var el1, el2;
  if(flag==undefined){
    var el1 = 'merril-vid';
    var el2 = 'lwl-fallback';
    YAHOO.util.Dom.setStyle(el2, 'opacity', 0);
  }else{
    var el1 = 'lwl-fallback';
    var el2 = 'merril-vid';
  }
  YAHOO.util.Dom.setStyle([el1, el2], 'display', 'block');
  var opc = 10;
  var timer = setInterval(function(){
  YAHOO.util.Dom.setStyle(el1, 'opacity', opc/10);
  YAHOO.util.Dom.setStyle(el2, 'opacity', 1/opc);
    if(opc-- == 0) {
      YAHOO.util.Dom.setStyle(el1, 'opacity', 0);
      YAHOO.util.Dom.setStyle(el2, 'opacity', 1);
      //IE fix--  need to get rid of "filter" attribute to show the contents propery inside of the the element which has "filter"
      if(document.all){
        try {
          document.getElementById(el2).style.removeAttribute('filter');
        }catch(err){
          alert(err);
        }
      }
      
      if (el1 == "merril-vid") so.write("merril-video-div"); //IE fix
      YAHOO.util.Dom.setStyle(el1, 'display', 'none');
      clearInterval(timer);
    }
   
  },100);
  
  
} 

var downloadPi = function(ev) {
  var el =  getTarget(ev);
  if(el.tagName.toUpperCase() != "A")el = el.parentNode;
  var piUrl = "http://www.gene.com/gene/products/information/pdf/rituxan-prescribing.pdf";
  var url = el.href;
  if(url!=piUrl){ 
    if(isIe6() || navigator.userAgent.indexOf('AppleWebKit/') > -1){
      window.open(piUrl, "Pi");
    }else{
      location.href = piUrl;
    }
  }
};

var isIe6 = function(){
  return document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0);
}

YAHOO.util.Event.onDOMReady(onLoadEvent); 