/*global window, $CQ */
(function($) {

    window.DQM = window.DQM || {};

    function handleInvalidConfiguration(message, configUrl) {
        if (confirm(message + " Click OK to configure it now.")) {
            window.open(configUrl);
        }
    }

    window.DQM.handleStatusCode = function(jqXHR, confirmConfig) {
        var result = {};
        switch (jqXHR.status) {
            case 500 :
                result = {
                    title: jqXHR.statusText,
                    message: "An error was encountered while validating the page. Please check the CQ logs for more information"
                };
                break;
            case 403 :
            case 404 :
                var configUrl = "/system/console/configMgr/com.crownpeakdqm.aem.service.ActiveStandardsValidationServiceImpl";
                result = {
                    title: "Invalid Configuration",
                    message: "The Crownpeak DQM API key and/or website id are probably misconfigured.",
                    configUrl: configUrl
                };
                if (confirmConfig) {
                    handleInvalidConfiguration(result.message, configUrl);
                }
                break;
            default :
                var msg = "An unexpected error occurred. HTTP Status code: " + jqXHR.status + " - " + jqXHR.statusText;
                try { msg = $.parseJSON(jqXHR.responseText).message; } catch (e) { /*ignore*/ }
                result = {
                    title : jqXHR.statusText,
                    message : msg
                };
        }
        return result;
    };
})($CQ);
