﻿/*
jsonAspNet v1.1, copyright (c) 2009 Chris O'Brien, prettycode.org
Requires jQuery and JSON.stringify()
*/
(function() {

    $.jsonAspNet = function(page, webMethod, data, success, error) {
        ///	<summary>
        /// <para>
        ///     Use $.jsonAspNet() to send Ajax requests to ASP.NET web services
        ///     using JSON as the interchange format. The function is a simple
        ///     wrapper for $.ajax() that ensures the options are appropriately
        ///     specified and that any data sent is correctly serialized. Arguments
        ///     may be overloaded with any of these combination:
        /// </para>
        /// <para>
        ///     A) $.jsonAspNet(page, webMethod, data)
        ///     B) $.jsonAspNet(page, webMethod, data, success)
        ///     C) $.jsonAspNet(page, webMethod, data, success, error)
        ///     D) $.jsonAspNet(page, webMethod, success, error)
        ///     E) $.jsonAspNet(page, webMethod, success)
        /// </para>
        /// </summary>  

        // function(page, webMethod, data, success, error)
        // Argument overloading for: (page, webMethod, success, error)

        if (
            typeof data === "function" &&
            typeof success === "function" &&
            typeof error === "undefined"
        ) {
            error = success;
            success = data;
            data = null;
        }

        // Argument overloading for (page, webMethod, success)

        else if (
            typeof data === "function" &&
            typeof success === "undefined" &&
            typeof error === "undefined"
        ) {
            success = data;
            data = null;
        }

        // ASP.NET returns .NET DateTime objects as strings in this format: 
        // "/Date(x)/" where x is the unix time in ms. JSON.parse() errors out
        // when trying to convert such a date. dateFix() below will convert all
        // "/Date(x)/" strings (at any depth) to JavaScript Date objects.

        function dateFix(obj) {

            if (obj == null) {
                return obj;
            }

            // ASP.NET JSON date?

            if (typeof obj === "string") {
                var match = obj.match(/^\/Date\((\d+)\)\/$/);

                if (!match) {
                    return obj;
                }

                return new Date(parseInt(match[1]));
            }

            // string or number

            if (typeof obj !== "object") {
                return obj;
            }

            // array or object

            jQuery.each(obj, function(key, val) {
                obj[key] = dateFix(val);
            });

            return obj;
        }

        // Automatically unwrap the return value from the service
        function successWrapper(data, textStatus) {
            if (success) {
                if (data && (data.d != undefined))
                //success(dateFix(data.d), textStatus); //datefix is slow, don't need?
                    success(data.d, textStatus);
                else
                //success(dateFix(data), textStatus); //datefix is slow, don't need?
                    success(data, textStatus);
            }
        };

        // Send request 
        return $.ajax({
            type: "POST",
            data: (!data ? "{}" : JSON.stringify(data)),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: page + "/" + webMethod,
            success: successWrapper,
            error: error
        });
    };
})();

var globalVars = {};

String.prototype.namespace = function(separator) {
    var ns = this.split(separator || '.'),
    o = window,
    i,
    len;
    for (i = 0, len = ns.length; i < len; i++) {
        o = o[ns[i]] = o[ns[i]] || {};
    }
    return o;
};

"com.ctc".namespace();

com.ctc.toISODateString = function(d) {
    function pad(n) { return n < 10 ? '0' + n : n; }
    return d.getUTCFullYear() + '-'
      + pad(d.getUTCMonth() + 1) + '-'
      + pad(d.getUTCDate()) + 'T'
      + pad(d.getUTCHours()) + ':'
      + pad(d.getUTCMinutes()) + ':'
      + pad(d.getUTCSeconds()) + 'Z';
}

com.ctc.clearFields = function(selector) {
    $(selector).find(':input').each(function() {
        switch (this.type) {
            case 'select-multiple':
            case 'select-one':
                $(this).val($('option:first', this).val());
                break;
            case 'password':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

com.ctc.set_captchaTimestamp = function(d) {
    $('#captchaTS').val(com.ctc.toISODateString(d));
}

//COMMON Scripts
com.ctc.submitForm = function() {
    $.blockUI();
    var values = {};
    $('#form :input').each(function() {
        var obj = $(this);
        if (obj.attr('type') != 'button') {
            switch (obj.attr('type')) {
                case 'checkbox':
                    values[obj.attr('id')] = obj.is(':checked');
                    break;
                case 'radio':
                    if (obj.is(':checked'))
                        values[obj.attr('id')] = obj.val();
                    break;
                default:
                    values[obj.attr('id')] = obj.val();
                    break;
            }
        }
    });

    //Captcha
    values['captchaPS'] = $('#captchaPS').val();
    values['captchaTS'] = $('#captchaTS').val();

    var jsonData = { values: values };
    //alert(JSON.stringify(jsonData)); //DEBUG

    $.jsonAspNet(globalVars['servicesUrl'], globalVars['webMethod'], jsonData, com.ctc.onAjaxSuccess, com.ctc.onAjaxError);
}

com.ctc.onAjaxError = function(error) {
    $.unblockUI();
    $.growlUI(globalVars['errorMessage']);
    $('#message').text(globalVars['errorMessage']);
    //alert(error.Status + "; " + error.StatusText); //DEBUG
}

com.ctc.onAjaxSuccess = function(result) {
    $.unblockUI();

    if (result == true) {
        //$.growlUI(globalVars['successMessage']);
        $('#message').text(globalVars['successMessage']);
        com.ctc.clearFields('#form');
        com.ctc.set_captchaTimestamp(new Date()); //Refresh timestamp
        $('#form').toggleClass('hide', true);
    }
    else {
        $.growlUI(globalVars['errorMessage']);
        $('#message').text(globalVars['errorMessage']);
    }
}
