var Accordion = Class.create({
  initialize: function(params) {
    this._accordion = $(params.accordion) || $('accordion') || null;
    this._contents = null;
    this._maxContentHeight = 0;
    this._ptr = 0;
    this._oldPtr = 0;
    this._running = false;
    this._toggleClass = params.toggle || 'accordion-switch';
    this._contentClass = params.content || 'accordion-content';
    if (!this._accordion) {
      throw Error('No accordion element was supplied.');
    } else {
      this._init();
    }
  },
  _init: function() {
    this._contents = this._accordion.select('.' + this._contentClass);
    this._contents.each(function(content) {
      var contentHeight = content.getHeight();
      if (contentHeight > this._maxContentHeight) {
        this._maxContentHeight = contentHeight;
      }
      if (content != this._contents[this._ptr]) {
        content.hide();
        content.style.height = 0;
      }
    }, this);
    this._contents[this._ptr].style.height = this._maxContentHeight + 'px';

    this._accordion.select('.' + this._toggleClass)
      .invoke('observe', 'click', this._toggleEvent.bind(this));
  },
  _toggleEvent: function(evt) {
    if (this._running) {
      return;
    }
    var el = evt.element();
    if (el.tagName == 'P') {
      el = el.up('div.' + this._toggleClass);
    }
    var nextContent = el.next('div.' + this._contentClass);
    if (nextContent == this._contents[this._ptr]) {
      return;
    }
    this._oldPtr = this._ptr;
    for (var i = 0; i < this._contents.length; i++) {
      if (nextContent == this._contents[i]) {
        this._ptr = i;
      }
    }
    this._contents[this._ptr].show();
    var scaleEffects = [
      new Effect.Scale(this._contents[this._ptr], 100, {
        sync: true,
        scaleX: false,
        scaleFrom: 0,
        scaleContent: false,
        scaleMode: {
          originalHeight: this._maxContentHeight,
          originalWidth: this._accordion.getWidth()
        }
      }),
      new Effect.Scale(this._contents[this._oldPtr], 0, {
        sync: true,
        scaleX: false,
        scaleContent: false
      })
    ];
    new Effect.Parallel(scaleEffects, {
      duration: .7,
      queue: {
        position: 'end',
        scope: 'Accordion'
      },
      beforeStart: function() { this._running = true; }.bind(this),
      afterFinish: function() {
        this._contents[this._oldPtr].hide();
        this._contents[this._ptr].style.height = this._maxContentHeight + 'px';
        this._running = false;
      }.bind(this)
    });
  }
});
var ContactValidator = function(evt) {
  evt.stop();

  var errorBlock = $('js_msg');

  var setError = function(error) {
    errorBlock.update('<p class="error">' + error + '</p>');
  }

  var emailRegex = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|biz|info|name|aero|info|jobs|museum|name|gov|edu|mil|asia|int)$/i;

  if ($F('company').blank()) {
    setError('The Company Name field is required.');
  } else if ($F('contact').blank()) {
    setError('The Contact Name field is required.');
  } else if ($F('address').blank()) {
    setError('The Address field is required.');
  } else if ($F('city').blank()) {
    setError('The City field is required.');
  } else if ($F('state').blank()) {
    setError('The State field is required.');
  } else if ($F('state').length != 2) {
    setError('The State field must be exactly 2 characters in length.');
  } else if ($F('postal').blank()) {
    setError('The Zip field is required.');
  } else if ($F('phone').blank()) {
    setError('The Phone field is required.');
  } else if ($F('email').blank()) {
    setError('The Email field is required.');
  } else if (!emailRegex.test($F('email'))) {
    setError('The Email field must contain a valid email address.');
  } else {
    var params = {
      'company': $F('company'),
      'contact': $F('contact'),
      'address': $F('address'),
      'city':    $F('city'),
      'state':   $F('state'),
      'postal':  $F('postal'),
      'phone':   $F('phone'),
      'email':   $F('email')
    };
    new Ajax.Request('contact/send_ajax', {
      method: 'post',
      parameters: params,
      onFailure: function() {
        var errorMsg = '<p class="error">Your information could not be ' +
                       'submitted. We apologize for the inconvenience. ' +
                       'Please try again later.</p>';
        $('js_msg').update(errorMsg);
      },
      onSuccess: function(transport) {
        var successMsg = '<p class="success">Your contact information has ' +
                         'been sent successfully. You will be contacted in a ' +
                         'timely fashion. Thank you.</p>'
        $('js_msg').update(successMsg);
        $('contact_btn').style.visibility = 'hidden';
        $('company', 'contact', 'address', 'city', 'state', 'postal', 'phone', 'email').invoke('clear');
      }
    });
  }
  return false;
};

document.observe('dom:loaded', function() {
  $$('a.newwin').invoke('observe', 'click', function(evt) {
    var a = evt.element();
    if (a.tagName != 'A') {
      a = a.up('a');
    }
    window.open(a.href);
    evt.stop();
    return false;
  });

  new Ajax.Request('/facilities/facility_list', {
    method: 'get',
    onSuccess: function(transport) {
      var content = transport.responseText;
      $(document.body).insert({bottom:content});
    }
  });

  new PeriodicalExecuter(function(pe) {
    var facilityBox = $('facilitybox');
    if (!facilityBox) {
      return;
    }

    var accordion = new Accordion({
      accordion: 'accordion',
      toggle:    'accordion-switch',
      content:   'accordion-content'
    });

    facilityBox.hide();

    (function() {
      var showing = false;
      $$('.facility-list').invoke('observe', 'click', function(evt) {
        if (showing) {
          evt.stop();
          return;
        }
        $('nav_inner').setStyle({zIndex:0}); // Lower zIndex so nav doesn't show
        var offsets = document.viewport.getScrollOffsets();
        facilityBox.show().absolutize().setStyle({top: (offsets.top + 50) + 'px'});
        showing = true;
        evt.stop();
      });

      $$('.close-facility-list').invoke('observe', 'click', function(evt) {
        facilityBox.hide();
        $('nav_inner').setStyle({zIndex:2}); // Raise zIndex on nav to show
        showing = false;
        evt.stop();
      });
    })();

    pe.stop();
  }, 2);

  var contactBtn = $('contact_btn');
  if (contactBtn) {
    contactBtn.observe('click', ContactValidator);
  }
});