var Search = {
  go:function(e){
    var form = Event.element(e);
    form.action = '/';
    form.select('select').each(function(input){
      if(/choose|search/i.test(input.value) || input.value.blank()) return;
      form.action += input.value + '/';
    });
    if(form.action == '') form.action = '/schools';
    form.action = form.action.gsub(/\/$/,'')
    return true
  }
}

Event.observe(window,'load',function(){

});

//==================

var Lead = {
  submit:function(){
    
    if($F('lead_client_id').blank()){
      var ids = $$('.client_checkbox input[value=1]').map(function(cb){
        return cb.up('.search_item').id.gsub(/client_/,'');
      }).join(',');
      
      if(ids.blank()) {
        alert('Please select one or more schools, thank you.');
        return false;
      }
      
      $('lead_client_id').value = ids;
    }
    
    return true;
  },
  select:function(on){
    $$('.client_checkbox input').each(function(cb){cb.checked = on;})
  }
}

// ================

function normalizeHeights(){
  //standard
  try{
    var max = $$('.standard_wr .search_item .content').invoke("getHeight").max() + 50;
    $$('.standard_wr .search_item').invoke("setStyle","height:"+max+'px');
  } catch(e){};

  //third-tier
  try{
    var max = $$('.third_tier_wr .search_item .content').invoke("getHeight").max() + 50;
    $$('.third_tier_wr .search_item').invoke("setStyle","height:"+max+'px');
  } catch(e){};
  
}

// =================

function validate_form(el){
  
  $('form_status').update();
  
  var valid = $('multi') && check_school_selection(el);
  
  if(!Val.validate('request_form', {messages:'alert', custom:true})){
    valid = false;
    add_form_error("Please correct the missing information highlighted in red above.");
  }

  if(!valid){
    try{$$('.validate_error').first().focus()}catch(e){}
    $(el).value = '';
  } else {
    add_form_error('Please wait...')
  }
  
  return valid;
}

function check_school_selection(el) {
  var selected = $(el).up('form').select('input[name="lead[client_ids][]"]:checked').length;

  if(selected > 10){
    add_form_error('We allow a maxium of 10 schools per selection. Please limit the schools of interest to 10 and re-submit your information.');
    return false;
  } else if(selected == 0){
    add_form_error('Please select a school.');
    return false;
  }
    
  return true;
}

function add_form_error(txt){
  $('form_status').insert('<div class="form_fail_message">'+txt+'</div>');
}

function submit_error(msg){
  $('form_status').update(msg);
  $('form_status').previous().disabled = false;
  $('form_status').previous().value = '';
}