
/* =IE6-Flixker-Fix
--------------------------------------------------------------*/

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}


var site = {
  
  /** init 
   * initialize all the main features 
   * page specific items need to go to the inside of initializeOnLoadItems func
   */
  init: function(){  
    this.textZoom.init(this);
    this.cssBrowserSelector();
    this.initializeOnLoadItems(this.getOnLoadConfig());
    this.initializeEvents(this.getElementEventConfig());
    this.initializeLinks();
  },
  
  /** textzoom */
  textZoom: {
    init:function(_site){ 
      this._site = _site;
      this.DEFAULT_INDEX = 1;
      this.LEVELS = [62.5, 77, 85, 93];
      this.index = Number(this._site.getCookie('zoom') || this.DEFAULT_INDEX);
      this.update(); 
    },
    
    /** these functions are to be called in the textZoom scope so 'this' is textZoom */
    zoomIn: function(){ 
      this.index = Math.min(this.index + 1, this.LEVELS.length - 1);
      this.update(); 
    },
  
    zoomOut: function(){
      this.index = Math.max(this.index - 1, 0);
      this.update();
    },
    
    zoomDefault: function(){
      this.index = this.DEFAULT_INDEX;
      this.update();
    },
    
    update: function(){
      document.body.style.fontSize = this.LEVELS[this.index] + '%';
      this._site.setCookie('zoom', this.index, 365, '/');
    }
    
  },
  
  /** Specific-Browser-Selection  */
  cssBrowserSelector: 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;
  },
  
  /** initializeEvents: set events for all classes */
  initializeEvents: function(config) { 
     
     /** Based on the class name, this loop finds all the elements and assign specific events to them */
     config.each(function(item){
       
       $$("."+item.cName).each(function(el){ 
         
          item.event.each(function(ev){ 
          
          /** setting a specific sope. If it's not defined it's set to namespace 'site'*/
            var scope = (typeof ev.scope == "undefined")?site:ev.scope; 
            var handler = (ev.scope=="self")? ev.handler:ev.handler.bind(scope);
            
            if(ev.type == "onload"){
              handler(el);
            }else{
              el.observe(ev.type, handler);
            };
           
         });
       });
     });
  
  },
  
  getElementEventConfig: function(){
     /**  elementEventConfig is the configuration for assigning events to elements with specific classes
     *   cName: the name of class that you want to add events 
     *   event: the array that stores event objects
     *     scope: event scope. Setting it null makes the scope as the element
     *     type: event type 
     *     func: function to execute for the event
     */
    
    var tz = this.textZoom;
    
    var elementEventConfig  = [
      {
        cName: "external",
        event: [{
          type: "onload",
          handler: function(el){el.setAttribute("target","_blank")}
        }]
      },{
        cName: "third-party",
        event: [{
          type: "click",
          handler: this.disclaimLink
        }]
      },{
        cName: "hcp-link",
        event: [{
          type: "click",
          handler: this.warnApop
        }]
      },{
        cName: "text-zoom-in",
        event: [{
          type: "click",
          scope: tz,
          handler: tz.zoomIn
        }]
      },{
        cName: "text-zoom-out",
        event: [{
          type: "click",
          scope: tz,
          handler: tz.zoomOut
        }]
      },{
        cName: "text-zoom",
        event: [{
          type: "click",
          scope: tz,
          handler: tz.zoomDefault
        }]
      },{
        cName: "swap_value",
        event: [{
          type: "focus",
          handler: this.clearText
        },{
          type: "blur",
          handler: this.restoreText  
        },{
          type: "onload",
          handler: this.restoreText
        }]
      },{
        cName: "email-slider-button",
        event: [{
          type: "mousedown",
          scope: this.email,
          handler: this.email.initEmailForm
        }]
      },{
        cName: "email-slider-button-close",
        event: [{
          type: "click",
          handler: this.email.emailSlideUp
        }]
      },{
        cName: "video-player",
        event: [{
          type: "onload",
          scope: this.mediaPlayer,
          handler: this.mediaPlayer.videoPlayerInit
        }]
      },{
        cName: "oo-feedback",
        event: [{
          type: "mouseover",
          handler: function(ev){ ev.findElement("a").select("span").invoke("setStyle","{'display':'block'}"); }
        },{
          type: "mouseout",
          handler: function(ev){ ev.findElement("a").select("span").invoke("setStyle","{'display':'none'}"); }
        }]
      }];
      
      return elementEventConfig;
  },
  
  /** initializing items that need to get initialized when pages are loaded */
  initializeOnLoadItems: function(config){ 
    var ilCh = ["#","?"];
    var loc = location.href;
    ilCh.each(function(ch){ 
      loc = loc.split(ch)[0];
    });
   
    config.each(function(item){
      
      var handler = item.handler.bind(site);
      
      if(typeof item.pages!= "undefined"){
        
        item.pages.each(function(page){
          
          if(loc.endsWith(page)){ 
            handler();
            throw $break;
          }
          
        });
        
      }else{
        handler();
      };
      
    });
  },
  
  /** config for onload items */
  
  getOnLoadConfig: function(){
    
    /** onLoadConfig 
     * All page specific initalizing codes need to go here!
     * pages: pages that handler gets called. If you don't list any pages, it means it applys for all the pages.
     * handler: the function that gets called when the page is loaded
     */ 
    
    /** page specific items */
    
    var onLoadConfig = [{
      pages: ["resources-insurance/lwl/register/index.xhtml",
              "resources-insurance/lwl/register/"],
      handler: this.initRequestForm
    },{
      handler: function(){ 
                 if($$('[class*="modal-btn-"]').length>0) this.flashModal = new FlashModal(this.flashModalConfig,'modal-btn',common.contextPath);
               }
    },{
      pages: ["resources-insurance/tools-videos/patient-stories/index.xhtml",
              "resources-insurance/tools-videos/patient-stories/"],
      handler: function(){
                 this.patientStory = new PatientStory();
               }
    },{
     handler: omniture.init.bind(omniture)     
    }];
    
    return onLoadConfig;
  },
  
  
  /** utility functions */

  getCookie: function(name) {
      var pattern = new RegExp('(^|; )' + name + '=([^;]*)');
      var m = document.cookie.match(pattern);
      return m && unescape(m[2]);
  },
  
  setCookie: function(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;
  },

  clearText: function(ev){
    var el = ev.findElement('input');
    if(el.value==el.title)el.clear(); 
  },
  
  restoreText: function(ev){ 
    var el = (typeof ev.tagName!="undefined")?ev:ev.findElement('input');
    if(el.value.blank())el.value=el.title;
  },
    
  /** conform modal window functions */
  staticText:{
    RituxanLymphoma_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.',
    LINK_DISCLAIMER: '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.',
    WINDOWS_DISCLAIMER: 'Windows only!'
  },
  
  windowsLink: function(e) {
    this.confirmRedirect(e, this.staticText.WINDOWS_DISCLAIMER);
  },

  disclaimLink: function(e) {
    this.confirmRedirect(e, this.staticText.LINK_DISCLAIMER);
  },

  warnApop: function(e) { 
    this.confirmRedirect(e, this.staticText.RituxanLymphoma_WARNING);
  },
  
  /** this function creats simple dialog for user conformation of leaving the site */
  confirmRedirect: function(e, disclaimer) {
    var target = e.findElement("a");
   
    var href = target.href;
    e.stop();

    function handleOK() {
      dialog.hide();
      dialog.destroy();
      if (target.target="_blank") {
        window.open(href);
      } else {
        location = href;
      }
    }

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

    var popUpText = new Element("div",{"class":"warning"}).update("<img src='"+common.contextPath+"/images/warn16_1.gif' class='dialog-icon' />"+disclaimer);
    
    var config = {
      modal:true,
      center: true,
      positionFixed: true,
      width: 315,
      containerCls: "dialog-container",
      cls: "dialog-bd",
      header: {
        cls: "dialog-hd",
        text: 'Rituxan.com/lymphoma'
      },
      footer:{
        cls: "dialog-ft",
        btns: {
          cls: "btns-cls",
          items: [{
            label: "OK",
            events: [{
              type: "click",
              func: handleOK
            }]
          },{
            label: "Cancel",
            events:[{
              type: "click",
              func: handleCancel
            }]
          }]
        } 
      }
     
    };
    var dialog = new meltmedia.Dialog(popUpText,config);
    dialog.init();
  },
  
  
  /** media player  */
  mediaPlayer: {
    DEFAULT_WIDTH: 480,
    DEFAULT_HEIGHT: 360,
    PLAYER_CONTROLLER_HEIGHT: 24,
    
    videoPlayerInit: function(el){ 
      
      if(el.href!=""){
        var bgImg = (el.select("img").length>0)? el.select("img")[0] : null;
        var cfg = {
          autoPlay: el.hasClassName("auto-play"),
          backgroundImage: (bgImg!=null)?"url("+bgImg.src+")": null,
          duration: el.className.include("videoDur")? this.getPlayerDur(el): 0
        }
        if(bgImg!=null) el.removeChild(bgImg);
        var size = el.className.include("videoDim")?this.getPlayerDim(el):[this.DEFAULT_WIDTH,this.DEFAULT_HEIGHT];
        
        el.style.width = size[0] + "px";
        el.style.height = size[1] + this.PLAYER_CONTROLLER_HEIGHT + "px";

        this.createFlowplayer(el, el.href, cfg);
      } 
    },
    
    
    /** getPlayerDim 
     *  this function return width and height based on the class that the target html element contains
     *  the class has to be the format of "videoDim-" + width + "x" + height
     *  example: videoDim-480x300
     * @param {Object} el
     */
    getPlayerDim: function(el){ 
      var cName = el.className;
      var size = [];
      if(cName.include('videoDim')){
        cName.strip().split(" ").each(function(c){ 
          if(c.include('videoDim')){
            size = c.split("-")[1].split("x");
            size[0] = parseInt(size[0]);
            size[1] = parseInt(size[1]);
            throw $break
          }
        });
      }
      return size;
    },
    
   /** getPlayerDur 
   *  this function return the duration of the video since some video doesn't show the correct duration
   *  the class has to be the format of "videoDur-" + time(in minutes)
   *  example: videoDim-300
   *  this is 5 minutes
   * @param {Object} el
   */

    getPlayerDur: function(el){
      return parseInt(el.className.split("videoDur-")[1].split(" ")[0].strip());
    },
   
   createFlowplayer: function(idOrEl, mediaUrl, cfg){ 
   
      var playerConfig = {
          
          key: "#@0f117348e4b3e97a3d7",
          
          clip: {
            url: mediaUrl,
            scaling: "fit",
            autoPlay: cfg.autoPlay,
            duration: cfg.duration
          },
          
          screen: {
            backgroundColor: "#0000FF",
            bottom: 24
          },
          
          canvas: {
            backgroundGradient: "none",
            backgroundImage: (typeof cfg.backgroundImage!="undefined")?cfg.backgroundImage:null
          },
          
          plugins: {
            controls: {
              backgroundGradient: 'high',
              bufferGradient: 'none',
              borderRadius: '15',
              bufferColor: '#9c9c9c',
              timeBgColor: '#555555',
              durationColor: '#ffffff',
              buttonColor: '#8d8f96',
              progressGradient: 'medium',
              sliderGradient: 'none',
              tooltipTextColor: '#ffffff',
              timeColor: '#ffffff',
              progressColor: '#112233',
              sliderColor: '#9cc4c2',
              volumeSliderGradient: 'none',
              buttonOverColor: '#728B94',
              volumeSliderColor: '#000000',
              backgroundColor: '#E0E0E0',
              tooltipColor: '#5F747C',
              height: 24,
              opacity: 1.0,
              bottom: 0
            }
          }
      }
      
      /** loading flowplayer */
      flowplayer(idOrEl, {
        src:common.contextPath+"/media/flowplayer/flowplayer.swf",
        wmode: 'transparent'}, 
        playerConfig
      ); 
   
   }
 },
  /** request form */
  initRequestForm: function(){ 
    this.requestFormConfig.each(function(config){
      var item = new meltmedia.Tab(config);
    });
  },
  
  requestFormConfig: [{
     items: [{
       id:'joinLwl',
       childCls: ['joinLwlChild'],
       trigger: "check"
     }]
  },{
     items: [{
       id: "diagnosed1",
       childCls: ["diagnosed1Child"],
       trigger: "check"
     },{
       id: "diagnosed2",
       trigger: "check"
     }]
  },{
     items: [{
       id: "diagnosisType1",
       childCls: ["diagnosisChild1or3"],
       trigger: "check"
     },{
       id: "diagnosisType2",
       childCls: ["diagnosisChild2"],
       trigger: "check"
     },{
       id: "diagnosisType3",
       childCls: ["diagnosisChild1or3"],
       trigger: "check"
     }]
  }],
  
  /** email form */
  email: EmailForm,
  
  /** config for flash modal */
  
  flashModalConfig: [{
    name: 'virtualCareBinder',
    closeMethod: "site.flashModal.closeModal",
    assetsPath: "/media/modal-flash/virtual-care-binder/assets",
    contentPath: "/media/modal-flash/virtual-care-binder/VirtualCareBinder.swf",
    piUrl: "http://www.gene.com/gene/products/information/pdf/rituxan-prescribing.pdf",
    height: "625",
    width: "1024"
  },{
    name: 'resourceCenter',
    closeMethod: "site.flashModal.closeModal",
    assetsPath: "/media/modal-flash/resource-center/assets",
    contentPath: "/media/modal-flash/resource-center/ResourceCenter.swf",
    piUrl: "http://www.gene.com/gene/products/information/pdf/rituxan-prescribing.pdf",
    height: "625",
    width: "1024"
  }],
  
  initializeLinks: function() {
    var links = $$("a.pi-download");
    for (var i=0;i<links.length;i++) {
      links[i].observe('click', this.downloadPi.bind(this));
    }
  },
  
  downloadPi: function(ev) {
    var el = ev.findElement("a");
    var piUrl = "http://www.gene.com/gene/products/information/pdf/rituxan-prescribing.pdf";
    var url = el.href;
    if(url!=piUrl && url.endsWith(".pdf")){ 
      if(this.isIe6() || Prototype.Browser.WebKit){ 
        window.open(piUrl, "PI");
      }else{
        location.href = piUrl;
      };
    }
  },
  
  downloadPiHandler: function(url){ 

    if(Prototype.Browser.WebKit){
      var ok = new Element("a",{"class":"btn-confirm-ok","href":url,"target":"_blank"});
      var no = new Element("a",{"class":"btn-confirm-no"});
      var popUpText = new Element("div",{"id":"confirm-box","href":url,"target":"_blank"}).update("<p>Click 'YES' to confirm download.<br /> Click 'NO' to cancel.</p>");
      popUpText.appendChild(ok);
      popUpText.appendChild(no);
      
      var config = {
        modal: true,
        center: true,
        positionFixed: true,
        width: 390,
        height: 270,
        killOnHide: true,
        containerCls: "confirm-button-container",
        zIndex: 200,
        cls: "confirm-button-body"
      };
      
      var dialog = new meltmedia.Dialog(popUpText,config);
      ok.observe("click",function(e){
        this.downloadPi(e);
        $A(arguments)[1].hide();
      }.bindAsEventListener(this,dialog));
      
      no.observe("click",function(e){
        $A(arguments)[1].hide();
      }.bindAsEventListener(this,dialog));
      
      dialog.init();
    }else{
      var piUrl = "http://www.gene.com/gene/products/information/pdf/rituxan-prescribing.pdf";
      window.open(url);
      if(url!=piUrl && url.endsWith(".pdf")){ 
         location.href = piUrl;
      };
    }
  },  
  
  isIe6: function(){
    return document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0);
  }
}

document.observe("dom:loaded", site.init.bind(site));
