﻿function WebService(url) {
	// The callback function is passed the following arguments:
	//
	// result       - The resulting object.
	// status       - The status text of the response.
	// errorThrown  - The exception, if applicable.
	//
	// In case of error, result is null

    this.invoke = function(method, args, callback) {
        var success = null;
        var failure = null;
        if (callback != null) {
            failure = function(request, status, errorThrown) {
                callback(null, status, errorThrown);
            }

            success = function(data, status) {
                var root = data.firstChild;
                while (root != null && root.nodeType != 1) {
                    root = root.nextSibling;
                }

                var result = WebService.xmlToObject(root);
                callback(result, status, null);
            }
        }

        $.ajax({
            cache: false,
            data: args,
            dataType: "xml",
            error: failure,
            success: success,
            type: "POST",
            url: url + "/" + method
        });
    }
}

WebService.xmlToObject = function(node) {
    var child = node.firstChild;

    if (child == null) {
        return null;
    }

    if (child == node.lastChild && child.nodeType == 3) {
        return child.nodeValue;
    }

    var result = {};
    while (child != null) {
        if (child.nodeType == 1) {
            result[child.localName] = WebService.xmlToObject(child);
        }
        child = child.nextSibling;
    }
    return result;
}

