/*
@author : Alexander Far.        
@version: 0.1
@change : 08.04.2009  AFar moved in separate file

Example
   var proxy = new serviceProxy("Service.svc/");
   proxy.invoke("test", { BoolValue: true, StringValue: "asdasd", text: "" }, 
      function(result,status) { 
              result.company.name;       
      }, 
      function (xhr, errorMsg, thrown) { });

  OR

proxy.invoke("test", { BoolValue: true, StringValue: "asdasd", text: "" }, function(result,status) { 
      result.getText('company>name');   
      result.getObj('company>project').length;   - get list of project as jQuery object and get property 'length' 
      result.getAttr('name','company>project:eq(2)');  - get attrinbute 'name' of project which third in list
      result.getAttr('name','company>project[id=333]');  - get attrinbute 'name' of project with id=333       
   }, function (xhr, errorMsg, thrown) { }, 'xml');


 *** Generic Service Proxy class that can be used to 
 *** call JSON Services generically using jQuery
 *** Depends on JSON2 modified for MS Ajax usage
 if type='xml' - return result is jQuery object, else  - evel(json) object 
*/
function serviceProxy(serviceUrl) {
    return {
        serviceUrl: serviceUrl,
        invoke: function(method, data, callback, error, type) {
            // *** Convert input data into JSON - REQUIRES Json2.js
            var json = JSON2.stringify(data);
            
            // *** The service endpoint URL        
            var url = ApplicationUrlNew + this.serviceUrl + method;

            $.ajax({
                url: url,
                data: json,
                dataType: 'xml',
                type: "POST",
                processData: false,
                contentType: "application/json",
                //timeout: 40000,
                dataType: type == "xml" ? "xml" : "text",  // not "json" we'll parse
                success:
            function(res, status) {
               
                if (!callback) return;
                if (type != "xml") {
                    // *** Use json library so we can fix up MS AJAX dates
                    var r = JSON2.parse(res);
                    if (r.ExceptionDetail) {
                        OnPageError(r.Message);
                        return;
                    }
                } else {
                    var r = $(res);
                }
                //alert($('root>tasks',r).length);
                callback(r, status);
            },
                error: function(xhr, errorMsg, thrown) {
                    if (error & (typeof error == 'function')) error(xhr, errorMsg, thrown);
                }
            });
        }
    }
}

