// -----------------------------------------------------------------------------------
//
//	Virgin Money Navigation
//	by Jim Starling
//
//             
//             19/01/08 - EBO Microsite Functionality
//             26/01/08 - Social Bookmarking Functionality
//	06/02/08 - My Offers Functionality
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Navigation Class Declaration
    - initialize()
    - addObservers()
    - findlinks()
    - setBg()
    - findsubnav()
    - enhanceSubnav()
    - arrangeSubnav()
    - enhanceContent()
    - hideContent()
    - idContent()
    - writeContentNav()
    - writeContentArrows()
    - showContentSection()
    - enhanceHomepageMessages()
    - hideMessages()
    - idMessages()
    - writeMessageNav()
    - writeMesageNavBorder()
    - writeMessageArrows()
    - showMessage()
    - timeHomepageMessages()
    - processQAs()
    - hideQAs()
    - idQAs()
    - activateQAs()
    - actionQA()
    - mouseover()
    - mouseout()
    - subnavMouseover()
    - subnavMouseout()
    - checkActiveNavigation()
    - loadFlash()
    - loadFlashMicrosite()
    - activateFooter()
    - activatePopoutPanel()
    Function Calls
    - document.observe()
    - Event.observe()

*/

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

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 = 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.micrositeIframe = 0;
    		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.enhanceHomepageMessages();
		this.enhanceCarousel();
		this.activateFooter();
		this.processQAs();
		this.processSliders();
		this.findPopups();
		this.findCTARollovers();
		this.findLinks();
		this.activatePopoutPanel();
		this.deactivateLogoLink();
		this.findMyOffersPanel();
		this.findLoginPanels();
		//this.activateFlashMicrosite();
		//this.findShareLink();
	},
	
	
      //
      // 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() {
	
	   document.observe('mouseover', function(event) {
    			var target = event.findElement('a[rel^=subnav]');
			if (target) {		
				this.mouseover(target);

			}
    		}.bind(this));
    		
	   document.observe('mouseout', function(event) {
    			var target = event.findElement('a[rel^=subnav]');
			if (target) {		
				this.mouseout(target);

			}
    		}.bind(this));
    		
 	   document.observe('click', function(event) {
    			var target = event.findElement('a[rel^=subnav]');
			if (target) {		
				this.mouseover(target);

			}
    		}.bind(this));	
	
	},
	
	findLinks: function() {
	
	$$('a').each(function(s){
		Event.observe(s,'focus',this.removeBlur);
	
	}.bind(this));
	
	},

	findPopups: function() {
	
	var popupItems = $$('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";
                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() {

		if (this.NewWin && (! this.NewWin.closed)) {
    			this.NewWin.close ();
  		} else {
    			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,'popup',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().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':'#','class': navStyle}).update(this.contentCount);
		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");

		}


		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));
			
			$('main-panel-message').setStyle({'display':'block'});
			
		        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() {

		var questions = $$('.section .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.id != this.activeQuestion && this.activeQuestion) {
		
		$(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 {
	
			element.setStyle({'fontWeight':'bold'});
			element.next().show();
			element.addClassName('question-over');
			element.removeClassName('question');
		
		}
		
		this.activeQuestion = element.id;
	
	},

	
	mouseover: function(target) {
	
		window.clearTimeout(this.timeout);
	
		subnavId = target.rel;
		
		if (subnavId == this.activeNavigation) {
		
		return false;
		
		} else {
	
		this.checkActiveNavigation(subnavId);
		$(subnavId).show();
		
		Event.observe(subnavId,'mouseover',this.subnavMouseover.bind(this));
		Event.observe(subnavId,'mouseout',this.subnavMouseout.bind(this));

		this.activeNavigation = target.rel;
		
		}

	},
	
	mouseout: function(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() {
	
		this.deleteCookie("micrositeIframe");

		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"

		}
		
		return result
	
	
	},


	loadFlashMicrosite: function(value) {

		if (value == "yes") {


			this.initializeMicrosite()


		} else {

			return false

		}

	},
	
	initializeMicrosite: function() {
							
	if ($('page-body-flash-panel-microsite')) {
	
		var bodyElmt = $$('body')[0];
		var micrositeIFrame = new Element('iframe', { 'src':'iframe.jsp?flash=notLoaded','id':'dummyFrame'}).setStyle({'top':'-1000px','left':'-1000px','position':'absolute'});
		new Element.insert(bodyElmt, {bottom:micrositeIFrame});
	
		flashId = $('page-body-flash-panel-microsite')
		flashId.absolutize();
		flashId.setStyle({'zIndex':'100','top':'163px','left':'726px'})
		
		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");
	
		}
	
	},
	
	swapMicrosite: function() {
	
	alert("SWAPPAGE!!")
	
	var bodyElmt = $$('body')[0];	
	var micrositeDiv = new Element('div', { 'id':'page-body-flash-panel-microsite-full'});
	new Element.insert(bodyElmt, {bottom:micrositeDiv});
	$("dummyFrame").src="iframe.jsp?flash=loaded"
	
				
	if ($('page-body-flash-panel-microsite-full')) {
	
		
		flashId = $('page-body-flash-panel-microsite-full')
		flashId.absolutize();
		flashId.setStyle({'zIndex':'400','display':'none','paddingTop':'20px'})
		
		var flashteaser = new SWFObject("/virgin/Images/UnderTheSkin_flash_v14_rob_tcm23-3736.swf?flash=true", "full", "1000", "700", "8", "");
		flashteaser.addParam("wmode", "transparent");
		flashteaser.addParam("allowScriptAccess","always")
		flashteaser.write("page-body-flash-panel-microsite-full");
	
		}
		
		this.showMicrosite();
	
	},
	
	showMicrosite: function() {
	
		new Effect.Fade('site-width');
		new Effect.Appear('page-body-flash-panel-microsite-full');
	
	},

	hideMicrosite: function() {

		this.deleteCookie("micrositeIframe");
		$("dummyFrame").src="iframe.jsp?flash=notLoaded"
		new Effect.Appear('site-width');
		new Effect.Fade('page-body-flash-panel-microsite-full');
	
	},

	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($('share-link')) {


			shareLink = $('share-link');
			this.activateShareLink(shareLink)
			this.writeShareElement();

		}


	},


	activateShareLink: function(element) {

		Event.observe(element,'mouseover', this.shareMouseOver.bindAsEventListener(this));
		Event.observe(element,'mouseout', this.shareMouseOut.bindAsEventListener(this));

	},

	shareMouseOver: function() {


		window.clearTimeout(this.shareTimeout)

		$("share-popup").show();

		Event.observe("share-popup",'mouseover',this.sharePopupMouseOver.bind(this));
		Event.observe("share-popup",'mouseout',this.sharePopupMouseOut.bind(this));


	},

	shareMouseOut: function() {

		window.clearTimeout(this.shareTimeout)
		this.shareTimeout = setTimeout(function() { $("share-popup").hide(); }, 1000 )

	},

	writeShareElement: function() {

		var pageUrl   = document.location;
		var pageTitle = document.title;

		buttonPos = $("shareButton").positionedOffset();
		popPosTop = buttonPos[1] + 16
		popPosLeft = buttonPos[0] - 200 + $("shareButton").getWidth()

		var bodyElmt = $$('body')[0];

	   // Determine which browser we're in //

		var IE = document.all ? true : false;

		if (IE) {
		  bookmarkLink = "<a title='Add this page to your favourites' href='javascript:window.external.AddFavorite(\""+pageUrl+"\", \""+pageTitle+"\")'><img src='images/favourites.gif'>&nbsp;Favourites</a>";
		}else{
		  bookmarkLink = "<a title='Add this page to your bookmarks' href='javascript:window.sidebar.addPanel(\""+pageTitle+"\", \""+pageUrl+"\",\"\")'><img src='images/favourites.gif'>&nbsp;Bookmark</a>";
		}

	   // Create the content for the popup //

		sharePopupContent  = "<div class='shareColumn'><div>";
		sharePopupContent += "<a title='Post this page to Facebook' href='http://www.facebook.com/sharer.php?u="+pageUrl+"' target='_blank'><img src='images/facebook.gif'>&nbsp;Facebook</a><br />";
		sharePopupContent += "<a title='Post this page to Del.icio.us' href='http://del.icio.us/post?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/delicious.gif'>&nbsp;Delicious</a><br />";
		sharePopupContent += "<a title='Post this page to Digg' href='http://digg.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/digg.gif'>&nbsp;Digg</a>";
		sharePopupContent += "</div></div><div class='shareColumn'><div>";
		sharePopupContent += "<a title='Post this page to Reddit' href='http://reddit.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/reddit.gif'>&nbsp;Reddit</a><br />";
		sharePopupContent += "<a title='Post this page to Stumbleupon' href='http://www.stumbleupon.com/submit?url="+pageUrl+"&title="+pageTitle+"' target='_blank'><img src='images/stumbleupon.gif'>&nbsp;StumbleUpon</a><br />";
		sharePopupContent += bookmarkLink+"</div></div>";


		var sharePopupContainerElmt = new Element('div', { 'id':'popup-message'}).update(sharePopupContent);
		var sharePopupElmt = new Element('div', { 'id':'share-popup'}).update(sharePopupContainerElmt).hide();
		sharePopupElmt.setStyle({'position':'absolute','top':popPosTop+'px','left':popPosLeft+'px'});

		new Element.insert(bodyElmt, {bottom:sharePopupElmt});

	},



	sharePopupMouseOver: function() {

		window.clearTimeout(this.shareTimeout);

	},


	sharePopupMouseOut: function() {

		window.clearTimeout(this.shareTimeout)
		this.shareTimeout = setTimeout(function() { $("share-popup").hide(); }, 1000 )


	},

	findMyOffersPanel: function() {

		if ($("my-offers-main-panel")) {

			activeOfferNavigation = "";
			this.dealCount = 0;
			this.navCount = 0;
			this.dealId = "deal";

			this.panelHeightModifier = 20;
			this.panelHeight = $('my-offers-container').getHeight() - 20;

			selectedDeal = "";
			selectedPanel = "panel-0";

			this.activateOfferNavigation("deal-nav-0")

			this.findDeepLinks();

			this.findDealLayers();

			this.initializePanel();
		}

	},

	findDeepLinks: function() {

		var deeplinkItems = $$('a[rel^=deeplink]');

		deeplinkItems.each(function(s) {

			this.activateDeeplink(s);

		}.bind(this));



	},

	activateDeeplink: function(element) {

	deeplinkId = this.extractPopupAttributes(element);
	element.writeAttribute("onclick", "return false");
	Event.observe(element,'click', function(event){Event.stop(event);});
	Event.observe(element,'click', this.findSpecificDeal.bindAsEventListener(this, deeplinkId));

	},

	extractDeeplinkId: function(id) {

			popupStr = element.rel;
			popupStrSpl = popupStr.split("[");
			popupStrSpl = popupStrSpl[1].split("]");

			return popupStrSpl;

	},

	findDealLayers: function() {


		var dealLayers = $$('.deal-detail', '.deal-panel');

		dealLayers.each(function(s) {


			this.hideLayers(s);

		}.bind(this));


	},

	setDealNavigationHeight: function() {

		var dealDetails = $$('.deal-detail');

		dealDetails.each(function(s) {


			if(s.getDimensions().height < this.panelHeight) {

				dealNavigationAdjustment = this.panelHeight - s.getHeight();

				this.adjustDealNavigation(s.down(".deal-navigation"),dealNavigationAdjustment);

			}

		}.bind(this));



	},

	adjustDealNavigation: function(element,adjustment) {

		element.setStyle({'paddingTop':adjustment-15+'px'});

	},

	hideLayers: function(element) {

		element.setStyle({'visibility':'visible'}); // To remove this style already preset in CT
		element.hide();

	},


	previousDealDetail: function(e, previousDealElement) {

	$(selectedDeal).hide();
	$(previousDealElement).show()
	selectedDeal = previousDealElement

	},


	nextDealDetail: function(e, nextDealElement) {

	$(selectedDeal).hide();
	$(nextDealElement).show()
	selectedDeal = nextDealElement


	},



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

	clickDealNav: function(e,element,navElement) {

			if(selectedDeal!="") { $(selectedDeal).hide()}

			$(selectedPanel).hide()
			$(element).show()

			selectedPanel = element;
			vbNavigation.prototype.showSummaryInPanel(selectedPanel);
			vbNavigation.prototype.activateOfferNavigation(navElement)

	},

	showSummaryInPanel: function(selectedPanel) {

			var dealItem = $$('#'+ selectedPanel +' .deal .deal-summary');
			dealItem.each(function(s) {

				s.show();

			}.bind(this));


	},

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



	callDealWebtrendCall: function(element) {

	webtrendInfo = this.getAllWebtrendInfo(element)
	eval(webtrendInfo)

	},

	clickDealDetail:function(e, detailElement ) {

		if(selectedDeal !="") {

			$(selectedDeal).hide();

		}

		selectedDeal = detailElement
		$(detailElement).show();
		vbNavigation.prototype.hideSummaryInPanel(selectedPanel);


	},

	hideSummaryInPanel: function(selectedPanel) {

			var dealItem = $$('#'+ selectedPanel +' .deal .deal-summary');

			dealItem.each(function(s) {

				s.hide();

			}.bind(this));


	},

	//End of third function call
	/////////////////////////////
	/////////////////////////////

	initializePanel: function() {

		this.checkDealParameter()
		this.setDealHeight();


		$('panel-loader').hide()
		$('panel-0').show()

	},


	checkDealParameter: function() {

		if (this.getUrlParameter("deal")) {

			this.findSpecificDeal('click',this.getUrlParameter("deal"))

		}

	},

	setDealHeight: function(element) {

		var dealDetails = $$('.deal-panel', '.deal-home-panel');

		dealDetails.each(function(s) {

				s.setStyle({'height':this.panelHeight+'px'})

		}.bind(this));



	},

	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;


	},


	findSpecificDeal: function(event, dealId) {

		dealIdStr = dealId.toString();

		selectedDealPanel = $(dealIdStr).up(2).id;

		$(selectedPanel).hide()
		$(selectedDealPanel).show()

		selectedPanel = selectedDealPanel

		this.hideSummaryInPanel(selectedPanel);

		dealNav = this.getDealNav($(dealIdStr));
		dealLink = this.getDealLink($(dealIdStr));

		specificOfferNavigation = $$('a[rel="'+ dealNav +'"]')[0].id
		this.activateOfferNavigation(specificOfferNavigation)


	},

	getDealNav: function(element) {

		return element.up(2).id;

	},

	getDealLink: function(element) {

		return element.previous().down().next().down().onclick()

	},

	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];

		}

	},
	
	
	//End of My Offers methods
	/////////////////////////////
	/////////////////////////////	
	
	findLoginPanels: function() {
	
		if($('credit-card-login')) {
		
			this.validateCreditCardLoginPanel();
		
		}
		
		if($('prepaid-credit-card-login')) {
		
			this.validatePrepaidCreditCardLoginPanel();
		
		}
	
	
	},
	
	validateCreditCardLoginPanel: function() {
	
		loginPanel = $('credit-card-login');
		
		Event.observe(loginPanel,'submit',function(event) {
		
			passwordError = false;
			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($F(loginPanel['password']).length == 0){

				this.showValidationError('error-password','Please enter your password')
				passwordError = true;
				Event.stop(event)
			} 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-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')
				
				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','800','450',{'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');

				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();
	
	},
	
	test: function() {
	
	alert("Hello");
	
	}
	
}