var contextPath;

// text zoom control

textzoom = {};
textzoom.LEVELS = [62.5, 77, 85, 93];
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, '/');
};
document.write('<style type="text/css" media="screen">body { font-size: ' + textzoom.LEVELS[textzoom.index] + '%; }</style>');

/* 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;
}();

// special case link initialization

ResearchVEGF_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 USA, Inc. Genentech USA, 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>';

function initialize() {
    initializeLinks();
    fo.init("flyout");
    mochaDrawers.init("drawer");
    videos.init("video-link");
    initTabs();
}

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.parentNode, 'apop-link'))
            addEvent(anchor, 'click', warnApop);
    }
}

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

function warnApop(e) {
    if (!location.pathname.match(/\/apop\//)) {
        var target = getTarget(e);
        target.href = rewriteHref(target.href);
        confirmRedirect(e, ResearchVEGF_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 = 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('researchvegf.com');
    dialog.render(document.body);
    dialog.show();
}

// adding tab functions
var tab = function(cfg){
            var cfg = cfg;
    
            this.openTab = function(){
              cfg.onOpenTab();
              removeClass(cfg.tabEl,'closed');
              removeClass(cfg.tabContEl,'closed');
              addClass(cfg.tabEl,'open');
              addClass(cfg.tabContEl,'open');
            }
            
            this.closeTab = function(){
              removeClass(cfg.tabEl,'open');
              removeClass(cfg.tabContEl,'open');
              addClass(cfg.tabEl,'closed');
              addClass(cfg.tabContEl,'closed');
            }
            
            this.getTabEl = function(){
              return cfg.tabEl;
            }
          }

function initTabs(){
  var tabCont;
  var tabEls;
  var tabs;
  if(document.getElementById('multimedia-callout-contents')){
    tabCont = document.getElementById('multimedia-callout-contents').getElementsByTagName('div');
    tabEls = document.getElementById('multimedia-callout-header').getElementsByTagName('div');
    tabs = new Array();
  for(var i=0;tabEls.length > i; i++){
    tabs.push(new tab({tabEl:tabEls[i].getElementsByTagName('a')[0],
                       tabContEl:tabCont[i],
                       parent:this,
                       onOpenTab:closeOtherTabs
                     }));
    YAHOO.util.Event.addListener(tabEls[i],'mousedown', tabs[i].openTab,this);
  }
  
  }
  function closeOtherTabs(tb){
    for(var i=0;i<tabs.length;i++){
      if(hasClass(tabs[i].getTabEl(),'open')) tabs[i].closeTab();
    }
  }

  if(location.href.match(/type-slides/))tabs[1].openTab();
}
// 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 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 = "";
}

var common = {
    pageInfo: {
	init: function(context, page) {
	    this.page = page;
	    this.contextPath = context;
	}
    }
};

/*** 
 * SlideDeck Controller 
 * Requires: YAHOO, YAHOO.Event, YAHOO.Dom, YAHOO.Container, common, meltmedia.widget.SlideDeck
 ***/

var slidedecks = {
    findAndActivate: function(cn, slidePrefix, fullDeckPrefix) {
	this.decks = [];
	this.slidePrefix = common.pageInfo.contextPath+slidePrefix;
	this.fullDeckPrefix = common.pageInfo.contextPath+fullDeckPrefix;
	var els = YAHOO.util.Dom.getElementsByClassName(cn);
	this.activate(els);
    },

    activate: function(els) {
	for ( var key in els ) {
	    if(typeof els[key] != "function") {
		YAHOO.util.Event.addListener(els[key], "click", this.show, this, true);
		if(this.checkDuplicate(this.parseQuery(els[key].href.split("?").pop()).deck)) {
		    this.create(els[key]);
		}
	    }
	}
    },

    checkDuplicate: function(id) {
	for ( var key in this.decks ) {
	    if(this.decks[key].id == id) return false
	}
	return true;
    },

    getSlides: function(deck, total, title) {
	var slides = [];
	for (var i=0; i<total; i++ ) {
	    var s = {
		src: this.slidePrefix+"/"+deck+"/Slide"+(i+1)+".jpg",
		title: title,
		description: ""
	    };
	    slides.push(s);
	}
	return slides;
    },

    parseQuery: function(query) {
	var properties = query.split("&");
	var o = {};
	for (var key in properties) {
	    if(typeof properties[key] != "function") {
		var p = properties[key].split("=")[0];
		var v = properties[key].split("=")[1];
		o[p] = (Number(v) == v) ? Number(v) : v;
	    }
	}
	return o;
    },

    swap: function(str, search, replace) {
	var l = str.lastIndexOf(search);
	var j = 0;
	
	var find = function() {
	    return str.indexOf(search);
	};

	var swap = function(s) {
	    var before = str.substring(0, s);
	    var after = str.substring(s+search.length, str.length);
	    str = before + replace + after;
	};

	while (j < l) {
	    j = find();
	    swap(j);
	    if(j <= -1) return str;
	}

	return str;
    },

    create: function(el) {
	var query = this.parseQuery(el.href.split("?").pop());

	var code = document.getElementById("slidedeck");
	var counter = document.getElementById("slidedeck_counter");
	counter.innerHTML = "1 of " + query["slides"];

	var newDeckCode = document.createElement("DIV");
	newDeckCode.id = "slidedeck-"+query["deck"];
	newDeckCode.style.visibility = "hidden";
	newDeckCode.innerHTML = code.innerHTML;
	var str = newDeckCode.innerHTML.toString();
	newDeckCode.innerHTML = this.swap(str, "slidedeck_", "slidedeck-"+query["deck"]+"_");
	document.body.appendChild(newDeckCode);
  var shouldCenter  = (screen.height>=900)? true : false; 
	var sd = new meltmedia.widget.SlideDeck(newDeckCode, {
		    fixedcenter: shouldCenter,
		    constraintoviewport: shouldCenter,
		    underlay:"none",
		    close:true,
		    visible:false,  
		    draggable:false,
		    modal:true,
		    slides: this.getSlides(query["deck"], query["slides"], el.title),
		    fulldeck: this.fullDeckPrefix+"/"+query["deck"]+"-slidedeck.ppt",
		    count:true,
		    width:"660px",
		    height:"700px"
	    });

	sd.render();

	var deck = {
	    id: query["deck"],
	    slides: sd
	};

	this.decks.push(deck);
    },

    show: function(ev) {
      
     if(screen.height<900){ 
       var slidedeckWindows = YAHOO.util.Dom.getElementsByClassName('slidedeck');
       for(var i=0; i<slidedeckWindows.length; i++){
         var sWind = slidedeckWindows[i]; 
         var wx = parseFloat(sWind.style.width);
         //var wy = parseFloat(sWind.style.height);
         sWind.parentNode.style.left = (screen.width - wx) / 2+ "px"; 
         //sWind.parentNode.style.top = (screen.height - wy) / 2 + "px"; 
         sWind.parentNode.style.top = "0px";
       }
     }
      
	   YAHOO.util.Event.preventDefault(ev);
	   var t = YAHOO.util.Event.getTarget(ev);
	   var query = this.parseQuery(t.href.split("?").pop());
	   for(var key in this.decks) {
	     if(typeof this.decks[key] != "function") {
		     if(this.decks[key].id == query["deck"]) {
		        this.decks[key].slides.show();
		     }
	     }
	   }
	   if(videos.players.length > 0) videos.disable();
   }
};

/**** Video Player Code ****/

var videos = {
    init: function(cn) {
	this.players = new Array();
	this.activate(YAHOO.util.Dom.getElementsByClassName(cn));
    },

    activate: function(els) {
	var url = window.location.toString();
	if(url.indexOf("?") > -1) this.overrideDefault = this.parseQuery(url.split("?").pop()).video;

	for ( var key in els ) {
	    if(typeof els[key] != "function") {
		this.create(els[key]);
	    }
	}
    },

    parseQuery: function(query) {
	var properties = query.split("&");
	var o = {};
	for (var key in properties) {
	    if(typeof properties[key] != "function") {
		var p = properties[key].split("=")[0];
		var v = properties[key].split("=")[1];
		o[p] = (Number(v) == v) ? Number(v) : v;
	    }
	}
	return o;
    },

    create: function(el) {
	// Snag the URL and parse the query if it's available
	var query = this.parseQuery(el.href.split("?").pop());
	if(this.overrideDefault) {
	    query["default"] = "false";
	    if(query.video == this.overrideDefault) {
		query["default"] = "true";
	    }
	}

	var v = new meltmedia.widget.MediaPlaya("flash-video", {
		// Switch this to true for testing the fail mode for the flash object (not required)
		testMode: false,
		player: common.pageInfo.contextPath+"/media/media-player/mmplaya.swf",
		id: query.video,
		params: {
		    scale: "noscale",
		    allowFullScreen: "true",
		    wmode: "window",
		    allowScriptAccess: "always"
		},
		variables: {
		    configURL: common.pageInfo.contextPath+"/media/videos/"+query.video+"/config.xml",
		    contextPath: common.pageInfo.contextPath
		},
		properties: query,
		metadata: {
		    titleEl: document.getElementById("media-title"),
		    title: el.title,
		    mediaEl: document.getElementById("media-downloads"),
		    mov: common.pageInfo.contextPath+"/media/videos/"+query.video+"/"+query.mov,
		    wmv: common.pageInfo.contextPath+"/media/videos/"+query.video+"/"+query.wmv
		},
		style: {
		    color: "#F9F9F9",
		    height: "411px",
		    width: "475px"
		}
	    });

	this.players.push(v);

	YAHOO.util.Event.addListener(el, "click", this.beforeOnChange, this, true);
    },

    beforeOnChange: function(ev) {
	YAHOO.util.Event.preventDefault(ev);
	var el = YAHOO.util.Event.getTarget(ev);
	this.onChange(el);
    },

    onChange: function(el) {
	var q = this.parseQuery(el.href.split("?").pop());
	var noVid = document.getElementById("no-video");
	//noVid.className = noVid.className.replace("disabled", "enabled");
	for(var k in this.players) {
	    if(typeof this.players[k] == "object") {
		if(this.players[k].id == q.video) {
		    //alert("Enabling: "+ q.video);
		    this.players[k].enable();
		    noVid.className = noVid.className.replace("enabled", "disabled");
		} else {
		    //alert("Disabling: "+ this.players[k].id);
		    this.players[k].disable();
		}
	    }
	}
    },

    disable: function() {
	var noVid = document.getElementById("no-video");
	noVid.className = noVid.className.replace("disabled", "enabled");
	for(var k in this.players) {
	    if(typeof this.players[k] == "object") {
		this.players[k].disable();
		this.players[k].disableMetaData();
	    }
	}
    }
};

/**** Flyout Menu Code ****/

var fo = {
    init: function(cn) {
	this.menus = [];
	var fos = YAHOO.util.Dom.getElementsByClassName(cn);
	if(fos.length > 0) {
	    this.create(fos);
	}
    },

    create: function(els) {
	for ( var key in els ) {
	    if(els[key]) {
		try {
		    if( !els[key].parentNode.id ) {
			els[key].parentNode.id = "flyout-menu-"+this.menus.length;
			this.menus.push(els[key].parentNode);
		    }
		} catch (e) {
		    // Do Nothing
		}
	    }
	}

	for ( var key in this.menus ) {
	    if ( typeof this.menus[key] == "object" ) {
		this.menus[key] = new meltmedia.widget.FlyOut(this.menus[key], {
			FLYOUT_CLASS: "mm-flyout-menu",
			offset: [ 150, 10 ]
		    });
		this.menus[key].hide();
	    }
	}
    }
};

/**** Drawer Callout Code ****/

var mochaDrawers = {
    init: function(cn) {
	this.drawers = [];
	var drs = YAHOO.util.Dom.getElementsByClassName(cn);
	if(drs.length > 0) {
	    this.create(drs);
	}
    },

    create: function(els) {
	for ( var key in els ) {
	    if(typeof els[key] == 'object') {
		var tmp = new meltmedia.widget.Drawer(els[key], {
			calloutLinkId: "drawer-link",
			// Start mode options are cycle, and all
			startMode: "cycle",
			delay: 1500
		    });
		this.drawers.push(tmp);
	    }
	}
    }
};

var toggleVideo = function() {
    videos.disable();
};

addEvent(window, 'load', initialize);