﻿ASP = {
    NET: {
        Page: {
            CallPageMethod: function(method, data, onSuccess, onFailure) {
                var currentPage = window.location.href;

                if (currentPage.indexOf("?") != -1) {
                    currentPage = currentPage.substr(0, currentPage.lastIndexOf("?"));
                }

                ASP.NET.Page.CallMethod(currentPage, method, data, onSuccess, onFailure);
            },

            /// Provides a means for calling a WebMethod of the web service that
            /// backs this page. This will take a data object (<b>not</b> a string)
            /// and convert it into the correct string format for use with the
            /// ASP.NET WebMethod implementation.
            CallMethod: function(url, method, data, onSuccess, onFailure) {
                $.ajax({
                    type: "POST",
                    url: url + "/" + method,
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",

                    success: function(msg) {
                        if (msg.d != null && msg.d.Error !== undefined) {
                            alert("An error has occured whilst processing your request.\n\n " + msg.d.Error);
                        } else {
                            if (onSuccess) {
                                onSuccess(msg);
                            }
                        }
                    },

                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        var ex = JSON.parse(XMLHttpRequest.responseText);

                        if (onFailure) {
                            onFailure(ex.ExceptionType, ex.Message);
                        } else {
                            alert("An exception has been raised by the server:\n\n" +
                               "Type: " + ex.ExceptionType + "\n" +
                               "Message: " + ex.Message);
                        }
                    }
                });
            }
        }
    }
}