var _checkQueue = [],
    _onresponseQueue = [];

window.parseJSONP = function(response) {
    if (_onresponseQueue.length) {
        _onresponseQueue.pop()(response);
        if (_checkQueue.length) {
            _checkQueue.pop()();
        }
    }
};

(function() {

    function _onsuccess_checkProfanity(form, input, responseJsonObject, callback) {
        var callSucessful = true,
            isProfane = false;

        if (responseJsonObject.response == "invalidResponseFromWebservice") {
    	    //alert("The Profanity-Filtering Service is not available at the moment. Please contact the administrator, and please try again later.");
            callSucessful = false;
        }

        if (callSucessful == true)
        {
            var screen = responseJsonObject.response[0].filter,
                replacementText = screen.replacement;
                
            if (screen.matched == true) {
       	        isProfane = true;
   	        }
   	        if (replacementText == "#") {
   	            replacementText = "";
   	        }
   	        if (replacementText.match("##") != null) {
   	            isProfane = true;
   	        }
   	        replacementText = decodeURIComponent(replacementText);
   	        replacementText = replacementText.replace(/ temp_percent /g, "%25");
   	        replacementText = replacementText.replace(/ temp_registered_trademark /g, "%AE");
   	        replacementText = replacementText.replace(/ temp_trademark /g, "%u2122");
   	        replacementText = replacementText.replace(/ temp_lesser_than /g, "%3C");
   	        replacementText = replacementText.replace(/ temp_greater_than /g, "%3E");
   	        replacementText = unescape(replacementText);
   	        input.value = replacementText;
        }
        $(input)
            .attr('data-is-profane', isProfane)
            .removeAttr('disabled');
        form = $(form);
        var count = form.data('inputs-to-check');
        form.data('inputs-to-check', count--);
        if (isProfane) {
            DYP.filter.markAsProfane(input);
        }
        else {
            DYP.filter.markAsClean(input);
            if (count < 1 && form.find('input[data-is-profane=true]').length < 1 && form[0].tagName == 'FORM') {
                form.data('is-ok-to-submit', true);
                if (callback) {
                    callback();
                }
                else {
                    form[0].submit();
                }
            }
        }
    }
    
    if (!window.DYP) {
        window.DYP = {};
    }

    DYP.filter = {
        errorTemplate: "<em class='profane'></em>",
        message: "We don't allow profanity on this site. Please choose something else.",
        errorClass: 'profane',
        checkForProfanity: function(form, callback) {
            var inputs = form.find('.profanityFilter');
            form
                .data('is-ok-to-submit', false)
                .data('inputs-to-check', inputs.length);
            inputs.each(function(i, input) {
                $(input).attr('disabled', 'disabled');
                DYP.filter.check(form, input, 'Slang', 'en', callback);
            });
            if (_checkQueue.length) {
                _checkQueue.pop()();
            }
        },
        markAsProfane: function(input) {
            input = $(input);
            if (!input.data('hasError')) {
                input
                    .data('hasError', true)
                    .addClass(DYP.filter.errorClass);
                var error = $(DYP.filter.errorTemplate).html(DYP.filter.message);
                input.parent().prepend(error);
            }
        },
        markAsClean: function(input, override) {
            $(input)
                .removeClass(DYP.filter.errorClass)
                .data('isProfane', false)
                .data('hasError', false)
                .siblings('em.profane')
                    .remove();
        },
        check: function(form, input, category, locale, callback) {
            var params = "",
    	        rawContent = input.value,
                wordContent,
                url;
            inputChecked = input;
            if (rawContent == "") {
                rawContent = "#";
            }
            rawContent = escape(rawContent)
                .replace(/%3E/g, "")
                .replace(/%3C/g, "")
                .replace(/%u2122/g, "")
                .replace(/%AE/g, "")
                .replace(/%25/g, "")
                .replace(/%28/g, "")
                .replace(/%7B/g, "")
                .replace(/%7D/g, "")
                .replace(/%29/g, "");
            wordContent = encodeURIComponent(rawContent);
            params += ("word=" + wordContent + "&");
            params = params.substr(0, (params.length-1));
            params += ("&category=" + category); 
            params += ("&locale=" + locale);
            _checkQueue.push(function() {
                $.ajax({
                    url: KelloggsServiceURL + '/bin/filter.json', 
                    jsonp: 'callback',
                    jsonpCallback: "parseJSONP",
                    data: params,
                    dataType: 'jsonp',
                    error: function(jqXHR, textStatus, errorThrown) {                        
                        parseJSONP({"response": [{"filter":{"matched":false,"matches":[],"replacement":input.value}}]});
                    }
                });
            });
            _onresponseQueue.push(function(response) {
                _onsuccess_checkProfanity(form, input, response, callback);
            });
        }
    }
})();
