// request.js

var methodBaseURL = '/services/DataService.svc/';

function WebRequest() {
    // Gets the XMLHttpRequest object for the browser. Due
    // to the way IE uses this object, a new XmlHttpRequest
    // should be created each time a request is made.
    this.createXmlHttpRequest = function () {
        var xmlRequest = false;
        // all modern browsers
        if (window.XMLHttpRequest) {
            xmlRequest = new XMLHttpRequest();
        }
        // old versions of IE
        else if (window.ActiveXObject) {
            xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }
        return xmlRequest;
    }

    // get a file from the server
    this.callWebMethod = function (method, queryParams, evtHandler) {
        var xmlRequest = this.createXmlHttpRequest();
        if (!xmlRequest) {
            // browser does not support requests, show an error
            alert('Your browser is not supported.');
        }
        else {
            // prepare the request
            var url = methodBaseURL + method + '?' + queryParams;
            xmlRequest.open('GET', url, true);
            xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            // prepare to handle the response
            xmlRequest.onreadystatechange = function () {
                if (xmlRequest.readyState == 4) {
                    if (xmlRequest.status == 200) {
                        var obj = null;
                        if (window.JSON) {
                            obj = JSON.parse(xmlRequest.responseText).d;
                        }
                        if (obj === null) {
                            // non-standard json or no browser support
                            obj = eval('(' + xmlRequest.responseText + ')').d;
                        }
                        evtHandler(obj);
                    }
                }
            };
            // send the request
            xmlRequest.send(null);
        }
    }
}


