﻿var Json = function () {
    var jsonObject = {};

    this.Init = function () {
        jsonObject = {};
    };

    this.Add = function (jsonKey, value) {
        var keysObject = jsonKey.split('.');
        this.AddToMultiDimJson(jsonObject, keysObject, value);
    };

    this.AddToMultiDimJson = function (jsonRecurs, keysObjectRecurs, value) {
        if (jsonRecurs[keysObjectRecurs[0]] == undefined) {
            jsonRecurs[keysObjectRecurs[0]] = {};
        }
        if (keysObjectRecurs.length > 1) {
            this.AddToMultiDimJson(jsonRecurs[keysObjectRecurs[0]], keysObjectRecurs.slice(1), value);
        } else {
            jsonRecurs[keysObjectRecurs[0]] = value;
        }
    };

    this.GetJSON = function () {
        switch (BrowserDetect.name) {
            case 'Explorer':
                if (parseInt(BrowserDetect.version) <= 7) {
                    return this.StringifyCustom(jsonObject);
                } else {
                    return JSON.stringify(jsonObject);
                }
            default:
                return JSON.stringify(jsonObject);
        }
    };

    this.StringifyCustom = function (jsonData) {
        var strJsonData = '{';
        var itemCount = 0;
        for (var item in jsonData) {
            if (itemCount > 0) {
                strJsonData += ', ';
            }
            strJsonData += '"' + item + '":"' + jsonData[item] + '"';
            itemCount++;
        }
        strJsonData += "}";
        return strJsonData;
    };

    this.SendToServer = function (urlTo, action, resultObjSucces, resultObjError) {
        $.ajax({
            url: urlTo,
            type: 'POST',
            dataType: 'json',
            data: this.GetJSON(),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // get the result and do some magic with it
                delegateFunction(data, action);
            },
            error: function (msg) {
                //$(resultObjError).html(msg.xml);
                delegateFunction(data, action);
            }
        });
    };
};
var Json = new Json();
