// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
  var Cookie = {
    set: function(name, value, daysToExpire) {
      var expire = '';
      if (daysToExpire !== undefined) {
        var d = new Date();
        d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
        expire = '; expires=' + d.toGMTString();
      }
      return (document.cookie = escape(name) + '=' + escape(value || '') + expire + "; path=/");
    },
    get: function(name) {
      var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
      return (cookie ? unescape(cookie[2]) : null);
    },
    erase: function(name) {
      var cookie = Cookie.get(name) || true;
      Cookie.set(name, '', -1);
      return cookie;
    },
    accept: function() {
      if (typeof navigator.cookieEnabled == 'boolean') {
        return navigator.cookieEnabled;
      }
      Cookie.set('_test', '1');
      var return_val = (Cookie.erase('_test') === '1');
      return return_val;
    }
  };

  var Request = {
    remote: function(update,url,method) {
      var args = Request.get_args;
      args['method'] = method;
      new Ajax.Updater(update, url, args);
    },
    get: function(update,url) {
      Request.remote(update,url,'get');
    },
    post: function(update,url) {
      Request.remote(update,url,'post');
    },
    put: function(update,url) {
      Request.remote(update,url, 'put');
    },
    destroy: function(update,url) {
      Request.remote(update,url,'delete');
    },
    get_args: function(args) {
      return new Hash({asynchronous:true, evalScripts:true });
    }
  }

  var Account = { 
    update_terms: function() { 
      if ($('terms_accepted').checked) {
        Request.post('','/home/accept_terms');
        $('subscribe').enable();
      } else { 
        Request.post('','/home/deny_terms');
        $('subscribe').disable();
      }
    }
  }

  var PaymentType = {
    select: function() { 
      var pt = $('payment_type_select').getValue();
      var opt = $('payment_type_' + pt); 
      var is_check = opt.readAttribute('is_check');
      if (is_check == 'true') { 
        $('check_number').show();
        $('check_number_field').focus();
      } else { 
        $('check_number').hide();
      }
    }
  }

  var Report = { 
    set_template: function() { 
      var rt = $('report_template').getValue();
      Request.post('','/reports/set_template?report_template_id=' + rt);
    }
  }
  
  var InterestLevel = {
    menu_change: function(id) {
      var constituent_id = id.split('_').last();
      var val   = $(id).getValue();
      if (val === null) { val = ''; }
      var url   = '/constituent_interest_levels/';
      url += 'save_level?constituent_id=' + constituent_id;
      url += '&constituent[constituent_interest_level_id]=' + val;
      Request.post('',url);
    },
    update: function(constituent_id,text) {
      var update_id = InterestLevel.update_id(constituent_id);
      var link_id   = InterestLevel.link_id(constituent_id);
      var url       = InterestLevel.url(constituent_id);
      Request.get(update_id,url);
    },
    url: function(constituent_id) {
      return "/constituent_interest_levels/select?constituent_id=" + constituent_id;
    },
    link_id: function(constituent_id) {
      return "interest_level_for_constituent_" + constituent_id;
    },
    update_id: function(constituent_id) {
      return "level_constituent_" + constituent_id;
    }
  }

  var Invitation = { 
    set_flag: function(key,id) { 
      var el = $(key + '_invitation_' + id);
      var url = '/invitations/' + id + '/set_' + key;
      if (el.checked) { 
        url += "?" + key + "=1";
      } else { 
        url += "?" + key + "=0";
      }
      url += "&respond=false"
      Request.post('',url);
    },
    set_attended: function(id) { 
      var el = $('attended_invitation_' + id);
      var url = '/invitations/' + id + '/set_attended';
      if (el.checked) { 
        url += "?attended=1";
      } else { 
        url += "?attended=0";
      }
      Request.post('',url);
    },
    set_rsvp: function(id) { 
      var el = $('rsvp_invitation_' + id);
      var url = '/invitations/' + id + '/set_rsvp';
      if (el.checked) { 
        url += "?rsvp=1";
      } else { 
        url += "?rsvp=0";
      }
      Request.post('',url);
    }
  }

  var Duplicate = {
    merge: function(id,type) {
      var main    = $('main_for_dupe_' + id);
      var related = $('related_for_dupe_' + id);
      var url     = '/duplicates/' + id + '/save?op=merge&' + type + '=true';
      Request.post('',url);
    },
    invalidate: function(id) {
      var url     = '/duplicates/' + id + '/save?op=invalid';
      Request.post('',url);
    }
  }

  var MoreActions = {
    submit: function(id) {
      var val   = $(id).getValue();
      if (val === null) { val = '#'; }
      location.href = val; 
    }
  }

  var Mailing = { 
    menu_change: function() {
      var select_id = 'mailing_template';
      var el        = $(select_id);
      var val       = el.getValue();
      var list_id   = el.readAttribute('list_id');
      if (val === null) { val = ''; }
      if (list_id === null) { list_id = ''; }
      var url   = '/mailings/';
      url += 'set_template?template_id=' + val + "&list_id=" + list_id;
      var message = 'Warning: Selecting a template will override all of your current settings for this mailing.  Are you sure you want to use this template?';
      if (confirm(message)) {
        Request.post('',url);
      } else {
        $(select_id).setValue('');
      }
    },
    select_page: function() { 
      var val = $('select_page').getValue();
      if (val == "Custom") { 
        $('custom_page_size').show(); 
      } else { 
        $('custom_page_size').hide(); 
      }
    },
    select_env_page: function() { 
      var val = $('select_env_page').getValue();
      if (val == "Custom") { 
        $('custom_env_page_size').show(); 
      } else { 
        $('custom_env_page_size').hide(); 
      }
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var mail_id           = li.readAttribute('obj_id');
      var input_id          = "set_constituent_for_mailing_" + mail_id;
      var url               = "/mailings/set_constituent?obj_id=" + mail_id+ "&constituent_id=" + constituent_id; 
      Request.get('',url)
    },
    refresh_details: function(id) {
      var url = '/mailings/' + id + '/refresh_details?source=' + source;
      Request.get('',url);
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/mailings/edit_constituent?obj_id=' + id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    }
  }
  
  var Help = { 
    show: function() { 
      if ($('help_content').visible()) { 
        Effect.SlideUp('help_content');
      } else { 
        Effect.SlideDown('help_content');
      }
      $('help_content').select('img').each( function(img) {
        var img_src = img.readAttribute('src');
        img.setAttribute('src',img_src);
      } );
    }
  }

  var ConstituentContactType = {
    menu_change: function(id) {
      var constituent_id = id.split('_').last();
      var val   = $(id).getValue();
      if (val == null) { val = ''; }
      var url   = '/constituent_contact_types/';
      url += 'save_contact_type?constituent_id=' + constituent_id;
      url += '&constituent[constituent_contact_type_id]=' + val;
      Request.post('',url);
    },
    update: function(constituent_id,text) {
      var update_id = ConstituentContactType.update_id(constituent_id);
      var link_id   = ConstituentContactType.link_id(constituent_id);
      var url       = ConstituentContactType.url(constituent_id);
      Request.get(update_id,url);
    },
    url: function(constituent_id) {
      return "/constituent_contact_types/select?constituent_id=" + constituent_id;
    },
    link_id: function(constituent_id) {
      return "constituent_contact_type_for_" + constituent_id;
    },
    update_id: function(constituent_id) {
      return "contact_type_constituent_" + constituent_id;
    }
  }


  var ConstituentRating = {
    menu_change: function(id) {
      var constituent_id = id.split('_').last();
      var val   = $(id).getValue();
      if (val == null) { val = ''; }
      var url   = '/constituent_ratings/';
      url += 'save_rating?constituent_id=' + constituent_id;
      url += '&constituent[constituent_rating_id]=' + val;
      Request.post('',url);
    },
    update: function(constituent_id,text) {
      var update_id = ConstituentRating.update_id(constituent_id);
      var link_id   = ConstituentRating.link_id(constituent_id);
      var url       = ConstituentRating.url(constituent_id);
      Request.get(update_id,url);
    },
    url: function(constituent_id) {
      return "/constituent_ratings/select?constituent_id=" + constituent_id;
    },
    link_id: function(constituent_id) {
      return "constituent_rating_for_" + constituent_id;
    },
    update_id: function(constituent_id) {
      return "rating_constituent_" + constituent_id;
    }
  }

  var Activity = {
    details: function(id) {
      var new_id = "details_for_activity_" + id;
      $(new_id).toggle();
      var url = "/activities/" + id + "/details";
      Request.get('',url);
    }
  }

  var ImportForm = {
    select: function() { 
      var val = $('import_type').getValue();
      $('gift_import_form').hide();
      $('email_import_form').hide();
      $('constituent_import_form').hide();
      $('phone_import_form').hide();
      $('street_address_import_form').hide();
      $(val + '_import_form').show();
      Cookie.set('import_type',val,30);
    },
    show: function(tab) {
      if (tab == 'gift') {
        $('gift_import_form').show();
        $('constituent_import_form').hide();
        Cookie.set('import_type',tab,30);
      } else {
        $('gift_import_form').hide();
        $('constituent_import_form').show();
        Cookie.set('import_type',tab,30);
      }
    },
    show_description: function(type) {
      var id        = type + '_import_selection';
      var import_id = $(id).getValue();
      if (import_id == '') {
        $(type + '_import_description').innerHTML = '';
      } else {
        var url       = '/import_maps/' + import_id + '/description';
        Request.get('',url);
      }
    }
  }

  var GiftForm = { 
    basic_submit: function(id) {
      var form  = $(id);
      var total = $('total').getValue();
      var count = $('count').getValue();
      var url   = form.action;
      if (count) { url += "/count/" + count }
      if (total) { url += "/total/" + total }
      location.href = url;
    }
  }
 
  var SearchForm = {
    basic_submit: function(id) {
      var form  = $(id);
      var val   = $(id + '_value').getValue();
      var def   = $(id + '_value').readAttribute('default');
      var url   = form.action;
      if (val != def) { 
        url       += "/name/" + val;
        location.href = url;
      }
    },
    remote_submit: function(id) {
      var form  = $(id);
      var val   = $(id + "_value").getValue();
      var url   = form.action;
      url       += "/name/" + val;
      url       += "?source=" + source;
      Request.get('',url);
    } 
  }

  var DashBoard = {
    show_tab: function(tab) {
      tabs = ['recent','upcoming']; 
      for (i=0; i < tabs.length; i++) {
        var close_tab = tabs[i] + '_tab';
        $(close_tab).removeClassName('Active');
        $(close_tab).addClassName('Inactive');
      }
      var open_tab = tab + '_tab';
      $(open_tab).removeClassName('Inactive');
      $(open_tab).addClassName('Active');
    }
  }
  var ConstituentSearch = {
    show: function(tab) {
      if (tab == 'simple') {
        $('simple').show();
        $('advanced').hide();
        $('advanced_tab').removeClassName('Active');
        $('advanced_tab').addClassName('Inactive');
        $('simple_tab').removeClassName('Inactive');
        $('simple_tab').addClassName('Active');
        Cookie.set('constituent_search_type',tab,30);
      } else {
        $('simple').hide();
        $('advanced').show();
        $('advanced_tab').removeClassName('Inactive');
        $('advanced_tab').addClassName('Active');
        $('simple_tab').removeClassName('Active');
        $('simple_tab').addClassName('Inactive');
        Cookie.set('constituent_search_type',tab,30);
      }
    },
    custom_dates: function() {
      var val   = $('gift_date_selector').getValue();
      if (val == 'custom') { 
        $('custom_giving_dates').show();
      } else {
        $('custom_giving_dates').hide();
      }
    },
    basic_submit: function() {
      var form  = $('basic_constituent_search');
      var val   = $('constituent_name_search').getValue();
      val       = val.gsub('/',' ')
      var url   = form.action;
      url       += "/name/" + val;
      //Cookie.set('constituent_search_type','simple',30);
      location.href = url;
    },
    remote_submit: function() {
      var form  = $('basic_constituent_search');
      var val   = $('constituent_name_search').getValue();
      var url   = form.action;
      url       += "/name/" + val;
      url       += "?source=" + source;
      Request.get('',url);
    },    
    advanced_submit: function() {
      var form    = $('advanced_search');
      var url     = form.action; 
      var inputs  = form.getInputs();
      var l       = inputs.length;
      var gift_date = $('basic_date_selector').getValue();
      for (var i=0; i < l; i++) {
        var input = inputs[i];
        var name = input.readAttribute('name');
        var value = input.getValue();
        if (name == 'years') { 
          school_tie = $('school_tie_type_id').getValue();
          if ((value != null && value.length > 0) || (school_tie != null && school_tie.length > 0) ) {
            value = value.gsub('/',' ');
            value = school_tie + "|" + value; 
            url += "/" + name + "/" + value;
          }
        } else if (name == 'school_years') {
          var school_name = $('school_name').getValue();
          var school_year = $('school_years').getValue();
          if ((school_name != null && school_name.length > 0) || (school_year != null && school_year.length > 0) ) {
            school_name = school_name.gsub('/',' ');
            url += "/schools/" + school_name + "|" + school_year;
          }
        } else if (name == 'school_name') { 
          //taken care of above
        } else if (value !== null && value.length > 0 && name != 'basic_date') {
          value = value.gsub('/',' ');
          url += "/" + name + "/" + value;
        }
      }
      var campaign   = $('filter_by_campaign_id').getValue();
      if (campaign  != null && campaign.length > 0) { url += "/campaign/" + campaign }
      var fund       = $('filter_by_fund_id').getValue();
      if (fund      != null && fund.length > 0) { url += "/fund/" + fund }
      var appeal     = $('filter_by_appeal_id').getValue();
      if (appeal    != null && appeal.length > 0) { url += "/appeal/" + appeal }
      var event_id   = $('filter_by_event_id').getValue();
      if (event_id  != null && event_id.length > 0) { url += "/event/" + event_id }

      location.href = url;
    }
  }

  var Search = { 
    controller: "",
    field_count: 0,
    selected_options: new Hash({}),
    advanced_submit: function() {
      var form    = $('advanced_search');
      var url     = form.action; 
      var inputs  = form.select('*[inp="1"]');
      var l       = inputs.length;
      for (var i=0; i < l; i++) {
        var input = inputs[i];
        var name = input.readAttribute('name');
        var value = input.getValue();
        if (name == 'years') { 
          school_tie = $('school_tie_type_id').getValue();
          if ((value != null && value.length > 0) || (school_tie != null && school_tie.length > 0) ) {
            value = value.gsub('/',' ');
            value = school_tie + "|" + value; 
            url += "/" + name + "/" + value;
          }
        } else if (name == 'school_name') {
          var school_name = $('school_name').getValue();
          var school_year = $('school_years').getValue();
          if ((school_name != null && school_name.length > 0) || (school_year != null && school_year.length > 0) ) {
            url += "/schools/" + school_name + "|" + school_year;
          }
        } else if (value !== null && value.length > 0 && name != 'basic_date') {
          if ($(name + '_prefix')) { 
            var pref_val = $(name + '_prefix').getValue();
            name = pref_val + name;
          }
          value = value.gsub('/',' ');
          url += "/" + name + "/" + value;
        }
      }
      location.href = url;
    },
    add_row: function() { 
      Search.field_count ++;
      var next_field = Search.next_available_field();
      var url = '/' + Search.controller + '/add_search_row?num=' + Search.field_count + '&field=' + next_field + '&view=' + Search.view;
      Request.get('',url); 
    },
    set_field_counts: function() { 
      var form    = $('advanced_search');
      Search['selected_options'] = new Hash({});
      form.select('*[sel="1"]').each(function(sel) {
        var value   = sel.getValue();
        var current = Search.selected_options[value];
        if (current == null) { 
          Search.selected_options[value] = 1;
        } else if (current > 0) { 
          Search.selected_options[value] += 1; 
        }
      });
    },
    can_add_field: function(field) { 
      var count = Search.selected_options[field];
      var limit = 1;
      if (count >= limit) { 
        return false;
      } else  {
        return true;
      }
    },
    next_available_field: function() { 
      var form    = $('advanced_search');
      Search.set_field_counts();
      var selected    = false;
      var return_val  = Search.fields.first();
      Search.fields.each(function(field){
        if (Search.can_add_field(field) && !selected) { 
          selected = true;
          return_val = field;
        }
      });
      return return_val;
    },
    set_criteria: function(num) { 
      var val     = $('search_select_' + num).getValue();
      var url     = "/" + Search.controller + "/set_criteria?field=" + val + "&num=" + num;
      var count   = Search.selected_options[val];
      Search.set_field_counts();
      if (count && count > 0) { 
        alert('It is not possible to use this term more than once in a given search. Please select a different term.');
        var field = Search.next_available_field();
        $('search_select_' + num).setValue(field); 
        Search.selected_options[field] = 1;
      } else { 
        Spinner.set('search_body_' + num, 'Loading ...');
        Request.get('',url);
      }
    }
  }

  var LGLDate = { 
    edit_date: function(id,single,plural,date_field) {
      var update_id   = date_field + '_for_' + single + '_' + id;
      var update_url  = '/' + plural + '/' + id + '/edit_date?date_field=' + date_field;
      Request.get(update_id, update_url);
    },
    show_date: function(id,single,plural,date_field) {
      var update_url  = '/' + plural + '/' + id + '/show_date?date_field=' + date_field;
      Request.get('', update_url);
    },
    save_date: function(id,single,plural,date_field) {
      var form_id  = date_field + '_form_for_' + single + '_' + id;
      LGLForm.remote_submit(form_id);
    }
  }

  var Searcher = { 
    search: function(id) { 
      var value = $(id + '_search').getValue();
      Searcher.results(id).each(function(name) { 
        var text  = name.readAttribute('val'); 
        var rgx   = new RegExp('.*' + value + '.*', 'i'); 
        if (text.match(rgx) || value == '') { 
          name.show();
        } else { 
          name.hide();
        }
      });
    },
    results: function(id) { 
      return $(id + '_results').select('*[search="true"]')
    },
    select_all: function(id) {
      var main  = $(id + '_selector');
      var value = $(id + '_search').getValue();
      Searcher.results(id).each(function(name) { 
        var text  = name.readAttribute('val'); 
        var rgx   = new RegExp('.*' + value + '.*', 'i'); 
        var inp   = name.down('input');
        if (text.match(rgx) || value == '') { 
          if (main.checked) { 
            inp.checked = true;   
          } else {
            inp.checked = false;   
          }
        }
      });
    }
  }
  
  var DateFilter = {
    menu_change: function(id) {
      var val   = $(id).getValue(); 
      var args  = val.split('/');
      if (args.length == 2) {
        if (args[0] =~ /from/) {
          $(id + '_start').setAttribute('value',args[1]);
          $(id + '_end').setAttribute('value','');
        } else {
          $(id + '_start').setAttribute('value','');
          $(id + '_end').setAttribute('value',args[1]);
        }
      } else if (args.length == 4) { 
        $(id + '_start').setAttribute('value',args[1]);
        $(id + '_end').setAttribute('value',args[3]);
      } else {
        $(id + '_start').setAttribute('value','');
        $(id + '_end').setAttribute('value','');
      }
      return val;      
    },
    basic_submit: function(remote) {
      var form  = $('date_filter');
      var val   = DateFilter.menu_change('basic_date_selector');
      var clean_url = $('date_filter_clean_url').getValue();       
      var is_deposit = ($('form_is_deposit') && $('form_is_deposit').checked);
      if (val != 'custom') {
        $('summary_spinner_for_date').show();
        clean_url += "/" + val;
      }
      if (is_deposit) { 
        clean_url += "/deposit/1";
      }
      if (remote) { 
        Request.get('',clean_url);
      } else { 
        location.href = clean_url;
      }
    },
    set_filter_type_value: function(type) {
      var filter_type = $('date_filter_search_type');
      filter_type.setAttribute('value', type);
    },
    custom_submit: function(remote,selector_id) {
      var clean_url = $('date_filter_clean_url').getValue();
      var from      = $(selector_id + '_start').getValue();
      var to        = $(selector_id + '_end').getValue();
      var is_deposit = ($('form_is_deposit') && $('form_is_deposit').checked);
      if (to != null && to.length > 0) {
        to = to.gsub('/','-');
        clean_url = clean_url + '/to/' + to;
      }
      if (from != null && from.length > 0) {
        from = from.gsub('/','-');
        clean_url = clean_url + '/from/' + from;
      }
      if (is_deposit) { 
        clean_url += '/deposit/1';
      }
      if (remote) { 
        Request.get('',clean_url);
      } else { 
        location.href = clean_url;
      }
    },
    show_basic: function() {
      $('custom_date_form').hide();
    },
    show_custom: function() {
      $('custom_date_form').show();
    }
  }

  var Segment = { 
    set_list: function(id) { 
      var list_id = $(id + "_select").getValue();
      var opt     = $(id + '_list_id_' + list_id).readAttribute('name'); 
    },
    moveup: function(id) { 
      var url = "/segments/" + id + "/move_up";
      $('spinner_' + id).show();
      Request.post('', url);
    },
    movedown: function(id) { 
      var url = "/segments/" + id + "/move_down";
      $('spinner_' + id).show();
      Request.post('', url);
    }
  }
  
  var List = {
    page: 1,  
    set_page: function(page) { List['page'] = page },    
    observe: function() { List.set_functions($$('input.FlagConstituent')); }, 
    observe_flagged: function() { List.set_functions($$('img.FlagConstituent')); }, 
    update: function(event) {
      var el        = Event.element(event);
      var const_id  = el.readAttribute('constituent_id');
      var list_id   = el.readAttribute('list_id');
      var del       = el.readAttribute('delete');
      List.add_or_remove(const_id,list_id,del);
    },
    add_or_remove: function(const_id,list_id,del) {
      var input_id  = "input_for_flag_constituent_" + const_id;
      var el        = $(input_id)      
      var url       = '/lists/flag_constituent/?constituent_id=' + const_id + '&id=' + list_id;
      url += '&source=' + source + '&page=' + List.page;
      if (del == 'true') {
        if (el) { el.setAttribute('delete','false'); el.checked = false;  el.setAttribute('add','false'); el.setAttribute('suppress','true'); }
        url += '&delete=true'
      } else {
        if (el) { el.setAttribute('delete','true'); el.setAttribute('add','true');el.setAttribute('suppress','false');}
      }
      //$('flag').show();
      Request.post('',url);
    },
    add_all: function(list_id) {
      var url   = '/lists/flag_all_results?id=' + list_id + '&source=' + source;
      var elts  = $$('input.FlagConstituent');
      var l     = elts.length;
      for (var i=0; i < l; i++) {
        elt = elts[i];
        if (elt.readAttribute('suppress') != 'true') { 
          elt.checked = true;
          elt.setAttribute('delete','true');
        }
      }
      Request.post('',url);
    },
    remove_all: function(list_id) {
      var url = '/lists/remove_all_results?id=' + list_id + '&source=' + source;
      var elts  = $$('input.FlagConstituent');
      var l     = elts.length;
      for (var i=0; i < l; i++) {
        elt = elts[i];
        if (elt.readAttribute('add') != 'true') { 
          elt.checked = false;
          elt.setAttribute('delete','false');
        }
      }
      Request.post('',url);
    },
    add_remove_all: function(list_id) { 
      if ($('add_remove_all').checked) { 
        List.add_all(list_id);
      } else {
        List.remove_all(list_id);
      }
    },
    set_functions: function(elts) {
      var l = elts.length;
      for (var i=0; i < l; i++) {
        var elt = elts[i];
        List.set_function(elt);
      }      
    },    
    set_function: function(el) { el.observe('click',List.update.bindAsEventListener(List)); },
    save_form: function() {
      $('save_form').show();
      $('buttons').hide();  
      $('list_name_field').focus();
    },
    cancel_save: function() {
      $('save_form').hide();
      $('buttons').show();      
    }, 
    take_action: function(list_id) { 
      var menu  = $('list_action'); 
      var val   = menu.getValue();
      if (val == 'save_list') { 
        $('save_form').show();
      } else if (val == 'add_all') { 
        List.add_all(list_id);
      } else if (val == 'remove_all') { 
        List.remove_all(list_id);
      } else if (val == 'update_tags') { 
        location.href = List.master_path + "/tag?source=" + source
      } else if (val == 'update_groups') { 
        location.href = List.master_path + "/group?source=" + source
      } else if (val == 'add_task') { 
        location.href = List.master_path + "/task?source=" + source
      } else { 
        // do nothing
      }
      menu.setValue('');
    }
  }
  
  var ListAction = {
    undo: function(id) {
      var form_id = 'undo_list_action_' + id;
      var message = 'Are you sure you want to undo this action? All of the associated tasks will be deactivated.';
      if (confirm(message)) {
        $(form_id).submit();
      }
    }
  }

  var Spinner = {
    set: function(id,text) {
      $(id).innerHTML = '<img tag="spinner" src="/images/spinning-circle.gif" /> ' + text;
    },
    hide: function() {
      $$('img[tag="spinner"]').each(function(el) {
        el.style.visibility = 'hidden';
      });
    }
  }

  var LGLCopy = { 
    from_to: function(from,to) {
      var f = $(from);
      var fprior = f.readAttribute('prior_value')
      to.each(function(to_id) {
        var t = $(to_id); 
        if (t) {
          var prior = t.readAttribute('prior_value')
          if (prior == null || prior == '' || fprior == prior) {
            t.value = f.value;
            t.value = f.value;
          }
        }
      });
    }
  }

  var GiftLink = {
    select: function(el) {
      GiftLink.clear_all();
      $(el).addClassName('Selected');
    },
    clear_all: function() {
      $$('a[tag="gift_link"]').each(function(el) {
        el.removeClassName('Selected');
      });
    },
    show_results: function(url,type,phase) { 
      var container = $('container_for_' + phase);
      if ($(container.style.display == 'none')) {
        Rows.hide_all('dyno');
        Request.get('',url); 
        $(type+ '_spinner_' + phase).style.visibility = 'visible';
        GiftLink.select($(type + '_link_for_' + phase));
      } else { 
        Rows.hide_all('dyno');
        GiftLink.clear_all();
      }
    }
  }
  
  var Work = {
    complete: function(id,view) {
      var close_url = '/works/' + id + '/mark_complete';
      close_url += '?source=' + source + "&view=" + view;
      Request.put('',close_url);
    },
    incomplete: function(id,view) {
      var incomplete_url = '/works/' + id + '/mark_incomplete';
      incomplete_url += '?source=' + source + "&view=" + view;
      Request.put('',incomplete_url);
    },
    cancel_complete: function(id) {
      var close_id   = 'closing_comment_for_work_' + id;    
      var input_id  = 'complete_work_' + id;
      $(input_id).checked = false;
      $(close_id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
      $(close_id).toggle();
      $('blackout').toggle();
    },
    edit_assignee: function(id) {
      var update_url  = '/works/' + id + '/edit_assignee';
      Request.get('', update_url);
    },
    show_assignee: function(id) {
      var update_id   = 'assignee_for_work_' + id;
      var update_url  = '/works/' + id + '/show_assignee';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    save_assignee: function(id) {
      var form_id     = 'form_for_assignee_for_work_' + id;
      LGLForm.remote_submit(form_id);
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/works/edit_constituent?obj_id=' + id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    },
    show_constituent: function(id) {
      var update_id   = 'constituent_for_work_' + id;
      var update_url  = '/works/' + id + '/show_constituent';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var work_id           = li.readAttribute('obj_id');
      var input_id          = "set_constituent_for_work_" + work_id;
      var url               = "/works/set_constituent?obj_id=" + work_id + "&constituent_id=" + constituent_id; 
      Request.get('',url)
    }
  }

  var VolunteerTime = { 
    edit_constituent: function(id,update_id) {
      var update_url  = '/volunteer_times/edit_constituent?obj_id=' + id;
      Request.get('', update_url);
    },
    show_constituent: function(id) {
      var update_id   = 'constituent_for_volunteer_time_' + id;
      var update_url  = '/volunteer_times/' + id + '/show_constituent';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var volunteer_time_id           = li.readAttribute('obj_id');
      var input_id          = "set_constituent_for_volunteer_time_" + volunteer_time_id;
      var url               = "/volunteer_times/set_constituent?obj_id=" + volunteer_time_id + "&constituent_id=" + constituent_id; 
      Request.get('',url)
    }
  }

  var ConstituentAutoComplete = { 
    search: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var constituent_field = $('constituent_id_value'); 
      constituent_field.value = constituent_id;
      var form              = $('constituent_auto_search_form');
      var url     = form.action; 
      var inputs  = form.getInputs();
      var l       = inputs.length;
      if (constituent_id != null && constituent_id != "") { 
       url = url + "/constituent/" + constituent_id;
      } else { 
       url = url + "/name/" + $('constituent_search_form_value').getValue(); 
      }
      location.href = url;
    }
  }

  var ConstituentRelationship = {
    show_constituent: function(id) {
      var update_id   = 'constituent_for_constituent_relationship_' + id;
      var update_url  = '/constituent_relationships/' + id + '/show_constituent';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/constituent_relationships/edit_constituent?obj_id=' + id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var obj_id            = li.readAttribute('obj_id');
      var update_id         = li.readAttribute('update_id');
      var focus             = li.readAttribute('focus');
      var field             = li.readAttribute('field');
      var url               = "/constituent_relationships/set_constituent?obj_id=" + obj_id + "&constituent_id=" + constituent_id; 
      url                   += "&update_id=" + update_id + "&field=" + field + "&focus=" + focus;
      Request.get('',url)
    }
  }

  var GiftBatch = {
    new_gift: function(id) {
      var url = "/gift_batches/" + id + "/new_gift";
      Request.get('',url);
    }
  }

  var Gift = {
    edit_assignee: function(id) {
      var update_url  = '/gifts/' + id + '/edit_assignee';
      Request.get('', update_url);
    },
    show_assignee: function(id) {
      var update_id   = 'assignee_for_gift_' + id;
      var update_url  = '/gifts/' + id + '/show_assignee';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    save_assignee: function(id) {
      var form_id     = 'form_for_assignee_for_gift_' + id;
      LGLForm.remote_submit(form_id);
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/gifts/edit_constituent?obj_id=' + id + "&update_id=" + update_id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    },
    show_constituent: function(id) {
      var update_id   = 'constituent_for_gift_' + id;
      var update_url  = '/gifts/' + id + '/show_constituent';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var gift_id           = li.readAttribute('obj_id');
      var update_id         = li.readAttribute('update_id');
      var focus             = li.readAttribute('focus');
      var field             = li.readAttribute('field');
      var input_id          = "set_constituent_for_gift_" + gift_id;
      var url               = "/gifts/set_constituent?obj_id=" + gift_id + "&constituent_id=" + constituent_id; 
      url                   += "&update_id=" + update_id + "&field=" + field + "&focus=" + focus;
      Request.get('',url)
    }
  }

  var Goal = {
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var goal_id           = li.readAttribute('obj_id');
      var input_id          = "set_constituent_for_goal_" + goal_id;
      var url               = "/goals/set_constituent?obj_id=" + goal_id + "&constituent_id=" + constituent_id; 
      Request.get('',url)
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/goals/edit_constituent?obj_id=' + id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    }
  }
  

  var Task = {
    complete: function(id) {
      var close_id = 'closing_comment_for_task_' + id;
      var close_url = '/tasks/confirm_complete/' + id;
      close_url += '?source=' + source;
      $(close_id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
      $(close_id).toggle();
      $('blackout').toggle();
      new Ajax.Updater(close_id, close_url, {asynchronous:true, evalScripts:true });      
    },
    cancel_complete: function(id) {
      var close_id   = 'closing_comment_for_task_' + id;    
      var input_id  = 'complete_task_' + id;
      $(input_id).checked = false;
      $(close_id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
      $(close_id).toggle();
      $('blackout').toggle();
    },
    edit_assignment: function(id) {
      var update_id   = 'assignment_for_tasks_' + id;
      var update_url  = '/tasks/edit_assignment/' + id;
      Request.get(update_id, update_url);
    },
    show_assignment: function(id) {
      var update_id   = 'assignment_for_tasks_' + id;
      var update_url  = '/tasks/show_assignment/' + id;
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    },
    save_assignment: function(id) {
      var form_id     = 'form_for_tasks_' + id;
      var update_url  = '/tasks/save_assignment/' + id;
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'put', 
        parameters:Form.serialize(form_id) });
    }
  }
 
  var Constituent = {
    set_required: function(input) {
      var form = input.up('form');
      if (input.checked) {
        form.select('input[name="constituent[org_name]"]').each(function(inp) {
          inp.setAttribute('required','true');
          inp.setAttribute('default',required_field_default);
          LGLForm.set(inp);
          if (inp.getValue() == inp.readAttribute('default')) {
            inp.addClassName('Required');
          }
        });
        form.select('input[name="constituent[first_name]"]').each(function(inp) {
          inp.removeAttribute('required');
          inp.removeClassName('Required');
          LGLForm.clear(inp);
        });
        form.select('input[name="constituent[last_name]"]').each(function(inp) {
          inp.removeAttribute('required');
          inp.removeClassName('Required');
          LGLForm.clear(inp);
        });
        form.select('tr[show="individual"]').each(function(tr) { tr.style.display = 'none' });
        LGLForm.check_required(form);
      } else {
        form.select('input[name="constituent[org_name]"]').each(function(inp) {
          inp.removeAttribute('required');
          inp.removeClassName('Required');
          LGLForm.clear(inp);
        });
        form.select('input[name="constituent[first_name]"]').each(function(inp) {
          inp.setAttribute('required','true');
          inp.setAttribute('default',required_field_default);
          LGLForm.set(inp);
          if (inp.getValue() == inp.readAttribute('default')) {
            inp.addClassName('Required');
          }
        });
        form.select('input[name="constituent[last_name]"]').each(function(inp) {
          inp.setAttribute('required','true');
          inp.setAttribute('default',required_field_default);
          LGLForm.set(inp);
          if (inp.getValue() == inp.readAttribute('default')) {
            inp.addClassName('Required');
          }
        });
        form.select('tr[show="individual"]').each(function(tr) { tr.style.display = '' });
        LGLForm.check_required(form);
      }
    },
    set_form: function(name) { 
      var url = '/constituents/' + name;
      if ($('set_is_org') && $('set_is_org').checked) {
        url += "?is_org=1";
      }
      Request.get('',url);
    }
  }

  var Signup = {
    validate: function(input) {
      if (input.checked) {
        $('submit_button').enable();
      } else {
        $('submit_button').disable();
      }
    }
  }

  var LGLForm = {
    blur: function(event) {
      var input = Event.element(event);
      if (input.value.match(/^\s*$/)) {
        LGLForm.set(input);
        input.addClassName('Empty');
        if (input.readAttribute('required') == 'true') {
          input.addClassName('Required');
        }
      }
      if (input.readAttribute('required') == 'true') {
        LGLForm.check_required(input.up('form'));
      }
    },
    keypress: function(event) {
      var input = Event.element(event);
      if (input.readAttribute('required') == 'true') {
        LGLForm.check_required(input.up('form'));
      }
    },
    focus: function(event) {
      var input = Event.element(event);
      if (input.hasClassName('Empty')) {
        LGLForm.clear(input);
        input.removeClassName('Empty');
        input.removeClassName('Required');

        if (input.readAttribute('required') == 'true') {
          LGLForm.check_required(input.up('form'));
        }
      }       
    },
    set: function(input) {
      var value = input.readAttribute('default');
      var current = input.getValue();
      if (current.match(/^\s*$/)) { LGLForm.set_value(input,value); }
    },
    check_required: function(form) {
      var inputs  = form.select('*[required="true"]');
      var l = inputs.length;
      var enabled = true;
      inputs.each(function(input) {
        var def   = input.readAttribute('default');
        var val   = input.getValue();
        if (def != val && val != '' && enabled) {
          enabled = true;
        } else { 
          enabled = false;
        }
      });     
      LGLForm.toggle_saves(form,enabled);
      return enabled;
    },
    toggle_saves: function(form,enabled) {
      var saves   = form.select('input[save="true"]'); 
      saves.each(function(s) {
        if (enabled) {
          s.enable();
        } else {
          s.disable();
        }
      });
    },
    clear: function(input) {
      var value = input.readAttribute('default');
      var current = input.getValue();      
      if (current == value) { LGLForm.set_value(input,''); }       
    },
    get_value: function(input) {
      var type  = input.nodeName;
      if (type == 'TEXTAREA') {
        var value = input.innerHTML;
        return value;
      } else if (type == 'INPUT') {
        return input.value;
      }      
    },
    set_value: function(input,value) {
      if (value != null && value != 'null') {
        var type  = input.nodeName;
        if (type == 'TEXTAREA') {
          input.innerHTML = value;
        } else if (type == 'INPUT') {
          input.value = value;
        }
      }
    },
    observe_all: function() {
      LGLForm.observe($$('.Field'));
    },
    observe: function(inputs) {
      var l = inputs.length;
      for (var i=0; i < l; i++) {
        var input = inputs[i];
        if (input.readAttribute('required') == 'true') {
          if(input.value.match(/^\s*$/)) {
            input.addClassName('Required');
          }
        }
        LGLForm.set(input);
        input.observe('blur',LGLForm.blur.bindAsEventListener(LGLForm));
        input.observe('focus',LGLForm.focus.bindAsEventListener(LGLForm));
        input.observe('keypress',LGLForm.keypress.bindAsEventListener(LGLForm));
      }       
      LGLForm.check_required(inputs.first().up('form'));
    },
    submit: function(form) {
      LGLForm.clear_all(form);
      form.submit();
    },
    remote_submit: function(id) {
      var form = $(id);
      LGLForm.clear_all(form);
      var update_url  = form.readAttribute('action');
      new Ajax.Request(update_url, {
        asynchronous:true,
        evalScripts:true, 
        parameters:Form.serialize(id) });      
    },
    clear_all: function(form) {
      if ($(form)) { 
        var empties = $(form).getElementsByClassName('Field');
        var l = empties.length;
        for (var i=0; i < l; i++) {
          var input = empties[i];
          LGLForm.clear(input);
        }
        LGLForm.deactivate_saves(form)
      }
    },
    deactivate_saves: function(form) { 
      if ($(form)) { 
        $(form).select('input[save="true"]').each(function(inp) { inp.disable(); });
      }
    },
    select_date_type: function(obj_type,date_field,id) {
      var selector_id   = date_field + '_selector_for_' + obj_type + '_' + id;
      var date_field_id = date_field + '_for_' + obj_type + '_' + id;
      var val   = $(selector_id).getValue();
      if (val == 'custom') {
        $(date_field_id).show();
      } else {
        $(date_field_id).hide();
      }
    }
  }

  var GiftType = {
    current_focus: "",
    blur: function(event) {
      var input = Event.element(event);
      GiftType.current_focus = "";
      GiftType.set_installments();
    },
    focus: function(event) {
      var input = Event.element(event);
      GiftType.current_focus = input.readAttribute("name");
      GiftType.set_installments();
    },
    type_change: function() {
      var typ_val   = $('gift_type_select').getValue();
      $('gift_type_select').insert({after: loading_html()});
      var camp_val  = $('campaign_select').getValue();
      var fund_val  = $('fund_select').getValue();
      var tm_val    = $('team_member_select').getValue();
      var amount    = $('gift_amount').getValue();
      var form      = $('gift_amount').up('form');
      var note      = $('gift_note').getValue();
      var url       = "/gifts/set_form?gift[goal_state_id]=" + typ_val + '&gift[received_amount]=' + amount + '&gift[note]=' + note;
      url          += "&gift[campaign_id]=" + camp_val + "&gift[fund_id]=" + fund_val + "&gift[assigned_to]=" + tm_val + "&source=" + source;
      var con       = $(form['gift[constituent_id]']);
      if (con != null) { 
        url += "&gift[constituent_id]=" + con.getValue();
      }
      Request.post('',url);
    },
    toggle_related: function() {
      var id = $('gift_type_select').getValue();
      var related = $('related_gifts');
      var pledges = related.select('input[gift_type="13"]');
      if (id == '7') { 
        pledges.each(function(p) { p.disable(); p.checked = false; $('related_for_gift_' + p.value).hide() })
      } else { 
        pledges.each(function(p) { p.enable(); $('related_for_gift_' + p.value).show() })
      }
      return true;
    },
    activate_pledge_fields: function() { 
      $('pledge_options').select('input').each(function(p) { 
        p.setAttribute('required','true');
        if (p.readAttribute('default') == null) { p.setAttribute('default', required_field_default) }
        LGLForm.set(p);
        if (p.getValue() == p.readAttribute('default')) { p.addClassName('Required') }
      }) 
    },
    deactivate_pledge_fields: function() { 
      $('pledge_options').select('input').each(function(p) { 
        p.removeAttribute('required');
        p.removeClassName('Required');
        LGLForm.clear(p); 
      })
    },
    set_installments: function() { 
      var ga   = $('gift_amount').getValue();
      var has_ga = (ga != '' || $('gift_amount').readAttribute('name') == GiftType.current_focus); 
      var gpi  = $('gift_payment_interval').getValue();
      var dp   = $('pledge_options').select('input')[0]
      var rpa  = $('received_pledge_amount').getValue();
      var dpv  = dp.getValue();
      var has_dpv = (dpv != '' || dp.readAttribute('name') == GiftType.current_focus); 
      var ia   = $('payment_amount').getValue();
      var has_ia = (ia != '' || $('payment_amount').readAttribute('name') == GiftType.current_focus); 
      if (gpi == 'O') { 
        $('installments_list').innerHTML = '';
        $('add_installments').hide();
        $('interval_amount').hide();
        $('interval_date').show();
        $('interval_date').select('div[class="Label"]').each(function(div) { 
          if (div.readAttribute('type') == 'interval') { 
            div.hide();
          } else { 
            div.show(); 
          } } ); 
      } else if (gpi == 'N') { 
        $('add_installments').hide();
        $('interval_amount').hide();
        $('interval_date').hide();
      } else {
        $('interval_amount').show();
        $('interval_date').show();
        $('interval_date').select('div[class="Label"]').each(function(div) { 
          if (div.readAttribute('type') == 'one-time') { 
            div.hide();
          } else { 
            div.show(); 
          } } ); 
      }
      if (gpi != 'O' && has_ga && has_dpv && has_ia) {
        $('installments_container').show();
        $('add_installments').show();
      } else { 
        $('add_installments').hide();
      }
      return true;
    }
  }
 
  var User = {
    change: function() {
      var user  = $('selected_user_field').getValue();
      var url   = '/users'
      if (user == 'all') {
        Cookie.set('calendar_user','all');
      } else if (user != null && user.length > 0) {
        Cookie.set('calendar_user',user);
        url += '/' + user; 
      }
      location.href = url; 
    },
    set_constituent: function(li) {
      var constituent_id    = li.readAttribute('constituent_id');
      var obj_id            = li.readAttribute('obj_id');
      var url               = "/users/set_constituent?obj_id=" + obj_id + "&constituent_id=" + constituent_id; 
      Request.get('',url)
    },
    edit_constituent: function(id,update_id) {
      var focus_id = $(update_id).readAttribute('focus_id'); 
      var update_url  = '/users/edit_constituent?obj_id=' + id + '&focus_id=' + focus_id;
      Request.get('', update_url);
    },
    show_constituent: function(id) {
      var update_id   = 'constituent_for_user_' + id;
      var update_url  = '/users/' + id + '/show_constituent';
      new Ajax.Request(update_url, {
        asynchronous:true, 
        evalScripts:true, 
        method:'get' });
    }
  }

  var Dashboard = { 
    set_user: function() { 
      var _id = $('filter_by_user_id').getValue();
      var url = $('filter_by_user_url').getValue();
      if (_id != null && _id.length > 0) {
        url += '/' + 'user' + '/' + _id;
      }
      Cookie.set('dashboard_activity_user',_id);
      Request.get('',url);
    }
  }
  
  var Filter = {
    user: function() {
      Filter.param('user')
    },
    steward: function() {
      Filter.param('steward')
    },
    list: function() {
      Filter.param('list')
    },
    appeal: function() {
      Filter.param('appeal')
    },
    event: function() {
      Filter.param('event')
    },
    fund: function() {
      Filter.param('fund')
    },
    param: function(p) {
      var _id = $('filter_by_' + p + '_id').getValue();
      var url = $('filter_by_' + p + '_url').getValue();
      if (_id != null && _id.length > 0) {
        url += '/' + p + '/' + _id;
      }
      location.href = url;
    },
    remote_param: function(p) {
      var _id = $('filter_by_' + p + '_id').getValue();
      var url = $('filter_by_' + p + '_url').getValue();
      if (_id != null && _id.length > 0) {
        url += '/' + p + '/' + _id;
      }
      Request.get('',url);
    },
    rating: function() {
      Filter.param('capacity')
    },
    interest: function() {
      Filter.param('interest')
    },
    show_more: function(type) {
      $('hide_href').show();
      $('more_filters').show();
      $('show_more_href').hide();
      var key = type + '_filters';
      Cookie.set(key, 'show', 1);
    },
    hide_more: function(type) {
      $('hide_href').hide();
      $('more_filters').hide();
      $('show_more_href').show();
      var key = type + '_filters';
      Cookie.set(key, 'hide', 1);
    }
  }

  var GroupBar = { 
    open: function(key) { 
      Opener.open(key);
    },
    close: function(key) {
      Opener.close(key);
    }
  }

  var Opener = {
    open: function(key) { 
      $(key + "_opener").hide();
      $(key + "_closer").show();
      $(key).show();
      Cookie.set(key + '_state', 'open', 1);
    },
    close: function(key) {
      $(key + "_opener").show();
      $(key + "_closer").hide();
      $(key).hide();
      Cookie.set(key + '_state', 'closed', 1);
    }
  }

  var BrowseBy = { 
    base_url: '',
    search_url: '',
    klass: '',
    open: function(key) { 
      $(key + "_opener").hide();
      $(key + "_closer").show();
      if ($(key + '_spinner')) { 
        var url  = '/get_filter?base_url=' + BrowseBy.base_url + '&klass=' + BrowseBy.klass;
        url     += '&search_url=' + BrowseBy.search_url + '&key=' + key;
        Request.get('',url);
      } 
      $(key).show();
      Cookie.set(key + '_state', 'open', 1);
    },
    close: function(key) {
      $(key + "_opener").show();
      $(key + "_closer").hide();
      $(key).hide();
      Cookie.set(key + '_state', 'closed', 1);
    }
  }

  var MoreLess = { 
    close: function(key) { 
      $('more_' + key).hide(); 
      $('show_more_' + key).show(); 
      Cookie.set(key + '_more_state', 'closed', 1);
    },
    open: function(key) { 
      $('more_' + key).show(); 
      $('show_more_' + key).hide(); 
      Cookie.set(key + '_more_state', 'open', 1);
    }
  }

  var Node = { 
    set_state: function(key) {
      var el = $(key);
      if (el.visible()) {
        el.hide();
        Cookie.set(key, 'closed', 1);
      } else {
        el.show();
        Cookie.set(key, 'open', 1);
      }
    }
  }

  var MenuButton = {
    toggle: function(id) {
      var b       = $('button_for_' + id);
      var a       = $('actions_for_' + id);
      var offset  = b.getDimensions().width - a.getDimensions().width;
      var left    = b.positionedOffset()[0];
      var ll      = offset + left;
      if (a.style.left == '') { 
        a.setStyle({ left: ll + 'px' })
      }
      if (a.style.display == '') { 
        a.style.display = 'none';
      } else { 
        a.style.display = '';
      }
    }
  }
  
  var Notice = {
    fade: function() {
      $('notice_message').fade({duration: 3.0});
      $('notice_message_show').appear();
    },
    show: function() {
      $('notice_message_show').fade();
      $('notice_message').appear();
    },
    hide: function() {
      $('notice_message_show').appear();
      $('notice_message').fade();      
    }
  }

  var Affiliation = {
    menu_change: function(id) {
      var constituent_id = id.split('_').last();
      var val   = $(id).getValue();
      var url   = '/affiliations/'
      if (val == 'new') {
        url += 'new?constituent_id=' + constituent_id;
        Request.get('',url);
      } else if (val == '') { 
      
      } else {
        url += 'create?affiliation[constituent_id]=' + constituent_id 
        url += '&affiliation[affiliation_type_id]=' + val;
        Request.post('',url);
      }
    }
  }

  var GiftParams = { 
    set: function(type) { 
      var campaign  = $('campaign_select').getValue();
      var fund      = $('fund_select').getValue();
      var appeal    = $('appeal_select').getValue();
      var ev        = $('event_select').getValue();
      var url       = '/campaigns/set_values?type=' + type + '&campaign_id='; 
      url           += campaign + "&fund_id=" + fund;
      url           += '&appeal_id=' + appeal + '&event_id=' + ev;
      Request.get('',url);
    }
  }

  var ShowHide = {
    observers: {},
    over: function(event) {
      var el            = $(Event.element(event));
      var sh            = el.readAttribute('show_hide');
      if (sh != 'true') { 
        el = el.up('div[show_hide="true"]')
      }
      var id = el.readAttribute('id');
      var edit_id = 'edit_' + id;
      if ($(edit_id)) { $(edit_id).style.visibility = 'visible'; }
    },
    out: function(event) {
      var el            = $(Event.element(event));
      var sh            = el.readAttribute('show_hide');
      if (sh != 'true') { 
        el = el.up('div[show_hide="true"]')
      }
      var id = el.readAttribute('id');
      var edit_id = 'edit_' + id;
      if ($(edit_id)) { $(edit_id).style.visibility = 'hidden'; }
    },
    init_all: function() {
      $$('*[show_hide="true"]').each(function(el) {
        $(el).observe('mouseover',ShowHide.over.bindAsEventListener(ShowHide));
        $(el).observe('mouseout',ShowHide.out.bindAsEventListener(ShowHide));
      });
    }
  }

  var Rows = {
    open: function(id) {
      var opener  = $(id + "_opener");
      var closer  = $(id + "_closer");
      Cookie.set(id+'_state','open');
      closer.style.display = '';
      opener.style.display = 'none';
      $$('tr[tag="' + id + '"]').each(function(el) {
        el.style.display = '';
      });
    },
    close: function(id) {
      var opener  = $(id + "_opener");
      var closer  = $(id + "_closer");
      Cookie.set(id+'_state','closed');
      opener.style.display = '';
      closer.style.display = 'none';
      $$('tr[tag="' + id + '"]').each(function(el) {
        el.style.display = 'none';
      });
    },
    hide_all: function(item) {
      $$('tr[tag="' + item + '"]').each(function(el) {
        el.style.display = 'none';
      });
    }
  }

  

  var ConstituentEdit = {
    observers: {},
    over: function(event) {
      var el            = $(Event.element(event));
      var id            = el.readAttribute('id');
      if ((id == -1) || (id =~ /container/)) { el = el.up('div') }
      id            = el.readAttribute('id');
      var container_id  = el.readAttribute('container_id');
      var external_id   = el.readAttribute('external_id');
      var obj_id        = el.readAttribute('obj_id');
      var field         = el.readAttribute('field');
      var rows          = el.readAttribute('rows') || 1;
      var cols          = el.readAttribute('cols') || 30;
      var edit_id = 'edit_' + id;
      if ($(edit_id)) { $(edit_id).style.visibility = 'visible'; }
      if (container_id && ConstituentEdit.observers[container_id] == null) {
        ConstituentEdit.observers[container_id] = 1;
        new Ajax.InPlaceEditor(container_id, '/constituents/' + obj_id + '/save_field', {
          autoRows: 1,
          rows: rows,
          cols: cols,
          loadTextURL: '/constituents/' + obj_id + '/read_field?name=' + field,
          externalControl: external_id,
          highlightEndColor: '#FFFFFF',
          highlightColor: '#FFFFFF',
          hoverClassName: 'inPlaceHover',
          okText: 'Save'
        });
      }
    },
    out: function(event) {
      var el            = $(Event.element(event));
      var id            = el.readAttribute('id');
      if ((id == -1) || (id =~ /container/)) { el = el.up('div') }
      id            = el.readAttribute('id');
      var edit_id = 'edit_' + id;
      if ($(edit_id)) { $(edit_id).style.visibility = 'hidden'; }
    },
    init_all: function() {
      $$('*[constituent_field_edit="true"]').each(function(el) {
        $(el).observe('mouseover',ConstituentEdit.over.bindAsEventListener(ConstituentEdit));
        $(el).observe('mouseout',ConstituentEdit.out.bindAsEventListener(ConstituentEdit));
      });
    }
  }


  // Conditional getters and setters
  function hide_if_present(id) { if ($(id)) { $(id).hide(); } }
  function show_if_present(id) { if ($(id)) { $(id).show(); } }
  function disable_if_present(id) { if ($(id)) { $(id).disable(); $(id).value = ''; } }
  function enable_if_present(id) { if ($(id)) { $(id).enable(); } }
  function get_value_if_present(id) { if ($(id)) { $(id).getValue(); } }

  function loading(id) {
    $(id).innerHTML = '<img src="/images/spinning-circle.gif" />';
  }
  
  function loading_html() {
    html = '&nbsp; <img src="/images/spinning-circle.gif" />';
    return html;
  }

  function complete(id) {
    $(id).hide();  
  }
  
  function reset_container(id) {
    $(id).innerHTML = '';
  }
  
  function reset_and_hide_container(id) {
    reset_container(id);
    $(id).hide();
  }
  
  function show_blackout_with_id(id) {
    show_blackout();
    $(id).show();
  }
  
  function hide_blackout_with_id(id) {
    hide_blackout();
    $(id).hide();   
    $(id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
  }
  
  function show_blackout() {
    $('blackout').show();    
  }
  
  function hide_blackout() {
    $('blackout').hide();    
  }
  
  var attachment_count = 0;
  function add_attachment(id) {
    var attachment_id = 'attachments_' + attachment_count 
    var html = '<div id="' + attachment_id + '"><input type="file" name="attachments[]" />'
    html += '<span="types_for_' + attachment_id + '"></span> ' + remove_html(attachment_id) + '</div>';
    new Insertion.Bottom(id,html);
    Request.get('','/document_types/show_types?attachment_id='+attachment_id);
    attachment_count++;
  }
  
  function edit_attachment(id) {
    var dom_id    = 'edit_attachment_' + id;
    var url       = '/attachments/' + id + '/edit';
    url       += '?source=' + source;
    $(dom_id).show();
    show_blackout();
    new Ajax.Updater(dom_id, url, { asynchronous:true, method:'get', evalScripts:true, onLoading:function(request){ loading(close_id); } });
  }  
  
  function cancel_edit_attachment(id)  {
    var dom_id    = 'edit_attachment_' + id;
    $(dom_id).innerHTML = '';
    $(dom_id).hide();
    hide_blackout();
  }

  function edit_comment(id) {
    var dom_id    = 'edit_comment_' + id;
    var url       = '/comments/' + id + '/edit';
    url       += '?source=' + source;
    $(dom_id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
    $(dom_id).show();
    show_blackout();
    new Ajax.Updater(dom_id, url, { asynchronous:true, method:'get',  evalScripts:true,onLoading:function(request){ loading(close_id); } });
  }  
  
  function cancel_edit_comment(id)  {
    var dom_id    = 'edit_comment_' + id;
    $(dom_id).innerHTML = '';
    $(dom_id).hide();
    hide_blackout();
  }  
  
  function edit_note(id) {
    var dom_id    = 'edit_note_' + id;
    var url       = '/notes/' + id + '/edit';
    url       += '?source=' + source;
    $(dom_id).innerHTML = '<img src="/images/spinning-circle-large.gif" />';
    $(dom_id).show();
    show_blackout();
    new Ajax.Updater(dom_id, url, { asynchronous:true, method:'get',  evalScripts:true,onLoading:function(request){ loading(close_id); } });
  }  
  
  function cancel_edit_note(id)  {
    var dom_id    = 'edit_note_' + id;
    $(dom_id).innerHTML = '';
    $(dom_id).hide();
    hide_blackout();
  }  
  
  var task_count = 0;
  function add_task() {
    var form_id   = 'tasks_' + task_count;
    var url       = '/tasks/followup?header=false&form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    task_count++;
  }  

  var work_count = 0;
  function add_work() {
    var form_id   = 'works_' + work_count;
    var url       = '/works/followup?header=false&form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    work_count++;
  }  

  var volunteer_time_count = 0;
  function add_volunteer_time() {
    var form_id   = 'volunteer_times_' + volunteer_time_count;
    var url       = '/volunteer_times/new_time?header=false&form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    volunteer_time_count++;
  }  

  var segment_count = 0;
  function add_segment() {
    var form_id   = 'segments_' + segment_count;
    var url       = '/segments/followup?header=false&form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    segment_count++;
  }  

  var soft_credit_count = 0;
  function add_soft_credit() {
    var form_id   = 'soft_credits_' + soft_credit_count;
    var url       = '/gifts/add_soft_credit?form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    soft_credit_count++;
  }  

  var gift_count = 0;
  function add_gift() {
    var form_id   = 'gifts_' + gift_count;
    var url       = '/gifts/add_gift?form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    gift_count++;
  }  

  var installment_count = 0;
  function add_installmentz(id) {
    var url       = '/gifts/add_installments?';
    url           += 'gift_amount=' + $('gift_amount').getValue();
    url           += '&received_pledge_amount=' + $('received_pledge_amount').getValue();
    url           += '&pledge_start_date=' + $(id).getValue();
    url           += '&payment_interval=' + $('gift_payment_interval').getValue();
    url           += '&payment_amount=' + $('payment_amount').getValue();
    url           += '&write_off_amount=' + $('write_off_amount').getValue();
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    installment_count++;
  }  

  function add_one_installment() {
    var form_id   = 'installments_' + installment_count;
    var url       = '/gifts/add_installment?form_id=' + form_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    installment_count++;
  }  
  
  var email_count = 0;
  function add_email() {
    var email_id  = 'emails_' + email_count;
    var url       = '/contact_information/new_email_address?form_id=' + email_id;
    if ($('set_is_org') && $('set_is_org').checked) { url += "&is_org=1" }
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    email_count++;
  }  

  function set_alternating_css(id) {
    var s = 'even';
    $(id).select('*[item="row"]').each(function(el){
      s   = s == 'even' ? 'odd' : 'even';
      el.removeClassName('even');
      el.removeClassName('odd');
      el.addClassName(s);
    });
  }
  
  var phone_count = 0;
  function add_phone() {
    var phone_id = 'phones_' + phone_count;
    var url       = '/contact_information/new_phone_number?form_id=' + phone_id;
    if ($('set_is_org') && $('set_is_org').checked) { url += "&is_org=1" }
    new Ajax.Updater('', url, { asynchronous:true, method:'get', evalScripts:true });
    phone_count++;
  }

  var street_address_count = 0;
  function add_street_address() {
    var street_address_id = 'street_addresss_' + street_address_count;
    var url       = '/contact_information/new_street_address?form_id=' + street_address_id;
    if ($('set_is_org') && $('set_is_org').checked) { url += "&is_org=1" }
    new Ajax.Updater('', url, { asynchronous:true, method:'get', evalScripts:true });    
    street_address_count++;
  }

  var web_address_count = 0;
  function add_web_address() {
    var web_address_id = 'web_addresss_' + web_address_count;
    var url       = '/contact_information/new_web_address?form_id=' + web_address_id;
    new Ajax.Updater('', url, { asynchronous:true, method:'get', evalScripts:true });    
    web_address_count++;
  }

  var school_tie_count = 0;
  function add_school_tie() {
    var school_tie_id = 'school_ties_' + school_tie_count;
    var url           = '/school_ties/new?form_id=' + school_tie_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    school_tie_count++;
  }  

  var member_tie_count = 0;
  function add_member_tie() {
    var member_tie_id = 'member_ties_' + member_tie_count;
    var url           = '/member_ties/new?form_id=' + member_tie_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    member_tie_count++;
  }  

  var school_count = 0;
  function add_school() {
    var school_id = 'schools_' + school_count;
    var url           = '/schools/new?form_id=' + school_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    school_count++;
  }  

  var constituent_relationship_count = 0;
  function add_constituent_relationship(const_id) {
    var constituent_relationship_id = 'constituent_relationships_' + constituent_relationship_count;
    var url           = '/constituent_relationships/new?form_id=' + constituent_relationship_id;
    url += "&constituent_id=" + const_id;
    new Ajax.Updater('',url, { asynchronous:true, method:'get', evalScripts:true });
    constituent_relationship_count++;
  }  

  function remove_html(id) {
    var html = '<a href="" onclick="Element.remove(\'' + id + '\'); return false;">';
    html += '<img src="/images/delete.png" /></a>';
    return html;
  }
  
  function add_hidden_field(form, name, value) {
    var s = document.createElement('input'); s.setAttribute('type', 'hidden');
    s.setAttribute('name', name); s.setAttribute('value', value);
    form.appendChild(s);    
  }
 
  var Role = {
    select: function() {
      var val   = $('roles_for_sharing').getValue();
      Role.disable('notifications')
      val.split('/').each(function(id) { if (id != '' && id != null) { Role.enable('notify_role_' + id) } });
    },
    set_notification: function(selector_id) {
      var user_id = $(selector_id).getValue();
      if (user_id != null && user_id != "") {
        $('notifications').select('input[name="recipients[]"]').each(function(n) { 
          if (n.value == user_id) { n.disabled=false; n.checked=true} 
      });
      }
    },
    enable: function(id) {
      $(id).select('input[name="recipients[]"]').each(function(n) { n.disabled=false });
    },
    disable: function(id) {
      $(id).select('input[name="recipients[]"]').each(function(n) { if (!n.checked) { n.disabled=true; n.checked=false } });
    }
  }

  function set_notify_all(section_id, value, checked) {
    var section     = $("notify_" + section_id);
    var all_name    = "all_" + section_id;
    var elements    = section.select('input[name="recipients[]"]');
    var selectAll   = false;
    var isAll       = false;
    if (value == all_name) { isAll = true; } 
    if (isAll && checked) {
      selectAll = true ;
    } else {
      selectAll = false;
    }
    
    for (var i = 0; i < elements.length; i++) {
      var el = elements[i];
      if (isAll) {
        el.checked = selectAll;
      } else {
        if (!checked && el.value == all_name) {
          el.checked = false;
        }
      }
    }
  }
  
  function toggle_conditionally(id) {
    if ($(id)) { $(id).toggle(); }
  }
 
function insertField(target_id,value_id) { 
  var target  = $(target_id); 
  var value   = $(value_id).getValue();
  insertAtCursor(target,value);
  $(value_id).value = "";
}

function insertValue(target_id,value) { 
  tinyMCE.execCommand('mceInsertContent', false, value);
}

function insertAtCursor(myField, myValue) {
  //IE support
  if (document.selection) {
      myField.focus();

      //in effect we are creating a text range with zero
      //length at the cursor location and replacing it
      //with myValue
      sel = document.selection.createRange();
      sel.text = myValue;

  //Mozilla/Firefox/Netscape 7+ support
  } else if (myField.selectionStart || myField.selectionStart == '0') {

      myField.focus();
      //Here we get the start and end points of the
      //selection. Then we create substrings up to the
      //start of the selection and from the end point
      //of the selection to the end of the field value.
      //Then we concatenate the first substring, myValue,
      //and the second substring to get the new value.
      var startPos = myField.selectionStart;
      var endPos = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
      myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
  } else {
      myField.value += myValue;
  }
}

function set_focus_for(id) { 
  if ($(id)) {
    var focus_id = $(id).readAttribute('focus_id');
    if (focus_id != null && focus_id != '' && $(focus_id)) { 
      $(focus_id).focus(); 
    }
  }
}

function toggle_menu(id) {	$(id).toggle(); }
function open_menu(id) {	$(id).show(); }
function close_menu(id) { $(id).hide(); }

function toggle_checkbox(id) { 
  if($(id).checked) {
    $(id).checked = false; 
  } else {
    $(id).checked = true; 
  }
}


var TextAreaResize = Class.create();
TextAreaResize.prototype = {
    initialize: function(element, options) {
        this.element = $(element);        
        this.options = Object.extend({maxRows: 50}, options || {} );

        Event.observe(this.element, 'keyup', this.onKeyUp.bindAsEventListener(this));
        this.onKeyUp();
    },

    /*
    * PUBLIC FUNTIONS
    */    
    onKeyUp: function() {        
        while (this.element.scrollHeight > this.element.offsetHeight && this.element.rows < this.options.maxRows) {
            if (this.element.rows < this.options.maxRows) {
                this.element.rows = this.element.rows + 1;
            }
        }
    }
};

