<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  [WebMethod(EnableSession = true)]
  [System.Web.Script.Services.ScriptMethod]
  public static bool SaveTime()
  {
    HttpContext.Current.Session["PageLoaded"] = DateTime.Now;
    return true;
  }

  [WebMethod(EnableSession = true)]
  [System.Web.Script.Services.ScriptMethod]
  public static double CalculateDifference()
  {
      if (HttpContext.Current.Session["PageLoaded"] == null)
      {
      return -1;
    } else {
        DateTime then = (DateTime)HttpContext.Current.Session["PageLoaded"];
      TimeSpan diff = DateTime.Now.Subtract(then);
      return diff.TotalSeconds;
    }
  }

  [WebMethod]
  public float DivideNumbers(int a, int b)
  {
    if (b == 0)
    {
      throw new DivideByZeroException();
    }
    else
    {
      return (float)a / b;
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>ASP.NET AJAX</title>

  <script language="Javascript" type="text/javascript">
  function pageLoad() {
    PageMethods.SaveTime(doNothing, doNothing, doNothing);
  }
  function doNothing(result) {
    //nic :-)
  }

  function callService(f) {
    document.getElementById("c").innerHTML = "";
    PageMethods.CalculateDifference(
      showDifference,
      callTimeout,
      callError);
    PageMethods.DivideNumbers(
      parseInt(f.elements["a"].value),
      parseInt(f.elements["b"].value),
      callComplete,
      callTimeout,
      callError);
  }
function showDifference(result) {
    if (result != -1) {
      document.getElementById("output").innerHTML =
        "Formularz był wyświetlany przez " + result + " sekund";
    }
  }

  function callComplete(result) {
    document.getElementById("c").innerHTML = result;
  }
  function callTimeout(result) {
    window.alert("Błąd! " + result);
  }

  function callError(result) {
    if (result == null) {
      window.alert("Błąd!");
    } else {
      document.getElementById("output").innerHTML =
        "<b>" +
        result.get_exceptionType() +
        "</b>: " +
        result.get_message() +
        "<br />" +
        result.get_stackTrace();
    }
  }
  </script>

</head>
<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"
      EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
      <nobr>
        <input type="text" id="a" name="a" size="2" />
        :
        <input type="text" id="b" name="b" size="2" />
        = <span id="c" style="width: 50px;"></span>
      </nobr>
      <br />
      <input type="button" value="Podziel liczby" onclick="callService(this.form);" />
      <br />
      <div id="output" style="width: 600px; height: 300px;">
      </div>
    </div>
  </form>
</body>
</html>
