﻿if ("undefined" === typeof window.ServiceHelper) {
    window.ServiceHelper = {};
}

ServiceHelper.showStatus = function (message, timeout) {
    alert(message);
};

ServiceHelper.onPageError = function (xhr, errorMsg, thrown) {
    if ("string" === typeof xhr) {
        ServiceHelper.showStatus(xhr, 5000);
        return;
    }

    if (errorMsg && (errorMsg !== "error")) {
        ServiceHelper.showStatus("errormsg: " + errorMsg, 5000);
    }
    else if (("string" === typeof xhr.responseText) && (xhr.responseText !== "")) {
        ServiceHelper.showStatus(xhr.responseText, 5000);
    }
    else
        ServiceHelper.showStatus("Unknown error occurred in callback.", 5000);
};

// *** Service Calling Proxy Class
ServiceHelper.setupServiceProxy = function (serviceUrl) {
    ServiceHelper.initialUrl = serviceUrl;
    ServiceHelper.serviceUrl = serviceUrl;

    // *** Call a wrapped object
    ServiceHelper.invokeServiceMethod = function (method, data, callback, bare, timeout, errback) {
        // *** Set the service endpoint URL        
        var url = ServiceHelper.serviceUrl + "/" + method;

        // *** Reset the service url to the default
        ServiceHelper.serviceUrl = ServiceHelper.initialUrl;

        if ("undefined" === typeof timeout) {
            timeout = 10000;
        }

        // *** Convert input data into JSON
        var json = jQuery.toJSON(data);

        jQuery.ajax({
            url: url,
            data: json,
            type: "POST",
            processData: false,
            contentType: "application/json",
            timeout: timeout,
            dataType: "json",
            success:
                function (result) {
                    if ("undefined" === typeof callback) {
                        return;
                    }

                    // *** Bare message IS result
                    if (bare === true) {
                        callback(result);
                        return;
                    }

                    // *** Wrapped message contains top level object node
                    // *** strip it off
                    for (var property in result) {
                        callback(result[property]);
                        break;
                    }
                },
            error:
                function (xhr, errorMsg, thrown) {
                    if ("undefined" !== typeof errback) {
                        errback(xhr, errorMsg, thrown);
                        return;
                    }

                    ServiceHelper.onPageError(xhr, errorMsg, thrown);
                }
        });
    };
};

