/**
 * Sends an AJAX request.
 * @param type  the request type ('GET' or 'POST')
 * @param reqUrl  the URL to send request to
 * @param data  the URL encoded data to be sent
 * @param fn    the callback function that will be called when response is received
 * @param waitForResp  if true wait for the response before returning 
 *                     (ie. synchronous request)
 */
function wsReq(type, reqUrl, data, fn, waitForResp) {
    if (waitForResp == undefined) var waitForResp = false;
    $.ajax({
        type: type,
        url: reqUrl,
        data: data,
        dataType: 'json',
        async: !waitForResp,
        beforeSend: function (reqObj) {
            showLoadingIndicator();
        },
        success: function (json) {
            fn(json);
        },
        error: function (reqObj, txtStatus, errObj) {
            alert('Error: '+txtStatus);
            hideLoadingIndicator();
        },
        complete: function (reqObj, txtStatus) {
            hideLoadingIndicator();
        }
    });
}

/**
 * Sends a VIEW request.
 * @param reqUrl   the URL to send request to
 * @param data  the URL encoded data to be sent
 * @param fn    the callback function that will be called when response is received
 */
function wsView(reqUrl, fn, waitForResp) {
    wsReq('POST', reqUrl, 'cmd=view', fn, waitForResp);
}

/**
 * Sends a DELETE request.
 * @param reqUrl   the URL to send request to
 * @param fn    the callback function that will be called when response is received
 */
function wsDelete(reqUrl, fn, waitForResp) {
    wsReq('POST', reqUrl, 'cmd=delete', fn, waitForResp);
}

/**
 * Sends a CREATE request.
 * @param reqUrl   the URL to send request to
 * @param data  the URL encoded data to be sent
 * @param fn    the callback function that will be called when response is received
 */
function wsCreate(reqUrl, data, fn, waitForResp) {
    wsReq('POST', reqUrl, data+'&cmd=create', fn, waitForResp);
}

/**
 * Sends a UPDATE request.
 * @param reqUrl   the URL to send request to
 * @param data  the URL encoded data to be sent
 * @param fn    the callback function that will be called when response is received
 */
function wsUpdate(reqUrl, data, fn, waitForResp) {
    wsReq('POST', reqUrl, data+'&cmd=update', fn, waitForResp);
}

/**
 * Sends a LIST request.
 * @param reqUrl   the URL to send request to
 * @param data  the URL encoded data to be sent
 * @param fn    the callback function that will be called when response is received
 */
function wsList(reqUrl, data, fn, waitForResp) {
    wsReq('POST', reqUrl, data+'&cmd=list', fn, waitForResp);
}


