var DOM = YAHOO.util.Dom;
var EVT = YAHOO.util.Event;

// text zoom control

textzoom = {};
textzoom.LEVELS = [51.5, 62.5, 74.5, 90.0];
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, '/');
		fontSize = this.LEVELS[this.index];
    fontIndex = this.index;
    omniture.changeFontSize(fontSize,fontIndex);
};
document.write('<style type="text/css" media="screen">body { font-size: ' + textzoom.LEVELS[textzoom.index] + '%; }</style>');

// special case link initialization

HCP_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>';

function initVideos() {
    videos.init("video-link");
}

function init() {
    // initialize nav sub-menus
    var nav = document.getElementById('nav-primary');
    var hasSub = DOM.getElementsByClassName('has-sub', 'a', nav);
    for (var i = 0; i < hasSub.length; i++) {
        var span = document.createElement('span');
        hasSub[i].appendChild(span);
    }

    var el, i=0;
    while((el = DOM.getElementsByClassName('drawer')[i++]) != null) {
  var prefix = el.id.split("-label")[0];
  // initialize drawer sliders
  var drawer = document.getElementById(prefix+'-drawer');
  if (drawer) {
      new Drawer(prefix+'-drawer', 0.15, Drawer.RIGHT);

      var label = document.getElementById(prefix+'-label');
      var a = label.getElementsByTagName('a')[0];
    
      YAHOO.util.Event.addListener(a, 'click', toggleDrawer);
      // for popup "how to save"
    var avideo = label.nextSibling.nextSibling.getElementsByTagName("a");
    EVT.addListener(avideo[1], 'mouseover', popHowToSave);
    EVT.addListener(avideo[2], 'mouseover', popHowToSave);
  }
    }


    // initialize links
    var anchor, i = 0;
    while ((anchor = document.getElementsByTagName('a')[i++]) != null) {
        if (DOM.hasClass(anchor, 'external'))
          anchor.setAttribute('target', '_blank');
        if (DOM.hasClass(anchor, 'third-party'))
          EVT.addListener(anchor, 'click', disclaimLink);
        if (DOM.hasClass(anchor, 'swap-btn'))
          EVT.addListener(anchor, 'mousedown', swapTxt);
        if (hasClass(anchor, 'pi-download'))
          EVT.addListener(anchor, 'click', downloadPi);
    }
    
    if(location.href.match("hcp/overview/resources/moa")){
      
      loadVideoJs();
      initMoaToggle();
      //initFlowPlayer(moa);
    }
}


function initMoaToggle(){
 
  var j$ = jQuery,
      index = 0,
      btns = j$(".moaAnimationToggle a"),
      videos = j$(".moaPlayer .video-js-box");
      

  var showCss = {
    "left": null,
    "position": "relative"
  }      

  
  var hideCss = {
    "left": "-999999px",
    "position": "absolute"
  }

  videos.css(hideCss);
  videos.show();
  videos.eq(index).css(showCss);
  
  btns.each(function(i){
    
    btns.eq(i).click(function(e){
      
      e.preventDefault();
              videos.eq(index).css(hideCss);
        videos.eq(i).css(showCss);
      var flashplayer = $f("fallback-player-"+videos.eq(index).attr("id")),
          newFlashplayer = $f("fallback-player-"+videos.eq(i).attr("id"));
      if(flashplayer==null){
        j$("video",videos.eq(index))[0].pause();
        j$("video",videos.eq(i))[0].play();
        omniture.onVideoStartHandler(videos.eq(i)[0].id);
      }else{
       
        flashplayer.pause();
    　　newFlashplayer.play();
      }
 


      index = i;
    
    })
    
  })
  
  
}

function loadVideoJs(){
  
  jQuery.extend(VideoJS.flashPlayers.flowplayerConfig,{
    
    "moa-video-short": {
      "name": "moa-video-short",
      "flowplayerPath":getContextPath()+getSubPath()+"/base/hcp/media/video/player/flowplayer.commercial-3.1.5.swf",
      "player":{       
        "width":480, 
        "height":272,
        "clip":{
          "url":"http://prod.avastin.gene.s3.amazonaws.com/videos/hcp-isi/20110316/avastin-isi_short/avastin-isi_short-480x272.mp4",
          "autoBuffering":false
        },
        "canvas":{
          "backgroundImage": getContextPath()+getSubPath()+"/base/hcp/images/moa-video.jpg"
        }
      }
    },
    
    "moa-video-full": {
      "name": "moa-video-long",
      "flowplayerPath":getContextPath()+getSubPath()+"/base/hcp/media/video/player/flowplayer.commercial-3.1.5.swf",
      "player":{       
        "width":480, 
        "height":272,
        "clip":{
          "url":"http://prod.avastin.gene.s3.amazonaws.com/videos/hcp-isi/20110316/avastin-isi-long/avastin-isi-long-480x272.mp4",
          "autoBuffering":false
        },
        "canvas":{
          "backgroundImage": getContextPath()+getSubPath()+"/base/hcp/images/moa-video.jpg"
        }
      }
    }

  })
  
  
  
  VideoJS.DOMReady(function(){
   
    jQuery("video").each(function(){
      
      var player = VideoJS.setup(this.id);
      
      jQuery(this).css({"height":null});
      
      _initVideoEvents(player,{name:this.id})
      
    })    
      
       
  });

}


function _initVideoEvents(video,cfg){

    var started = false,
        finished = false,
        lastSec = 0,
        duration = null,
        isFlowplayer = video.hasOwnProperty("flowplayer");
    
 
    video.onCurrentTimeUpdate(function() {       
      
      var action = null,
          newSec = parseInt(this.currentTime());
      
      duration = duration || this.duration();
      
      if(newSec-lastSec==0) {
        return;
      }else{
        lastSec = newSec
      }
   
      
      if(newSec==0) return;
      
      switch(newSec) {
        case 1:
          
          if(started) return;
          
          if(finished){
            omniture.onVideoRestartHandler(cfg.name);
          }else{
            omniture.onVideoStartHandler(cfg.name);
          }
          
          started = true;
          
          return;
          
        break;
        case parseInt(duration * 0.25):
          action = 25;
        break;
        case parseInt(duration * 0.5):
          action = 50;
        break;
        case parseInt(duration * 0.75):
          action = 75;
        break;
        default:
          break;
      }
      
      if (action!=null) omniture.watchedHandler(cfg.name,action);
      
    });

    
    video.onEnded(function() {
      started = false;
      finished = true;
      omniture.watchedHandler(cfg.name,100);
    });
    

};


function downloadPi(ev){
  var el = getTarget(ev);
  if(el.tagName.toUpperCase() != "A")el = el.parentNode;
  var piUrl = "http://www.gene.com/gene/products/information/pdf/avastin-prescribing.pdf";
  var url = el.href;
  var att = (Prototype.Browser.Gecko)? "width=0,height=0": "";
  if(url!=piUrl && url.endsWith(".pdf"))  window.open(piUrl,'Prescribing_Information',att);
}

function toggleDrawer(e) {
    var target = EVT.getTarget(e);
    var prefix = target.parentNode.id.split("-label")[0];
    var drawer = Drawer.all[prefix+'-drawer'];
    if (drawer && !drawer.moving) {
        drawer.activate();
    }
    EVT.stopEvent(e);
}

//swap text for oncologist efficacy page

function swapTxt(e){
  var target = (EVT.getTarget(e).tagName == 'a')? EVT.getTarget(e) : EVT.getTarget(e).parentNode;
  var tgImg = target.getElementsByTagName('img')[0];
  if(target.title=="BIO"){
    target.title = "QUOTE";
    tgImg.src =  getContextPath()+getSubPath()+"/base/hcp/images/btn-quotes-quote.gif";
    tgImg.alt = "QUOTE";
  }else{
    target.title = "BIO";
    tgImg.src = getContextPath()+getSubPath()+"/base/hcp/images/btn-quotes-bio.gif";
    tgImg.alt= "BIO";
  }
  
  var txs = target.parentNode.parentNode.getElementsByTagName('div');
  for(var i=0;i<txs.length;i++){
    if(hasClass(txs[i],'hide')){
      removeClass(txs[i],'hide')
    }else{
      addClass(txs[i],'hide');
    }
  }
}



// for popup "how to save"
function popHowToSave(ev){
  
  var thisNode = YAHOO.util.Event.getTarget(ev);
  if(thisNode.className.indexOf('quicktime') > -1)
  var media = "Quicktime";
  else
  var media = "Windows Media Player";
  var pwindow = document.createElement("div");
  
  pwindow.style.display = "block";
    updatePopupPos(ev, pwindow);
    pwindow.innerHTML = "<h4>How to use this File!</h4><p>Right-click and choose \"Save target as...\" to download, save file where you can easily find it then 'double-click' on saved file to open.</p> <h4>"+media+" required to view downloadable video.</h4>"; 
  pwindow.className = "howtosave";
  thisNode.onmouseout = function(){window.document.body.removeChild(pwindow);};
  
  window.document.body.appendChild(pwindow);
  EVT.addListener(thisNode, 'mousemove', updatePopupPos, pwindow);
}

function updatePopupPos(ev, pwin){
  pwin.style.left = EVT.getPageX(ev) + "px";
  pwin.style.top = EVT.getPageY(ev)+20 + "px";  
}


YAHOO.util.Event.addListener(window, 'load', init);

function toggleDiv(id) {
    var divs=YAHOO.util.Dom.getElementsByClassName('bigImage');
    var links=YAHOO.util.Dom.getElementsByClassName('linkHighlight');

    for (i=0;i<divs.length;i++) {
      YAHOO.util.Dom.removeClass(divs[i], 'show');
      YAHOO.util.Dom.removeClass(links[i], 'active');
    }
      YAHOO.util.Dom.addClass(divs[id], 'show');
      YAHOO.util.Dom.addClass(links[id], 'active');
}


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, 'hcp-link'))
            addEvent(anchor, 'click', warnHcp);
        if (hasClass(anchor.parentNode, 'pat-link'))
            addEvent(anchor, 'click', goPat);
        if (anchor.id=='edetail-callout')
            addEvent(anchor,'click', onClickCallOut)
    }
}

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

function warnHcp(e) {
    if (!location.pathname.match(/\/hcp\//)) {
        var target = getTarget(e);
        target.href = rewriteHref(target.href);
        confirmRedirect(e, HCP_WARNING);
    }
}

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

function onClickCallOut(e){
    doPageEvent(s.pageName,"");
}


function rewriteHref(href) {
    return href;
}

function confirmRedirect(e, disclaimer) {
    var target = getTarget(e);
    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,
                                                   icon: YAHOO.widget.SimpleDialog.ICON_WARN,
                                                   text: disclaimer,
                                                   underlay: 'none',
                                                   visible: false,
                                                   width: '315px'
                                               });
    dialog.setHeader('Avastin.com');
    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 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 printResults(date, infusions, weight, weightType, dosing, freq, cancerType, isOver) {
  var printHTML = '<div style="font-family: Arial; width: 509px; height: 400px; border: 1px solid #000; padding: 5px">'+
            '<h3 style="font-size: 1.3em; margin-top: 0px">Avastin Calculator Results</h3>'+
            '<p>Patients Name: ___________________________________________</p>';

  if(isOver == 'false') {
      printHTML += '<p>You entered the following information into the calculator:<br />'+
          'Patient weight: '+weight+' '+weightType+'s<br />'+
          'Patient dosing: '+dosing+'mg/kg every '+freq+' weeks for '+cancerType+'.</p>'+
          '<p>Based on the information entered, this patient is estimated to reach the 10,000 mg threshold and may become eligible to receive free Avastin for the remainder of the year on '+date+' or after '+infusions+' infusions.</p>'+
          '<p style="font-size:.8em"><i>Note: The Avastin Patient Assistance program is open to all patients treated with Avastin for an FDA-approved indication and with a household adjusted gross income of up to $100,000.</i></p>'+
          '<p>To enroll a patient in the Avastin Patient Assistance program, or to get additional program details:</p>'+
          '<p>Visit: www.AvastinAccessSolutions.com</p>'+
          '<p>Call: 888-249-4918</p>';
  } else {
      printHTML += '<p>This patient is estimated to receive less than 10,000 mg of Avastin in a 12 month period and so will not qualify for the Avastin Patient Assistance program. To get additional program details, visit www.AvastinAccessSolutions.com</p>';
  }
  
  printHTML += '</div>';
  
  var printWindow = window.open("", "_blank", "height=435, top=25, width=538, left=25, directories=no, location=no, menubar=no, resizeable=no, status=no");
  printWindow.document.body.innerHTML = printHTML;
  printWindow.document.body.onLoad = printWindow.print();
}

var common = {
    pageInfo: {
  init: function(context, page) {
      this.page = page;
      this.contextPath = context;
      this.subPath = "/avastin"; // TODO CHANGE THIS LATER <=== BAD
  }
    }
};

var initCoPayChart =  function(){
  var chart = document.getElementById("co-pay-chart");
  if(chart!=null){
    var btns = chart.getElementsByTagName("div");
    for(var i=0;i<btns.length;i++){
      addEvent(btns[i],"click",initBtn);
    }
  }
};

var initBtn = function(ev){
  EVT.stopEvent(ev);
  var el = getTarget(ev);
  var btns =  el.parentNode.parentNode.getElementsByTagName("a");
  DOM.removeClass(btns[0],"selected");
  DOM.removeClass(btns[1],"selected");
  DOM.addClass(el,"selected");
  updateResult();
};

var updateResult = function(){
  var btns = document.getElementById("co-pay-chart").getElementsByTagName("div");
  var numOfYes = 0;
  var numOfNo = 0;
  for(var i=0;i<btns.length;i++){
    var child = btns[i].getElementsByTagName('a')[0];
    if(DOM.hasClass(child,"selected")){
      if(DOM.hasClass(btns[i],"yes-btn")) numOfYes+=1;
      if(DOM.hasClass(btns[i],"no-btn")) numOfNo+=1;
    };
  };
  
  var resBox = document.getElementById("copay-result").getElementsByTagName("p");
  for(var i=0;i<resBox.length;i++){
    resBox[i].style.display = "none";
  };
  
  var result;
  if(numOfNo>0){
    result = resBox[1];  
  }else if(numOfYes==btns.length/2){
    result = resBox[2];
  }else{
    result = resBox[0];
  };
  
  result.style.display = "block";
  
}





