// -----------------------------------------------------------------------------------

var vbNavigation = Class.create();

document.write('<script type="text/javascript" src="/virgin/assets/js/ccLookup.js"><\/script>');

vbNavigation.prototype = {

   // initialize()
   // Constructor runs on completion of the Page loading.

   initialize: function(keyword) {
      _this = this;
      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 = 5;
      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.imageSwapStart = 1;
      this.imageSwapTotal = 0;
      this.clientCookieStatus = 0;


      this.browserQuirks();
      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.findMyOffersPanel();
      this.findLoginPanels();
      this.findShareLink();
      this.findLightbox();
      this.findGlossary();
      this.findProcessLoungeMaps();
      this.findImageSwap();
      this.highlightSubNav();
      this.creditCardApply();


   },
   
   //
   // 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','#footer-extralinks a').each(function(s){
            this.changeSecureUrl(s);
         }.bind(this));
      }
   },
   
   changeSecureUrl: function(element) {
      elementUrl = element.href;
      //only update internal urls
      if (!$(element).hasClassName('external-nossl')) {
         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.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() 
      };
   },
   
   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 #main-panel-padding #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;
         new Effect.Fade($('message'+this.activeMessage));
         new Effect.Appear($('message'+section), { 
            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 = ""
      }else{
         elementId += " "
      }

      var questions = $$('.section '+ elementId +'.question');
      if(questions.length > 0) {
         questions.each(function(s) {
            this.questionCount++;
            this.hideQAs(s);
            this.activateQAs(s);   
         }.bind(this));
      }
   },
   
   hideQAs: function(element) {
      element.next().setStyle({'display':'none'});
   },
   
   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;
   
         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));
      }
   },
   
   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)
         }
      }
   },

   // 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;

      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;
         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-register-url").writeAttribute("href",registerLink);
         $("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();
      }
   },

   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 = 1;
         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) {

      if (!(BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 6)) { 

         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: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() {
     this.findLightboxPopups();
   },

   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;
            }
         });
      }
   },

   findProcessLoungeMaps: function() {
      if($("lounge-locator")) {
         this.processLoungeMaps();
      }
   },   
   
   processLoungeMaps: function() {
      var getItems = $$('.map-details');
      var getItemsMaps = $$('.uk-map-details');
      var form = $('map-form');
      var dropDown = form['locator'];
      var dropDownValueToCheck = $(dropDown).getValue();
      $(dropDown).observe('change', this.processLoungeMaps.bind(this));

      if (getItems.length > 0) {
         getItems.each(function(s) {
         
            var itemId = $(s.id);
            var itemIdToCheck = itemId.id;
            if (itemIdToCheck != dropDownValueToCheck) {
               itemId.addClassName('hide-maps');
            }else{   
               itemId.removeClassName('hide-maps');
            }
         }.bind(this));
      }

      if (getItemsMaps .length > 0) {
         getItemsMaps .each(function(s) {
         
            var itemId = $(s.id);
            var itemIdToCheck = itemId.id;
            if (itemIdToCheck != 'uk-map-'+dropDownValueToCheck) {
               itemId.addClassName('hide-maps');
            }else{   
               itemId.removeClassName('hide-maps');
            }
         }.bind(this));
      } 
   },

   findImageSwap: function() {
      if($("image-swap")) {
         this.imageSwapTotal = $$('#image-swap img').length;
         this.processImageSwap();
      }
   },   

   processImageSwap: function() {
      //Get all images
      var getImages = $$('#image-swap img');
      //image ID
      var i = 1;
     
      if (getImages.length > 0) {
         getImages.each(function(s) {
            //give the images an ID
            $(s.id = 'imageSwap'+i);
            //check to see if it is the first image if not hide it.
            var itemId = $(s.id);
            if(i !=1){
              itemId.setStyle({'display':'none'});
            }
            i++;
         }.bind(this));
      }
      this.timeHomepageMessagesImages();
   },

   processImageSwapFade: function(id, last) {
      window.clearInterval(this.messageInterval);
      new Effect.Fade($('imageSwap'+id), { 
         afterFinish: function() {
      
            if(!last){
              this.imageSwapStart ++;
            }
            new Effect.Appear($('imageSwap'+this.imageSwapStart));
            }.bind(this)
         });
      this.timeHomepageMessagesImages();
   },

   timeHomepageMessagesImages: function() {
      this.messageInterval = window.setInterval(function() {
         if(this.imageSwapStart == $$('#image-swap img').length){
            this.processImageSwapFade(this.imageSwapStart, true);
            this.imageSwapStart = 1;
         }else{
           this.processImageSwapFade(this.imageSwapStart,false);
         }
      }.bind(this), (4000));
   },

   highlightSubNav: function() {
      if (document.body.id == "help-guides") {
         startPoint = document.body.id;
         subNavItems = $$('#product-nav-list li a');
         subNavItems.each(function(s) {
            linkUrl = s.href.substring((s.href.indexOf(startPoint)+startPoint.length),s.href.lastIndexOf("/"));

            if (window.location.toString().indexOf(linkUrl) > 0 && linkUrl.length > 0) {
               s.addClassName('selected');
            }
         });
      }
   },
   
   creditCardApply: function() {
      /* Credit Card Apply - Kicks off source code recording / lookup etc */
      this.firstCheckForBannerCookie();

      if($("credit-card-apply")) {
         this.processCreditCardApplyPage();
      }
      if($("credit-card-choose")) {
         this.processCreditCardChoosePage();
      }
   },

   processCreditCardApplyPage: function() {
      this.checkForBannerCookie();   
   },   
   
   processCreditCardChoosePage: function() {

      if ($("javascript-warning")) { $("javascript-warning").hide()};
      if ($("cookie-warning")) {$("cookie-warning").hide()};

      if(document.cookie) {
 
         var source = this.returnCookieStatus("source"+'=');         
         var ciRef = this.returnCookieStatus("ciRef"+'=');

         if (ciRef) {

            ciRefArray = ciRef.split(",");

            $$(".cc-intermediary").each(function(t) { 
            
            $(t).hide()       
            
            })

            ciRefArray.each(function(s) {

               if($(s)) {
               
                  elementId = $(s).id;
                              
                     applicationUrlFull = $$('#'+ elementId +' a')[0].href;            
                     applicationUrl = applicationUrlFull.split("?")[0];
                     applicationParams = applicationUrlFull.split("?")[1];

                     bannerCodePos = applicationParams.indexOf('mc=');
                     newBannerCodeParam = "mc="+ source +"";
                  
                     if (bannerCodePos) {
                  
                        bannerCodeParam = applicationParams.slice(bannerCodePos).split("&")[0];
                        applicationUrlFull = applicationUrlFull.replace(bannerCodeParam,newBannerCodeParam);

                     }   
                  
                     $$('#'+ elementId +' a')[0].href = applicationUrlFull;
            
                  $(s).show();
               }          
            })
         }
      
      } else {
   
         $("cookie-warning").show();
   
      }
   },

   firstCheckForBannerCookie: function() {
   /* This check is always performed so that a banner is 
      recorded even if the user doesn't visit the pre-apply page */

      if(document.cookie) {
            var bannerCookie = this.returnCookieStatus('source=');
         if (bannerCookie) {      
            this.creditIntermediaryRef = bannerCookie.split("-")[0].substring(0,3).toUpperCase();
            writeCookie = this.writeClientCookie("ciRef",this.creditIntermediaryRef)
         }
      }  
   },
   
   checkForBannerCookie: function() {
 
     this.cardInfoForm = $("card-apply-information-form");   
  
      if(document.cookie) {
      
         var bannerCookie = this.returnCookieStatus('source=');
   
         if (!bannerCookie) {
         
            /* No cookie means no bannercode = replace form URL with default app URL */

            this.replaceFormAction();

         } else {     
         
            /* Otherwise start processing the bannerCode */
            
            this.replaceBannerFormUrl(bannerCookie);    

            this.creditIntermediaryRef = bannerCookie.split("-")[0].substring(0,3).toUpperCase();
            this.productCode = this.getProductCode(this.cardInfoForm);   
         
            this.writeClientCookie("ciRef",this.creditIntermediaryRef)
      
            if (_this.clientCookieStatus == "multiple")  {
               ciRefs = this.returnCookieStatus('ciRef=');
               this.checkValidCIForProduct(this.productCode,ciRefs);            

            } else if (_this.clientCookieStatus == "single") {
               ciRefs = this.returnCookieStatus('ciRef=');
               this.checkValidCIForProduct(this.productCode,ciRefs);  
            
            } else {
         
               this.replaceFormAction();       

            }
            
         }
        
      } else {

            this.replaceFormAction("default")  

      }
   
   },   checkValidCIForProduct: function(product, ciRef) {
      productFound = false;
      ciRefFound = false;
      noFound = 0;     
      ciRefArray = ciRef.split(",");
      cardProductCodes = cardCodes.products;
      
      for (var prop in cardProductCodes) {
         if (cardProductCodes.hasOwnProperty(prop)) {
            if(prop == product) {
               productFound = true;
               for(i=0;i<ciRefArray.length;i++) {
                  for(var key in cardProductCodes[prop].intermediaryCodes) {
                     if(key == ciRefArray[i]) {   
                          ciRefFound = true;
                          noFound++;
                          ciRef = key;
                     }
                  }
               }  
            }
         }
      }     
   
      if (!ciRefFound) {
         this.replaceFormAction();
      }

      if(noFound == 1) {
         this.checkLookupTable(product,ciRef);   
      }

      if(noFound > 1) {
         this.replaceFormAction("default")   
      } 
   },
   
   writeClientCookie: function(cookieName,value) {
      var ciRef = this.returnCookieStatus(cookieName+'=');

      if (ciRef) {
         if(ciRef.indexOf(value) == -1) {
            if(this.ciRefExists(value)) {
               document.cookie = cookieName+'='+ciRef+","+ value+";path=/virgin";
               _this.clientCookieStatus = "multiple";
             }else{
               this.checkClientCookie(ciRef);
            }
         }else{
           this.checkClientCookie(ciRef);
         }
      }else{
         if(this.ciRefExists(value)) {
            document.cookie = cookieName+'='+value +";path=/virgin";
            _this.clientCookieStatus = "single";
         } else {
            _this.clientCookieStatus = "invalid";
         }
      }
   },
   
   checkClientCookie: function(cookieName) {
      if (cookieName.split(",").length > 1) {
         _this.clientCookieStatus = "multiple";
      } else {
         _this.clientCookieStatus = "single";
      }
   },   
   
   ciRefExists: function(ciRef) {
      intermediaryCodes = cardCodes.intermediaryCodes;
      for (i=0;i<intermediaryCodes.length;i++) {
         if(ciRef == intermediaryCodes[i]) {
            return true;   
         }
      }  
   return false;
   },
   
   getProductCode: function(cardForm) {
      return cardForm['product'].value;
   },   
   
   checkLookupTable: function(product, ciRef) {
      productFound = false;
      ciRefFound = false;
      cardProductCodes = cardCodes.products;
      for (var prop in cardProductCodes) {

         if (cardProductCodes.hasOwnProperty(prop)) {
            if(prop == product) {
               productFound = true;
               for(var key in cardProductCodes[prop].intermediaryCodes) {
                  if(key == ciRef) {   
                     ciRefFound = true;
                     sourceCode = cardProductCodes[prop].intermediaryCodes[key];
                     this.replaceFormUrl(this.returnCookieStatus('source='),sourceCode);
                  }         
               }
            }
         }
      }     
   
      if(!productFound || !ciRefFound) {
         this.replaceFormUrl(this.returnCookieStatus('source='))   ;   
      }   
   },
   
   replaceBannerFormUrl: function(bannerCode) {   
     applicationBannerUrlFull = $("card-apply-information-form")['applicationURL'].value.toString();
     applicationBannerUrl = applicationBannerUrlFull.split("?")[0];
     applicationBannerParams = applicationBannerUrlFull.split("?")[1];
     bannerCodePos = applicationBannerParams.indexOf('mc=');
     newBannerCodeParam = "mc="+ bannerCode +"";
       
     if (bannerCodePos !=-1 ) {
        bannerCodeParam = applicationBannerParams.slice(bannerCodePos).split("&")[0];
        applicationBannerUrlFull = applicationBannerUrlFull.replace(bannerCodeParam,newBannerCodeParam);
     }   
     $("card-apply-information-form")['applicationURL'].value = applicationBannerUrlFull;
   },
   
   replaceFormUrl: function(bannerCode) {    
     applicationUrlFull = $("card-apply-information-form")['applicationURL'].value.toString();
     applicationUrl = applicationUrlFull.split("?")[0];
     applicationParams = applicationUrlFull.split("?")[1];
     if (arguments[1]) {
        sourceCode = arguments[1];
        sourceCodePos = applicationParams.indexOf('sc=');
        newSourceCodeParam = "sc="+ sourceCode +"";
        sourceCodeParam = applicationParams.slice(sourceCodePos).split("&")[0];
        applicationUrlFull = applicationUrlFull.replace(sourceCodeParam,newSourceCodeParam);
     } 
     
     $("card-apply-information-form")['applicationURL'].value = applicationUrlFull;
     this.replaceFormAction();
   },
   
   replaceFormAction: function() {
      if (arguments[0]) {
         applicationUrlFull = "choose.jsp";         
      } else {
         applicationUrlFull = $("card-apply-information-form")['applicationURL'].value.toString();      
      }
      
      $("validForm").action = applicationUrlFull;
      $("apply-now-button").href = "#";
      Event.observe($("apply-now-button"),'click',this.submitForm.bindAsEventListener(this));  

      setTimeout(function() {$("apply-now-button").removeClassName("disabled")}, 200);
         
   },  
   
   submitForm: function() {

      _this.checkForBannerCookie();  

      webtrends = this.cardInfoForm['webtrends'].value;    
      verify = this.cardInfoForm['verify'];   
      if(verify.checked == true) {
         if(document.colourForm) {
            radioSet = document.colourForm.productCode;
            radioLength = radioSet.length;

            for(i=0;i<radioLength;i++) {
               if(radioSet[i].checked) {
                  selectedValue = radioSet[i].value;
                  $('validForm').productCode.value = selectedValue;
               }         
            }
         }
      
         eval(webtrends);
         $("validForm").submit();
      } else {
         var errorMsg = $('error');
         errorMsg.innerHTML = "<span class=\"error-text\">Please tick the box above to confirm you've read the summary box. </span>";
         var errorMark = $('error-mark');
         errorMark.innerHTML = "<span><strong>x</strong></span>";   
      }
   },
      
   returnCookieStatus: function(cookieStr) {
      var cookieString = document.cookie;
      cookieBannerPos = cookieString.indexOf(cookieStr);

      if (cookieBannerPos !=-1 ) {
         cookieBannerString = cookieString.slice(cookieBannerPos);
         cookieBannerArray = cookieBannerString.split(";");
         cookieBannerParam = cookieBannerArray[0];
         cookieBannerValue = this.getValueFromParameter(cookieBannerParam);
         return cookieBannerValue;
      } else {
         return false;
      }
   },
   
   getValueFromParameter: function(parameter) {
      newParameter = parameter.split("=");
      return newParameter[1];
   },
  
   test: function() {
      alert("Hello");
   }
}
