/*


Dynamic Application of Functions to DOM
*/
var _debugMode = false;

document.observe('dom:loaded', init);

Event.observe(window, 'load', initAfterImages);

function initAfterImages () {

  $$('#come-to-a-meeting', '#refer-someone', '#member-list', '#join-leaders').invoke('pngHack');
  
}

function init () {

  if ($$('.newsBar li').last())
    $$('.newsBar li').last().addClassName('last');

}

var PrintableMemberList = Class.create({
  initialize: function(name){
    if(!String(document.location).include('Printable')) return;
    document.observe('dom:loaded', this.go.bind(this));
  },
  go: function(){
    this.acquireObjects();
    this.sortRows();
  },
  acquireObjects: function(){
    this.table = $('sorted-table');
    this.tableRowArray = $$('table#sorted-table tbody tr');
  },
  sortRows: function(){
    this.sortedTable = this.tableRowArray.sortBy(function(row){
      return row.down('td.organization').innerHTML.gsub('&', '').gsub('-', '');
    });
    this.sortedTable.flatten().each(function(tr, i){
      this.table.insert(tr);
    }.bind(this));
  }
  
});


var MemberListTable = Class.create({
  initialize: function(name){
    document.observe('dom:loaded', this.go.bind(this));
  },
  go: function(){
    if (!$(document.body).hasClassName('memberlist')) return;
    this.acquireObjects();
    this.sortRows();
    this.hideTRDescriptions();
    this.addTRAlts();
    this.setupTRBehavior();
    this.setupReferalButtonBehavior();
    
    // this.requestForm();
  },
  acquireObjects: function(){
    this.table = $('members-table');
    this.tbody = this.table.down('tbody');
    
    this.defineRowObjects();

    // create grouped array of desc & title trs
    this.groupedArray = new Array();
    this.titleRows.each(function(tr, i){
      this.groupedArray.push(new Array(tr, this.descriptionRows[i]));
    }.bind(this));
    
    // this.inspectFirstThreeItems(this.groupedArray);
  },
  defineRowObjects: function(){
    this.rows = this.table.select('tbody tr');
    this.descriptionRows = this.table.select('tbody tr:nth-child(even)');
    this.titleRows = this.table.select('tbody tr:nth-child(odd)');
  },
  sortRows: function(){
    this.sortedArray = this.groupedArray.sortBy(function(rowPair){
      return rowPair[0].down('a.organization').innerHTML.gsub('&', '').gsub('-', '');
    });
    
    // update table with the guts of the sorted array
    
    this.sortedArray.flatten().each(function(tr, i){
      if (i == 0) this.tbody.update(tr);
      else this.tbody.insert(tr);
    }.bind(this));
    
    this.defineRowObjects();
  },
  inspectFirstThreeItems: function(array){
    $A(array).each(function(rowPair, i) {
      if (i < 3) {
        console.log(rowPair[0].down('a.organization').innerHTML.split(' '))
        console.log(rowPair[1].down('img.interior-image').alt)
      }
    });
  },
  addTRAlts: function(){
    this.titleRows.collect(function(tr, i){
      if (i % 2 != 0) return tr;
    }).compact().invoke('addClassName', 'alt');
  },
  hideTRDescriptions: function(){
    this.descriptionRows.invoke('hide');
  },
  setupTRBehavior: function(){
    this.table.observe('click', function(e){
      var el = $(e.target);
      // if title anchor
      if (el.match('tbody tr:nth-child(odd) td:first-child a')){
        var thisRow = el.up('tr');
        thisRow.toggleClassName('selected');
        var nextRow = thisRow.next();
        nextRow.toggle();
        e.stop();
      } else if (el.match('.closeRow')) {
        el.up('tr').hide().previous().removeClassName('selected');
        e.stop();
      }
      el.blur();
    });
  },
  setupReferalButtonBehavior: function(){
    this.table.observe('click', function(e){
      var el = $(e.target);
      if (el.match('a.refer-button')){
        this.requestForm(this.getOrganization(el));
        el.blur();
        e.stop();
      }
    }.bind(this));
  },
  getOrganization: function(el){
    return el.up('tr').down('.organization').innerHTML;
  },
  requestForm: function(organization){
    new Ajax.Request('/referral-form', {
      method: 'get',
      onComplete: function(t){
        $(document.body).insert(t.responseText);
        new AjaxForm(organization);
      }
    });
  }
});


var SearchMemberListTable = Class.create({
  initialize: function(name){
    document.observe('dom:loaded', this.go.bind(this));
  },
  go: function(){
    if (!$(document.body).hasClassName('memberlist')) return;
    this.form = $('search-form');
    this.fieldNames = ['first-name', 'last-name', 'organization', 'category'];
    this.data = $H();
    
    this.acquireObjects();
    this.sortOptions();
    this.setupFormBehavior();
  },
  acquireObjects: function(){
    this.fields = this.fieldNames.collect(function(id){
      return $(id);
    });
    this.fieldNames.each(function(className){
     this.data.set(className, $$('.' + className));
    }.bind(this));
    this.table = $('members-table');
    this.rows = this.table.select('tbody tr');
    this.descriptionRows = this.table.select('tbody tr:nth-child(even)');
    this.titleRows = this.table.select('tbody tr:nth-child(odd)');
  },
  
  sortOptions: function(){
    this.fields.each(function(field){
      var arrayOfOptions = field.select('option');
      var firstOption = arrayOfOptions.first();
      var sortedOptions = arrayOfOptions.without(firstOption).sortBy(function(option){
        return option.innerHTML;
      });
      [firstOption, sortedOptions].flatten().each(function(option, i){
        if (i == 0)
          field.update(option);
        else
          field.insert(option);
      }.bind(this));
    }.bind(this));
  },
  
  setupFormBehavior: function(){
    this.fields.each(function(field){
      field
        .observe('change', this.filterTable.bind(this))
        .observe('focus', this.resetForm.bind(this));
    }.bind(this));
  },
  filterTable: function(e){
    var value = e.target.value;
    var fieldName = e.target.id;
    if (value != 'first') {
      this.rows.invoke('hide');
      this.data.get(fieldName).find(function(el){
        if (el.innerHTML == value.escapeHTML())
          return el;
      }).up('tr').show().addClassName('selected').next('tr').show();
      e.target.addClassName('selected');
    } else {
      this.resetForm();
      this.resetTable();
    }
  },
  resetForm: function(e){
    this.fields.invoke('removeClassName', 'selected');
    this.form.reset();
  },
  resetTable: function(){
    this.descriptionRows.invoke('hide');
    this.titleRows.invoke('show').invoke('removeClassName', 'selected');
  }
});




var AjaxForm = Class.create({
  initialize: function(organization){
    if (!$('popup-shell')) return;
    this.organization = organization || false;
    this.shell = $('popup-shell');
    this.background = $('white-mask');
    this.close = $('close').down('img');
    this.cancel = this.shell.select('button[type=reset]').first();
    this.referOrganization = $('referOrganization');
    this.form = $('referral-form');
    
    this.shellTop = Number(this.shell.getStyle('top').gsub('px', ''));
    
    (function(){
      this.showOrganization();
    }.bind(this)).delay(.2);
    
    this.setupStyles();
    this.setupBehavior();
  },
  showOrganization: function(){
    if (this.organization){
      // alert(this.referOrganization.inspect());
      // Form.Element.disable('referOrganization');
      // $('refer-organization').select('option').find(function(opt){
      //   if (opt.innerHTML == this.organization) return true;
      // }.bind(this)).selected = true;
    }
  },
  setupStyles: function(){
    $('popup-head').down('h1').pngHack();
    this.close.pngHack();
    this.fixFormElementsInIE6();
    this.fixBackgroundStyles();
    this.shell.setStyle({ top: this.shellTop + document.viewport.getScrollOffsets().top + 'px' });
  },
  setupBehavior: function(){
    [this.close, this.cancel, this.background].invoke('observe', 'click', this.closePopup.bind(this));
    this.form.observe('submit', this.submitForm.bind(this));
  },
  fixBackgroundStyles: function(){
    this.background.setStyle({
      height: (document.viewport.getHeight() < document.body.getHeight()) ? document.body.getHeight() + 'px' : document.viewport.getHeight() + 'px',
      opacity: (Prototype.Browser.IE) ? .75 : this.background.getStyle('opacity')
    });
  },
  fixFormElementsInIE6: function(){
    if (Prototype.Browser.IE)
      this.hiddenFields = $$('#shell form').map(function(form){
        return form.getElements().invoke('hide');
      }).flatten();
  },
  unFixFormElementsInIE6: function(){
    if (Prototype.Browser.IE && this.hiddenFields)
      this.hiddenFields.invoke('show');
  },
  closePopup: function(){
    Try.these(function(){
      [this.shell, this.background].invoke('remove');
    }.bind(this));
    this.unFixFormElementsInIE6();
  },
  submitForm: function(event){
	  event.stop();
    this.form.request({
      onComplete: function(response){
        
     	  // update the popup with the html
     	  cl("before");
     	  cl(this);
     	  this.closePopup();
     	  $(document.body).insert(response.responseText);
        new AjaxForm();
        //cl("after");
        //cl(this);
        //this.tryToCloseOnSuccess();
        
      }.bind(this)
    });
  },
  tryToCloseOnSuccess: function() {
    if($('referral-success')) {
      this.closePopup();
    }    
  }
});


var table = new MemberListTable();

var searchTable = new SearchMemberListTable();

var printTable = new PrintableMemberList();




var Ads = Class.create({
  initialize: function(shell){
    this.shell = shell;
    document.observe('dom:loaded', this.go.bind(this));
  },
  go: function(){
    if (!$(this.shell)) return;
    this.shell = $(this.shell);
    this.ads = this.shell.select('a').invoke('hide');
    Event.observe(window, 'load', function(e){
      this.randomlyShowAd();
      this.shell.show();
    }.bind(this));
  },
  randomlyShowAd: function(){
    this.ads[(this.ads.length).rand() - 1].show();
  }
});

var headerAds = new Ads('sponsorAd');



