
function ajaxLoading() {
  new Effect.Opacity('search-list', { to: 0.25, duration: 0 });
  $('searchingdotdotdot').show();      
}
function ajaxComplete() {
  $('searchingdotdotdot').hide();
  new Effect.Opacity('search-list', { to: 1.0, duration: 0 });
}

Event.addBehavior({'#filters select' : Behaviors.Form.AccessibleSelect});

var ToggleSection = Behavior.create({
  initialize : function(){
    if (!this.element.hasClassName('minimized')){
      this.element.addClassName('maximized');
      this.maximize();
    }
    else{
      this.minimize();
    }
  },
  onclick: function(e){
    e.stop();
    if (this.element.hasClassName('minimized')){
      this.maximize();
    }
    else {
      this.minimize();
    }
  },
  minimize: function(){
    var togglePanels = this.element.up('dl').select('dd');
    togglePanels.invoke('hide');
    this.element.addClassName('minimized');
    this.element.removeClassName('maximized');
  },
  maximize: function() {
    var togglePanels = this.element.up('dl').select('dd');
    togglePanels.invoke('show');
    this.element.addClassName('maximized');
    this.element.removeClassName('minimized');
  }

});


var AutoUpdateSearchForm = Class.create({
  initialize: function(options) {
    this.options = $H(options);
    this.containerSelector = this.options.get('containerSelector');
    if (!this.containerSelector){
      throw new Error("must specify containerSelector option to AutoUpdateSearchForm constructor");
    }
    this.container = $$(this.containerSelector).first();
    this.form().reset();
    
    // hide border on last-child because of <= IE7
    this.container.select('dl').each(function(item) {
      $($(item.immediateDescendants()).last()).setStyle({borderWidth: '0'});
    });

    this.container.observe('select:changed', Event.delegate({
      'select' : this.doUpdate,
      'ul' : this.doUpdate
    }).bindAsEventListener(this));

    this.container.observe('click', Event.delegate({
      'input[type=checkbox]' : this.doUpdate
    }).bindAsEventListener(this));

    // sadly jQuery.trigger('change') doesn't make ie over the wall
    // firing this prototype style from within jquery
    this.container.observe('prototype:change', Event.delegate({
      'select' : this.sliderChanged
    }).bindAsEventListener(this));
    
    this.container.observe('change', Event.delegate({
      'input[type=radio]' : this.doUpdate
    }).bindAsEventListener(this));
    
    selectSelector = this.contentSelector + ' select';
    Event.addBehavior.reassignAfterAjax = true;
    Event.addBehavior({
      selectSelector : Behaviors.Form.AccessibleSelectFactory.create()
    });

  // initialize slider ranges on page load
    this.container.select('slider-txt').each(function(el) { this.updateSliderText(el); },this);
    $('results').observe('click',Event.delegate(
    {
      '.pagination a': this.doPagination.bindAsEventListener(this)
    }));
    
  },
  form: function(){
    return this.container.select('form').first()
  },
  sliderChanged : function(e){
    sliderDiv = e.element().up('dd');
    this.updateSliderText(sliderDiv.down('.slider-txt'));
    this.requestUpdate(e);
  },
  updateSliderText : function(sliderRangeLabel) {
    selectBoxes = sliderRangeLabel.up('dd').select('select');

    values = $A();
  for (var i=0; i<2; i++) {
    var val = selectBoxes[i].value;
    if (val.blank()) { val = 'Any'; }
    values.push(val);
  }
  // if min and max are the same, just show that value, otherwise join values with a dash
  sliderRangeLabel.innerHTML = values.uniq().join(' - ');;
},
doUpdate: function() {
  throw new Error('override doUpdate!')
},
requestUpdate: function(e) {
  clearTimeout(this.cur_request);
  this.cur_request = setTimeout(this.doUpdate.bindAsEventListener(this), 1000);
},
doPagination:function(event){
  event.stop();
  new Ajax.Updater('search-list',event.element().href,
    {
    method: 'get',
    onLoading: function(request) {
      ajaxLoading();
    },
    onComplete: function(response) {
      ajaxComplete();
    }
  });
  }
});

var AdvSearch = Class.create(AutoUpdateSearchForm,{
initialize: function($super,options){
  $super(options);
  this.container.select('dl dt a').each(function(element){
    ToggleSection.attach(element);
  });
},
doUpdate: function() {
  new Ajax.Updater('search-list', this.form().action, {
    method: this.form().method,
    parameters: Form.serialize(this.form()),
    onLoading: function(request) {
      ajaxLoading();
    },
    onComplete: function(response) {
      ajaxComplete();
    }
  });
}
});

var WelcomeFindSearch = Class.create(AutoUpdateSearchForm,{
initialize: function($super,options){
  $super(options);
  this.resultsTitle = this.options.get('resultsTitle') || 'Find Patients Like You';
  this.container.observe('click',Event.delegate(
  {
    'input[type=submit]': this.showPatients.bindAsEventListener(this)
  }
  ));
    
  $('results').observe('click', Event.delegate({
    'a.reset': this.showForm.bindAsEventListener(this)

  }));
  if (window.location.hash == '#patients'){
    this.showPatients();
  }
  else {
    this.showForm();
  }


},
doUpdate:function() {
  // get a patient count
  new Ajax.Request('/patients/count.js',{
    method: 'get',
    parameters: this.form().serialize(),
    onLoading: this.countLoading.bindAsEventListener(this),
    onSuccess: this.countSuccess.bindAsEventListener(this)
  });
  
},
showForm: function(event){
  if (event) {event.stop();}
  $('results').hide();
  $('find-container').show();
  window.location.hash = 'form';

},
showPatients: function(event){
  if (event) {event.stop();}
  $('results').show();
  $('find-container').hide();
  new Ajax.Updater('search-list', this.form().action, {
    method: this.form().method,
    parameters: Form.serialize(this.form()),
    onLoading: function(request) {
      window.scrollTo(0,0);
      ajaxLoading();
    },
    onComplete: function(response) {
      window.location.hash = 'patients';
      titleContent = '<h3>' + this.resultsTitle + '</h3>';
        $('results-header').insert({top: titleContent});
        ajaxComplete();
      }.bindAsEventListener(this)
    });

  },
  countSuccess:function(e){
    data = $H(e.transport.responseText.evalJSON());
    $$('#count-results strong').first().update(data.get('total_matches') + ' patients ');
    visible_matches = data.get('visible_matches');
    vis_text = visible_matches > 0 ? visible_matches : 'None';
    $('public-count').update(vis_text + ' ');
    $$('#count-results .spinner').first().remove();
  },
  countLoading:function(e) {
    $$('#count-results .helptext').first().insert({before: $div({className: 'spinner'})});
  }


})


