﻿
(function($) {
    $.fn.toggleChecks = function(sel) {
        /// <summary>
        /// Toggles all checkboxes contained within the provided selector to match the 
        /// the state of the calling object.
        /// </summary>
        /// <param name="sel" type="Selector">
        /// The parent selector containing the checkboxes to check.
        /// </param>
        var selectAll = this;
        selectAll.click(function() {
            $('input:checkbox', sel).each(function() {
                $(this).attr('checked', selectAll.attr('checked'));
            });
        });
    };

    $.formatDate = function(value) {
        if (typeof (value) === 'string') {
            if (value.indexOf("Date(") >= 0) {
                a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                if (a) {
                    var theDate = new Date(parseInt(a[1], 10));
                    return theDate.getMonth() + '/' + theDate.getDate() + '/' + theDate.getFullYear();
                }
            }
        }
        return value;
    };

    $.ajaxPost = function(options) {
        var settings = $.extend({}, options);

        //var data;
        //        if (settings.selector) {
        //            if (settings.dtoName)
        //                data = '{"' + settings.dtoName + '":' + $.toJSON($('*[name]', $(options.selector)).serializeObject(settings.data)) + '}';
        //            else
        //                data = $.toJSON($('*[name]', $(options.selector)).serializeObject(settings.data));
        //        }
        //        else
        //            data = $.toJSON(settings.data);

        //alert(data);
        //alert(settings.data);

        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: settings.url,
            data: settings.data,
            cache: false,
            dataFilter: function(data, type) {
                jdata = $.evalJSON(data).d;
                for (k = 0; k < jdata.length; k++) {
                    for (var d in jdata[k])
                        var value = $.formatDate(jdata[k][d]);
                }
                return jdata;
            },
            beforeSend: function(xhr) {
                if (!settings.beforeSend)
                    return true;
                return settings.beforeSend(xhr);
            },
            success: function(response, statusText) {
                if (settings.success)
                    return settings.success(response, statusText);
            },
            error: function(xhr, errorStatus, errorThrown) {
                var errorResponse = $.evalJSON(xhr.responseText);
                if (settings.error)
                    settings.error(xhr, errorStatus, errorResponse);
                else
                    alert(errorResponse.Message);
            },
            complete: function(xhr, statusText) {
                if (settings.complete)
                    settings.complete(xhr, statusText);
            }
        });
        return false;
    };

    $.fn.serializeObject = function(additionalData) {
        var o = {};
        var a = this.serializeArray();

        if (additionalData && typeof (additionalData) == 'object')
            $.merge(a, $.formParam(additionalData));

        $.each(a, function() {
            var el = $('input[name=' + this.name + ']');
            var useArr = (el.length > 1 && el.attr('type') === 'checkbox');
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                if (useArr)
                    o[this.name] = [this.value || ''];
                else
                    o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $.formParam = function(a) {
        var s = [];

        function add(key, value) {
            s[s.length] = { name: key, value: value };
        };

        if ($.isArray(a) || a.jquery)
            $.each(a, function() {
                add(this.name, this.value);
            });

        else
            for (var j in a) {
            if ($.isArray(a[j])) {
                $.each(a[j], function() {
                    add(j, this);
                });
            }
            else
                add(j, $.isFunction(a[j]) ? a[j]() : a[j]);
        }
        return s;
    };

    function toIntegersAtLease(n) {
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date) {
        return this.getUTCFullYear() + '-' +
             toIntegersAtLease(this.getUTCMonth()) + '-' +
             toIntegersAtLease(this.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    };

    $.quoteString = function(string) {
        if (escapeable.test(string)) {
            return '"' + string.replace(escapeable, function(a) {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };

    $.toJSON = function(o, compact) {
        var type = typeof (o);

        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";

        if (type == "string") {
            return $.quoteString(o);
        }

        if (type == "object" && typeof o.toJSON == "function")
            return o.toJSON(compact);

        if (type != "function" && typeof (o.length) == "number") {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push($.toJSON(o[i], compact));
            }
            if (compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        }

        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }

        var ret = [];
        for (var k in o) {
            var name;
            type = typeof (k);

            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys

            var val = $.toJSON(o[k], compact);
            if (typeof (val) != "string") {
                // skip non-serializable values
                continue;
            }

            if (compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    };

    $.evalJSON = function(src) {
        return eval("(" + src + ")");
    };

    $.secureEvalJSON = function(src) {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };

    //(c) 2008 Michael Manning 
    jQuery.parseQuery = function(A, B) { var C = (typeof A === "string" ? A : window.location.search), E = { f: function(F) { return unescape(F).replace(/\+/g, " ") } }, B = (typeof A === "object" && typeof B === "undefined") ? A : B, E = jQuery.extend({}, E, B), D = {}; jQuery.each(C.match(/^\??(.*)$/)[1].split("&"), function(F, G) { G = G.split("="); G[1] = E.f(G[1]); D[G[0]] = D[G[0]] ? ((D[G[0]] instanceof Array) ? (D[G[0]].push(G[1]), D[G[0]]) : [D[G[0]], G[1]]) : G[1] }); return D };
})(jQuery);
