window.addEvent('domready', function() {
  MainContent.init();
});

// Handles the opening of appropriate Sections and sub-sections
var MainContent = (function(){
  var sectionTogglers, subsectionTogglers, panelTogglers, sectionContainers,
    subsectionContainers, panelContainers, panelAccordion;

  var setupVariables = function(){
    sectionTogglers = $$('.section-toggle');
    subsectionTogglers = $$('.subsection-toggle');
    panelTogglers = $$('.panel-toggle');

    sectionContainers = $$('.section-container');
    subsectionContainers = $$('.subsection-container');
    panelContainers = $$('.panel-container');
  };

  var insertForm = function(url, action) {
    new Request.HTML({
      url: url + '?isAjax=true',
      update: this.getElement('section'),
      onSuccess: function() {
        // Form validation:
        var form = $(document.body).getElement('[action="' + action + '"]');
        if (
            typeof(form) !== 'object'
            || !Modernizr.input.required
            || !Modernizr.inputtypes.email
        ) {
          new Form.Validator.Inline(form);
        }
        form.set('action', action + '?isAjax=true');
        new Form.Request(form, form.getParent());
      }
    }).get();
  }

  var pullFormsInViaAjax = function(){
    insertForm.apply($('ask-dr'), ['/contact', '/forms/contact.php']);
    insertForm.apply(
      $('appointment'), ['/appointment', '/forms/appointment.php']
    );
  };

  var getInitialSection = function() {
    var section = document.location.pathname.match(/[^\/]+/g);
    if (section) {
      var main = $(section[0]).getElement('.container');
      if (section[1]) {
        var sub = $(main).getElement('.' + section[1]);
      } else {
        var sub = main.getElement('.subsection-container');
      }
    } else {
      var main = sectionContainers[0];
      var sub = main.getElement('.subsection-container');
    }
    return {
      main: main,
      sub: sub
    }
  }

  var triggerSubsection = function(){
    $$('.selected:not(h1)').removeClass('selected');
    this.addClass('selected');
    var index = subsectionTogglers.indexOf(this);
    var element = subsectionContainers[index];
    element.getSiblings('nav').addClass('selected');
    var url = this.get('href');
    new Request.HTML({
      url: url + '?isAjax=true',
      update: element,
      onSuccess: function(){
        element.addClass('selected');
        $$('[href^="/media"]').cerabox({width: 630, height: 370});
        $$('[href^="http"]:not([href*="' + window.location.host + '"])')
          .set('target', '_blank');
      }
    }).get();
    History.update(url);
  };

  var activateSubsection = function(sectionToggler, sectionContainer){
    sectionTogglers.getParent().removeClass('selected');
    sectionToggler.getParent().addClass('selected');
    if (section.sub) {
      triggerSubsection.apply(
        subsectionTogglers[subsectionContainers.indexOf(section.sub)]
      );
      section.sub = false; // sub only pays attention to initial URI,
                           // so we set it to false
    } else {
      // get the index of the 1st sub-section within the activated
      // element with respect to the subsectionContainers array
      var firstSection = subsectionTogglers.indexOf(
        sectionContainer.getElement('nav li:first-child a')
      );
      triggerSubsection.apply(subsectionTogglers[firstSection]);
    }
  };

  var setupSectionAccordion = function(){
    section = getInitialSection();
    new Fx.Accordion(sectionTogglers, sectionContainers, 
      {
        display: sectionContainers.indexOf(section.main),
        opacity: false,
        height: false,
        width: true,
        fixedWidth: '803px',
        onActive: activateSubsection
      }
    );
  };

  var setupSubsectionClickEvent = function(){
    subsectionTogglers.addEvent('click', function(event){
      triggerSubsection.apply(event.target);
    });
  };

  var setupPanelAccordion = function(){
    panelAccordion = new Fx.Accordion(panelTogglers, panelContainers,
      {
        opacity: false,
        display: -1,
        alwaysHide: true
      }
    );
  };

  var attachLightboxes = function(){
    $$('.specials, .testimonials').each(function(tab){
      tab.set('href', tab.href + '?isAjax=true');
    });
    $$('.tab').cerabox({width: 656, height: 496, group: false});
    $$('#links a:not([href*="facility"])').cerabox({width: 656, height: 496, group: false});
  };

  var setupContactClickEvent = function(){
    // make /contact links open contact accordion:
    $$('[href="/contact"]:not(.ask-dr-fisher)').addEvent('click', function(anchor) {
      $('ask-dr').scrollIntoView();
      anchor.preventDefault();
      panelAccordion.display(1);
    });
  };

  var setupAppointmentClickEvent = function(){
    // make /appointment links open appointment accordion:
    $$('[href="/appointment"]:not(#appointment > a)').addEvent('click', function(anchor) {
      $('appointment').scrollIntoView();
      anchor.preventDefault();
      panelAccordion.display(0);
    });
  };

  var preventDefaultOnTogglers = function(){
    $$('[class$="toggle"]').addEvent('click', function (anchor) {
      anchor.preventDefault();
    });
  };

  var init = function(){
    setupVariables();
    pullFormsInViaAjax();
    setupSectionAccordion();
    setupSubsectionClickEvent();
    setupPanelAccordion();
    attachLightboxes();
    setupContactClickEvent();
    setupAppointmentClickEvent();
    preventDefaultOnTogglers();
  };

  return {
    init: init
  }
})();

// Uses html5 history API to modify browser history, if supported
var History = (function(){
  // Update browser history
  var update = function(url){
    if (Modernizr.history) {
      if (window.location.pathname === '/') {
        history.replaceState({}, "", url);
      } else {
        if (window.location.pathname !== url) {
          history.pushState({}, "", url);
        }
      }
      var currentPage = window.location.pathname;
      window.onpopstate = function(){
        if (window.location.pathname !== currentPage) {
          window.location = window.location;
        }
      };
    }
  };

  return {
    update: update
  }
})();

