// -----------------------------------------------------------------------------------
//
// 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()

*/

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

document.observe = document.addEvent;

var vlmNavigation = new Class({


//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),
         subnavMouseover: this.subnavMouseover.bind(this),
         subnavMouseout: this.subnavMouseout.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 (Browser.Engine.trident && Browser.Engine.version <= 4) {

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

            $('page-body-panel-content').removeClass('page-body-panel-content-default');
            $('page-body-panel-content').addClass('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.addEvent('mouseover', (function(event) {
        var target = $(event.target).getFirstAncestor('a[rel^=subnav]');
         if (target) {
 
              this.navTimeout = setTimeout(function() {
 
               this.mouseover(target);
 
                 }.bind(this), 200);
 
 
         }
        }).bind(this));
 
      document.addEvent('mouseout', (function(event) {
           var target = $(event.target).getFirstAncestor('a[rel^=subnav]');
         if (target) {
 
           this.mouseout(target);
 
         }
        }).bind(this));
 
      document.addEvent('click', (function(event) {
           var target = $(event.target).getFirstAncestor('a[rel^=subnav]');
         if (target) {
           this.mouseover(target);
 
         }
        }).bind(this));
 
     document.addEvent('mouseover', (function(event) {
           var target = $(event.target).getFirstAncestor('a[rel^=extra]');
         if (target) {
           this.extraMouseover(target);
 
         }
        }).bind(this));
 
        document.addEvent('mouseout', (function(event) {
              var target = $(event.target).getFirstAncestor('a[rel^=extra]');
           if (target) {
              this.extraMouseout(target);
 
           }
        }).bind(this));
 
 
   },

   findLinks: function() {

   $$('a').each(function(s){
      s.addEvent('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(/branding/london2011b/'+url+')'});
   },
   
   findLinks: function() {

   $$('a', 'input[type="submit"]').each(function(s){
      s.addEvent('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);

		element.addEvent('mouseover',this.mouseoverCTA.bindAsEventListener(this, element));
		element.addEvent('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)

	 s.addEvent('click', this.showHelp.bindAsEventListener(this, s.id,s.rel));
	 //s.addEvent('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).getPosition();
         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.x + 30 +'px',
           top: (helpPos.y- (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).getPosition($(s).getOffsetParent());
         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) {

                  s.addEvent('click', function() {

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

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

                        }
                  });

             }.bind(this))
   },
   
   arrangeSubnav: function(id,pos) {
    if (!$(id)) return;
    
   	globalNavWidth = $('page-body-global-nav').getWidth();
   	globalNavPos = $('page-body-global-nav').getPosition().x
   	
   	navWidth = $(id).getWidth();
   	
      	xPos = pos.x - 8;
     	yPos = pos.y;
     	navId = $(id);
   	xRightPos = xPos + navWidth
   	   	
   	if (xRightPos > globalNavWidth) {
   	
   	xPos = globalNavWidth - navWidth

   	}

      	navId.setStyles({'backgroundRepeat':'repeat-x','backgroundImage':'url(/branding/london2011b/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.target.getElement('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});
      navList.addEvent('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});
         next.addEvent('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});
         prev.addEvent('click',this.showContentSection.bindAsEventListener(this, this.activeContent-1));

      }



   },



   showContentSection: function(e, section) {

      if(section != this.activeContent) {
         $('section'+this.activeContent).style.display = 'none';
         $('nav-section'+this.activeContent).removeClassName('content-nav-selected')
         $('nav-section'+this.activeContent).addClassName('content-nav')
         $('section'+section).style.display = '';
         $('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').style.display = 'none';;
			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).style.display = 'none';

         }
         $('section-list-nav').addClassName('section-nav-list-bg')
         $(section).style.display = '';
         $(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()
      summaryLink.addEvent('mouseover',this.actionContentSummary.bindAsEventListener(this,summaryDesc));
      summaryLink.addEvent('mouseout',this.timeoutContentSummary.bindAsEventListener(this,summaryDesc));

   },


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

         $(this.activeContent).style.display = 'none';

      }

      $(desc.id).style.display = '';;
      this.activeContent = desc.id;
   },
   
   timeoutContentSummary: function() {
   
   window.clearTimeout(this.summaryTimeout);
   this.summaryTimeout = setTimeout(function() {
           $(this.activeContent).style.display = 'none';
      }.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) {

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


   },


   actionQA: function(e, element, style) {


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

      $(this.activeQuestion).next().style.display = 'none';;
      $(this.activeQuestion).className = style

      }

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

         element.next().style.display = 'none';
         element.className = style

      } else {

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

      }

      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').style.display = 'none';
    	}
    	
    	if (subnavId) {
	      	$(subnavId).style.display = '';
	      
			$(subnavId).addEvent('mouseover',this.events.subnavMouseover);
			$(subnavId).addEvent('mouseout',this.events.subnavMouseout);
			
			this.activeNavigation = target.rel;
		} else {
			this.activeNavigation = "";
		}
		
 
		
	}
   
   },

   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).style.display = 'none';

         if ($('ticker')) {

            $('ticker').style.display = '';;

         }

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

            $('nav-section-list-form').style.display = '';

         }

         //new Effect.Fade(this.activeNavigation, { duration: this.animateSpeed })
         $(current).removeEvent('mouseover',this.events.subnavMouseover);
         $(current).removeEvent('mouseout',this.events.subnavMouseout);
      }

   },

   activateFooter: function() {




   },
   
	preloadImage: function(imgUrl) {

		imageNumber = "imgpl"+this.imgNum

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

		this.imgNum++;


	}

});
