﻿  Object.toJSON = function(object) {
    /*var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return '"'+object.toString()+'"';
    }    

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (typeof object[property] != 'object') {
        value = '"' + value + '"';
      }
      if (object[value] != 'null' && typeof(object[value]) != 'function')
        results.push( '"' + property.toJSON() + '" : ' + value +'');
    }    

    return '{' + results.join(', ') + '}';*/
    return Ext.util.JSON.encode(object);
  };

JSON = function(){};
JSON.Logger = [];
JSON.Cache = {};
JSON.DefaultPacket = function(module, action) {
    return {
        type:'request',
        query: {
            module:module,
            action:action
        },
        xmldata:{}
    };
};

JSON.Template = function(callback) {
    this.callback = callback;
};
JSON.Template.prototype = {
    callback: null,
    load: function(template, url, module, action) {
        var req = new JSON.Request(this.onLoad.bind(this), this.onError.bind(this));
        var doc = new JSON.Document('packet', JSON.DefaultPacket(module, action));
        doc.packet.query.tmpl= template;
        req.send(url, doc);
    },
    /* default callbacks */
    onLoad: function(response) {
        JSON.Cache[response.packet.query.tmpl] = function(){
            var t = TrimPath.parseTemplate(response.packet.xmldata['xsl:stylesheet']);
            return {
                transform: function(data) {
                    return t.process(data);
                }
            };
        }();
        alert('called');
        this.callback ? this.callback() : '';
    },
    onError: function(response) {
        alert('Response is not valid JSON');
    }
};

JSON.Document = function(base, obj) {
    this[base] = obj;
    this.document = {};
    this.document[base] = obj;
    this.rootNode = base;
};
JSON.Document.prototype = {
    serialize: function() {
        return Object.toJSON(this.document);         
    },
    transform: function(xmldoc) {
        //take xmldoc as data and put it into template
    }
};


JSON.Request = function(onLoad, onError){
    this.request = this.__create()
    this.onError = onError; 
    this.onLoad = onLoad
    this.request.onreadystatechange = this.__receive.bind(this);   
}

JSON.Request.prototype.__create = function(){
    /* no cross browser stuff, FF only */
    return new XMLHttpRequest();
}

JSON.Request.prototype.__receive = function(){
    if ( this.request.readyState == 4 && this.request.status == 200 ) {
        if(this.onLoad) { 
            if(this.request.responseText.substr(0,17) == '_(Error in query)'){
                application.error(10001,this.request.responseText);
            }
            var obj = eval('('+this.request.responseText+')');
            if( obj.packet.xmldata.error ) {
                obj.packet.xmldata.error.cdata == 'You don\'t have permission' ?
                    application.accessDenied() : application.showError(obj.packet.xmldata, 'Error')
                application.stopLoad();
                return;
            } else {
                this.onLoad( new JSON.Document('packet', obj.packet) );
            }
        } else if(this.onError) this.onError(this.request.status)
    }
}

JSON.Request.prototype.send = function(url, packet){
    JSON.Logger.push(packet)
    var data = packet.serialize()
    this.request.open('POST', url, true);
    this.request.setRequestHeader("Content-Type", "application/json")
    this.request.send(data);
}

JSON.Request.prototype.post = function(url, packet){
    JSON.Logger.push(packet)
    var data = packet.serialize()
    this.request.open('POST', url, true);
    this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    this.request.send(data);
    
}


