<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>ASP.NET AJAX</title>

  <script type="text/javascript">
  function clearList() {
    var list = $get("Results");
    while (list.firstChild != null) {
      list.removeChild(list.firstChild);
    }
  }

  function Search() {
    var query = new Sys.Preview.UI.TextBox($get('Query'))
    $get("Button").disabled = true;
    clearList();
    OReilly.AspNetAJAX.Amazon.Search(
      { "query": query.get_text() },
      callComplete, callTimeout, callError
    );
    new Sys.Preview.UI.Label($get('Count')).set_text("...");
  }
  
  function callComplete(result)  {
    new Sys.Preview.UI.Label($get('Count')).set_text(result.TotalResults);
    if (result.Item != null) {
      for (var i = 0; i < result.Item.length; i++) {
        var article = result.Item[i];
        var author = (article.ItemAttributes.Author != null ? 
          join(article.ItemAttributes.Author) + ": " : "");
        var title = article.ItemAttributes.Title;
        var li = document.createElement("li");
        var liText = document.createTextNode(author + title);
        li.appendChild(liText);
        $get("Results").appendChild(li);
      }
    }
    $get("Button").disabled = false;
  }
  function callTimeout(result) {
    window.alert("Error! " + result.get_message());
    new Sys.Preview.UI.Label($get('Count')).set_text("0");
    $get("Button").disabled = false;
  }
  function callError(result) {
    window.alert("Error! " + result.get_message());
    new Sys.Preview.UI.Label($get('Count')).set_text("0");
    $get("Button").disabled = false;
  }
  
  function join(a) {
    var s = "";
    for (var i=0; i < a.length - 1; i++) {
      s += a[i] + "/";
    }
    s += a[a.length - 1];
    return s;
  }
  </script>

</head>
<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Services>
        <asp:ServiceReference Path="~/Amazon.asbx" />
      </Services>
      <Scripts>
        <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="PreviewScript.js" />
      </Scripts>
    </asp:ScriptManager>
    <div>
      <input type="text" id="Query" />
      <input type="button" id="Button" value="Search" onclick="Search();" />
    </div>
    <div>
      <p>
        <span id="Count">0</span> results.</p>
      <ul id="Results">
      </ul>
    </div>
  </form>
</body>
</html>
