/* JQuery.JSON */
(function ($) {
    $.toJSON = function (o) {
        if (typeof (JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o); var type = typeof (o); if (o === null)
            return "null"; if (type == "undefined")
            return undefined; if (type == "number" || type == "boolean")
            return o + ""; if (type == "string")
            return $.quoteString(o); if (type == 'object') {
            if (typeof o.toJSON == "function")
                return $.toJSON(o.toJSON()); if (o.constructor === Date) {
                var month = o.getUTCMonth() + 1; if (month < 10) month = '0' + month; var day = o.getUTCDate(); if (day < 10) day = '0' + day; var year = o.getUTCFullYear(); var hours = o.getUTCHours(); if (hours < 10) hours = '0' + hours; var minutes = o.getUTCMinutes(); if (minutes < 10) minutes = '0' + minutes; var seconds = o.getUTCSeconds(); if (seconds < 10) seconds = '0' + seconds; var milli = o.getUTCMilliseconds(); if (milli < 100) milli = '0' + milli; if (milli < 10) milli = '0' + milli; return '"' + year + '-' + month + '-' + day + 'T' +
hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"';
            }
            if (o.constructor === Array) {
                var ret = []; for (var i = 0; i < o.length; i++)
                    ret.push($.toJSON(o[i]) || "null"); return "[" + ret.join(",") + "]";
            }
            var pairs = []; for (var k in o) {
                var name; var type = typeof k; if (type == "number")
                    name = '"' + k + '"'; else if (type == "string")
                    name = $.quoteString(k); else
                    continue; if (typeof o[k] == "function")
                    continue; var val = $.toJSON(o[k]); pairs.push(name + ":" + val);
            }
            return "{" + pairs.join(", ") + "}";
        } 
    }; $.evalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src); return eval("(" + src + ")");
    }; $.secureEvalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(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.");
    }; $.quoteString = function (string) {
        if (string.match(_escapeable)) {
            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 + '"';
    }; var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g; var _meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' };
})(jQuery);

jQuery(document).ready(function () {
    var sfEls = document.getElementById("menu").getElementsByTagName("li");

    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onmouseover = function () {
            this.className += " sfhover";
        }
        sfEls[i].onmouseout = function () {
            this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
        }
    }

    //Zebra striping and hover effects for tables
    $('table.tableCommon tr:even').addClass('oddRow');

    $('.slider .handle').click(function () {
        var slider = $(this).parents('.slider');
        $('.content', slider).slideToggle();
        return false;
    });

    $('#friendReferralForm').ReferralForm({ 'sendReferralMethodName': 'SendFriendReferral' });
    $('#clientReferralForm').ReferralForm({ 'sendReferralMethodName': 'SendRealtorReferral' });
    $('#sportsTeamReferralForm').ReferralForm({ 'sendReferralMethodName': 'SendSportsTeamReferral' });
    $('#charityReferralForm').ReferralForm({ 'sendReferralMethodName': 'SendCharityReferral' });

});

function CallJSONService(methodName, data, successCallback, errorCallback) {
    $.ajax({
        type: "POST",
        url: "/services/referral-services.asmx/" + methodName,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { if (successCallback) successCallback(data) },
        error: function (jqXHR, textStatus, errorThrown) { if (errorCallback) errorCallback(errorThrown) }
    });
}

//JQuery function to get a serialized Array ready for conversion to JSON
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();

    $.each(a, function () {
        var isFieldGroup = (this.name.indexOf("[]") != -1);
        var cleanFieldName = this.name.replace("[]", "");

        //If the field is already in the array or it's a form field group we'll then drop it into our output as an array
        if (isFieldGroup || o[cleanFieldName]) {
            //If we can't push a new value then the original value is a string so we'll convert it to an array.
            if (o[cleanFieldName] && !o[cleanFieldName].push) {
                o[cleanFieldName] = [o[cleanFieldName]];
            }

            //Push the new value.
            if (o[cleanFieldName])
                o[cleanFieldName].push(this.value || '');
            else
                o[cleanFieldName] = [this.value || '']
        }
        else {
            o[cleanFieldName] = this.value || '';
        }
    });
    return o;
};

//AJAX Edit Table component for all of the ajax calls on the impact sheet pages for indicators, projects and capacities
(function ($) {
    $.fn.ReferralForm = function (options) {
        var settings = {
            'sendReferralMethodName': '',
            'formSent': false
        };

        return this.each(function () {
            // If options exist, lets merge them
            // with our default settings
            if (options) {
                $.extend(settings, options);
            }

            var referralForm = this;

            $('.button', referralForm).live('click', function () {
                var parentContainer = $(this).parents('.referralForm');

                if (parentContainer.validationEngine('validate') && !options.formSent) {
                    //Show a saving animation and then hide it once the ajax response is received.
                    $(this).after('<div class="message warning sending"><img src="/_img/loading.gif" class="alignLeft" /> Sending Referral</div>');
                    $('.sending', parentContainer).fadeIn(500);

                    CallJSONService(
                        options.sendReferralMethodName,
                        $.toJSON($('*', parentContainer).serializeObject()),
                        function (msg) {
                            options.formSent = true;

                            var result = jQuery.parseJSON(msg);
                            $('.sending', parentContainer).fadeOut(500).queue(function() {
                                $('.referralSent', parentContainer).fadeIn(500).delay(5000).queue(function () {
                                    $('.sending', parentContainer).remove();
                                    $('.referralSent', parentContainer).hide();
                                    $('.content', parentContainer).slideUp('slow');
                                    clearForm(parentContainer);
                                    options.formSent = false;
                                });
                            });
                        }
                    );
                }
                return false;
            });
        });
    };
})(jQuery);

function clearForm(container) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', container).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};
