/*
 * jMsAjax 0.2.1 - Microsoft Ajax jQuery Plugin
 *
 * Copyright (c) 2008 Adam Schröder (schotime.net)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-07-12 $
 */
(function($)
{
    $.jmsajax=function(options)
    {
        var defaults={
                        type:"POST",
                        dataType:"msjson",
                        data:{},
                        beforeSend:function(xhr) {
                            xhr.setRequestHeader("Content-type","application/json; charset=utf-8");
                        },
                        contentType:"application/json; charset=utf-8",
                        error:function(x,s,m) {
                            alert("Status: "+((x.statusText)?x.statusText:"Unknown")+"\nMessage: "+JSON.parse(((x.responseText)?x.responseText:"Unknown")).Message);
                        }
        };
                       
        var options=$.extend(defaults,options);
        
        if(options.method) options.url+="/"+options.method;
            
        if(options.data)
        {
            if(options.type=="GET")
            {
                var data="";
                for(var i in options.data)
                {
                    if(data!="") data+="&";
                    
                    data+=i+"="+JSON.stringify(options.data[i]);
                }
                options.url+="?"+data;
                data=null;
                options.data="{}";
            }
            else if(options.type=="POST")
            {
                
                options.data=JSON.stringify(options.data);
            }
        }
        
        if(options.success)
        {
            if(options.dataType)
            {
                if(options.dataType=="msjson")
                {
                    var base=options.success;
                    options.success=function(response,status) {
                        
                        var y=JSON.parse(response);
                        
                        if (y.d) y=JSON.parse(y.d);
                        
                        base(y,status);
                    }
                }
            }
        }
    
        return $.ajax(options);
    };
})(jQuery);