// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function toggle_name(element) {
  if(element.getValue() == 1) {
    element.nextSibling.removeAttribute('name');
  } else {
    var elem_name = element.name;
    element.nextSibling.setAttribute('name', elem_name);
  }
}

Event.observe(window,'load', function() {
  tables = $$('table.stripe');
  for(current=0; tables.length > current; current++) { 
    table = tables[current];
    var tbodies = table.getElementsByTagName("tbody");

    for (var h = 0; h < tbodies.length; h++) {
      // find all the <tr> elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {  
        if((i % 2) == 0) { style = 'even'; } else { style = 'odd'; }
        Element.addClassName(trs[i],style);
      }
    }
  }
})

Event.observe(window,"load", function() {
  //click to clear functionality
  $$('input.hinted\_field').each(function(element) {
    new FieldHint(element);
  });
});

var FieldHint = Class.create();
  Object.extend(FieldHint.prototype, {
  initialize: function(element) {
    this.element = $(element);
    this.originalValue = $F(element);
    this.element.observe("blur", this.onBlur.bind(this));
    this.element.observe("focus", this.onFocus.bind(this));
    var form = this.element.up("form");
    if(form) $(form).observe("submit", this.onFocus.bind(this));
  },
  onFocus: function(event) {
    if($F(this.element) == this.originalValue) {
      this.element.value = "";
      this.element.removeClassName("clear\_on\_click");
    }
  },
  onBlur: function(event) {
    if($F(this.element).match(/^\s*$/)) {
      this.element.value = this.originalValue;
      this.element.addClassName("clear\_on\_click");
    }
  }
}
);

Event.observe(window,"load", function() {
  //click to clear functionality
  $$('select.new_option_possible').each(function(element) {
    new NewOptionPossible(element);
  });
});

var NewOptionPossible = Class.create();
  Object.extend(NewOptionPossible.prototype, {
  initialize: function(element) {
    this.element = $(element);
    this.originalValue = $F(element);
    this.element.observe("change", this.onChange.bind(this));
  },
  onChange: function(event) {
    if(this.element.value == '!') {
      name = prompt("Enter new donor name:");

      if(name.length > 0) {
        new Ajax.Request(location.pathname+"/donors", {
          method: 'post',
          parameters: 'authenticity_token='+AUTH_TOKEN+'&name=' + name
        });
				
      } else {
        alert("You must enter a name to create a new donor.");
      }
    }
  }
}
);

function select_items_all() {
  var checkboxes = $$('.selectable input[type=checkbox]');
  checkboxes.each(function(e){ e.checked = 1 });
}
function select_items_none() {
  var checkboxes = $$('.selectable input[type=checkbox]');
  checkboxes.each(function(e){ e.checked = 0 });
}
function select_items_active() {
  select_items_none();
  var checkboxes = $$('.selectable tr.active input[type=checkbox]');
  checkboxes.each(function(e){ e.checked = 1 });
}
function select_items_inactive() {
  select_items_none();
  var checkboxes = $$('.selectable tr.inactive input[type=checkbox]');
  checkboxes.each(function(e){ e.checked = 1 });
}

function modify_selections(name) {
  var path = $('selection_options').down('form').getAttribute('action')
  var modification = $('selections_action').value;
  var checkboxes = $$('.selectable table input[type=checkbox]');

  var items = []
  checkboxes.each(function(e){ 
    if(e.checked == 1) {
      items.push(e.value)
    }
  });  
  if(items.length > 0 && modification.length > 0) {
    if(modification == 'delete') {
      var confirmed = confirm("Are you sure you want to delete these "+items.length+" "+name+"(s)?")
    }
    if((modification == 'delete' && confirmed) || modification != 'delete') {
      new Ajax.Request(path, 
        { 
          asynchronous: true, 
          method: 'put', 
          evalJS: true, 
          parameters: 'modification='+modification+'&items='+items+'&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)
        }
      )
    }
  } else if(modification.length == 0) {
  } else {
    alert("No "+name+"s selected. You must select "+name+"s to perform this action upon.")
  }
}

function get_remaining_items() {
  new Ajax.Request('', 
    { 
      asynchronous: true, 
      method: 'get', 
      evalJS: true, 
      parameters: 'remaining=true'
    }
  );
}

Event.observe(window,'load', function() {
  table = $$('table tbody tr#loading');
  if(table.length > 0) {
    get_remaining_items();
  }
});

replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}


var myrules = {
  '.remove': function(e){
    el = Event.findElement(e);
    target = el.href.replace(/.*#/, '.');
    if(hidden_input = el.previous("input[type=hidden]")) { 
      el.up(target).hide();
      hidden_input.value = '1';
    } else {
      el.up(target).remove();
    }
    return false;
  },
  '.add_nested_item': function(e){
    el = Event.findElement(e);
    template = eval(el.href.replace(/.*#/, ''));
    $(el.rel).insert({ bottom: replace_ids(template) });
  }
};
Event.observe(window, 'load', function(){ $('content').delegate('click', myrules); });