// -----------------------------------------------------------------------------------
//
// Virgin London Marathon Navigation
// by Jim Starling
//
//
//
// -----------------------------------------------------------------------------------
/*

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

    Navigation Class Declaration
    - initialize()
    - addObservers()
    - findlinks()
    - setBg()
    - findsubnav()
    - enhanceSubnav()
    - arrangeSubnav()
    - enhanceContent()
    - hideContent()
    - idContent()
    - writeContentNav()
    - writeContentArrows()
    - showContentSection()
    - processQAs()
    - hideQAs()
    - idQAs()
    - activateQAs()
    - actionQA()
    - mouseover()
    - mouseout()
    - subnavMouseover()
    - subnavMouseout()
    - checkActiveNavigation()
    - extraMouseover()
    - activateFooter()

    Function Calls
    - document.observe()
    - Event.observe()

*/

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

var vlmNavigation = Class.create();

vlmNavigation.prototype = {


   // initialize()
      // Constructor runs on completion of the DOM loading. Calls updateNavList
      //

      initialize: function(bg) {
         this.bg = bg;
         this.activeHelp = "";
         this.pagePanel = $('page-body');
         this.bodyPanel = $('page-body-panel');
   	   this.bodyFlashPanel = $('page-body-flash-panel');
    	  this.mainContentPanel = $('main-content-panel');
         this.navHeight = 40;
         this.contentCount = 0;
         this.activeContent = 0;
         this.contentArrowHeight = 240;
         this.activeQuestion = null;
         this.questionCount = 0;
         this.subnavCount = 0;
         this.transition = 0;
         this.totalContent = 0;
         this.timeout = null;
         this.helpTimeout = null;
         this.helpTime = 1000;
         this.animateSpeed = 0.1,
         this.subnavTime = 500,
         this.footerMoving = false;
         this.footerTimeout = null;
         this.footerTime = 1000,
         this.wrapper = $('global-nav-list');
         this.activeNavigation = "";
         this.activeHelp = "";
         this.events = {
         mouseover: this.mouseover.bind(this),
         mouseout: this.mouseout.bind(this),
         showContentSection: this.showContentSection.bind(this)
         };


     	 this.initTimeout = setTimeout(function() {


         this.browserQuirks();
         this.addObservers(); // Definately needed!
         this.findSubnav();
         this.findHelp();
         this.enhanceSubnav();
         this.processQAs();
         this.enhanceContent();
         this.enhanceContentList();
         this.enhanceContentSummary();
         this.activateFooter();
	 this.findCTARollovers();
         this.findLinks();
     	 this.setBg()
      }.bind(this), 0);





   },

      //
      // browserQuirks()
      // REQUIRES BROWSER.JS FILE
      // Sorts out quirks we have encountered along the way
      //

   browserQuirks: function() {

      // Toggles height of min-height for '#page-body-panel-content' for IE or Firefox

      if (BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 6) {

         if($('page-body-panel-content')) {

            $('page-body-panel-content').removeClassName('page-body-panel-content-default')
            $('page-body-panel-content').addClassName('page-body-panel-content-ie')

         }     
         
         
         if ($('main-panel-content-errors')) {
         
            $('main-panel-content-errors').setStyle({'backgroundColor':'#CC0000'})
         
         }

      }


      if (BrowserDetect.browser == "Firefox") {


      }


   },

      //
      // 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.navTimeout = setTimeout(function() {
 
               this.mouseover(target);
 
                 }.bind(this), 200);
 
 
         }
        }).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));
 
     document.observe('mouseover', (function(event) {
           var target = event.findElement('a[rel^=extra]')
         if (target) {
           this.extraMouseover(target);
 
         }
        }).bind(this));
 
        document.observe('mouseout', (function(event) {
              var target = event.findElement('a[rel^=extra]')
           if (target) {
              this.extraMouseout(target);
 
           }
        }).bind(this));
 
 
   },

   findLinks: function() {

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

   }.bind(this))

   },

   removeBlur: function() {
      if (this.blur) this.blur();

   },

   setBg: function() {

		if (typeof this.bg == "object") {
			this.setRandomBg(this.bg.image)
		}
   
   },

   setRandomBg: function(array) {

      arrLength = array.length
      random = Math.floor(Math.random()*arrLength);
      this.loadBg(array[random]);
   },

	loadBg: function(url) {
		$('page-body-panel-content') ? bgPanel = $('page-body-panel-content') : bgPanel = $('page-body-panel-homepage');
		bgPanel.setStyle({'backgroundImage':'url(/static/images/'+url+')'});
   },
   
   findLinks: function() {

   $$('a', 'input[type="submit"]').each(function(s){
      Event.observe(s,'focus',this.removeBlur);

   }.bind(this))

   },


	findCTARollovers: function() {

		var ctaItems = $$('a[rev]');
		
		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];

	},

	findHelp: function(target) {

	helpCount = 1;
	help = $$('.help');
	help.each(function(s) {
	 var helpUrl = s.rel
	 s.writeAttribute('href',"#")
	 s.writeAttribute("id", "help"+helpCount)

	 Event.observe(s,'click', this.showHelp.bindAsEventListener(this, s.id,s.rel));
	 //Event.observe(s,'mouseout', this.hideHelp.bindAsEventListener(this, s.id,s.rel));

	 helpCount++;
	}.bind(this))

	bubble = $$('.help-bubble')
	bubble.each(function(s) {

	s.setStyle({'display':'none'})

	}.bind(this))


	},



   showHelp: function(e,id,url) {

      helpBubbleId = $(id +'-bubble')

      if($(helpBubbleId).visible()) {

         new Effect.Fade($(helpBubbleId), { duration: 0.3 });


      } else {
      
      
      	 if (id != this.activeHelp && $(this.activeHelp)) {	 
      	 
      	 new Effect.Fade($(this.activeHelp), { duration: 0.3 });
      	 
      	 }
      
      	 this.activeHelp = id;

         window.clearTimeout(this.timeout);

         helpPos = Event.element(e).cumulativeOffset();
         helpBubbleId = $(id +'-bubble')

         helpHeight = helpBubbleId.getHeight()
         arrowPosition = (helpHeight - 26)/2
         helpBubbleId.down().down().setStyle({'height':helpHeight+'px','backgroundPosition':'0px '+ arrowPosition +'px'})

         helpBubbleId.setStyle({
           display: 'block',
           left: helpPos[0] + 30 +'px',
           top: (helpPos[1] - (helpHeight/2)+8) +'px'

         });

         this.activeHelp = helpBubbleId

      }

   },


   hideHelp: function(e,id,url) {

      helpId = $(this.activeHelp)
      window.clearTimeout(this.helpTimeout);

      this.helpTimeout = setTimeout(function() {

         new Effect.Fade(helpId, { duration: 0.3 });

      }.bind(this), this.helpTime);


   },

   findSubnav: function(target) {

      subnavs = $$('#global-nav-list a[rel]');
      subnavs.each(function(s) {
         var position = $(s).positionedOffset();
         subnavId = s.rel;
         this.arrangeSubnav(subnavId,position)
      }.bind(this))
   },
   
   enhanceFeaturedPanel: function() {

	if($('page-featured-panels')) {

		panelHeight = $('page-featured-panels').getHeight();
		panelPos = $('page-featured-panels').positionedOffset();
		panelBottomPos = panelHeight + panelPos[1]
		mainPanelHeight = $('page-body-panel-homepage').getHeight();
		mainPanelPos = $('page-body-panel-homepage').positionedOffset();
		mainPanelBottomPos = mainPanelHeight + mainPanelPos[1]   

		finalPos = mainPanelBottomPos - panelBottomPos;
		$('page-featured-panels').setStyle({'paddingTop':finalPos+'px'})
	}
   
   },

   enhanceSubnav: function() {

                  var listItems = $$('.subnav-item');
                  listItems.each(function(s) {

                  Event.observe(s,'click', function() {

                        if(!this.down(2).target) {

                              listItemHref = this.down(2).href;
                              document.location.href = listItemHref;

                        }
                  });

             }.bind(this))
   },
   
   arrangeSubnav: function(id,pos) {
   
   	globalNavWidth = $('page-body-global-nav').getWidth();
   	globalNavPos = $('page-body-global-nav').cumulativeOffset()[0]   	
   	navWidth = $(id).getWidth();
   	
      	xPos = pos[0] - 8;
     	yPos = pos[1];
     	navId = $(id);
   	xRightPos = xPos + navWidth
   	   	
   	if (xRightPos > globalNavWidth) {
   	
   	xPos = globalNavWidth - navWidth

   	}

      	navId.setStyle({'backgroundRepeat':'repeat-x','backgroundImage':'url(/static/images/dropdown-top-border.gif)','paddingTop':'1px','position':'absolute','top':yPos+ this.navHeight -5 +'px','left':xPos +'px','display':'none','zIndex':'1500'});

   },


   enhanceContent: function() {

      var contentItems;
      $('main-panel-content') ? contentItems = $$('#main-panel-content .main-panel .section') : contentItems = $$('#main-panel-content-full-width .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()
      }

   },

   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, 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) {

	sectionheaderHeight = 0;

	if ($('section-header')) {
	
	sectionheaderHeight = $('section-header').getHeight();
	
	}

      sectionHeight = $('section'+ section).getHeight() + sectionheaderHeight

      if ($('main-panel-content-full-width')) {

         $('main-panel-content-full-width').setStyle({'height':(sectionHeight)+50+'px'})

      }

      if ($('main-panel-content')) {

         //$('main-panel-content').setStyle({'height':(sectionHeight)+50+'px'})

      }


      $('section-buttons').update("");



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

      }

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

      }



   },



   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 = section
         this.writeContentArrows(section)

      }


   },

   enhanceContentList: function() {

      var contentItems;
      contentItems = $$('#main-panel-content-list .main-panel .section-list');



      if(contentItems.length > 1) {
		 this.prepareContentList()
		 this.activeContent = 0;
		 contentItems.each(function(s) {

		    this.contentCount++
		    this.hideContentList(s)
		    this.idContentList(s)
		    this.extractContentList(s)

		 }.bind(this))

      } else {
      
		 contentItems.each(function(s) {
			
			$('section-list-nav').hide();
			s.setStyle({'display':'block'});

		 }.bind(this))
      
      }

   },

   prepareContentList: function() {

   var navOption = new Element('option', { 'value':'0','id':'nav-section-list-option-0'}).update("Select:")
   var navSelect = new Element('select', { 'id':'nav-section-list'}).update(navOption)
   var navForm = new Element('form', { 'id':'nav-section-list-form'}).update(navSelect)
   var navFormLabel = '<label for="nav-section-list" style="display:none">Select:</label>'
   this.navForm = navForm;
   $('section-list-nav-text').update('Select your guide from the list below:<br/><br/>');   
   new Element.insert(navForm, {bottom:navFormLabel});
   new Element.insert('section-list-nav', {bottom:navForm});
   Event.observe(navSelect,'change',this.actionContentList.bindAsEventListener(this,this.navForm));


   },

   actionContentList: function(e, form) {

   selected = form[0].selectedIndex;
   optionValue = form[0].options[ selected ].value;

      if (selected > 0) {

         this.showContentList(optionValue)

      }

   },

   showContentList: function(section) {

      if(section != this.activeContent) {

         if($(this.activeContent)) {

            $(this.activeContent).hide()

         }
         $('section-list-nav').addClassName('section-nav-list-bg')
         $(section).show()
         $(section).setStyle({'display':'block'})
         this.activeContent = section


      }

   },

   extractContentList: function(element) {

   var navOption = new Element('option', { 'value':element.id}).update($(element.down().down()).innerHTML)
   $('nav-section-list').insert({'bottom':navOption});

   },


   hideContentList: function(element) {

      element.setStyle({'display':'none'})


   },

   idContentList: function(element) {

   element.writeAttribute("id", "section-list"+this.contentCount)
   element.writeAttribute("name", "section-list"+this.contentCount)

   },

   enhanceContentSummary: function() {

         var contentItems;
         contentItems = $$('.main-panel .section-list-summary');



         if(contentItems.length > 1) {
            this.activeContent = 0;
            contentItems.each(function(s) {

               this.contentCount++
               this.styleContentSummary(s)
               this.idContentSummary(s)
               this.prepareContentSummary(s)


            }.bind(this))

         }

      },

   prepareContentSummary: function(element) {

      summaryLink = element.down(2)
      summaryDesc = element.down(1).next()
      Event.observe(summaryLink,'mouseover',this.actionContentSummary.bindAsEventListener(this,summaryDesc));
      Event.observe(summaryLink,'mouseout',this.timeoutContentSummary.bindAsEventListener(this,summaryDesc));

   },


   actionContentSummary: function(e, desc) {
      window.clearTimeout(this.summaryTimeout);
      if ($(this.activeContent)) {

         $(this.activeContent).hide()

      }

      $(desc.id).show();
      this.activeContent = desc.id;
   },
   
   timeoutContentSummary: function() {
   
   window.clearTimeout(this.summaryTimeout);
   this.summaryTimeout = setTimeout(function() {
           $(this.activeContent).hide()
      }.bind(this), this.subnavTime);
   	
   
   },


   styleContentSummary: function(element) {


      summaryDesc = element.down().down().next();

      summaryDesc.setStyle({'display':'none'})


   },

   idContentSummary: function(element) {

      element.writeAttribute("id", "section-summary"+this.contentCount)
      element.down().down().next().writeAttribute("id", "section-dummary-description"+this.contentCount)

   },

   processQAs: function() {

	var questions = new Array();
 
     if ($$('.main-panel .section .question-right').length > 0) {

      	questions = $$('.main-panel .section .question-right');
      	style = "question-right";
      
     } else if ($$('.main-panel .section .question').length > 0) {

      	questions = $$('.main-panel .section .question');
      	style = "question";
      
      
     }

      if(questions.length > 0) {

         questions.each(function(s) {

            this.questionCount++
            this.hideQAs(s)
            this.idQAs(s)
            this.activateQAs(s, style)

         }.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, style) {

      Event.observe(element,'click',this.actionQA.bindAsEventListener(this, element, style));


   },


   actionQA: function(e, element, style) {


      if (element.id != this.activeQuestion && this.activeQuestion) {

      $(this.activeQuestion).next().hide();
      $(this.activeQuestion).className = style

      }

      if(element.next().visible()) {

         element.next().hide()
         element.className = style

      } else {

         element.className = style + "Expanded"
         element.next().show();

      }

      this.activeQuestion = element.id;

   },


   mouseover: function(target) {
 
     window.clearTimeout(this.navTimeout);
     window.clearTimeout(this.timeout);
 
      subnavId = target.rel;
 
      if (subnavId == this.activeNavigation) {
 
      return false;
 
      } else {
 
     this.checkActiveNavigation(subnavId);
 
 
      if ($('nav-section-list-form')) {
 
        $('nav-section-list-form').hide();
 
      }
 
      $(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.navTimeout);
      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();

         if ($('ticker')) {

            $('ticker').show();

         }

         if ($('nav-section-list-form')) {

            $('nav-section-list-form').show();

         }

         //new Effect.Fade(this.activeNavigation, { duration: this.animateSpeed })
         Event.stopObserving(current,'mouseover',this.subnavMouseover.bind(this));
         Event.stopObserving(current,'mouseout',this.subnavMouseout.bind(this));
      }

   },

   activateFooter: function() {




   },
   
	preloadImage: function(imgUrl) {

		imageNumber = "imgpl"+this.imgNum

		imageNumber = new Image();
		imageNumber.src = imgUrl;

		this.imgNum++;


	}

}
