﻿
// this ajax service uses json/wcf paradigm to move data to the client
var xmlHttp = null;

var returnFuncion = null

function CallAjaxJsonService(retfuncToCall, funcToCall, qString) {

    //xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XmlHttp");


    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xmlHttp = new XMLHttpRequest();

        if (xmlHttp.overrideMimeType) {
            xmlHttp.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }

    var curUrl = document.URL

    
    
    var url = "/RecNut3Wcf1.svc/ajaxEndpoint/";
    
    
    url = url + funcToCall;
    // set the return function to app scope
    returnFuncion = retfuncToCall
    // Send the HTTP request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");

    try {
        xmlHttp.send(qString);
    }
    catch (e) {
        alert(e);
    }
    
    
    // Create result handler
    xmlHttp.onreadystatechange = HandleReadyJson
}

function HandleReadyJson() {
    if (xmlHttp == null)
    { return; }
    if (xmlHttp.readyState == 4) // loaded and finished
    {
        if (xmlHttp.status == 200) { // success
            if (xmlHttp.readyState == 4) {
                // our convention is that we always return a json string
                var result = xmlHttp.responseText;
                if (result.length > 0) {
                    // this creates a generic json object
                    var p = eval("(" + result + ")");
                    // this create 'our' generic json object
                    var x = eval("(" + p.d + ")");
                }
            }
            // this will call the return function in the application scope
            returnFuncion(x.data)
        } else {  // not success - probably need more error correction
            if (window.console) {
                window.console.log('There was a problem with the request.' + xmlHttp.status);
            }
            else {
                alert('There was a problem with the request.' + xmlHttp.status);
            }
        }
    }
}
