function fadeFlash() { if ($('flash')) {setTimeout('$("flash").fade({duration:1.5})', 3000);} }

  function $onload(func) {
      document.observe('dom:loaded', func)
  }


document.observe('dom:loaded', fadeFlash.bind(this));


AddressForm = Class.create({

  initialize: function(prefix, handle_mapping) {
    this.checkbox       = $('same');
    this.handle_mapping = handle_mapping;
    this.mailing_county = $(prefix+'address_attributes_county_id');
    this.mailing_state  = $(prefix+'address_attributes_state_id');
    this.mapping_county = $(prefix+'map_address_attributes_county_id');
    this.mapping_state  = $(prefix+'map_address_attributes_state_id');
    this.county_selects = {};
    this.observe_dom();
  },

  observe_dom: function() {
    if (this.handle_mapping) {
      document.observe('dom:loaded', this.observe_checkbox.bind(this));
    }
    document.observe('dom:loaded', this.observe_state_selection.bind(this));
  }, 
  
  observe_checkbox: function() {
    this.checkbox.observe('change', function() {
      if (this.checkbox.checked) {
        $$('#mailing-address input[type=text]').each(function(item) {
          var map_address_id = item.identify().replace(/business_address/i, 'business_map_address');
          $(map_address_id).value = item.value;
        });
        this.mapping_state.options[this.mailing_state.selectedIndex].selected = true;
        this.update_select(this.mapping_state);
        this.mapping_county.options[this.mailing_county.selectedIndex].selected = true;
      }
    }.bind(this));
  },
  
  observe_state_selection: function() {
    this.mailing_state.observe('change', this.update_counties.bind(this));
    this.update_select(this.mailing_state);

    if (this.handle_mapping) {
      this.mapping_state.observe('change', this.update_counties.bind(this));
      this.update_select(this.mapping_state);
    }
  },
  
  update_counties: function(selection_event) {
    this.update_select(Event.element(selection_event));
  },
  
  update_select: function(select_element) {
    var county_select  = $(select_element.identify().replace(/state/i, 'county'));
    county_select.update(this.county_selects[select_element.options[select_element.selectedIndex].value]);
		
	  current_county = $('current_county_id');
		current_map_county = $('current_map_county_id');
		console.log(current_county);
		
		if(current_county)
		{
			current_county_id = current_county.getValue();
			options = county_select.options;
			
			for(var i = 0; i < options.length; i++)
			{
				if(options[i].value == current_county_id)
					options[i].selected = true;
					
			}
		}
		if(current_map_county)
		{
			current_map_county_id = current_map_county.getValue();
			options = county_select.options;
			
			for(var i = 0; i < options.length; i++)
			{
				if(options[i].value == current_map_county_id)
					options[i].selected = true;
					
			}
		}
  },
  
  add_counties_for: function(state, counties) {
    this.county_selects[state] = counties;
  }
  
});

AddressForm.toggle = function(div_one, div_two) {
  $(div_one).toggle();
  $(div_two).toggle();
}

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(/.*#/, '.')
    el.up(target).hide();
    if(hidden_input = el.previous("input[type=hidden]")) hidden_input.value = '1'
  },
  '.add_nested_item': function(e){
    add_nested_item(Event.findElement(e));
  }
};

function add_nested_item(el) {
  template = eval(el.href.replace(/.*#/, ''))
  $(el.rel).insert({     
    bottom: replace_ids(template)
  });  
}
function delegateClicks() { if ($('viewport')) { $('viewport').delegate('click', myrules); } }
document.observe('dom:loaded', delegateClicks.bind(this));
 

function showListing(id) {
  listing     = "more_info_" + id;
  more_click  = "more_click_" + id;
  short_desc  = "short_description_" + id;
  description = "description_" + id;
	$(short_desc).hide();
	$(description).show();
  $(listing).show();
  $(more_click).hide();
}

function hideListing(id) {
  listing     = "more_info_" + id;
  more_click  = "more_click_" + id;
  short_desc  = "short_description_" + id;
  description = "description_" + id;
	$(short_desc).show();
	$(description).hide();
  $(more_click).show();
  $(listing).hide();
}

function toggleRefineResults() {
  if ($('refine_results').visible()) {
    Effect.Fade('refine_results');
    new Effect.Highlight('refine_link', { startcolor: '#d8c9a0', endcolor: '#ffffff', restorecolor: '#ffffff' });
  } else {
    Effect.Appear('refine_results');
    new Effect.Highlight('refine_link', { startcolor: '#ffffff', endcolor: '#d8c9a0', restorecolor: '#d8c9a0' });
  }
}

WordCounter = Class.create({

  initialize: function(counted, counter, max) {
    this.counted = $(counted);
    this.counter = $(counter);
    this.max     = max;
    this.observe_dom();
  },
  
  count_words: function() {
    var words = this.counted.value.replace(/\W+/g, ' ').split(' ');
    return words.without('');
  },
  
  update_counter: function() {
    var count = this.count_words().length;
    this.counter.update(count);
    if (count > this.max) { this.counted.addClassName('fieldWithErrors'); }
    else { this.counted.removeClassName('fieldWithErrors'); }
  },
  
  observe_counter: function() {
    this.counted.observe('keyup', this.update_counter.bind(this));
  },
  
  observe_dom: function() {
    document.observe('dom:loaded', this.update_counter.bind(this));
    document.observe('dom:loaded', this.observe_counter.bind(this));
  }
  
});


BusinessTypeObserver = Class.create({

  initialize: function() {
    this.observe_dom();
  },
  
  display_catering: function() {
    this.partner.hide();
    this.catering.show();
    new Effect.Highlight(this.catering, {startcolor:'#fbf1d8'});
  },
  
  display_partner: function() {
    this.catering.hide();
    this.partner.show();
    new Effect.Highlight(this.partner, {startcolor:'#fbf1d8'});
  },
  
  hide_display: function() {
    this.catering.fade();
    this.partner.fade();
  },
  
  update_display: function() {
    switch(this.selector.options[this.selector.selectedIndex].innerHTML) {
      case 'Farm':
        this.display_partner();
        break;
      case 'Restaurants and Bakeries':
        this.display_catering();
        break;
      default:
        this.hide_display();
    }
  },
  
  observe_selector: function() {
    this.partner  = $('farm-partner-info');
    this.catering = $('catering-info');
    this.selector = $('business_business_entity_attributes_entity_type_id');
    this.selector.observe('change', this.update_display.bind(this));
  },
  
  observe_dom: function() {
    document.observe('dom:loaded', this.observe_selector.bind(this));
  }

});


  var RegionMap = Class.create({
      initialize: function(region_id, region_name) {
          this.region_id = region_id
          this.region_name = region_name
      },

      add_region: function() {
          this.add_region_to_id_list()
          this.add_region_to_region_display()
          this.show_header()
      },

      remove_region: function() {
          this.remove_region_from_id_list()
          this.remove_region_from_region_display()
          this.hide_header_if_necessary()
      },

      add_region_to_id_list: function() {
          holder = $('selected_regions_holder')
          if (!holder.down('#region_id_' + this.region_id)) {
              holder.insert({
                  bottom: new Element('input', {
                      name: 'search[region_id_list][]', 
                      id: 'region_id_' + this.region_id,
                      value: this.region_id,
                      type: 'hidden'
                  })
              })
          }
      },

      add_region_to_region_display: function() {
          region_class = 'region_display_' + this.region_id
          region_name_class = 'region_display_' + this.region_name.gsub(' ', '_')
          $$('.selected_regions').each(function(holder) {
              if (!holder.down('.' + region_class)) {
                  region_div = new Element('div').update(this.region_name)
                  region_div.addClassName('region_display')
                  region_div.addClassName(region_class)
                  region_div.addClassName(region_name_class)
                  region_closer = new Element('img', {
                      src: '/images/close_icon.png'
                  })
                  region_closer.observe('click', function(event) {
                      event.stop()
                      this.remove_region()
                  }.bind(this))

                  region_div.insert({bottom: region_closer})
                  holder.insert({bottom: region_div})
              }
          }.bind(this))
      },

      show_header: function() {
          $$('.selected_regions').each(function(holder) {
              holder.down('.heading').show()
          })
      },

      hide_header_if_necessary: function() {
          if ($$('.selected_regions .region_display').size() == 0) {
              $$('.selected_regions').each(function(holder) {
                  holder.down('.heading').hide()
              })
          }
      },

      remove_region_from_id_list: function() {
          holder = $('selected_regions_holder')
          region = holder.down('#region_id_' + this.region_id)
          if (region) {
              region.remove()
          }
      },

      remove_region_from_region_display: function() {
          region_class = 'region_display_' + this.region_id
          $$('.selected_regions').each(function(holder) {
              region = holder.down('.' + region_class)
              if (region) {
                  region.remove()
              }
          })
      }
  })


  RegionMap.observe_map_clicks = function(map_id) {
      $$('#' + map_id + ' area').each(function(area) {
          map_obj = new RegionMap(area.readAttribute('rel'), area.readAttribute('alt'))
          area.observe('click', function(event) {
              event.stop()
              this.add_region()
          }.bind(map_obj))
      })
  }

  $onload(function() {
      if ($('region_map')) {
          RegionMap.observe_map_clicks('region_map')
      }
  })

  $onload(function() {
      trigger = $$('a.lightwindow.region_map_trigger').first()
      if (location.href.match(/#regions$/) && trigger) {
          lightwindowInit() //init here in case the it hasn't been called yet
          myLightWindow.activate(null, trigger)
      }
  })


  




