<%@ 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 language="JavaScript" 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.Google.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.estimatedTotalResultsCount);
    if (result.resultElements != null) {
      for (var i = 0; i < result.resultElements.length; i++) {
        var page = result.resultElements[i];
        var li = document.createElement("li");
        var a = document.createElement("a");
        a.setAttribute("href", page.URL);
        a.innerHTML = page.title; 
        li.appendChild(a);
        $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;
  }
  </script>

</head>
<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Services>
        <asp:ServiceReference Path="~/Google.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>Approx. <span id="Count">0</span> results.</p>
      <ul id="Results">
      </ul>
    </div>
  </form>
</body>
</html>
