var last_q = "";

function process() {
  var s = document.getElementById("q").value;
  var c = 0;
  if (s.length > 0)
    $.get("search.php", {q: s, r: Math.random()}, function(xml) {
      var html = "";
      var m = "";
      $(xml).find("data").each(function() {
        if ($(this).attr("n") == -1)
          html += "<h3>Извините, сервис временно не доступен</h3>"
        else {
          $(this).find("msg").each(function() {
            html += "<h3>" + $(this).attr("n") + "</h3>";
          });
          $(this).find("g").each(function() {
            html += "<h2>" + $(this).attr("n") + "</h2><ul>";
            $(this).find("r").each(function() {
              c = $(this).find("sr").size();
              if (c > 0)
                m = "&nbsp;-&nbsp;<span class=\"m\">похожие рецепты: " + c + "</span>"
              else
                m = "";
              html += "<li><a href=\"" + $(this).attr("a").replace("@", "?") + "\" target=\"_blank\">" + $(this).attr("n") + "</a>" +
                m + "<p class=\"s\">" + $(this).attr("s") + "</p></li>";
              if (c > 0) {
                html += "<ul class=\"mr\">";
                $(this).find("sr").each(function() {
                  html += "<li><a href=\"" + $(this).attr("a").replace("@", "?") + "\" target=\"_blank\">" + $(this).attr("n") + "</a>" +
                    "<p class=\"s\">" + $(this).attr("s") + "</p></li>";
                });
                html += "</ul>";
              }
            });
            html += "</ul>";
          });
        }
      });
      $("#r").html(html);
      window.location.hash = "#" + s;
      last_q = s;
    });
}

function checkHash() {
  var h = window.location.hash.replace('#', '');
  if (h != last_q) {
    document.getElementById("q").value = h;
    process();
  }
}

$(document).ready(function() {

  document.getElementById("q").focus();
  
  setInterval("checkHash()", 500);
  
  $("#q").keypress(function(e) {
    var k = e.keyCode || e.which;
    if (k == 13)
      process();
  });

  $("#p").click(function(){process();});

  $(".m").live("click", function(){$(this).parents("li").next("ul").slideToggle("slow");});
  
  $("#r").ajaxStart(function(){$(this).html("<h3>Поиск рецептов...</h3>");});

  $("#r").ajaxError(function(){$(this).html("<h3>Извините, поиск временно не доступен</h3>");});

});
