function is_in_list(list, num) {
  for (i = 0; i < list.length; i++) {
    if (list[i] == num)
      return true;
  }
  return false;
}

function any_allergies_set()
{
  for (a = 0; a < allergies.length; a++) {
    var e = document.getElementById("allergy_" + allergies[a]);
    if (e.checked)
      return true;
  }
  return false;
}

function unhighlight() {
  for (f = 0; f < food_count; f++) {
    var e = document.getElementById("f"+f);
    e.style.background = "#ffffff";
  }
}

function fix_hrefs() {
  // change all links to submit-buttons
  for (f = 0; f < document.links.length; f++) {
    var href = document.links[f].href;
    var i = href.lastIndexOf('/') + 1;
    if (href[i] >= '1' && href[i] <= '7' && href[i+1] == '.') {
      document.links[f].onclick = function() {
	document.forms[0].action = this.href;
	document.forms[0].submit();
	return false;
      }
    }
  }
}

function highlight() {
  fix_hrefs();
  if (!any_allergies_set()) {
    unhighlight();
    return;
  }

  for (f = 0; f < food_count; f++) {
    var eatable = 1;
    for (a = 0; a < allergies.length; a++) {
      var e = document.getElementById("allergy_" + allergies[a]);
      if (e.checked) {
	if (is_in_list(eatable_foods[allergies[a]], f)) {
	  // still (maybe) eatable
	} else if (is_in_list(maybe_eatable_foods[allergies[a]], f)) {
	  // just maybe eatable
	  eatable = 0;
	} else {
	  eatable = -1;
	}
      }
    }
    var e = document.getElementById("f"+f);
    if (eatable < 0) {
      e.style.background = "#ffffff";
      //e.style.display = "none";
    } else {
      //e.style.display = "list-item";
      e.style.background = eatable > 0 ? "#ffff00" : "#cccccc";
    }
  }
}

function url_param(name)
{
  // From http://www.netlobo.com/url_query_string_javascript.html
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function set_allergies()
{
  for (a = 0; a < allergies.length; a++) {
    var e = document.getElementById("allergy_" + allergies[a]);
    if (url_param("allergy_" + allergies[a]) != "")
      e.checked = true;
  }
  highlight();
}
