// -----------------------------------------------------------------------------------

var vbNavigation = Class.create();

vbNavigation.prototype = {

   // initialize()
   // Constructor runs on completion of the Page loading.

   initialize: function(bg,popout,keyword) {
      this.bg = bg;
      this.popout = popout;
      this.keyword = keyword;
      this.pagePanel = $('page-body');
      this.bodyPanel = $('page-body-panel');
      this.messagesNav = $('main-panel-messages-nav');
      this.navHeight = 40;
      this.contentCount = 0;
      this.carouselCount = 0;
      this.carouselHeight = 50;
      this.carouselFullHeight = 140;
      this.carouselTop = 0;
      this.carouselBottom = 0;
      this.carouselTopAfter = 0;
      this.carouselMoving = false;
      this.activeCarousel = 0;
      this.activeContent = 0;
      this.sliderCount = 0;
      this.sliderMoving = false;
      this.contentArrowHeight = 289;
      this.messageCount = 0;
      this.messageInterval = null;
      this.messageDuration = 3;
      this.activeQuestion = null;
      this.questionCount = 0;
      this.transition = 0;
      this.activeMessage = 0;
      this.totalContent = 0;
      this.totalMessage = 0;
      this.timeout = null;
      this.animateSpeed = 0.1;
      this.imgNum = 0;
      this.subnavTime = 500;
      this.activeNavigation = "";
      this.micrositeCookieName = "microsite";
      this.micrositePercent = 100;
      this.activeGlossaryCharacter = "none";
      this.events = {
         mouseover: this.mouseover.bind(this),
         mouseout: this.mouseout.bind(this),
         showContentSection: this.showContentSection.bind(this)
      };

      this.browserQuirks();
      this.setBg();
      this.addObservers();
      this.highlightGlobalNav();
      this.findSubnav();
      this.enhanceSubnav();
      this.enhanceContent();
      this.checkProtocol();
      this.enhanceHomepageMessages();
      this.enhanceCarousel();
      this.activateFooter();
      this.processQAs();
      this.processSliders();
      this.findInsuranceAppLinks();  //Need to do this before popups are processed
      this.findPopups();
      this.findCTARollovers();
      //this.findLinks();
      this.activatePopoutPanel();
      //this.deactivateLogoLink();
      this.findMyOffersPanel();
      this.findLoginPanels();
      //this.activateFlashMicrosite();
      this.findShareLink();
      this.findLightbox();
      this.findGlossary();
   },
   
   //
   // browserQuirks()
   // REQUIRES BROWSER.JS FILE
   // Sorts out quirks we have encountered along the way - contains some placeholder conditions for other browsers.
   //

   browserQuirks: function() {

      if (BrowserDetect.browser == "Explorer") {
         if(BrowserDetect.version <= 6) { 
            productLozenge = $$('.main-panel-lozenge');
            productLozenge.each(function(s){
               s.removeClassName('main-panel-lozenge');
               s.addClassName('main-panel-lozenge-ie');
            }.bind(this));

            if ($("main-panel-content")) {
               $("main-panel-content").setStyle({'height':'400px'})
            }

            if ($("main-panel-content-full-width")) {
               $("main-panel-content-full-width").setStyle({'height':'400px'})
            }       

            if ($("main-panel-content-long")) {
               $("main-panel-content-long").setStyle({'height':'525px'})
            }

            if ($("main-panel-content-full-width-long")) {
               $("main-panel-content-full-width-long").setStyle({'height':'525px'})
            }       
         }; 

      } else {
         if($('mvm-bookmark')) {
            $('mvm-bookmark').setStyle({'display':'none'});
         }
      }
      if (BrowserDetect.browser == "Firefox") { };
      if (BrowserDetect.browser == "Safari") { };
   },
   
   //
   // addObservers()
   // Loops through anchor tags looking for 'lightbox' references and applies onclick
   // events to appropriate links. You can rerun after dynamically adding images w/ajax.
   //   
   addObservers: function() {

      var nav = $$('a[rel^=subnav]');
      nav.each(function(s) {
         Event.observe(s,'focus',this.mouseover.bindAsEventListener(this, s));
         Event.observe(s,'mouseover',this.mouseover.bindAsEventListener(this, s));
         Event.observe(s,'click',this.mouseover.bindAsEventListener(this, s));
         Event.observe(s,'blur',this.mouseout.bindAsEventListener(this, s));
         Event.observe(s,'mouseout',this.mouseout.bindAsEventListener(this, s));
      }.bind(this));
   },
   
   findLinks: function() {
      $$('a').each(function(s){
         Event.observe(s,'focus',this.removeBlur);
      }.bind(this));
   },
   
   checkProtocol: function() {
      urlProtocol = window.location.protocol
      if (urlProtocol.indexOf("https") != -1) {
         $$('#page-body-global-nav a','#footer-panel-content a').each(function(s){
            this.changeSecureUrl(s);
         }.bind(this));
      }
   },
   
   changeSecureUrl: function(element) {
      elementUrl = element.href;
      elementUrl +="-NOSSL";
      element.href = elementUrl;
   },

   findPopups: function(event, elementId) {
      if (!elementId) {
         elementId = ""
      }
                  
      var popupItems = $$(elementId +' a[rel^=popup]');
      popupItems.each(function(s) {
         this.activatePopup(s);
      }.bind(this));
   },
   
   activatePopup: function(element) {
      popupAttr = this.extractPopupAttributes(element);
      popupUrl = element.href;
      popupId = element.id+"-popup";
      element.writeAttribute("onclick", "");
      var onClickCode = element.readAttribute("onclick");

      Event.observe(element,'click', function(event){
         try {
            eval(onClickCode);
         } catch(err) {
            eval(onClickCode.replace(new RegExp("return\s+\w*;?"),""));
         }
      });

      //element.addClassName('popup-link');
      //element.writeAttribute("title", "Link opens in new window");
      element.writeAttribute("onclick", "return false");
      Event.observe(element,'click', function(event){Event.stop(event);});
      Event.observe(element,'click', this.openPopup.bindAsEventListener(this, popupUrl, popupId, popupAttr));
   },
   
   extractPopupAttributes: function(id) {
      popupStr = $(id).rel;
      popupStrSpl = popupStr.split("[");
      popupStrSpl = popupStrSpl[1].split("]");
      popupAttr = popupStrSpl[0].split(",");
      return popupAttr;
   },

   closePopup: function() {  
   	try {
		if (this.NewWin && (! this.NewWin.closed)) { this.NewWin.close();
		} else {
		 return false;
		}	   
	} catch(err) { 
		return false
	}	   
   },
   
   openPopup: function(e, url,WinName,attr) {
      this.closePopup();

      // Set defaults according to the old function's settings
      var defaultParamObj = {
         resizable:'yes',
         toolbar:'no',
         scrollbars:'yes',
         menubar:'yes',
         status:'yes'
      }
      var params = ",";

      if(attr[2]) { // Checks to see if the fifth parameter exists
         var obj    = attr[2];
         for (var prop in obj) { //Loops through the values in the object
            defaultParamObj[prop] = obj[prop];  // replace defaults as necessary
         }
      }

      for (var defaultProp in defaultParamObj) {
         params+= defaultProp +"=" + defaultParamObj[defaultProp] +","; //rewrites the object in the correct string format
      }

      params = params.substring(0,params.length-1); //remove the comma at the end of the string
      var winl = (screen.width - attr[0]) / 2;
      var wint = (screen.height - attr[1]) / 2;
      winprops = 'height='+attr[1]+',width='+attr[0]+',top='+wint+',left='+winl+params;

      this.NewWin = window.open(url,null,winprops);
      this.NewWin.focus();
   },

   findCTARollovers: function() {
      var ctaItems = $$('a[rev^=rollover]');
      if(ctaItems.length > 0) {
         ctaItems.each(function(s) {
            this.activateCTA(s);
         }.bind(this));
      }         
   },
   
   activateCTA: function(element) {
      imageSrc = element.down().src;
      imageOverUrl = this.extractCTARolloverUrl(element);
      this.preloadImage(imageOverUrl);
   
      Event.observe(element,'mouseover',this.mouseoverCTA.bindAsEventListener(this, element));
      Event.observe(element,'mouseout',this.mouseoutCTA.bindAsEventListener(this, element, imageSrc));
   },

   mouseoverCTA: function(e,id) {
      mouseoverUrl = this.extractCTARolloverUrl(id);
      id.down().src = mouseoverUrl;
   },
   
   mouseoutCTA: function(e,id,src) {
      id.down().src = src;   
   },
   
   extractCTARolloverUrl: function(id) {
      rolloverStr = id.rev;
      rolloverStrSpl = rolloverStr.split("[");
      rolloverStrSpl = rolloverStrSpl[1].split("]");
      return rolloverStrSpl[0];
   },
   
   removeBlur: function() {
      if (this.blur) { 
         this.blur() 
      };
   },
   
   setBg: function() {
      if($('page')) {
         $('page').setStyle({'backgroundImage':'url('+this.bg+')'});
      }
   },

   highlightGlobalNav: function() {
      if ($("keyword-" + this.keyword)) {
         navItem = $("keyword-" + this.keyword);
         navItem.removeClassName('nav-item');
         navItem.addClassName('nav-item-selected');
      }
   },
   
   findSubnav: function(target) {
      subnavs = $$('#global-nav-list a[rel]', '#mvm-nav-list a[rel]');
      subnavs.each(function(s) {
         var position = $(s).positionedOffset();
         subnavId = s.rel;
         this.arrangeSubnav(subnavId,position);
      }.bind(this));
   },
   
   enhanceSubnav: function() {
      var listItems = $$('.subnav-item');
      listItems.each(function(s) {
         itemId = $(s.id);

         Event.observe(itemId,'click', function() {
            listItemHref = $(this.id).down().next().down().readAttribute('href');
            document.location.href = listItemHref;
         });
         
         if (BrowserDetect.browser != "Explorer") {
            Event.observe(itemId,'mouseover',function() {
               $(this.id).addClassName('over');
            });
         
            Event.observe(itemId,'mouseout',function() {
               $(this.id).removeClassName('over');
            });
         }
      }.bind(this));
   },
   
   arrangeSubnav: function(id,pos) {
      xPos = pos[0];
      yPos = pos[1];
      navId = $(id);
      navId.removeClassName("hidden");
      navId.setStyle({'position':'absolute','top':yPos+ this.navHeight +'px','left':xPos+'px','display':'none','zIndex':'1500'});
   },
   
   enhanceContent: function() {
      var contentItems;
      contentItems = $$('#main-panel-content .main-panel .section', '#main-panel-content-full-width .main-panel .section','#main-panel-content-long .main-panel .section', '#main-panel-content-full-width-long .main-panel .section')   
      if(contentItems.length > 1) {
         this.activeContent = 1;
         contentItems.each(function(s) {
            this.contentCount++;
            this.hideContent(s);
            this.idContent(s);
            this.writeContentNav(s);   
         }.bind(this));
         
         this.writeContentArrows(this.activeContent);
         this.findSectionLinks();

         if($("section-nav")) {
            $("section-nav").setStyle({'display':'block'});
            $("section-nav").absolutize();
         }
      }
   },
   
   findSectionLinks: function() {
      document.observe('click', (function(event) {
         var target = event.findElement('a[rel^=section]');
         if (target) {   
            section = target.rel.substring(target.rel.indexOf("[")+1,target.rel.indexOf("]"));
            this.showContentSection(this, parseInt(section));
         }
      }).bind(this));
   },   
   
   hideContent: function(element) {
      if (this.contentCount > 1) {
         element.setStyle({'display':'none'});
      }
   },
   
   idContent: function(element) {
      element.writeAttribute("id", "section"+this.contentCount);
      element.writeAttribute("name", "section"+this.contentCount);
   },

   writeContentNav: function(element) {
      navStyle = 'content-nav';
      if (this.contentCount == this.activeContent) {
         navStyle = 'content-nav-selected';
      }
   
      var navList = new Element('a', { 'id':'nav-section'+this.contentCount, 'href':'#'}).update(this.contentCount);
      navList.addClassName(navStyle);
      new Element.insert('content-nav-container', {bottom:navList});
      Event.observe(navList,'click',this.showContentSection.bindAsEventListener(this, this.contentCount));
   },
   
   writeContentArrows: function(section) {
      sectionHeight = $('section'+ section).getHeight();
      $('section-buttons').update("");
      if (section > 1) {
         var prev = new Element('a', { 'id':'prev-section', 'href':'#'}).update("<span>Previous</span>");   
         var prevDiv = new Element('div', { 'id':'prev-section-div', 'style':'float:left'}).update(prev);
         new Element.insert('section-buttons', {bottom:prevDiv});
         Event.observe(prev,'click',this.showContentSection.bindAsEventListener(this, this.activeContent-1));
      };

      if (section < this.contentCount) {
         var next = new Element('a', { 'id':'next-section', 'href':'#'}).update("<span>Next</span>");
         var nextDiv = new Element('div', { 'id':'next-section-div', 'style':'float:right'}).update(next);
         new Element.insert('section-buttons', {bottom:nextDiv});
         Event.observe(next,'click',this.showContentSection.bindAsEventListener(this, this.activeContent+1));
      };      
   },
   
   showContentSection: function(e, section) {
      if(section != this.activeContent) {
         $('section'+this.activeContent).hide();
         $('nav-section'+this.activeContent).removeClassName('content-nav-selected');
         $('nav-section'+this.activeContent).addClassName('content-nav');
         $('section'+section).show();
         $('nav-section'+section).removeClassName('content-nav');
         $('nav-section'+section).addClassName('content-nav-selected');

         this.activeContent = parseInt(section);
         this.writeContentArrows(parseInt(section));
      };
   },

   enhanceCarousel: function() {
      if ($('page-carousel')) {
         $('page-carousel').absolutize();
         $('page-carousel-padding').setStyle({'display':'block'});
      };   

      var carouselItems = $$('#page-carousel .carousel-item .carousel-content');
      if(carouselItems.length > 1) {
         carouselItems.each(function(s) {
            this.carouselCount++;
            $(s).absolutize();
            this.idCarousel(s);
            this.activateCarousel(s);
         }.bind(this));
      this.carouselTop = parseInt(carouselItems[0].getStyle('top'));
      carouselDiff = this.carouselFullHeight - this.carouselHeight;
      this.carouselTopAfter = this.carouselTop - carouselDiff;
      this.carouselBottom = this.carouselTop + this.carouselHeight;
      }      
   },
   
   idCarousel: function(element) {
      element.writeAttribute("id", "carousel"+this.carouselCount);
   },
   
   activateCarousel: function(element) {
      imageSrc = element.down().down().src;
      imageOverUrl = this.extractRolloverUrl(element);
      this.preloadImage(imageOverUrl);
   
      Event.observe(element,'mouseover',this.mouseoverCarousel.bindAsEventListener(this, element.id));
      Event.observe(element,'mouseout',this.mouseoutCarousel.bindAsEventListener(this, element.id, imageSrc));
   },
   
   mouseoverCarousel: function(e,id) {
      mouseoverUrl = this.extractRolloverUrl(id);
      $(id).down().down().src = mouseoverUrl;
      currentHeight = $(id).getHeight();
      intendedHeight = this.carouselFullHeight;
      heightRatio = (intendedHeight/currentHeight)*100;
      $(id).setStyle({'top':this.carouselBottom - currentHeight+'px'});

      new Effect.BlindDown(id,{duration:0.2,scaleFromBottom:true,scaleFrom:100,scaleTo:heightRatio,restoreAfterFinish:false,afterFinish: function() {
         $(id).setStyle({'top':this.carouselTopAfter+'px','height':this.carouselFullHeight+'px'});
      }.bind(this)});
   },
   
   mouseoutCarousel: function(e,id,src) {
      $(id).down().down().src = src;
      currentHeight = $(id).getHeight();
      intendedHeight = this.carouselHeight;
      heightRatio = (intendedHeight/currentHeight)*100;
      $(id).setStyle({'top':this.carouselBottom - currentHeight+'px'});

      new Effect.BlindUp(id,{duration:0.2,scaleFromBottom:true,scaleFrom:100,scaleTo:heightRatio,restoreAfterFinish:false,afterFinishInternal:false,afterFinish: function() {
         this.carouselMoving = false; 
         $(id).setStyle({'top':this.carouselTop+'px','height':this.carouselHeight+'px'});
      }.bind(this)});
   },
   
   extractRolloverUrl: function(id) {
      rolloverStr = $(id).down().rev;
      rolloverStrSpl = rolloverStr.split("[");
      rolloverStrSpl = rolloverStrSpl[1].split("]");
      return rolloverStrSpl[0];
   },   
   
   enhanceHomepageMessages: function() {
      if ($('main-panel-header-home')) {
         $('main-panel-header-home').removeClassName("overflow");
      }

      if ($('main-panel-message')) {
         $('main-panel-message').setStyle({'display':'block'});
      }

      var contentItems = $$('#page-body-main-panel-home #main-panel-padding-home #main-panel-header-home .messages')
      if(contentItems.length > 1) {
         this.activeMessage = 1;
         contentItems.each(function(s) {
            this.messageCount++;
            this.hideMessages(s);
            this.idMessages(s);
         }.bind(this));
         this.timeHomepageMessages();
      }
   },
   
   hideMessages: function(element) {
      if (this.messageCount > 1) {
         element.setStyle({'display':'none','position':'absolute','top':'0px','left':'0px','zIndex':'10'});
      }
   },
   
   idMessages: function(element) {
      element.writeAttribute("id", "message"+this.messageCount);
   },
   
   writeMessageNav: function(element) {
      navStyle = 'message-nav';
      if (this.messageCount == this.activeMessage) {
         navStyle = 'message-nav-selected';
      }
   
      var navList = new Element('a', { 'id':'nav-section'+this.messageCount, 'rel':'section'+this.messageCount,'href':'#','class': navStyle}).update("<span>"+ this.messageCount + "</span>");
      new Element.insert('main-panel-messages-nav', {bottom:navList});
      Event.observe(navList,'click',this.showMessage.bindAsEventListener(this, this.messageCount));
      Event.observe(navList,'focus',this.removeBlur);
   },
   
   writeMessageNavBorder: function() {
      var navLeft = new Element('div', { 'id':'nav-section-left'});
      var navRight = new Element('div', { 'id':'nav-section-right'});
      new Element.insert('main-panel-messages-nav', {top:navLeft});
      new Element.insert('main-panel-messages-nav', {bottom:navRight});
   },
   
   writeMessageArrows: function(section) {
      if ($('next-message-div')) {
         $('next-message-div').remove();
      }

      var next = new Element('a', { 'id':'next-message', 'href':'#'}).update("<span>Next</span>");
      var nextDiv = new Element('div', { 'id':'next-message-div', 'style':'float:left'}).update(next);
      new Element.insert('main-panel-messages-nav', {bottom:nextDiv});
      Event.observe(next,'click',this.showMessage.bindAsEventListener(this, this.activeMessage+1));
   },
   
   showMessage: function(e, section) {
      window.clearInterval(this.messageInterval);
      this.timeHomepageMessages();
      if(section > this.messageCount) {
         section = 1;
      }

      if(section != this.activeMessage && this.transition == 0) 
	  {
         this.transition = 1;
		 
		 for (var i=1; i<= this.messageCount; i++)
		 {
			 
		  if (i == this.activeMessage)
		  {
		 		$('message'+this.activeMessage).setStyle({'zIndex':'10', 'display':'block'});
		  }
		  else
		  if (i == section)
		  {
	  			$('message'+section).setStyle({'zIndex':'99', 'display':'block', 'position':'absolute', 'left':'0px', 'top':'0px', 'opacity':'0'});
		  }
		  else
		  {
			   if ($('message'+i))
			 	$('message'+i).setStyle({'zIndex':'1', 'display':'none'});
			  
		  }
	 	}
		 
         //new Effect.Fade($('message'+this.activeMessage), { duration: 0.1});
         new Effect.Appear($('message'+section), 
		 { 
		    duration:1,
            afterFinish: function() {this.transition = 0; }.bind(this)
		 }
		 );
         this.activeMessage = section;
      }
   },
   
   timeHomepageMessages: function() {
      this.messageInterval = window.setInterval(function() {
         this.showMessage(this, this.activeMessage+1);
      }.bind(this), (this.messageDuration*1000));
   },

   processSliders: function() {
      var sliders = $$('#main-panel-content .sub-panel .section .section-slider', '#main-panel-content-long .sub-panel .section .section-slider')
      if(sliders.length > 1) {
         sliderLength = sliders.size();
         sliders.each(function(s, index) {
            s.addClassName('over')
            if (index!= (sliderLength-1)) {
               this.hideSlider(s);
               s.removeClassName('over')         
            }

            this.sliderCount++;
            this.idSlider(s);
            this.activateSlider(s);
            this.activeSlider = s.id;
         }.bind(this));
      }
   },
   
   hideSlider: function(element) {
      element.next().setStyle({'display':'none'})
   },
   
   idSlider: function(element) {
      element.writeAttribute("id", "slider-header"+this.sliderCount);
      element.next().writeAttribute("id", "slider-content"+this.sliderCount);
   },

   activateSlider: function(element) {
      Event.observe(element,'mouseover',this.actionSlider.bindAsEventListener(this, element));   
   },
   
   actionSlider: function(e, element) {
      if(this.sliderMoving == false) {
         if (element.id != this.activeSlider) {
            this.sliderMoving = true;
            element.addClassName('over');

            new Effect.BlindDown(element.next(), { duration:0.3, afterFinish: function() { this.sliderMoving = false;}.bind(this)});
            if (this.activeSlider) {
               $(this.activeSlider).removeClassName('over');
               new Effect.BlindUp($(this.activeSlider).next(), { duration:0.3, afterFinish: function() { this.sliderMoving = false; }.bind(this)});
            }
            this.activeSlider = element.id;
         }
      }
   },
   
   processQAs: function(event, elementId) {
      this.activeQuestion = "";
      if (!elementId) {
         elementId = ""
      }
      var questions = $$('.section '+ elementId +' .question');
      if(questions.length > 0) {
         questions.each(function(s) {
            this.questionCount++;
            this.hideQAs(s);
            //this.idQAs(s);
            this.activateQAs(s);   
         }.bind(this));
      }
   },
   
   hideQAs: function(element) {
      element.next().setStyle({'display':'none'});
   },
   
   idQAs: function(element) {
      element.writeAttribute("id", "question"+this.questionCount);
      element.next().writeAttribute("id", "answer"+this.questionCount);
   },
   
   activateQAs: function(element) {
      Event.observe(element,'click',this.actionQA.bindAsEventListener(this, element));   
   },
   
   actionQA: function(e, element) {
      if (element != this.activeQuestion && this.activeQuestion) {
         if($(this.activeQuestion).next()) {
            $(this.activeQuestion).next().hide();
            $(this.activeQuestion).setStyle({'fontWeight':'normal'});
            $(this.activeQuestion).addClassName('question');
            $(this.activeQuestion).removeClassName('question-over');
         }
      }
   
      if(element.next().visible()) {
         element.next().hide();
         element.setStyle({'fontWeight':'normal'});
         element.addClassName('question');
         element.removeClassName('question-over');
      } else {
         pageTitle = document.title;
         questionTitle = element.innerHTML;
         questionNumber = element;
         pageUrl = location.href;
   
         //dcsMultiTrack('DCS.dcsuri',pageUrl+'/qa-'+questionNumber+'.html','WT.ti',pageTitle+' - Q&A:'+ questionTitle);
         element.setStyle({'fontWeight':'bold'});
         element.next().show();
         element.addClassName('question-over');
         element.removeClassName('question');
      }
      this.activeQuestion = element;
   },
   
   mouseover: function(event,target) {
      window.clearTimeout(this.timeout);
      subnavId = target.rel;
      if (subnavId == this.activeNavigation) {
         return false;
      } else {
         this.checkActiveNavigation(subnavId);
         $(subnavId).show();
         targetLinks = $$('#'+ subnavId +' a')
         targetLinks.each(function(s) {
            Event.observe(s,'focus',this.subnavMouseover.bind(this));
            Event.observe(s,'blur',this.subnavMouseout.bind(this));   
         }.bind(this));
         Event.observe(subnavId,'mouseover',this.subnavMouseover.bind(this));
         Event.observe(subnavId,'mouseout',this.subnavMouseout.bind(this));
         this.activeNavigation = target.rel;
      }
   },
   
   mouseout: function(event,target) {
      this.subnavMouseout();
   },
   
   subnavMouseover: function() {
      window.clearTimeout(this.timeout);
   },
   
   subnavMouseout: function() {
      subnavId = $(this.activeNavigation);
      window.clearTimeout(this.timeout);
      this.timeout = setTimeout(function() {
         this.checkActiveNavigation(subnavId);
         this.activeNavigation = "";
      }.bind(this), this.subnavTime);
   },   
   
   checkActiveNavigation: function(current) {
      if (this.activeNavigation != "" ) {
         $(this.activeNavigation).hide();
         Event.stopObserving(current,'mouseover',this.subnavMouseover.bind(this));
         Event.stopObserving(current,'mouseout',this.subnavMouseout.bind(this));
      }
   },
   
   setCookie: function(name,value) {
      /* Sets session cookie of (name,value) */ 
      document.cookie = name +"="+ value +";path=/;"
   },

   deleteCookie: function(name) {
      /*  Deletes session cookie of (name) */ 
      document.cookie = name + '=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT;';
   },
   
   getCookieValueFromName: function(name) {
      /* Returns cookie value from cookie name */ 
      var cookies = document.cookie.split(';');
      for(var i = 0; i < cookies.length; i++) {   
         var cookie = cookies[i].split("=");
         if(cookie[0].replace(" ", "") == name) {
            return cookie[1];    
         }
      }
   },

   readCookieValueFromName: function(name) {
      /* Returns true if cookie found */ 
      var cookies = document.cookie.split(';');
      for(var i = 0; i < cookies.length; i++) {   
         var cookie = cookies[i].split("=");
         if(cookie[0].replace(" ", "") == name) {
            return true    
         }
      }
   },
   
   activateFooter: function() {
      if($('footer-panel-content')) {
         var footer = $('footer-panel-content');
         if (this.getCookieValueFromName('footer') != 'show' ) {
            footer.hide();
         }

         Event.observe($('footer-link'),'click',function(e) {
            window.clearTimeout(this.footerTimeout);
            if(!footer.visible()) { //Footer is invisible
               this.deleteCookie('footer');
               this.setCookie('footer','show')
               $('footer-title').removeClassName('closed');
               $('footer-title').addClassName('open');
               footer.show();
               footer.scrollTo();
            } else {
               this.deleteCookie('footer');
               this.setCookie('footer','hide')
               $('footer-title').removeClassName('open');
               $('footer-title').addClassName('closed');
               footer.hide();
            }
         }.bind(this));
      }
   },
   
   activatePopoutPanel: function() {
      if ($('main-panel-lozenge-popout')) {
         var page = $('page-body').cumulativeOffset();
         var lozenge = $('main-panel-lozenge-popout').cumulativeOffset();
         var left = page[0] - lozenge[0];
         var top = page[1] - lozenge[1];
         $('main-panel-lozenge-popout').setStyle({'backgroundImage':'url('+ this.popout +')','backgroundPosition':left+'px '+ top +'px'});
      }
   },
   
   preloadImage: function(imgUrl) {
      imageNumber = "imgpl"+this.imgNum
      imageNumber = new Image();
      imageNumber.src = imgUrl;
      this.imgNum++;
   },

   deactivateLogoLink: function() {
      if (!$('global-nav-list')) {
         if($('logo')) {
            logoImg = $('logo').down().innerHTML
            $('logo').down().replace(logoImg)
         }
      }
   },

   // Flash Microsite Methods
   activateFlashMicrosite: function() {
      var bodyElmt = $$('body')[0];
      this.deleteCookie("eboValue");
      if (this.returnMicrositeCookie(this.micrositeCookieName)) {
         cookieValue = this.getCookieValueFromName(this.micrositeCookieName)
         this.loadFlashMicrosite(cookieValue)
      } else {
         cookieValue = this.determineFlashMicrosite()
         this.setCookie(this.micrositeCookieName, cookieValue)
         this.loadFlashMicrosite(cookieValue)
      }
   },
   
   determineFlashMicrosite: function() {
      number = Math.floor(Math.random()*100);            // Generate Random number (0-99)
      percent = parseInt(this.micrositePercent);
      if (number < percent) {   
         //alert("Number is: "+ number +" - Microsite will be loaded")
         result = "yes"
      } else {
         //alert("Number is: "+ number +" - Microsite will NOT be loaded")
         result = "no"
      }
      this.setCookie("eboValue", number)
      return result
   },


   loadFlashMicrosite: function(value) {
   // Have to put in a browser detect to disable Flash in Opera - doesn't work for some reason!! Needs further investigation.
      if (BrowserDetect.browser == "Opera") {
         return false
      }
      if (value == "yes") {
         this.initializeMicrosite()
      } else {
         return false
      }
   },
   
   initializeMicrosite: function() {
   if ($('page-body-flash-panel-microsite')) {
      flashId = $('page-body-flash-panel-microsite')
      flashId.absolutize();
      flashId.setStyle({'top':'163px','left':'726px','width':'255px'})
      var flashteaser = new SWFObject("/virgin/Images/pageCurl_tcm23-3737.swf", "curl", "255", "329", "8", "");
      flashteaser.addParam("wmode", "transparent");
      flashteaser.addParam("allowScriptAccess","always")
      flashteaser.write("page-body-flash-panel-microsite");
      dcsMultiTrack('DCS.dcsuri','/virgin/EBO/pagecurl.html','WT.ti','EBO%20Page%20Curl','WT.cg_n','General','WT.cg_s','EBO%20site');
      }
   },
   
   swapMicrosite: function(msg) {
      this.showMicrosite();
   },
   
   showMicrosite: function() {
      OpenNewSW('/virgin/ebo.jsp','newWindow','1050','750',{'scrollbars':'yes','resizable':'yes'})
      dcsMultiTrack('DCS.dcsuri','/virgin/EBO/EBO-launch.html','WT.ti', 'EBO > Site launched','WT.cg_n','General','WT.cg_s','EBO site')
   },

   hideMicrosite: function() {
      self.close()
   },

   returnMicrositeCookie: function() {
      if(this.readCookieValueFromName("microsite")) {
         return true
      } else {
         return false
      }
   },
   
   sendMicrositeComments: function(array) {
      new Ajax.Request('/form-recorder/record.htm', {
         method: 'post',
         parameters: 'formName=ebo-comments&redirect=&name='+ array[0] +'&city='+ array[1] +'&email='+ array[3] +'&comment='+ array[2]  ,
         onSuccess: function(transport) {
            //alert("success")            
            }
      });
   },

   // Social Bookmarking methods
   findShareLink: function() {
      if($('social-bookmark')) {
         this.writeSocialLink();
      }else if ($('social-bookmark-short')) {
         this.writeShortSocialLink();
      }
   },


   //Social Networking links
   writeSocialLink: function() {
      var pageUrl   = document.location;
      var pageTitle = document.title;
      var faveFlag  = false;
      pageTitle = escape(pageTitle.replace(/'/g, "\\'"));
      bookmarkLink = "";

      // Determine which browser we're in //
         if (BrowserDetect.browser == "Explorer") {
            bookmarkLink = "<a title=\"Add this page to your favourites\" href=\"javascript:window.external.AddFavorite('"+pageUrl+"', '"+pageTitle+"')\">Favourites</a>";
            faveFlag = true;
         }else if (BrowserDetect.browser == "Firefox") {
            bookmarkLink = "<a title=\"Add this page to your bookmarks\" href=\"javascript:window.sidebar.addPanel('"+pageTitle+"', '"+pageUrl+"','')\">Bookmark</a>";
            faveFlag = true;
         }

         // Create the content for the popup //
        shareContent   = "<div class='sharethis'><div class='share-padding'><ul class='social'>";
        shareContent += "<li style='margin:0;padding:0;padding-right:10px;font-weight:bold'>Share this:</li>";
        if (faveFlag){
           shareContent += "<li class='favourites'>"+bookmarkLink+"</li>";
        }

        shareContent += "<li class='digg'><a title='Post this page to Digg' href='http://digg.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Digg</a></li>";
        shareContent += "<li class='delicious'><a title='Post this page to Del.icio.us' href='http://del.icio.us/post?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Delicious</a></li>";
        shareContent += "<li class='reddit'><a title='Post this page to Reddit' href='http://reddit.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Reddit</a></li>";
        shareContent += "<li class='facebook'><a title='Post this page to Facebook' href='http://www.facebook.com/sharer.php?u="+pageUrl+"' target='_blank'>Facebook</a></li>";
        shareContent += "<li class='stumbleupon'><a title='Post this page to Stumbleupon' href='http://www.stumbleupon.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>StumbleUpon</a></li>";
        shareContent += "</ul></div></div>";
        $('social-bookmark').update(shareContent);
   },
   
   writeShortSocialLink: function() {
      var pageUrl   = document.location;
      var pageTitle = document.title;
      pageTitle = escape(pageTitle.replace(/'/g, "\\'"));

      // Create the content for the popup //
      shareContent   = "<div class='sharethis'><div class='share-padding'><ul class='social'>";
      shareContent += "<li style='margin:0;padding:0;padding-right:350px;font-weight:bold;height:20px'>Share this:</li>";
      shareContent += "<li class='digg'><a title='Post this page to Digg' href='http://digg.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Digg</a></li>";
      shareContent += "<li class='delicious'><a title='Post this page to Del.icio.us' href='http://del.icio.us/post?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Delicious</a></li>";
      shareContent += "<li class='reddit'><a title='Post this page to Reddit' href='http://reddit.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>Reddit</a></li>";
      shareContent += "<li class='facebook'><a title='Post this page to Facebook' href='http://www.facebook.com/sharer.php?u="+pageUrl+"' target='_blank'>Facebook</a></li>";
      shareContent += "<li class='stumbleupon'><a title='Post this page to Stumbleupon' href='http://www.stumbleupon.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'>StumbleUpon</a></li>";
      shareContent += "</ul></div></div>";
      $('social-bookmark-short').update(shareContent);
   },

   //End of My Offers methods
   /////////////////////////////
   /////////////////////////////   
   
   findLoginPanels: function() {
      if($('credit-card-login')) {
         this.validateCreditCardLoginPanel();
      }
      
      if($('prepaid-credit-card-login-router')) {
         this.validateNewPrepaidCreditCardLoginPanel();
      }
      
      if($('travel-prepaid-credit-card-login')) {
         this.validateTravelPrepaidCreditCardLoginPanel();
      }
   
      if($('charity-credit-card-login')) {
         this.validateCharityCreditCardLoginPanel();
      }

      if($('vlm-credit-card-login')) {
         this.validateVLMCreditCardLoginPanel();
      }
   },
   
   validateCreditCardLoginPanel: function() {
      loginPanel = $('credit-card-login');
      Event.observe(loginPanel,'submit',function(event) {
         usernameError = false;
         if($F(loginPanel['userID']).length == 0){
            this.showValidationError('error-username','Please enter your username')
            usernameError = true;
            Event.stop(event)
         } else {
            this.removeValidationError('error-username')
            usernameError = false;
         }
         
         if (usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','800','450',{'scrollbars':'yes','resizable':'yes'})
            dcsMultiTrack('DCS.dcsuri','/service/ MVM-creditcard-login.html','WT.ti', 'My Virgin Money > Credit Card > Login','WT.cg_n','My Virgin Money','WT.cg_s','My Card','WT.seg_1','Service Customer','WT.seg_2','Credit Card Service Customer','WT.pi','My%20Virgin%20Money%20Credit%20Card%20Login')
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },
   
   clearLoginPanel: function(formName) {
      formName.reset();
      window.clearTimeout(this.panelTimeout);
   },
   
   validatePrepaidCreditCardLoginPanel: function() {
      loginPanel = $('prepaid-credit-card-login');
      Event.observe(loginPanel,'submit',function(event) {
         passwordError = false;
         usernameError = false;
         if($F(loginPanel['username']).length == 0){
            this.showValidationError('error-username','Please enter your username')
            Event.stop(event)
            usernameError = true;
         } else {
            this.removeValidationError('error-username')
            usernameError = false;
         }
         
         if($F(loginPanel['password']).length == 0){
            this.showValidationError('error-password','Please enter your password')
            Event.stop(event)
            passwordError = true;
         } else {
            this.removeValidationError('error-password')
            passwordError = false;
         }
         
         if (passwordError || usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','900','550',{'scrollbars':'yes','resizable':'yes'})         
            dcsMultiTrack('DCS.dcsuri','/service/MVM-prepaid-login.html','WT.ti', 'My Virgin Money > Prepaid Card > Login','WT.cg_n','My Virgin Money','WT.cg_s','My Prepaid Card','WT.seg_1','Service Customer','WT.seg_2','Prepaid Card Service Customer','WT.pi','My%20Virgin%20Money%20Prepaid%20Card%20Login');
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },
   
   validateNewPrepaidCreditCardLoginPanel: function() {


      if($("prepaid-card-login-panel-step-visa")) { 
         $("prepaid-card-login-panel-step-visa").hide();
      }
      if($("prepaid-card-login-panel-step-mc")) {
         $("prepaid-card-login-panel-step-mc").hide();
      }

      loginPanel = $('prepaid-credit-card-login-visa');
      formElement = $('prepaid-credit-card-login-router');
      selectElement = $('prepaid-credit-card-login-router-url');
      stepVisa = $("prepaid-card-login-panel-step-visa");
      stepVisaWidth = parseInt(stepVisa.getWidth());
      stepVisaHeight = parseInt(stepVisa.getHeight());
      selectElement.options[0].selected = true;
     // this.checkSelectValue("load", selectElement)

      Event.observe(selectElement,'change',function(event) {
         this.checkSelectValue(event);
      }.bindAsEventListener(this));

      this.validatePrepaidVisaPanel()
      this.validatePrepaidMastercardPanel()
   },

   checkSelectValue: function(event, refElement) {
      if(refElement) {
         changedElement = refElement;
      } else {
         changedElement = Event.element(event);
      }

      if(changedElement.value.length > 0) {
         stepVisa.removeClassName("disabled");
         stepVisa.addClassName("enabled");
         if($("step-2-mask")) {
            $("step-2-mask").remove()
         }

         formId = changedElement.value.evalJSON().form;
         panelId = changedElement.value.evalJSON().panel;
         registerLink = changedElement.value.evalJSON().register;
         whyRegisterLink = changedElement.value.evalJSON().whyRegister;
         appTarget = changedElement.value.evalJSON().appTarget;
         regTarget = changedElement.value.evalJSON().regTarget;
         loginLink = changedElement.value.evalJSON().login;

         $("prepaid-card-login-panel-step-visa").hide()
         $("prepaid-card-login-panel-step-mc").hide()
         $(panelId).show();
         $(formId).writeAttribute("action",loginLink);
         $(formId).writeAttribute("target",appTarget);
         $("prepaid-card-why-register-url").writeAttribute("href",whyRegisterLink);
         $("prepaid-card-register-url").writeAttribute("href",registerLink);
         //$("prepaid-card-register-url").writeAttribute("target",regTarget);
         $("prepaid-card-step2-header-mask").hide();
      } else {
         $("prepaid-card-login-panel-step-mc").hide()
         $("prepaid-card-login-panel-step-visa").hide()
         $("prepaid-card-step2-header-mask").show();
      }
   },

   openLoginTooltip: function(event) {
      if(!$("loginToolTip")) {
         posX = Event.pointerX(event) - 22;
         posY = Event.pointerY(event) - 80;
         var compareTooltip = new Element("div", {'id':'loginToolTip'}).update("<div>Please choose your card from the options above</div>");
         compareTooltip.setStyle({'left':posX+'px','top':posY+'px'})
         var objBody = $$('body')[0];
         new Element.insert(objBody, {bottom:compareTooltip});
      }
   },

   closeLoginToolTip: function() {
      if($("loginToolTip")) {
         $("loginToolTip").remove();
      }
   },

   validatePrepaidMastercardPanel: function() {
      loginPanel = $('prepaid-credit-card-login-mc');
      Event.observe(loginPanel,'submit',function(event) {
         passwordError = false;
         usernameError = false;

         if($F(loginPanel['username-mc']).length == 0){
            this.showValidationError('error-username-mc','Please enter your username')
            Event.stop(event)
            usernameError = true;
         } else {
            this.removeValidationError('error-username-mc')
            usernameError = false;
         }

         if($F(loginPanel['password-mc']).length == 0){
            this.showValidationError('error-password-mc','Please enter your password')
            Event.stop(event)
            passwordError = true;
         } else {
            this.removeValidationError('error-password-mc')
            passwordError = false;
         }

         if (passwordError || usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','800','450',{'scrollbars':'yes','resizable':'yes'})
            dcsMultiTrack('DCS.dcsuri','/service/MVM-prepaid-login-mastercard.html','WT.ti', 'My Virgin Money > Prepaid Card (Mastercard)> Login','WT.cg_n','My Virgin Money','WT.cg_s','My Prepaid Card','WT.seg_1','Service Customer','WT.seg_2','Prepaid Card (Mastercard) Service Customer','WT.pi','My%20Virgin%20Money%20Prepaid%20Card%20Login%20Mastercard');
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },

   validatePrepaidVisaPanel: function() {
      loginPanelVisa = $('prepaid-credit-card-login-visa');
      Event.observe(loginPanel,'submit',function(event) {
         usernameError = false;
         if($F(loginPanelVisa['username-visa']).length == 0){
            this.showValidationError('error-username-visa','Please enter your username')
            Event.stop(event)
            usernameErrorVisa = true;
         } else {
            this.removeValidationError('error-username-visa')
            usernameErrorVisa = false;
         }

         if (usernameErrorVisa) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','1010','600',{'scrollbars':'yes','resizable':'yes'})
            dcsMultiTrack('DCS.dcsuri','/service/MVM-prepaid-login-visa.html','WT.ti', 'My Virgin Money > Prepaid Card (Visa) > Login','WT.cg_n','My Virgin Money','WT.cg_s','My Prepaid Card (Visa)','WT.seg_1','Service Customer','WT.seg_2','Prepaid Card (Visa) Service Customer','WT.pi','My%20Virgin%20Money%20Prepaid%20Card%20Login%20Visa');
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanelVisa);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },

   validateTravelPrepaidCreditCardLoginPanel: function() {
      loginPanel = $('travel-prepaid-credit-card-login');
      Event.observe(loginPanel,'submit',function(event) {
         passwordError = false;
         usernameError = false;
      
         if($F(loginPanel['username']).length == 0){
            this.showValidationError('error-username','Please enter your username')
            Event.stop(event)
            usernameError = true;
         } else {
            this.removeValidationError('error-username')
            usernameError = false;
         }
         
         if($F(loginPanel['password']).length == 0){
            this.showValidationError('error-password','Please enter your password')
            Event.stop(event)
            passwordError = true;
         } else {
            this.removeValidationError('error-password')
            passwordError = false;
         }
         
         if (passwordError || usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','800','450',{'scrollbars':'yes','resizable':'yes'})         
            dcsMultiTrack('DCS.dcsuri','/service/MVM-travel-prepaid-login.html','WT.ti', 'My Virgin Money > Prepaid Travel Card > Login','WT.cg_n','My Virgin Money','WT.cg_s','My Prepaid Travel Card','WT.seg_1','Service Customer','WT.seg_2','Prepaid Travel Card Service Customer','WT.pi','My%20Virgin%20Money%20Prepaid%20Travel%20Card%20Login');
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },

   validateCharityCreditCardLoginPanel: function() {
      loginPanel = $('charity-credit-card-login');
      Event.observe(loginPanel,'submit',function(event) {
         usernameError = false;
      
         if($F(loginPanel['userID']).length == 0){
            this.showValidationError('error-username','Please enter your username')
            usernameError = true;
            Event.stop(event)
         } else {
            this.removeValidationError('error-username')
            usernameError = false;
         }
         
         if (usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','800','450',{'scrollbars':'yes','resizable':'yes'})
            dcsMultiTrack('DCS.dcsuri','/service/ MVM-charitycreditcard-login.html','WT.ti', 'My Virgin Money > Credit Card > Login','WT.cg_n','My Virgin Money','WT.cg_s','Charity','WT.seg_1','Service Customer','WT.seg_2','Credit Card Service Customer','WT.pi','My%20Virgin%20Money%20Charity%20Credit%20Card%20Login')
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },

   validateVLMCreditCardLoginPanel: function() {
      loginPanel = $('vlm-credit-card-login');
      Event.observe(loginPanel,'submit',function(event) {
         usernameError = false;
      
         if($F(loginPanel['userID']).length == 0){
            this.showValidationError('error-username','Please enter your username')
            usernameError = true;
            Event.stop(event)
         } else {
            this.removeValidationError('error-username')
            usernameError = false;
         }
         
         if (usernameError) {
            Event.stop(event)
            return false
         } else {
            OpenNewSW('/virgin/blank-popup.jsp-SSL','newWindow','800','450',{'scrollbars':'yes','resizable':'yes'})
            dcsMultiTrack('DCS.dcsuri','/service/ MVM-marathoncreditcard-login.html','WT.ti', 'My Virgin Money > Credit Card > Login','WT.cg_n','My Virgin Money','WT.cg_s','Marathon','WT.seg_1','Service Customer','WT.seg_2','Credit Card Service Customer','WT.pi','My%20Virgin%20Money%20Marathon%20Credit%20Card%20Login')
            this.panelTimeout = setTimeout(function() {
               this.clearLoginPanel(loginPanel);
            }.bind(this), 50);
            return true
         }
      }.bindAsEventListener(this));
   },
   
   showValidationError: function(elementId,errorMessage) {
      $(elementId).update("<ul class=\"form-error\"><li>"+ errorMessage +"</li></ul>")
   },
   
   removeValidationError: function(elementId) {
      $(elementId).update();
   },

   findMyOffersPanel: function() {
      if ($("my-offers-main-panel")) {
         this.dealPadding = 6;
         this.navHeight = $("my-offers-category").getHeight();
         this.fadeSpeed = 0.3;
         this.loadingImg = "";
         this.lightboxWidth = 540;
         activeOfferNavigation = "";
         selectedDeal = "";
         selectedPanel = "panel-1";
         this.findLightboxTerms();
         this.findLightbox(); // Definately needed!
         this.findDealLayers();
         this.findPanelTabs();
         this.checkDealParameter();
         $('panel-loader').hide();
         this.clickDealNav('load','panel-1','deal-nav-1');
         this.clickDealNav('load','panel-1','deal-nav-1');
      }
   },

   findDealLayers: function() {
      var dealLayers = $$('.deal-detail', '.deal-panel');
      dealLayers.each(function(s) {
         this.hideLayers(s);
      }.bind(this));
   },

   findPanelTabs: function() {
      var panelTabs = $$('.my-offers-nav-link');
      panelTabs.each(function(s) {
         this.activatePanelTabs(s);
      }.bind(this));
   },

   activatePanelTabs: function(element) {
      panelId = element.rel;
      elementId = element.id;
      Event.observe(element,'click',this.clickDealNav.bindAsEventListener(this,panelId,elementId));
   },

   findDealLinks: function() {
      var dealLinks = $$('.deal-summary-link a');
      dealLinks.each(function(s) {
         this.activateDealLinks(s);
      }.bind(this));
   },

   activateDealLinks: function(element) {
      elementId = element.id;
      Event.observe(element,'click',this.clickDealDetail.bindAsEventListener(this,elementId));
   },

   hideLayers: function(element) {
      element.removeClassName("hidden"); // To remove this style already preset in CT
      element.hide();
   },

   // End of First function call
   /////////////////////////////
   /////////////////////////////

   clickDealNav: function(e,element,navElement) {
      navHeight = this.navHeight
      if ($(element).getHeight() < navHeight) {
         dealHeight = navHeight - (this.dealPadding * 2);
         $("my-offers-deals").setStyle({"height": dealHeight+"px"})
      } else {
         $("my-offers-deals").setStyle({"height": "auto"})
      }

      if(selectedDeal!="") { $(selectedDeal).hide()}
      $(selectedPanel).hide()
      $(element).show()
      selectedPanel = element;
      this.activateOfferNavigation(navElement)
   },

   activateOfferNavigation: function(element) {
      if(activeOfferNavigation != "") {
         $(activeOfferNavigation).addClassName('my-offers-nav-link')
         $(activeOfferNavigation).removeClassName('my-offers-nav-link-over')
      }

      $(element).addClassName('my-offers-nav-link-over')
      $(element).removeClassName('my-offers-nav-link')
      activeOfferNavigation = element;
   },

   //End of second function call
   /////////////////////////////
   /////////////////////////////

   clickDealDetail:function(e,detailElement) {
      detailElementID = detailElement.split("-link")[0];
      alert($(detailElementID).innerHTML);
   },

   // findLightbox()
   // Loops through anchor tags looking for 'lightbox' references and applies onclick
   // events to appropriate links. You can rerun after dynamically adding images w/ajax.

   findLightbox: function() {
      var lightboxItems = $$('a[rel^=lightbox]');
      lightboxItems.each(function(s) {
         this.activateLightbox(s);
      }.bind(this));

      if (lightboxItems.length > 0) {
         this.buildLightbox();
      }
   },

   buildLightbox: function() {
      var th = this;
      (function(){
         var ids =
            'contentOverlay lightbox lightboxContainer lightboxContentContainer lightboxContent lightboxTitle lightboxClose lightboxLoading';
         $w(ids).each(function(id){ th[id] = $(id); });
      }).defer();

      var objBody = $$('body')[0];
      var clearer = new Element("div", {'class':'clear'});
      var contentOverlay = new Element("div", {'id':'contentOverlay'});
      var lightbox = new Element("div", {'id':'lightbox'});
      var lightboxContainer = new Element("div", {'id':'lightboxContainer'});
      var lightboxTitle = new Element("div", {'id':'lightboxTitle'});
      var lightboxClose = new Element("div", {'id':'lightboxClose'}).update("<div>Close</div>");
      var lightboxContentContainer = new Element("div", {'id':'lightboxContentContainer'});
      var lightboxContent = new Element("div", {'id':'lightboxContent'});
      var lightboxHeader = new Element("div", {'id':'lightboxHeader'});

      new Element.insert(objBody, {bottom:contentOverlay});
      new Element.insert(lightboxContainer,{bottom:lightboxContentContainer});
      new Element.insert(lightboxHeader,{bottom:lightboxTitle});
      new Element.insert(lightboxHeader,{bottom:lightboxClose});
      new Element.insert(lightboxContentContainer,{bottom:lightboxHeader});
      //new Element.insert(lightboxContentContainer,{bottom:clearer});
      new Element.insert(lightboxContentContainer,{bottom:lightboxContent});
      new Element.insert(lightbox,{bottom:lightboxContainer});
      new Element.insert(objBody,{bottom:lightbox});

      lightbox.hide();

      contentOverlay.observe('click', (function() { this.end(); }).bind(this));
      lightboxClose.observe('click', (function() { this.end(); }).bind(this));
   },

   activateLightbox: function(element) {
      lightboxProps = element.rel
      lightboxProps = lightboxProps.split("=")[1]
      lightboxJSON = lightboxProps.evalJSON();
      lightboxContentType = lightboxJSON.type;
      lightboxContentSource = lightboxJSON.source;
      Event.observe(element,'click', this.openLightbox.bindAsEventListener(this,lightboxContentType,lightboxContentSource));
   },

   openLightboxFromFlash: function(source) {
      $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
      var arrayPageSize = this.getPageSize();
      $("contentOverlay").setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
      title = $(source+"-link").title;
      if (title==""){title="&nbsp;"};
      $("lightboxTitle").update(title);
      $("lightboxContent").update($(source).innerHTML);
      this.enhanceLightboxContent();
      posY = parseInt($$('body')[0].cumulativeScrollOffset()[1]) + 100;
      posX = (arrayPageSize[0] / 2) - 540 / 2;
      pagePos = $$('body')[0].positionedOffset();
      $("contentOverlay").setStyle({'top': pagePos[0]+'px','left':pagePos[1]+'px'});
      new Effect.Appear($("contentOverlay"), { duration: 0.3, from: 0.0, to: 0.7, afterFinish: function(){$("lightbox").show()}.bind(this) });
      $("lightbox").setStyle({'top': posY+'px','left':posX+'px'});
   },

   //  openLightbox()
   //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.

   openLightbox: function(event,type,source) {
      $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
      var arrayPageSize = this.getPageSize();
      this.contentOverlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
      var elt = Event.findElement(event, 'a');
      title = elt.title;
      if (title==""){title="&nbsp;"};
      this.lightboxTitle.update(title);
      this.showLoading();

      if (type == "id") {
         this.getContentFromID($(source));
      } else {
         this.getContentFromAJAX(source);
      }

      posY = parseInt($$('body')[0].cumulativeScrollOffset()[1]) + 100;
      posX = (arrayPageSize[0] / 2) - this.lightboxWidth / 2;
      pagePos = $$('body')[0].positionedOffset();
      this.contentOverlay.setStyle({'top': pagePos[0]+'px','left':pagePos[1]+'px'});
      new Effect.Appear(this.contentOverlay, { duration: this.fadeSpeed, from: 0.0, to: 0.7, afterFinish: function(){$(this.lightbox).show()}.bind(this) });
      $(this.lightbox).setStyle({'top': posY+'px','left':posX+'px'});
      dcsMultiTrack('WT.pi', false, 'WT.ac', false);
   },

   //  end()
   //
   end: function() {
      new Effect.Fade(this.lightbox, { duration: this.fadeSpeed });
      new Effect.Fade(this.contentOverlay, { duration: this.fadeSpeed });
      $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
   },

   showLoading: function() {
      var lightboxLoading = new Element("div", {'id':'lightboxLoading'}).update("<img src=\""+ this.loadingImg +"\"/>");
      this.lightboxContent.update(lightboxLoading)
   },

   getContentFromID: function(element) {
      content = element.innerHTML
      this.lightboxContent.update(content);
      this.enhanceLightboxContent();
   },

   enhanceLightboxContent: function() {
      //lightboxContent = $('lightboxContent');
     this.findLightboxPopups();
      // this.findLightboxTerms();
   },

   findLightboxTerms: function() {
      $$(".terms-content").each(function(s){
         s.setStyle({"display":"none"});
      }.bind(this))
      $$(".terms-title").each(function(s){
         s.writeAttribute("onclick","vbNavigation.prototype.showTerms(event);return false");
      }.bind(this))
   },

   showTerms: function(e) {
      clickedElement = Event.element(e);
      contentElement = clickedElement.next(".terms-content");
      if(!contentElement.visible()) {
         clickedElement.addClassName("selected");
         contentElement.show();
      } else {
         clickedElement.removeClassName("selected");
         contentElement.hide();
      }
   },

   findLightboxPopups: function() {
      var popupItems = $$('#lightboxContent a[rel^=popup]');
         popupItems.each(function(s) {
         this.activatePopup(s);
      }.bind(this));
   },

   // getContentFromAJAX()
   // Hide most elements and preload image in preparation for resizing image container.

   getContentFromAJAX : function(source) {
      new Ajax.Request(source, {
         method :'GET',
         evalScripts: true,
         onSuccess : function(transport) {
            content = transport.responseText;
            this.lightboxContent.update(content);
         }.bind(this)
      });
   },

   //  getPageSize()

   getPageSize: function() {
      var xScroll, yScroll;
      if (window.innerHeight && window.scrollMaxY) {
         xScroll = window.innerWidth + window.scrollMaxX;
         yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
         xScroll = document.body.scrollWidth;
         yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
         xScroll = document.body.offsetWidth;
         yScroll = document.body.offsetHeight;
      }

      var windowWidth, windowHeight;
      if (self.innerHeight) {   // all except Explorer
         if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
         } else {
            windowWidth = self.innerWidth;
         }
         windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
         windowWidth = document.documentElement.clientWidth;
         windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
         windowWidth = document.body.clientWidth;
         windowHeight = document.body.clientHeight;
      }

      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
         pageHeight = windowHeight;
      } else {
         pageHeight = yScroll;
      }

      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){
         pageWidth = xScroll;
      } else {
         pageWidth = windowWidth;
      }

      return [pageWidth,pageHeight];
   },

   checkDealParameter: function() {
      if (this.getUrlParameter("deal")) {
         this.findSpecificDeal('click',this.getUrlParameter("deal"))
      }
   },

   findSpecificDeal: function(event, dealId) {
      this.openLightboxFromFlash(dealId);
   },

   getUrlParameter: function(name) {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );

      if(results == null ) {
         return "";
      } else {
         return results[1];
      }
   },

   findGlossary: function() {
      if($("glossary-panel")) {
         this.activateGlossary();
      }
   },
   
   activateGlossary: function() {
      this.processGlossaryItems();
      this.processGlossaryCategories();
      this.buildGlossaryIndex();
      this.findGlossaryLinks();
   },
   
   findGlossaryLinks: function() {
      var glossaryLinks = $$('a[rel^=glossaryLink]');
      glossaryLinks.each(function(s) {
         this.activateGlossaryLink(s);
      }.bind(this));
   },
      
   activateGlossaryLink: function(element) {
      glossaryItem = element.rel.split("[")[1].split("]")[0]
      glossaryIndex = glossaryItem.charAt(0);
      element.writeAttribute("onclick","return false");
      element.onclick = function() { return false };
      Event.observe(element,'click', this.openGlossaryLink.bindAsEventListener(this, glossaryItem,glossaryIndex));
   },
   
   openGlossaryLink: function(e,glossaryItem,character) {
      this.actionGlossaryItemsByCharacter("load", character)   
      $$("div."+ character +" h3.g-header").each(function(s){
         if ((s.innerHTML).toLowerCase() == glossaryItem.toLowerCase()) {
            this.actionGlossaryItems("load", s, true)
         }
      }.bind(this))
   },
   
   buildGlossaryIndex: function() {
      indexStr = "abcdefghijklmnopqrstuvwxyz";
      firstIndex = true;      
      for(i=0;i<indexStr.length;i++) {
         character = indexStr.charAt(i);
         if ($$('#glossary-content-panel .'+ character).length > 0) {
            this.writeActiveLink(character);
            if (firstIndex) {
               this.actionGlossaryItemsByCharacter("load", character)
               firstIndex = false;
            }
         } else {
            this.writeInactiveLink(character);
         }
      }
   },
   
   writeActiveLink: function(character) {
      glossaryElmt = $("glossary-index");
      linkInner = new Element("span").update(character);
      activeLink = new Element("a",{'id':'index-'+ character}).addClassName('on').update(linkInner);      
      Event.observe(activeLink,'click',this.actionGlossaryItemsByCharacter.bindAsEventListener(this, character));
      glossaryElmt.insert(activeLink);
   },
   
   writeInactiveLink: function(character) {
      glossartElmt = $("glossary-index");
      linkInner = new Element("span").update(character);
      inactiveLink = new Element("div").addClassName('off').update(linkInner)
      glossartElmt.insert(inactiveLink);
   },
   
   actionGlossaryItemsByCharacter: function(e, character) {
      if($("index-"+ this.activeGlossaryCharacter)) {
         $("index-"+ this.activeGlossaryCharacter).removeClassName("selected")
      }
      $("index-"+ character).addClassName("selected");
      $$('#glossary-content-panel .'+ this.activeGlossaryCharacter).each(function(s) { s.hide()}.bind(this))
      $$('#glossary-content-panel .'+ character).each(function(s) { s.show()}.bind(this))
      $("glossary-header").update("Glossary: "+ character.toUpperCase())
      this.activeGlossaryCharacter = character
   },
   
   processGlossaryCategories: function() {
      $$('.g-item').each(function(s) {s.hide()}.bind(this))
   },
   
   processGlossaryItems: function() {
      var gItem = $$('.g-item .g-header');
      if(gItem.length > 0) {
         gItem.each(function(s) {
            this.gItem++;
            this.hideGlossaryItems(s);
            this.activateGlossaryItems(s);   
         }.bind(this));
      }
   },

   hideGlossaryItems: function(element) {
      element.next().setStyle({'display':'none'});
   },
   
   activateGlossaryItems: function(element) {
      Event.observe(element,'click',this.actionGlossaryItems.bindAsEventListener(this, element));   
   },
   
   actionGlossaryItems: function(e, element,timeout) {
      if (element != this.activeGlossaryItem && this.activeGlossaryItem) {
         $(this.activeGlossaryItem).next().hide();
         $(this.activeGlossaryItem).addClassName('g-header');
         $(this.activeGlossaryItem).removeClassName('g-header-over');
      }

      if(element.next().visible()) {
         element.next().hide();
         element.addClassName('g-header');
         element.removeClassName('g-header-over');
      } else {
         element.next().show();
         element.addClassName('g-header-over');
         element.removeClassName('g-header');
      }
      this.activeGlossaryItem = element;

      if(timeout) {
         setTimeout(function() {
            position = $(element).positionedOffset()
            window.scrollTo(position[0],position[1]);
         }.bind(this), 200);
      }      
   },

   findInsuranceAppLinks: function () {
      var windowTitle = document.title.toLowerCase();
      if(windowTitle.indexOf('car insurance') != -1) {
         this.rewriteAppLink('CAAAAA00', 'https://car.virginmoney.com/app/start.aspx','carInsRefer');
      }else if (windowTitle.indexOf('home insurance') != -1) {
         this.rewriteAppLink('HAAAAA00', 'https://home.virginmoney.com/app/start.aspx','homeInsRefer');
      }
   },

   rewriteAppLink: function(oldSource, baseUrl, cookieName) {
      sourceCode = "";
      //get value from cookie if it exists
      cookieString = getCookieValue(cookieName);
      if (cookieString) {
         sourceCode = cookieString.substring(cookieName.length+1,cookieString.length);
      }

      if (sourceCode == "") {
         //extract source code from url
         var url = window.location.toString();
         var linkParts = url.split('?');
         if (linkParts.length > 1) {
            var sourceCode = getValueFromParameter(linkParts[1]);

            //clean source code
            var regExPattern = /[\-,?~!@#$%&*+\-\'=\"]/g;
            sourceCode.replace(regExPattern,"");

            //put source code in a cookie
            document.cookie = cookieName+'='+sourceCode;
         }
      }

      //if we have a source code then use it
      if (sourceCode != "") {
         //add source code to all matching urls on page
         urlLength = baseUrl.length;
         allAnchors = $$('#page-body-panel-content a');
         allAnchors.each(function(s,i){
            if (s.href.indexOf(baseUrl) != -1) {
               //replace standard code with new code
               newLink = s.href.replace(oldSource, sourceCode);
               s.href = newLink;
            }
         });
      }
   },
   
   test: function() {
      alert("Hello");
   }
}
