(function ($) {
  // custom css expression for a case-insensitive contains()
  jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
  };

  function listFilter(header, list) { // header is any element, list is an unordered list to be filtered
    // create and add the filter form to the header
    var form = $("<form>").attr({"class":"filterform","action":"#"}),
        input1 = $("<input class='filterinput' type='radio' name='office_type' value='' checked='checked' />"),
        label1 = $("<label>").text("view all clinics"),
        input2 = $("<input class='filterinput' type='radio' name='office_type' value='Allergy'>"),
        label2 = $("<label>").text("view only Allergy clinics");
    $(form).append(input1).append(label1).append(input2).append(label2);
    $(form).insertAfter(header);

    $("input.filterinput")
      .change( function () {
        var filter = $(this).val();
        if(filter) {
          // this finds all links in a list that contain the input,
          // and hide the ones not containing the input while showing the ones that do
          $(list).find("a:not(:Contains(" + filter + "))").parent().hide();
          $(list).find("a:Contains(" + filter + ")").parent().show();
        } else {
          $(list).find("li").show();
        }
        return false;
      })
    .click( function () {
        // fire the above change
        $(this).change();
    });

  }


  //ondomready
  $(function () {
    listFilter($("#all_office_locations h2"), $("#all_office_locations ul"));
    listFilter($("#north_florida_office_locations h2"), $("#north_florida_office_locations ul"));
  });
}(jQuery));
