var activeColor = '#b84f3b';
var inactiveColor = '#FFF';
var stfWrapper;
var stfDiv;
var linkDiv;
var leftNav;
/**
 * Define a MooTools extension to allow us to extract
 * the hostname from the given URL string
 * @see http://beardscratchers.com/journal/using-javascript-to-get-the-hostname-of-a-url
 **/
String.implement({
  getHostname : function()
  {
    var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
    return this.match(re) ? this.match(re)[1] : false;
  }
});

/**
 * Hide's the border on the current active nav item's previous siblings
 * by comparing the Body's ID attribute with the classes of the nav items
 **/
var cleanSiblings = function ()
{
  if($('header').getElement('ul li.active'))
  {
    $('header').getElement('ul li.active').getPrevious().firstChild.style.borderRight = 'none';
    $('header').getElement('ul li.active').style.position = 'relative';
    $('header').getElement('ul li.active').style.left = '1px';
  }
  if(
    (
      document.getElement('body').id == 'location'
      || document.getElement('body').id == 'getting-here'
    )
    && document.getElement('body').hasClass('en'))
  {
    $('header').getElement('ul li.location').getPrevious().firstChild.style.borderRight = 'none';
    $('header').getElement('ul li.location').style.position = 'relative';
    $('header').getElement('ul li.location').style.left = '1px';
  }

  if(document.getElement('body').id == 'history-architecture')
  {
    $('header').getElement('ul li.history-architecture').getPrevious().firstChild.style.borderRight = 'none';
    $('header').getElement('ul li.history-architecture').style.position = 'relative';
    $('header').getElement('ul li.history-architecture').style.left = '1px';
  }
};

/**
 * Attaches listeners to the level2 nav items so they expand if they have children
 * or do whatever the href says if they don't
 **/
var initNav = function ()
{
  $$('#leftNav li.level2 ul').each(
    function (level3)
    {
      level3.style.display = 'none';
      }
  );

  langSel = document.getElement('form#languageSelector select');

  if(document.getElement('body').id != 'home')
  {
    $$('li.level2 > a').each(
      function (linky)
      {
        if(linky.getParent().hasClass('selected'))
        {
          toggleUl(linky.getNext());
        }

        linky.addEvent('click',
          function (ev)
          {
            ul = ev.target.getNext();
            if(ul)
            {
              ev.preventDefault();
              toggleUl(ul);
            }
          }
        );
      }
    );
            }
};

/**
 * Toggles visibility of the passed ul element
 **/
var toggleUl = function (ul)
{
  $$('#leftNav li ul').each(
    function (others)
    {
      deactivateUl(others);
    }
  );
  if(ul && ul.style.display == 'none')
    activateUl(ul);
  else
    deactivateUl(ul);
};

/**
 * Activate the given ul. Used by toggleUl()
 **/
var activateUl = function (ul)
{
  if(ul && document.getElement('body').id !== 'home')
  {
    deactivateAll();
    ul.parentNode.getElement('a').addClass('selected');
    ul.reveal();
  }
};

/**
 * Deactivate the given ul. Used by toggleUl()
 **/
var deactivateUl = function (ul)
{
  if(ul && document.getElement('body').id !== 'home')
  {
    ul.getParent().getElement('a').className = '';
    if(ul.getStyle('display') !== 'none')
    {
      ul.dissolve();
    }
  }
};

/**
 * does the above by for all ULs
 **/
var deactivateAll = function ()
{
  $$('#leftNav li.level2 > a').each(
    function (a)
    {
      a.className = '';
      a.parentNode.className = '';
    }
  );
};

/**
 * Attach an onChange listener to the language selector so it submits the form
 **/
var initLanguageListener = function ()
{
  languageList = new Element('ul', {'id': 'languageSelectorReplacement'});
  masterLang = new Element('li');
  $$('option').each(
  function (opTag)
  {
      a = new Element('a',
       {
         'class':      opTag.get('class'),
         'html':       opTag.get('html'),
         'lang':       opTag.get('lang'),
         'xml:lang':     opTag.get('xml:lang'),
         'href':       '/'+opTag.get('lang')+'/location'
       }
      );

      lang = masterLang.clone();
      lang.set('class',opTag.get('class'));
      lang.grab(a);
      languageList.grab(lang,opTag.get('selected') ? 'top' : 'bottom');
  }
  );
  $('languageSelector').dispose();
  $('container').grab(languageList,'bottom');
  languageList.addEvent('mouseenter',
  function ()
  {
    languageList.set('class','active');
  }
  );
  languageList.addEvent('mouseleave',
  function ()
  {
    languageList.set('class',null);
  }
  );
};

/**
 * Attaches the Print Page function to the Print Page link
 **/
var initPrintPage = function ()
{
  //<li class="first print"><a href="#">Print this page</a></li>
  li = new Element('li', {'class': 'first print'});
  a = new Element('a', {'html': 'Print This Page', 'href': '#'});
  li.grab(a,'top');
  a.addEvent('click',
    function (ev)
    {
      ev.preventDefault();
      window.print();
    }
  );
  $('page-options').grab(li,'top');
};

var initBackToTop = function ()
{
   checkBackToTopVisibility();
   link = $('backToTop').getElement('a');
   link.addEvent('click',
    function (ev)
    {
      ev.preventDefault();
      new Fx.Scroll(window).toTop();
    }
   );
   // Just in case the user resizes the browser window while the overlay's there,
   // reposition it from the wrapper's new position in the window
   window.addEvent('resize',
     function ()
     {
       checkBackToTopVisibility();
     }
   );
};

var checkBackToTopVisibility = function ()
{
  link = $('backToTop').getElement('a');
  if($('container').getSize().y <= window.getSize().y)
  {
    link.fade('hide');
  }
  else
  {
    link.fade('show');
  }
};

/**
 * Creates two divs and sticks them before the closing DIV, attaches the event to the button
 * and performs an XHR when the button's clicked, thus populating the divs
 **/
// var initSendToFriend = function ()
// {
//   // Create the divs
//   stfWrapper = new Element('div', { id: 'stf-wrapper' });
//   oBody = window.document.body;
//   oBody.grab(stfWrapper,'bottom');
//
//   stfDiv = new Element('div', { id: 'stf' });
//   oBody.grab(stfDiv,'bottom');
//
//   // Get the link and attach the event
//   stfLink = document.getElement('ul#page-options li.send-to-friend a');
//   stfLink.addEvent('click',
//     function (ev)
//     {
//       ev.preventDefault();
//       req = new Request.HTML(
//         {
//           update:     stfDiv,
//           evalScripts:  true
//         }
//       ).get('/ajax-send-to-a-friend?url='+window.location);
//       drawStfLightbox();
//
//       stfWrapper.addEvent('click',
//         function ()
//         {
//           killStfLightBox();
//         }
//       );
//
//     }
//   );
// };

/**
 * Hide the lightbox by changing id of it and its parent to one
 * styled so it's invisible, get rid of its content and set the height back to 0
 **/
var killStfLightbox = function ()
{
  killOverlay();
  stfDiv.set('id','stf');
  stfDiv.set('html','');
};

var killOverlay = function ()
{
  stfWrapper.set('id','stf-wrapper');
  stfWrapper.setStyle('height',0);
};

/**
 * Sets the Send To A Friend overlay as visible by changing it's ID to one that's style appropriately
 **/
var drawStfLightbox = function ()
{
  drawOverlay();
  new Fx.Scroll(window).toTop();
  stfDiv.fade('hide');
  stfDiv.set('id','stf-active');
  stfDiv.fade('show');

  // When you clikc the div, we should get rid of the overlay
  stfWrapper.addEvent('click',
    function (ev)
    {
      killStfLightbox();
    }
  );
};

var drawOverlay = function ()
{
  stfWrapper.fade('hide');

  // Use the height of the viewport if it's taller than the page for the overlay
  if($('container').getSize().y > document.getElement('body').getSize().y)
  {
    height = $('container').getSize().y;
  }
  else
  {
    height = document.getElement('body').getSize().y;
  }

  stfWrapper.setStyle('height',height);
  stfWrapper.set('id','stf-wrapper-active');
  stfWrapper.set('opacity',0.5);
};

Element.implement({
  externalLink: function ()
  {
    if(
      $defined(this.get('href'))
      && this.get('href').getHostname()
      && this.get('href').getHostname() !== document.domain
    ){
      this.addEvent('click',
        function (ev)
        {
          if(Cookie.read('links') == 'new')
          {
            this.set('target','_blank');
          }
          else if(Cookie.read('links') == 'same')
          {
            return;
          }
          else
          {
            ev.preventDefault();
            triggerLinkLightbox(this);
          }
        }
      );
    }
  }
});

var initExternalLinks = function ()
{
  oBody = window.document.body;
  linkDiv = new Element('div', {id: 'external-link'});
  oBody.grab(linkDiv,'bottom');

  $$('a').each(
    function (l)
    {
      l.externalLink();
    }
  );
};


var triggerLinkLightbox = function (link)
{
  drawOverlay();
  linkDiv.fade('hide');

  linkDiv.grab(new Element('p', {'html': 'You\'re about to leave the Covent Garden London website and launch:'}));
  linkDiv.grab(new Element('p',
    {
      'html':   '<strong>' + link.get('href') + '</strong>',
      'styles':
      {
        'text-align':   'center'
      }
    }
  ));
   linkDiv.grab(new Element('p', {'html': 'Please choose whether you\'d like to launch the new website in this window or a new one:'}));

  p = new Element('p',
    {
      'styles':
      {
        'text-align':   'center'
      }
    }
  );

  sameWindow = new Element('a',
    {
      'html':     'Use this window',
      'href':     link.get('href'),
      'class':    'button'
    }
  );

  sameWindow.addEvent('click',
    function ()
    {
      Cookie.write('links','same',
        {
          'domain':   document.domain,
          'path':   '/'
        }
      );
      killLinkLightbox();
    }
  );

  newWindow = new Element('a',
    {
      'html':     'Open a new window',
      'href':     link.get('href'),
      'target':    '_blank',
      'class':    'button'
    }
  );

  newWindow.addEvent('click',
    function ()
    {
      Cookie.write('links','new',
        {
          'domain':   document.domain,
          'path':   '/'
        }
      );
      killLinkLightbox();
    }
  );

  p.grab(sameWindow);
  p.appendText(' ');

  p.grab(newWindow);

  linkDiv.grab(p);

  linkDiv.set('id','external-link-active');
  linkDiv.fade('show');
  linkDiv.setStyle('top',window.getScroll().y + (window.getSize().y/2) - 100);

  stfWrapper.addEvent('click',
    function ()
    {
      killLinkLightbox();
    }
  );

};

var killLinkLightbox = function ()
{
  killOverlay();
  linkDiv.set('id','external-link');
  linkDiv.set('html','');
};

var compLinkTracking = function ()
{
    $$('a.20-off-voucher').addEvent('click', function(event){
        pageTracker._trackEvent('Downloads', 'PDF', '/uploads/covent-garden-20-off-shopping-voucher.pdf');
    });
};

window.addEvent('domready',
  function()
  {
    cleanSiblings();
    leftNav = new LeftNav();
    initLanguageListener();
    //initSendToFriend();
    initPrintPage();
    initBackToTop();
    compLinkTracking();
//    initExternalLinks();
  }
);

var k = 0;
var l = 0;

document.addEvent('keyup', function (ev)
{
  if(
  (ev.key == 'up' && k == 0)
  || (ev.key == 'up' && k == 1 && l == 'up')
  || (ev.key == 'down' && k == 2 && l == 'up')
  || (ev.key == 'down' && k == 3 && l == 'down')
  || (ev.key == 'left' && k == 4 && l == 'down')
  || (ev.key == 'right' && k == 5 && l == 'left')
  || (ev.key == 'left' && k == 6 && l == 'right')
  || (ev.key == 'right' && k == 7 && l == 'left')
  || (ev.key == 'b' && k == 8 && l == 'right')
  || (ev.key == 'a' && k == 9 && l == 'b')
  || (ev.key == 'enter' && k == 10 && l == 'a')
  ){
  k++;
  l = ev.key;
  }
  else
  {
  l = 0;
  k = 0;
  }
  if(k == 10)
  {
  document.getElement('body').setStyles({
    'background-image':   'url(/images/hamster.gif)',
    'background-color':   '#FFF'
  });
  }

});

var LeftNav = new Class({
  Implements: [Options, Events],
  options: {
    id: 'leftNav'
  },
  initialize: function(options) {
    this.setOptions(options);
    this.nav = $(this.options.id);

    this.accordions = [];

    this.setUpMenu();

    $$('#' + this.options.id + ' li ul li.selected > div > a').each(function(obj) {
      obj.setStyle('color', '#b84f3b');
    });

  },
  fixLink: function(obj) {
    obj.getParent().set('text', obj.dispose().get('text'));
  },
  disableDefaultEventOnClick: function(obj) {
    obj.addEvent('click', function(ev) {
      ev.preventDefault();
    });
  },
  improveStructure: function() {
    $$('.leftnav_toggler a').each(function(obj) {
      this.fixLink(obj);
    }, this);
  },
  setUpAccordion: function(ul) {
    var lvl = parseInt(ul.get('lvl'),10);
    var togglers_selector = 'li > div.level' + (lvl +1);
    var elements_selector = 'li > ul.level' + (lvl +1);

    // ugly
    if (ul.getPrevious('div').getFirst('a.newFeatures')) {
      ul.getPrevious('div').getFirst('a.newFeatures').addEvent('click', function() {
        ul.getPrevious('div').getNext('ul').setStyle('display','none');
      });
    } else {
      this.disableDefaultEventOnClick(ul.getPrevious('div').getFirst('a'));
    }

    var elements = ul.getElements(elements_selector);

    var togglers = new Array();
    ul.getElements(togglers_selector).each(function(obj) {
      if(obj.getParent().getChildren('ul').length != 0) {
        togglers.push(obj);
      }
    });

    if(togglers.length > 0 && elements.length > 0 && togglers.length == elements.length) {
      this.accordions.push(new Fx.Accordion(togglers, elements, {
          opacity: true,
          display: this.getOpenedIndex(togglers)
      }));
    }

  },
  getOpenedIndex: function(togglers) {
    var retVal = -1;
    togglers.each(function(obj, index) {
      if(obj.getParent().hasClass('selected')) {
        retVal = index;
//        obj.addClass('lnav_selected');
        
      }
    });
    return retVal;
  },
  rollOverToggable: function() {
    this.fireEvent('rollOverToggable');
  },
  activateUl: function(obj) {
    this.setUpAccordion(obj);    
    obj.getChildren('li').each(function(li) {
      li.getChildren('ul').each(function(obj) {
        //this.activateUl(obj);
      }, this);
    }, this);
  },
  
  setUpMenu: function() {
    
    this.nav.getElements('li.level2').each(function(level2) {
      level2.getChildren('ul').each(function(obj) {
        this.activateUl(obj);
      }, this);
    }, this);

    var elements_selector = 'li.level2 > ul.level2';
    var elements = $$(elements_selector);

    var togglers_selector = 'li.level2 > div.level2';

    var togglers = new Array();
    $$(togglers_selector).each(function(obj) {
      // alert(obj.getParent().getChildren('ul').length);
      // alert(obj.getParent().getChildren('ul').length);
      if(obj.getParent().getChildren('ul').length != 0) {
        togglers.push(obj);
        // alert(obj.get('text'));
      }
    });

    if(togglers.length > 0 && elements.length > 0 && togglers.length == elements.length ) {
      this.accordions.push(new Fx.Accordion(togglers, elements, {
          opacity: true,
          display: this.getOpenedIndex(togglers)
      }));
    }

  }
});
