<commit_before>define('bforms-ajax', [
    'bforms-namespace',
    'jquery'
], function () {

    var AjaxWrapper = function () {
        this._xhrStack = {};
    };

    //#region private methods and properties
    AjaxWrapper.prototype._defOptions = {
        cache: false,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        context: null,
        registerGlobal: true,
        killPrevious: true,
        loadingDelay: 100,
        parseQueryString: true,
        lang : typeof requireConfig !== "undefined" ? requireConfig.locale : 'en'
    };

    AjaxWrapper.prototype._getStack = function () {
        return this._xhrStack;
    };

    AjaxWrapper.prototype._statusEnum = {
        Success: 1,
        ValidationError: 2,
        Denied: 3,
        ServerError: 4
    };

    AjaxWrapper.prototype.getAjaxOptions = function () {
        return $.extend(true, {}, this._defOptions);
    };

    AjaxWrapper.prototype._updateXHRSettings = function (settings) {

        var XHROpts = $.extend(true, {}, settings);

        XHROpts.data = settings.contentType === this._defOptions.contentType ? JSON.stringify(this._serializeJsonData(settings.data)) : settings.data;

        return XHROpts;
    };

    AjaxWrapper.prototype._serializeJsonData = function (data) {

        var XHRData;

        //if array, clone it
        if (data instanceof Array) {
            XHRData = data.slice(0);
        } else {
            XHRData = $.extend(true, {}, data);
        }

        for (var key in XHRData) {
            if (XHRData.hasOwnProperty(key)) {

                if (typeof XHRData[key] === 'number') {
                    XHRData[key] += '';
                } else {
                    if (typeof XHRData[key] === 'object') {
                        XHRData[key] = this._serializeJsonData(XHRData[key]);
                    }
                }
            }
        }

        return XHRData;
    };

    AjaxWrapper.prototype._killPrevious = function (name) {
        var prevXhr = this._xhrStack[name];
        if (typeof prevXhr !== "undefined" && prevXhr != null && prevXhr.jqXHR != null && typeof prevXhr.jqXHR.abort === 'function' && prevXhr.finished !== true) {
            prevXhr.aborted = true;
            prevXhr.finished = true;
            prevXhr.jqXHR.abort();

            this._xhrStack[name] = prevXhr;
            this._toggleLoading(prevXhr, true);
        }
    };

    AjaxWrapper.prototype._toggleLoading = function (xhrReq, show) {
        var data = typeof xhrReq === 'string' ? this._xhrStack[xhrReq] : xhrReq,
              loadingClass = (typeof data !== 'undefined' && data.settings.loadingClass !== 'undefined') ? data.settings.loadingClass : this._defaultLoadingClass;

        if (typeof data !== 'undefined' && typeof data.settings !== 'undefined') {
            var $elem = data.settings.loadingElement;
            if ($elem != null && $elem.length) {
                window.clearTimeout(this.loadingTimeout);
                if (show) {
                    this.loadingTimeout = window.setTimeout(function () {
                        loadingClass == null ? $elem.show() : $elem.addClass(loadingClass);
                    }, data.settings.loadingDelay);
                } else {
                    loadingClass == null ? $elem.hide() : $elem.removeClass(loadingClass);
                }
            }
        }
    };

    AjaxWrapper.prototype._getQueryStringObject = function () {
        var pairs = location.search.slice(1).split('&');

        var result = {};
        pairs.forEach(function (pair) {
            pair = pair.split('=');
            result[pair[0]] = decodeURIComponent(pair[1] || '');
        });

        return JSON.parse(JSON.stringify(result));
    }
    //#endregion

    //#region public methods
    AjaxWrapper.prototype.ajax = function (opts, calldata) {
        var withFiles = false;
        if (typeof File !== "undefined") {
            for (var k in opts.data) {
                if (opts.data.hasOwnProperty(k)) {
                    if (opts.data[k] instanceof File) {
                        withFiles = true;
                        break;
                    }
                }
            }
        }

        var xhrSettings = $.extend({}, this.getDefaultOptions(), opts),
            jqXHR = null;

        if (this.getDefaultOptions().parseQueryString === true) {
            $.extend(true, xhrSettings.data, this._getQueryStringObject());
        }

        xhrSettings.name = xhrSettings.name || xhrSettings.url;

        if (xhrSettings.killPrevious === true) {
            this._killPrevious(xhrSettings.name);
        }

        //build deferred obj
        var deferredXHR = $.Deferred();

        deferredXHR.done($.proxy(function (status, args) {
            if (status === this._statusEnum.Success) {
                if (typeof opts.success === "function") {
                    opts.success.apply(opts.context, args);
                }
            } else if (status === this._statusEnum.ValidationError) {
                if (typeof opts.validationError === "function") {
                    opts.validationError.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

            if (status === this._statusEnum.ServerError) {
                if (typeof opts.serverError === "function") {
                    opts.serverError.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

            if (status === this._statusEnum.Denied) {
                if (typeof opts.denied === "function") {
                    opts.denied.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

        }, this));

        deferredXHR.fail($.proxy(function (status, args) {

            if (status === this._statusEnum.ServerError) {
                if (typeof opts.serverError === "function") {
                    opts.serverError.apply(opts.context, args);
                }
            } else if (status === this._statusEnum.Denied) {
                if (typeof opts.denied === "function") {
                    opts.denied.apply(opts.context, args);
                }
            }

            if (typeof opts.error === "function") {
                opts.error.apply(opts.context, args);
            }
        }, this));

        if (typeof opts.complete === "function") {
            deferredXHR.always($.proxy(opts.complete, opts.context));
        }

        if (typeof opts.progress === "function") {
            deferredXHR.progress($.proxy(opts.progress, opts.context));
        }

        if (withFiles) {
            jqXHR = this._ajaxWithFiles(xhrSettings, calldata, deferredXHR);
        }

        else {
            jqXHR = this._ajaxWithoutFiles(xhrSettings, calldata, deferredXHR);
        }

        var promise = deferredXHR.promise();
        promise.abort = jqXHR.abort;
        promise.success = deferredXHR.done;
        promise.error = deferredXHR.fail;

        this._toggleLoading(xhrSettings.name, true);

        if (typeof calldata !== 'undefined' && calldata != null) {
            calldata.deferred = deferredXHR;
        }

        return promise;
    };

    AjaxWrapper.prototype._ajaxWithoutFiles = function (xhrSettings, calldata, deferredXHR) {
        var self = this;

        var jqXHRSettings = $.extend({}, xhrSettings, {
            success: function (response, textStatus, jqXHR) {

                var xhrReq = self._xhrStack[xhrSettings.name];
                if (xhrReq.aborted === true) return;

                self._applyLocalization(response, xhrReq.settings.lang);

                try {
                    if (response.Status == self._statusEnum.Success || response.Status == self._statusEnum.ValidationError) {
                        deferredXHR.resolve(response.Status, [response.Data, xhrSettings.callbackData]);
                    } else {
                        deferredXHR.reject(response.Status, [response, jqXHR, textStatus, null, xhrSettings.callbackData]);
                    }
                } catch (ex) {

                    if (typeof ex.stack !== "undefined") {
                        console.warn("Exception occurred in ajax request");
                        console.log(ex.stack);
                    } else {
                        console.warn("Exception occurred in ajax request: " + ex);
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {

                var xhrReq = self._xhrStack[xhrSettings.name];
                if (typeof xhrReq !== 'undefined' && xhrReq != null && xhrReq.aborted === true) return;

                try {

                    if (typeof jqXHR.responseText !== "undefined") {
                        var response = JSON.parse(jqXHR.responseText);
                        deferredXHR.reject(response.Status, [response, jqXHR, textStatus, errorThrown, xhrSettings.callbackData]);
                    } else {
                        deferredXHR.reject(self._statusEnum.ServerError, [{
                            Message: errorThrown
                        }, jqXHR, textStatus, errorThrown, xhrSettings.callbackData]);
                    }

                } catch (ex) {
                    window.console.log(ex.stack);
                }
            },
            complete: function () {
                var xhrReq = self._xhrStack[xhrSettings.name];
                if (typeof xhrReq !== 'undefined') {
                    xhrReq.finished = true;
                }
                self._toggleLoading(xhrSettings.name, false);
            }
        });

        var _settings = this._updateXHRSettings(jqXHRSettings);

        var stackEntry = this._xhrStack[xhrSettings.name] = {
            jqXHR: $.ajax(_settings),
            aborted: false,
            settings: xhrSettings
        };

        return stackEntry.jqXHR;
    };

    AjaxWrapper.prototype._ajaxWithFiles = function (opts, calldata, deferredXHR) {

        var xhrRequest = new XMLHttpRequest(),
            data = new FormData(),
            self = this;

        for (var k in opts.data) {
            if (opts.data.hasOwnProperty(k)) {
                data.append(k, opts.data[k]);
            }
        }

        opts.contentType = '';

        $.extend(true, xhrRequest, $.extend(true, {}, this.getDefaultOptions(), opts));

        xhrRequest.upload.addEventListener('progress', $.proxy(function (e) {
            e.progress = e.progress / e.total;
            deferredXHR.notifyWith(e, opts.callbackData);
        }, this));

        xhrRequest.onreadystatechange = $.proxy(function (e) {
            var stackedXhr = this._xhrStack[xhrRequest.name];

            if (xhrRequest.readyState === 4 && stackedXhr.aborted !== true) {
                var response = JSON.parse(xhrRequest.responseText);
                if (response.Status == self._statusEnum.Success || response.Status == self._statusEnum.ValidationError) {
                    deferredXHR.resolve(response.Status, [response, opts.callbackData]);
                } else {
                    deferredXHR.reject(response.Status, [response != null ? null : response.Data, jqXHR, textStatus, errorThrown, opts.callbackData]);
                }

                self._toggleLoading(opts.name, false);
            }
        }, this);

        xhrRequest.open('POST', opts.url, true);
        xhrRequest.send(data);

        this._xhrStack[opts.name] = {
            jqXHR: xhrRequest,
            aborted: false,
            settings: opts
        };

        return this._xhrStack[opts.name].jqXHR;
    };

    AjaxWrapper.prototype.getDefaultOptions = function () {
        return $.extend(true, {}, this._defOptions);
    };

    AjaxWrapper.prototype.abort = function (name) {
        var xhrRequest = this._xhrStack[name];

        if (typeof xhrRequest !== 'undefined' && xhrRequest != null && xhrRequest.jqXHR != null) {
            xhrRequest.jqXHR.abort();
            xhrRequest.aborted = true;

        }
    };

    AjaxWrapper.prototype._applyLocalization = function (response, lang) {
        if (response.Release == true) {

            var statusName;

            for (var key in this._statusEnum) {
                if (this._statusEnum[key] == response.Status) {
                    statusName = key;
                    break;
                }
            }

            if (!response.Message && typeof statusName === "string" && typeof $.bforms.ajaxResources[lang] === "object" && typeof $.bforms.ajaxResources[lang][statusName] === "string") {
                response.Message = $.bforms.ajaxResources[lang][statusName];
            }
        }
    };

    //#endregion

    $.extend(true, $.bforms, new AjaxWrapper());

    $.bforms.ajaxResources = $.extend(true, $.bforms.ajaxResources, {
        en: {
            ValidationError: 'A validation error has occured',
            Denied: 'The request was denied',
            ServerError: 'Server error'
        }
    });

    $.bforms.addResources = function (lang, resources) {

        if (typeof $.bforms.ajaxResources[lang] !== "undefined") {
            $.extend(true, $.bforms.ajaxResources[lang], resources);
        } else {
            $.bforms.ajaxResources[lang] = resources;
        }
    };

    // return module
    return AjaxWrapper;
})<commit_msg>localization for error messages, part 2<commit_after>define('bforms-ajax', [
    'bforms-namespace',
    'jquery'
], function () {

    var AjaxWrapper = function () {
        this._xhrStack = {};
    };

    //#region private methods and properties
    AjaxWrapper.prototype._defOptions = {
        cache: false,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        context: null,
        registerGlobal: true,
        killPrevious: true,
        loadingDelay: 100,
        parseQueryString: true,
        lang: typeof requireConfig !== "undefined" ? requireConfig.locale : 'en'
    };

    AjaxWrapper.prototype._getStack = function () {
        return this._xhrStack;
    };

    AjaxWrapper.prototype._statusEnum = {
        Success: 1,
        ValidationError: 2,
        Denied: 3,
        ServerError: 4
    };

    AjaxWrapper.prototype.getAjaxOptions = function () {
        return $.extend(true, {}, this._defOptions);
    };

    AjaxWrapper.prototype._updateXHRSettings = function (settings) {

        var XHROpts = $.extend(true, {}, settings);

        XHROpts.data = settings.contentType === this._defOptions.contentType ? JSON.stringify(this._serializeJsonData(settings.data)) : settings.data;

        return XHROpts;
    };

    AjaxWrapper.prototype._serializeJsonData = function (data) {

        var XHRData;

        //if array, clone it
        if (data instanceof Array) {
            XHRData = data.slice(0);
        } else {
            XHRData = $.extend(true, {}, data);
        }

        for (var key in XHRData) {
            if (XHRData.hasOwnProperty(key)) {

                if (typeof XHRData[key] === 'number') {
                    XHRData[key] += '';
                } else {
                    if (typeof XHRData[key] === 'object') {
                        XHRData[key] = this._serializeJsonData(XHRData[key]);
                    }
                }
            }
        }

        return XHRData;
    };

    AjaxWrapper.prototype._killPrevious = function (name) {
        var prevXhr = this._xhrStack[name];
        if (typeof prevXhr !== "undefined" && prevXhr != null && prevXhr.jqXHR != null && typeof prevXhr.jqXHR.abort === 'function' && prevXhr.finished !== true) {
            prevXhr.aborted = true;
            prevXhr.finished = true;
            prevXhr.jqXHR.abort();

            this._xhrStack[name] = prevXhr;
            this._toggleLoading(prevXhr, true);
        }
    };

    AjaxWrapper.prototype._toggleLoading = function (xhrReq, show) {
        var data = typeof xhrReq === 'string' ? this._xhrStack[xhrReq] : xhrReq,
              loadingClass = (typeof data !== 'undefined' && data.settings.loadingClass !== 'undefined') ? data.settings.loadingClass : this._defaultLoadingClass;

        if (typeof data !== 'undefined' && typeof data.settings !== 'undefined') {
            var $elem = data.settings.loadingElement;
            if ($elem != null && $elem.length) {
                window.clearTimeout(this.loadingTimeout);
                if (show) {
                    this.loadingTimeout = window.setTimeout(function () {
                        loadingClass == null ? $elem.show() : $elem.addClass(loadingClass);
                    }, data.settings.loadingDelay);
                } else {
                    loadingClass == null ? $elem.hide() : $elem.removeClass(loadingClass);
                }
            }
        }
    };

    AjaxWrapper.prototype._getQueryStringObject = function () {
        var pairs = location.search.slice(1).split('&');

        var result = {};
        pairs.forEach(function (pair) {
            pair = pair.split('=');
            result[pair[0]] = decodeURIComponent(pair[1] || '');
        });

        return JSON.parse(JSON.stringify(result));
    }
    //#endregion

    //#region public methods
    AjaxWrapper.prototype.ajax = function (opts, calldata) {
        var withFiles = false;
        if (typeof File !== "undefined") {
            for (var k in opts.data) {
                if (opts.data.hasOwnProperty(k)) {
                    if (opts.data[k] instanceof File) {
                        withFiles = true;
                        break;
                    }
                }
            }
        }

        var xhrSettings = $.extend({}, this.getDefaultOptions(), opts),
            jqXHR = null;

        if (this.getDefaultOptions().parseQueryString === true) {
            $.extend(true, xhrSettings.data, this._getQueryStringObject());
        }

        xhrSettings.name = xhrSettings.name || xhrSettings.url;

        if (xhrSettings.killPrevious === true) {
            this._killPrevious(xhrSettings.name);
        }

        //build deferred obj
        var deferredXHR = $.Deferred();

        deferredXHR.done($.proxy(function (status, args) {
            if (status === this._statusEnum.Success) {
                if (typeof opts.success === "function") {
                    opts.success.apply(opts.context, args);
                }
            } else if (status === this._statusEnum.ValidationError) {
                if (typeof opts.validationError === "function") {
                    opts.validationError.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

            if (status === this._statusEnum.ServerError) {
                if (typeof opts.serverError === "function") {
                    opts.serverError.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

            if (status === this._statusEnum.Denied) {
                if (typeof opts.denied === "function") {
                    opts.denied.apply(opts.context, args);
                }

                if (typeof opts.error === "function") {
                    opts.error.apply(opts.context, args);
                }
            }

        }, this));

        deferredXHR.fail($.proxy(function (status, args) {

            if (status === this._statusEnum.ServerError) {
                if (typeof opts.serverError === "function") {
                    opts.serverError.apply(opts.context, args);
                }
            } else if (status === this._statusEnum.Denied) {
                if (typeof opts.denied === "function") {
                    opts.denied.apply(opts.context, args);
                }
            }

            if (typeof opts.error === "function") {
                opts.error.apply(opts.context, args);
            }
        }, this));

        if (typeof opts.complete === "function") {
            deferredXHR.always($.proxy(opts.complete, opts.context));
        }

        if (typeof opts.progress === "function") {
            deferredXHR.progress($.proxy(opts.progress, opts.context));
        }

        if (withFiles) {
            jqXHR = this._ajaxWithFiles(xhrSettings, calldata, deferredXHR);
        }

        else {
            jqXHR = this._ajaxWithoutFiles(xhrSettings, calldata, deferredXHR);
        }

        var promise = deferredXHR.promise();
        promise.abort = jqXHR.abort;
        promise.success = deferredXHR.done;
        promise.error = deferredXHR.fail;

        this._toggleLoading(xhrSettings.name, true);

        if (typeof calldata !== 'undefined' && calldata != null) {
            calldata.deferred = deferredXHR;
        }

        return promise;
    };

    AjaxWrapper.prototype._ajaxWithoutFiles = function (xhrSettings, calldata, deferredXHR) {
        var self = this,
            jqXHRSettings = $.extend({}, xhrSettings, {
                success: function (response, textStatus, jqXHR) {

                    var xhrReq = self._xhrStack[xhrSettings.name];
                    if (xhrReq.aborted === true) return;

                    self._applyLocalization(response, xhrReq.settings.lang);

                    try {
                        if (response.Status == self._statusEnum.Success || response.Status == self._statusEnum.ValidationError) {
                            deferredXHR.resolve(response.Status, [response.Data, xhrSettings.callbackData]);
                        } else {
                            deferredXHR.reject(response.Status, [response, jqXHR, textStatus, null, xhrSettings.callbackData]);
                        }
                    } catch (ex) {

                        if (typeof ex.stack !== "undefined") {
                            console.warn("Exception occurred in ajax request");
                            console.log(ex.stack);
                        } else {
                            console.warn("Exception occurred in ajax request: " + ex);
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {

                    var xhrReq = self._xhrStack[xhrSettings.name];
                    if (typeof xhrReq !== 'undefined' && xhrReq != null && xhrReq.aborted === true) return;

                    try {

                        if (typeof jqXHR.responseText !== "undefined") {

                            var response = JSON.parse(jqXHR.responseText);

                            self._applyLocalization(response, xhrReq.settings.lang);

                            deferredXHR.reject(response.Status, [response, jqXHR, textStatus, errorThrown, xhrSettings.callbackData]);
                        } else {
                            deferredXHR.reject(self._statusEnum.ServerError, [{
                                Message: errorThrown
                            }, jqXHR, textStatus, errorThrown, xhrSettings.callbackData]);
                        }

                    } catch (ex) {
                        window.console.log(ex.stack);
                    }
                },
                complete: function () {
                    var xhrReq = self._xhrStack[xhrSettings.name];
                    if (typeof xhrReq !== 'undefined') {
                        xhrReq.finished = true;
                    }
                    self._toggleLoading(xhrSettings.name, false);
                }
            });

        var _settings = this._updateXHRSettings(jqXHRSettings);

        var stackEntry = this._xhrStack[xhrSettings.name] = {
            jqXHR: $.ajax(_settings),
            aborted: false,
            settings: xhrSettings
        };

        return stackEntry.jqXHR;
    };

    AjaxWrapper.prototype._ajaxWithFiles = function (opts, calldata, deferredXHR) {

        var xhrRequest = new XMLHttpRequest(),
            data = new FormData(),
            self = this;

        for (var k in opts.data) {
            if (opts.data.hasOwnProperty(k)) {
                data.append(k, opts.data[k]);
            }
        }

        opts.contentType = '';

        $.extend(true, xhrRequest, $.extend(true, {}, this.getDefaultOptions(), opts));

        xhrRequest.upload.addEventListener('progress', $.proxy(function (e) {
            e.progress = e.progress / e.total;
            deferredXHR.notifyWith(e, opts.callbackData);
        }, this));

        xhrRequest.onreadystatechange = $.proxy(function (e) {
            var stackedXhr = this._xhrStack[xhrRequest.name];

            if (xhrRequest.readyState === 4 && stackedXhr.aborted !== true) {
                var response = JSON.parse(xhrRequest.responseText);
                if (response.Status == self._statusEnum.Success || response.Status == self._statusEnum.ValidationError) {
                    deferredXHR.resolve(response.Status, [response, opts.callbackData]);
                } else {
                    deferredXHR.reject(response.Status, [response != null ? null : response.Data, jqXHR, textStatus, errorThrown, opts.callbackData]);
                }

                self._toggleLoading(opts.name, false);
            }
        }, this);

        xhrRequest.open('POST', opts.url, true);
        xhrRequest.send(data);

        this._xhrStack[opts.name] = {
            jqXHR: xhrRequest,
            aborted: false,
            settings: opts
        };

        return this._xhrStack[opts.name].jqXHR;
    };

    AjaxWrapper.prototype.getDefaultOptions = function () {
        return $.extend(true, {}, this._defOptions);
    };

    AjaxWrapper.prototype.abort = function (name) {
        var xhrRequest = this._xhrStack[name];

        if (typeof xhrRequest !== 'undefined' && xhrRequest != null && xhrRequest.jqXHR != null) {
            xhrRequest.jqXHR.abort();
            xhrRequest.aborted = true;

        }
    };

    AjaxWrapper.prototype._applyLocalization = function (response, lang) {
        if (response && response.Release == true) {

            var statusName;

            for (var key in this._statusEnum) {
                if (this._statusEnum[key] == response.Status) {
                    statusName = key;
                    break;
                }
            }

            if (!response.Message && typeof statusName === "string" && typeof $.bforms.ajaxResources[lang] === "object" && typeof $.bforms.ajaxResources[lang][statusName] === "string") {
                response.Message = $.bforms.ajaxResources[lang][statusName];
            }
        }
    };

    //#endregion

    $.extend(true, $.bforms, new AjaxWrapper());

    $.bforms.ajaxResources = $.extend(true, $.bforms.ajaxResources, {
        en: {
            ValidationError: 'A validation error has occured',
            Denied: 'The request was denied',
            ServerError: 'Server error'
        }
    });

    $.bforms.addResources = function (lang, resources) {

        if (typeof $.bforms.ajaxResources[lang] !== "undefined") {
            $.extend(true, $.bforms.ajaxResources[lang], resources);
        } else {
            $.bforms.ajaxResources[lang] = resources;
        }
    };

    // return module
    return AjaxWrapper;
})<|endoftext|>


<commit_before>var docs_json = {{ docs_json }};
var render_items = {{ render_items }};

Bokeh.embed.embed_items(docs_json, render_items{%- if websocket_url -%}, "{{ websocket_url }}" {%- endif -%});
<commit_msg>HOTFIX: don't exec bokeh embed until dom ready<commit_after>var docs_json = {{ docs_json }};
var render_items = {{ render_items }};

Bokeh.$(function() {
    Bokeh.embed.embed_items(docs_json, render_items{%- if websocket_url -%}, "{{ websocket_url }}" {%- endif -%});
})<|endoftext|>


<commit_before>/*jslint browser:true devel:true*/
/*global self, Promise, resolve*/

var queueLength = 0;

function upload(data) {
    "use strict";
    var xhr = new XMLHttpRequest();
    while (xhr.status !== 200) {
        xhr = new XMLHttpRequest();
        xhr.open("POST", "/api/v1/faset", false);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.timeout = 5000;
        try {
            xhr.send(data);
            if (xhr.status >= 400) {
                self.postMessage("There was a permanent error uploading a response.")
                return;
            }
        } catch (e) {
            self.postMessage("There was a temporary error uploading a response. Retrying...");
        }
    }
    self.postMessage("");
}

self.addEventListener('message', function (e) {
    'use strict';
    queueLength += 1;
    self.postMessage("Some submissions are being uploaded.");
    upload(e.data);
}, false);
<commit_msg>Wording tweak for loading message<commit_after>/*jslint browser:true devel:true*/
/*global self, Promise, resolve*/

var queueLength = 0;

function upload(data) {
    "use strict";
    var xhr = new XMLHttpRequest();
    while (xhr.status !== 200) {
        xhr = new XMLHttpRequest();
        xhr.open("POST", "/api/v1/faset", false);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.timeout = 5000;
        try {
            xhr.send(data);
            if (xhr.status >= 400) {
                self.postMessage("There was a permanent error uploading a response.")
                return;
            }
        } catch (e) {
            self.postMessage("There was a temporary error uploading a response. Retrying...");
        }
    }
    self.postMessage("");
}

self.addEventListener('message', function (e) {
    'use strict';
    queueLength += 1;
    self.postMessage("Some submissions are still being uploaded.");
    upload(e.data);
}, false);
<|endoftext|>


<commit_before>'use strict';

// Title of event current user wants to unjoin
var event_title = "";

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
	$(".info").toggle();

	// displays created and joined events
	$.get("/data", displayEvents);

	// Clicking unjoin button will delete ID from current user
	$('.events_joined').on('click', '.unjoin_button' , function() {
	event_title = $(this).closest('.panel');
	console.log("unjoin_this: " + event_title.text());

	$.get("/data", unjoinEvent);
	});

	// Clicking unjoin button will delete ID from current user
	$('.events_hosted').on('click', '.delete_button' , function() {
	event_title = $(this).closest('.panel');
	console.log("delete_this: " + event_title.text());

	$.get("/data", deleteEvent);
	});

	// Google Analytics when joined events button is clicked
	$('#loginbuttons').on('click', '#viewEvent' , function() {
		// Send an analytics event when button "Events you've Created/Joined is clicked"
		ga("send", "event", "viewEvent", "click");
	});

	// Google Analytics when joined events button is clicked
	$('#loginbuttonsalt').on('click', '#viewEvent' , function() {
		// Send an analytics event when button "Create New Event" is clicked
		ga("send", "event", "viewEvent", "click");
	});
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	console.log("Javascript connected!");
	var dataURL = "/data";
	$.get(dataURL, changeLoginData);
    $("#submit_button").click(submit_btn);
	$("a.thumbnail").click(eventClick);
}

/*
 * Function that displays the events the user has created followed by the events the user has joined
 */
function displayEvents(result) {
	console.log(result);
	// display the events that the current user is hosting
	// Finds the current user
	var user;
	// Find User information
	var user_info = "";
	console.log("He");
	for(var i = 0; i < result.logindata.length; i++){
		if(result.logindata[i].currentusr == "1"){
			user_info = result.logindata[i]
			console.log(result.logindata[i].username);
			break;
		}
	}
	// current user name
	if (user_info != "") {
		user = user_info.username;

	console.log(user);
	for(var i = 0; i < user_info.joined_events.length; i++){
		for(var j = 0; j < result.events.length; j++){
			// Find events that the current user is the host of
			if(user_info.joined_events[i].id == result.events[j].id && user == result.events[j].host){
				$(".events_hosted").append('

' +
					result.events[j].title + '
' + '
' +
					'
<input class="btn btn-danger delete_button" type="button" value="delete" onclick="window.location.reload()"/>
' + '
'+ '

');
			}

			// Find events that the current user has joined and is not the host of
			else if(user_info.joined_events[i].id == result.events[j].id){
				$(".events_joined").append('

'+result.events[j].title+'
' + '
<input type="button" value="unjoin" class="btn btn-warning unjoin_button" onclick="window.location.reload()"/>
' +
				 	'
'+ '

');
			}
		}
	}
	}
}

function changeLoginData(result){
	console.log(result);
	var resultFound = false;
	for(var i = 1; i < result.logindata.length; i++){
		if(result.logindata[i].currentusr == "1"){
			document.getElementById("username").innerHTML = result.logindata[i].username + " (Logout)";

			$('#loginbuttonsalt').html(' <button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button>   <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You&#39ve Joined</button>');
			$('#loginbuttons').html(' <button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button>

 <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You&#39ve Created/Joined</button>');

			resultFound = true;
		}
	}
	if(!resultFound){
		document.getElementById("username").innerHTML = result.logindata[0].username;
	}
}

// Function that adds JSON information on events when title is clicked
function eventClick(e) {
	// Cancel the default action, which prevents the page from reloading
	e.preventDefault();
    // In an event listener, $(this) is the element that fired the event
 	var eventClicked = $(this).closest(".thumbnail");
    var eventInfo = $(eventClicked).find(".info");
	$(eventInfo).toggle();
	console.log("TOGGLING");

}

function submit_btn(result) {
	console.log("Clicked search button: " + result);
}

function unjoinEvent(result){
	console.log("clicked unjoin: " + event_title.text());

	for(var i = 0; i < result["logindata"].length; i++){
		// if current user then assign to curr
		if(result["logindata"][i].currentusr == "1"){
			for(var j = 0; j < result["events"].length; j++){
				if(event_title.text() == result["events"][j].title){
					$.post('/joined', { 'id': result["events"][j].id, 'user':result["logindata"][i].username });
				}
			}
		}
	}
}

function deleteEvent(result){
	console.log("clicked delete: " + event_title.text());

	for(var i = 0; i < result["logindata"].length; i++){
		// if current user then assign to curr
		if(result["logindata"][i].currentusr == "1"){
			for(var j = 0; j < result["events"].length; j++){
				if(event_title.text() == result["events"][j].title){
					$.post('/joined', { 'del_id': result["events"][j].id, 'user':result["logindata"][i].username });
					break;
				}
			}
		}
	}
}<commit_msg>Added space between buttons<commit_after>'use strict';

// Title of event current user wants to unjoin
var event_title = "";

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
	$(".info").toggle();

	// displays created and joined events
	$.get("/data", displayEvents);

	// Clicking unjoin button will delete ID from current user
	$('.events_joined').on('click', '.unjoin_button' , function() {
	event_title = $(this).closest('.panel');
	console.log("unjoin_this: " + event_title.text());

	$.get("/data", unjoinEvent);
	});

	// Clicking unjoin button will delete ID from current user
	$('.events_hosted').on('click', '.delete_button' , function() {
	event_title = $(this).closest('.panel');
	console.log("delete_this: " + event_title.text());

	$.get("/data", deleteEvent);
	});

	// Google Analytics when joined events button is clicked
	$('#loginbuttons').on('click', '#viewEvent' , function() {
		// Send an analytics event when button "Events you've Created/Joined is clicked"
		ga("send", "event", "viewEvent", "click");
	});

	// Google Analytics when joined events button is clicked
	$('#loginbuttonsalt').on('click', '#viewEvent' , function() {
		// Send an analytics event when button "Create New Event" is clicked
		ga("send", "event", "viewEvent", "click");
	});
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	console.log("Javascript connected!");
	var dataURL = "/data";
	$.get(dataURL, changeLoginData);
    $("#submit_button").click(submit_btn);
	$("a.thumbnail").click(eventClick);
}

/*
 * Function that displays the events the user has created followed by the events the user has joined
 */
function displayEvents(result) {
	console.log(result);
	// display the events that the current user is hosting
	// Finds the current user
	var user;
	// Find User information
	var user_info = "";
	console.log("He");
	for(var i = 0; i < result.logindata.length; i++){
		if(result.logindata[i].currentusr == "1"){
			user_info = result.logindata[i]
			console.log(result.logindata[i].username);
			break;
		}
	}
	// current user name
	if (user_info != "") {
		user = user_info.username;

	console.log(user);
	for(var i = 0; i < user_info.joined_events.length; i++){
		for(var j = 0; j < result.events.length; j++){
			// Find events that the current user is the host of
			if(user_info.joined_events[i].id == result.events[j].id && user == result.events[j].host){
				$(".events_hosted").append('

' +
					result.events[j].title + '
' + '
' +
					'
<input class="btn btn-danger delete_button" type="button" value="delete" onclick="window.location.reload()"/>
' + '
'+ '

');
			}

			// Find events that the current user has joined and is not the host of
			else if(user_info.joined_events[i].id == result.events[j].id){
				$(".events_joined").append('

'+result.events[j].title+'
' + '
<input type="button" value="unjoin" class="btn btn-warning unjoin_button" onclick="window.location.reload()"/>
' +
				 	'
'+ '

');
			}
		}
	}
	}" "
}

function changeLoginData(result){
	console.log(result);
	var resultFound = false;
	for(var i = 1; i < result.logindata.length; i++){
		if(result.logindata[i].currentusr == "1"){
			document.getElementById("username").innerHTML = result.logindata[i].username + " (Logout)";

			$('#loginbuttonsalt').html(' <button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button> &nbsp <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You&#39ve Joined</button>');
			$('#loginbuttons').html(' <button id="newEvent" type="button" class="btn btn-info btn-large">Create New Event</button>

 <button id="viewEvent" type="button" class="btn btn-info btn-large">Events You&#39ve Created/Joined</button>');

			resultFound = true;
		}
	}
	if(!resultFound){
		document.getElementById("username").innerHTML = result.logindata[0].username;
	}
}

// Function that adds JSON information on events when title is clicked
function eventClick(e) {
	// Cancel the default action, which prevents the page from reloading
	e.preventDefault();
    // In an event listener, $(this) is the element that fired the event
 	var eventClicked = $(this).closest(".thumbnail");
    var eventInfo = $(eventClicked).find(".info");
	$(eventInfo).toggle();
	console.log("TOGGLING");

}

function submit_btn(result) {
	console.log("Clicked search button: " + result);
}

function unjoinEvent(result){
	console.log("clicked unjoin: " + event_title.text());

	for(var i = 0; i < result["logindata"].length; i++){
		// if current user then assign to curr
		if(result["logindata"][i].currentusr == "1"){
			for(var j = 0; j < result["events"].length; j++){
				if(event_title.text() == result["events"][j].title){
					$.post('/joined', { 'id': result["events"][j].id, 'user':result["logindata"][i].username });
				}
			}
		}
	}
}

function deleteEvent(result){
	console.log("clicked delete: " + event_title.text());

	for(var i = 0; i < result["logindata"].length; i++){
		// if current user then assign to curr
		if(result["logindata"][i].currentusr == "1"){
			for(var j = 0; j < result["events"].length; j++){
				if(event_title.text() == result["events"][j].title){
					$.post('/joined', { 'del_id': result["events"][j].id, 'user':result["logindata"][i].username });
					break;
				}
			}
		}
	}
}<|endoftext|>


<commit_before>import ModalComponent from 'ghost-admin/components/modal-base';
import {action} from '@ember/object';
import {alias} from '@ember/object/computed';
import {inject as service} from '@ember/service';

const INJECTED_CSS = `
html::-webkit-scrollbar {
    display: none;
    width: 0;
    background: transparent
}
html {
    scrollbar-width: none;
}
body {
    pointer-events: none !important;
}
`;

export default ModalComponent.extend({
    ghostPaths: service(),
    ajax: service(),

    type: 'desktop',
    html: '',
    subject: '',

    post: alias('model'),

    actions: {
        changeType(type) {
            this.set('type', type);
        }
    },

    renderEmailPreview: action(async function renderEmailPreview() {
        await this._fetchEmailData();

        let iframe = this.element.querySelector('iframe');
        if (iframe) {
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(this.html);
            iframe.contentWindow.document.close();
        }
    }),

    async _fetchEmailData() {
        let {html, subject} = this;

        if (html && subject) {
            return {html, subject};
        }

        if (this.post.email) {
            // use sent email
            html = this.post.email.html;
            subject = this.post.email.subject;
        } else {
            // fetch email preview
            let url = this.get('ghostPaths.url').api('/email_preview/posts', this.post.id);
            let response = await this.ajax.request(url);
            let [emailPreview] = response.email_previews;
            html = emailPreview.html;
            subject = emailPreview.subject;
        }

        // inject extra CSS into the html for disabling links and scrollbars etc
        let domParser = new DOMParser();
        let htmlDoc = domParser.parseFromString(html, 'text/html');
        let stylesheet = htmlDoc.querySelector('style');
        let originalCss = stylesheet.innerHTML;
        stylesheet.innerHTML = `${originalCss}\n\n${INJECTED_CSS}`;
        html = htmlDoc.documentElement.innerHTML;

        this.setProperties({html, subject});
    }
});
<commit_msg>Allowed pointer-events on prerview modal<commit_after>import ModalComponent from 'ghost-admin/components/modal-base';
import {action} from '@ember/object';
import {alias} from '@ember/object/computed';
import {inject as service} from '@ember/service';

const INJECTED_CSS = `
html::-webkit-scrollbar {
    display: none;
    width: 0;
    background: transparent
}
html {
    scrollbar-width: none;
}
`;

export default ModalComponent.extend({
    ghostPaths: service(),
    ajax: service(),

    type: 'desktop',
    html: '',
    subject: '',

    post: alias('model'),

    actions: {
        changeType(type) {
            this.set('type', type);
        }
    },

    renderEmailPreview: action(async function renderEmailPreview() {
        await this._fetchEmailData();

        let iframe = this.element.querySelector('iframe');
        if (iframe) {
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(this.html);
            iframe.contentWindow.document.close();
        }
    }),

    async _fetchEmailData() {
        let {html, subject} = this;

        if (html && subject) {
            return {html, subject};
        }

        if (this.post.email) {
            // use sent email
            html = this.post.email.html;
            subject = this.post.email.subject;
        } else {
            // fetch email preview
            let url = this.get('ghostPaths.url').api('/email_preview/posts', this.post.id);
            let response = await this.ajax.request(url);
            let [emailPreview] = response.email_previews;
            html = emailPreview.html;
            subject = emailPreview.subject;
        }

        // inject extra CSS into the html for disabling links and scrollbars etc
        let domParser = new DOMParser();
        let htmlDoc = domParser.parseFromString(html, 'text/html');
        let stylesheet = htmlDoc.querySelector('style');
        let originalCss = stylesheet.innerHTML;
        stylesheet.innerHTML = `${originalCss}\n\n${INJECTED_CSS}`;
        html = htmlDoc.documentElement.innerHTML;

        this.setProperties({html, subject});
    }
});
<|endoftext|>


<commit_before>//Object that controls Checkbox Feed Status

function Checky(opts) {
    this.feed_selection   = opts.feed_selection;
    this.check_feed_id    = opts.check_feed_id;
    this.category_feed_id = opts.category_feed_id;
    this.click_all        = opts.click_all;
    this.checky_bar       = opts.checky_bar;
}

Checky.prototype.init = function() {

    var me = this;
    $(document).delegate(me.feed_selection, 'change', function(e) {
        var mode        = $(this).val();
        var checkFeed   = $(me.check_feed_id);
        var categoryFeed = $(me.category_feed_id);
        var ifChecked   = checkFeed.is(':checked');
        var currentUrl  = $(location).attr('href');
        var baseUrl     = $(this).attr('base-url');
        var checkyBar   = $('.checky-bar');
        var collection  = new Array();
        var exam_collection = new Array();

        if (ifChecked && mode != 'none') {

            var conf, color, parent_id;

            if (mode == 'restore' || mode == 'inbox') {
                conf     = confirm("Are you sure you want to restore these feedbacks?");
            }

            if (mode == 'remove') {
                conf  = confirm("Are you sure you want to permanently remove these feedbacks?");
            }

            if (mode == 'publish') {
                conf     = confirm("Are you sure want to publish these feedbacks?");
            }

            if (mode == 'feature') {
                conf     = confirm("Are you sure want to feature these feedbacks?");
            }

            if (mode == 'delete') {
                conf     = confirm("Are you sure want to delete these feedbacks?");
            }

            if (conf) {
                checkFeed.each(function() {
                    if ($(this).is(':checked')) {
                        if ( $('#' + $(this).val()).is(":hidden") == false ) {

                            var my_parent  = $(this).parents('div.feedback-group')
                            var my_ratings = $(this).siblings('.feed-ratings').val();
                            var my_perm = $(this).siblings('.perm-state').val();
                            var feed_unit  = '#' + $(this).val();

                            var data = {
                                "feedid": $(this).val()
                              , "contactid": $(this).siblings('.contact-feed-id').val()
                              , "siteid": $(this).siblings('.site-feed-id').val()
                              , "rating": $(this).siblings('.feed-ratings').val()
                              , "parent_id": my_parent.attr('id')
                              , "perm": my_perm
                              , "mode": mode
                              , "total_units": my_parent.attr('data-total')
                            };

                            //console.log(window.location.pathname.match(/published|contacts/g));
                            if(my_ratings != 'POOR' && (my_perm == 1 || my_perm == 2)) {
                                //console.log("all can pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if(my_ratings == 'POOR' && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("poor rated feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if((my_ratings != 'POOR' && my_perm == 3/*(my_perm == 2 || my_perm == 3)*/) && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("private and limited feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            exam_collection.push(data);
                        }
                    }
                });
                /*
                var limited_perm_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.perm == 2) && (el.mode == 'publish' || el.mode == 'feature');
                });

                var poor_feeds = exam_collection.filter(function(el) {
                    return el.rating == 'POOR' && (el.mode == 'publish' || el.mode == 'feature');
                });

                console.log(limited_perm_feeds);
                console.log(poor_feeds);
                */

                var restricted_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.rating == 'POOR') && (el.mode == 'publish' || el.mode == 'feature');
                });

                console.log(restricted_feeds);

                /*
                if(limited_perm_feeds.length > 0 && poor_feeds.length == 0) {
                    if(limited_perm_feeds.length == 1) {
                        confirm("Warning: This feedback has been marked as private/limited and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that has been marked as private/limited and will not be processed.");
                    }
                }

                if(poor_feeds.length > 0 && limited_perm_feeds.length == 0) {
                    if(poor_feeds.length == 1) {
                        confirm("Warning: This feedback has been rated as poor and will not be processed.");
                    } else {
                        confirm("Warning: There is feedback that has been rated as poor and will not be processed.");
                    }
                }

                if(limited_perm_feeds.length > 0 && poor_feeds.length > 0) {
                    confirm("Warning: There are feedback that have been marked as private/limited and poor and will not be processed.");
                }
                */
                if(restricted_feeds.length > 0) {
                    if(restricted_feeds.length == 1) {
                        confirm("Warning: There is feedback that has been marked as private/limited or poor and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that have been marked as private/limited or poor and will not be processed.");
                    }

                    $.each(restricted_feeds, function(index, value) {
                        $("#" + value.feedid).animate({
                           backgroundColor: '#ff6666'
                        }, 800, function() {
                            $(this).animate({
                                backgroundColor: '#fff'
                            }, 800);
                        })
                    });
                }

                $("option:first", this).prop("selected", true);
                if(collection.length > 0) {
                    $.ajax({
                        type: "POST"
                      , data: {
                          'col': mode
                        , 'feed_ids': collection
                        }
                      , url: $(this).attr("hrefaction")
                      , dataType: "json"
                      , beforeSend: function() {
                          var myStatus = new Status();
                          myStatus.notify("Processing...", 1000);
                      }
                      , success: function(msg) {

                          $.ajax({url: "/feedback/bust_hostfeed_data"});

                          for(var key in msg.ui) {
                              $('#' + key).hide();
                          }

                          var message = msg.message;

                          checkyBar.css({
                              'background': '#fef1b5'
                            , 'width': '200px'
                            , 'right': '35%'
                            , 'top': '15%'
                            , 'text-align': 'center'
                            , 'padding': '5px'
                            , 'font-weight': 'bold'
                          }).html(message).show();

                          //this is for clicking to make this mothafucka vanish
                          mouse_is_inside = false;
                       }
                    });
                }

            }

            $(this).val("none");
            $('.click-all').attr('checked', false);
            checkFeed.attr('checked', false);
        } else {
            $('.click-all').attr('checked', false);
        }
    });
}

Checky.prototype.clickAll = function() {
    var me = this;
    $(document).delegate(me.click_all, 'click', function(e) {
        if (this.checked) {
            $(me.check_feed_id).prop("checked", true);
            $(me.click_all).prop("checked", true);
        } else {
            $(me.check_feed_id).prop("checked", false);
            $(me.click_all).prop("checked", false);
        }
    });
}

function process_feedbacks(collection, data, units) {
    collection.push(data);
    //units to vanished
    $(units).fadeOut(300, function() { $(this).hide(); });
}
<commit_msg>eqw wq<commit_after>//Object that controls Checkbox Feed Status

function Checky(opts) {
    this.feed_selection   = opts.feed_selection;
    this.check_feed_id    = opts.check_feed_id;
    this.category_feed_id = opts.category_feed_id;
    this.click_all        = opts.click_all;
    this.checky_bar       = opts.checky_bar;
}

Checky.prototype.init = function() {

    var me = this;
    $(document).delegate(me.feed_selection, 'change', function(e) {
        var mode        = $(this).val();
        var checkFeed   = $(me.check_feed_id);
        var categoryFeed = $(me.category_feed_id);
        var ifChecked   = checkFeed.is(':checked');
        var currentUrl  = $(location).attr('href');
        var baseUrl     = $(this).attr('base-url');
        var checkyBar   = $('.checky-bar');
        var collection  = new Array();
        var exam_collection = new Array();

        if (ifChecked && mode != 'none') {

            var conf, color, parent_id;

            if (mode == 'restore' || mode == 'inbox') {
                conf     = confirm("Are you sure you want to restore these feedbacks?");
            }

            if (mode == 'remove') {
                conf  = confirm("Are you sure you want to permanently remove these feedbacks?");
            }

            if (mode == 'publish') {
                conf     = confirm("Are you sure want to publish these feedbacks?");
            }

            if (mode == 'feature') {
                conf     = confirm("Are you sure want to feature these feedbacks?");
            }

            if (mode == 'delete') {
                conf     = confirm("Are you sure want to delete these feedbacks?");
            }

            if (conf) {
                checkFeed.each(function() {
                    if ($(this).is(':checked')) {
                        if ( $('#' + $(this).val()).is(":hidden") == false ) {

                            var my_parent  = $(this).parents('div.feedback-group')
                            var my_ratings = $(this).siblings('.feed-ratings').val();
                            var my_perm = $(this).siblings('.perm-state').val();
                            var feed_unit  = '#' + $(this).val();

                            var data = {
                                "feedid": $(this).val()
                              , "contactid": $(this).siblings('.contact-feed-id').val()
                              , "siteid": $(this).siblings('.site-feed-id').val()
                              , "rating": $(this).siblings('.feed-ratings').val()
                              , "parent_id": my_parent.attr('id')
                              , "perm": my_perm
                              , "mode": mode
                              , "total_units": my_parent.attr('data-total')
                            };

                            //console.log(window.location.pathname.match(/published|contacts/g));
                            if(my_ratings != 'POOR' && (my_perm == 1 || my_perm == 2)) {
                                //console.log("all can pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if(my_ratings == 'POOR' && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("poor rated feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            if((my_ratings != 'POOR' && my_perm == 3/*(my_perm == 2 || my_perm == 3)*/) && (mode == 'delete' || mode == 'restore' || mode == 'remove')) {
                                //console.log("private and limited feeds cannot pass");
                                process_feedbacks(collection, data, feed_unit);
                            }

                            exam_collection.push(data);
                        }
                    }
                });
                /*
                var limited_perm_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.perm == 2) && (el.mode == 'publish' || el.mode == 'feature');
                });

                var poor_feeds = exam_collection.filter(function(el) {
                    return el.rating == 'POOR' && (el.mode == 'publish' || el.mode == 'feature');
                });

                console.log(limited_perm_feeds);
                console.log(poor_feeds);
                */

                var restricted_feeds = exam_collection.filter(function(el) {
                    return (el.perm == 3 || el.rating == 'POOR') && (el.mode == 'publish' || el.mode == 'feature');
                });

                /*
                if(limited_perm_feeds.length > 0 && poor_feeds.length == 0) {
                    if(limited_perm_feeds.length == 1) {
                        confirm("Warning: This feedback has been marked as private/limited and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that has been marked as private/limited and will not be processed.");
                    }
                }

                if(poor_feeds.length > 0 && limited_perm_feeds.length == 0) {
                    if(poor_feeds.length == 1) {
                        confirm("Warning: This feedback has been rated as poor and will not be processed.");
                    } else {
                        confirm("Warning: There is feedback that has been rated as poor and will not be processed.");
                    }
                }

                if(limited_perm_feeds.length > 0 && poor_feeds.length > 0) {
                    confirm("Warning: There are feedback that have been marked as private/limited and poor and will not be processed.");
                }
                */
                if(restricted_feeds.length > 0) {
                    if(restricted_feeds.length == 1) {
                        confirm("Warning: There is feedback that has been marked as private/limited or poor and will not be processed.");
                    } else {
                        confirm("Warning: There are feedback that have been marked as private/limited or poor and will not be processed.");
                    }

                    $.each(restricted_feeds, function(index, value) {
                        $("#" + value.feedid).animate({
                           backgroundColor: '#ff6666'
                        }, 800, function() {
                            $(this).animate({
                                backgroundColor: '#fff'
                            }, 800);
                        })
                    });
                }

                $("option:first", this).prop("selected", true);
                if(collection.length > 0) {
                    $.ajax({
                        type: "POST"
                      , data: {
                          'col': mode
                        , 'feed_ids': collection
                        }
                      , url: $(this).attr("hrefaction")
                      , dataType: "json"
                      , beforeSend: function() {
                          var myStatus = new Status();
                          myStatus.notify("Processing...", 1000);
                      }
                      , success: function(msg) {

                          $.ajax({url: "/feedback/bust_hostfeed_data"});

                          for(var key in msg.ui) {
                              $('#' + key).hide();
                          }

                          var message = msg.message;

                          checkyBar.css({
                              'background': '#fef1b5'
                            , 'width': '200px'
                            , 'right': '35%'
                            , 'top': '15%'
                            , 'text-align': 'center'
                            , 'padding': '5px'
                            , 'font-weight': 'bold'
                          }).html(message).show();

                          //this is for clicking to make this mothafucka vanish
                          mouse_is_inside = false;
                       }
                    });
                }

            }

            $(this).val("none");
            $('.click-all').attr('checked', false);
            checkFeed.attr('checked', false);
        } else {
            $('.click-all').attr('checked', false);
        }
    });
}

Checky.prototype.clickAll = function() {
    var me = this;
    $(document).delegate(me.click_all, 'click', function(e) {
        if (this.checked) {
            $(me.check_feed_id).prop("checked", true);
            $(me.click_all).prop("checked", true);
        } else {
            $(me.check_feed_id).prop("checked", false);
            $(me.click_all).prop("checked", false);
        }
    });
}

function process_feedbacks(collection, data, units) {
    collection.push(data);
    //units to vanished
    $(units).fadeOut(300, function() { $(this).hide(); });
}
<|endoftext|>


<commit_before>//page init function
    function init(){
        window.count = 0;
        window.main_old_fields =  $('.removeIndicator').clone();
        window.schema_json = {"resource":[{"name":"","description":"","field":[]}]  }
    }
    //destroy table
    function destroy_table(table_name, service_name){
        if(confirm('Are you sure you want to delete '+table_name+' table?')){
            var settings = {
           "async": true,
           "crossDomain": true,
           "url": "/api/v1/service/"+service_name+"/db",
           "method": "DELETE",
           "headers": {
             "content-type": "application/json",
             "cache-control": "no-cache",
           },
           "processData": false,
            "data": "{\"resource\":[{\"name\":\""+table_name+"\",\"params\":[{\"drop\":\"true\"}]}]}"
           }
         $(".delete-"+table_name)[0].innerText = "...";
         $.ajax(settings).done(function (response) {
             console.log(response)
           status_code = response.status_code;
           if (status_code != 613) {
             alert('could not delete table ');
           }
           partialUpdate(['service-tables']);

         });}
    }
  function append_field(){
    field_names = ['name', 'description', 'field-name', 'field-type', 'field-reference',
                'default','required', 'validate', 'unique'];
    old_fields = window.main_old_fields.clone();
          field_names.forEach(
    function(i){
              field_name = i+window.count;
              old_fields.find('#'+i).attr('name', field_name ).attr('id', field_name );
         }
    )
    new_fields = old_fields;
    $( ".dynamic-space").append(new_fields);
    old_fields.attr('class', 'fields'+window.count);
    old_fields.contents().each(function () {
        if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/removeIndicator/g, "fields"+window.count)
        if (this.nodeType === 1) $(this).html( $(this).html().replace(/removeIndicator/g, "fields"+window.count) )
        })
    window.count = window.count + 1 ;

    }

    function create_table(service_name){
         $('#crt-tbl').prop('disabled', true);
         $.fn.serializeObject = function()
        {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
        object = $('#form').serializeObject();
        var array = $.map(object, function(value, index) {
        return [value];
        });
        count = 0
        jQuery(
            function($)
            {
              count = 0 ;
              form_array = [];
              $.each($('#form')[0].elements,
                     function(i,o)
                     {
                      var _this=$(o);
                      field_id = _this.attr('id');
                       if(typeof field_id == "string" && field_id.indexOf("validate")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }
                       else if(typeof field_id == "string" && field_id.indexOf("required")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }
                       else if(typeof field_id == "string" && field_id.indexOf("unique")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }else{
                           form_array[count] = $('#'+_this.attr('id')).val();
                       }
                    count++;
                     })
            }
          );
            if(form_array.length > 4){
                function trim(str){
                    console.log(str);
                    if(typeof str == "string"){

                        return str.replace(/\s+/g, '').toLowerCase();
                    }else{
                        return str;
                    }
                }
                window.schema_json.resource[0].name = trim(form_array[0]);
                window.schema_json.resource[0].description = form_array[1]  ;
                var len = ((form_array.length)-4)/8;

                for (var i = 1; i <= len; i++) {
                    position = ((len-i)*8)
                    if(form_array[6+position] == ""){ _default = null;}else{_default = form_array[6+position]; }
                    console.log("field tpe", trim(form_array[4+position]));
                    if(trim(form_array[4+position]) == "reference")
                    {
                        console.log('appended service')
                        referenced_table_name = service_name+'_'+trim(form_array[5+position])+'_id';

                    }else{
                        referenced_table_name = trim(form_array[3+position]);
                        console.log('went for else instead')
                    }
                    console.log('ref after passing', referenced_table_name);
                    window.schema_json.resource[0].field[i-1] = {
                        "name":    referenced_table_name,
                        "field_type":trim(form_array[4+position]),
                        "ref_table":trim(form_array[5+position]),
                        "default":_default,
                        "required":trim(form_array[7+position]),
                        "validation":trim(form_array[8+position]),
                        "is_unique":trim(form_array[9+position]),
                     };
                }

                if (len => 1) {
                   table_schema =   JSON.stringify(window.schema_json);
                   var settings = {
                    "async": true,
                    "crossDomain": true,
                    "url": "/api/v1/service/"+service_name+"/schema",
                    "method": "POST",
                    "headers": {
                      "content-type": "application/json",
                      "cache-control": "no-cache",
                    },
                    "processData": false,
                    "data": table_schema
                  }
                $.ajax(settings).done(function (response) {
                  console.log(response);
                  if(typeof(response) == "string")
                  {
                      response = JSON.parse(response);
                  }
                  var status_code = response.status_code;
                  var message = response.message;
                  var payload = response.payload;

                  if(status_code == 700){
                      console.log(message)
                      alert(message);
                      $('#crt-tbl').prop('disabled', false);
                  }
                  else if(status_code == 606){
                          window.location.href = window.devless_edit_url;
//                        partialUpdate(['service-tables']);
//                        $('#schema-table').click()
                  }else{
                        alert(message);

                  }
                });} else {

                     alert('Please add at least a field');
                     $('#crt-tbl').prop('disabled', false);
                }
            }
            else{
                alert('Sorry seems like you have no fields set ');
                $('#crt-tbl').prop('disabled', false);
            }

    }
   function destroy_field(field_id){
       $('.'+field_id).remove();
   }
   function set_script(){
       setTimeout(function(){
          $('.code-box').ace({ theme: 'github', lang: 'php',

        });
        var editor = $('.code-box').data('ace');
        // var aceInstance = editor.editor.ace;
        // console.log(aceInstance);

       }, 1);
   }
   function run_script(){
       var form = new FormData();
form.append("call_type", "solo");
form.append("script", $('.code-box').val());
form.append("_method", "PUT");
var script_url = $('#script_url')[0].textContent;
var settings = {
  "async": true,
  "crossDomain": true,
  "url": script_url,
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
  },
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}
$('#saving')[0].style.display = 'block';
$.ajax(settings).done(function (response) {
  result = JSON.parse(response);
    $('#saving')[0].style.display = 'none';
   (result.status_code == 626)?$('.code-console').css('color','green')
 : $('.code-console').css('color','red');
  $('.code-console').html(''+result.message+'');
  if(result.status_code == 626){
      setTimeout(function(){
        $('.code-console').html('');
    }, 950);
  }

});
   }

//save script
document.addEventListener("keydown", function(e) {
    if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
        e.preventDefault();
        run_script();
    }
});

function partialUpdate(ids) {
    $.each(ids, function(index, id){
        $('#'+id).load(document.URL +  ' #'+id);
    });

}

function tableFieldPopulation(fields) {
	for (var i=0; fields.length > i; i++) {
		$('#'+fields[i].name)[0].value = fields[i].value;
	}
}

function updateTable() {
	var service = $('#edit-serviceName')[0].value;
	var table 	= $('#edit-tableName')[0].value;
	var newTableName = $('#newTableName')[0].value;
	var newDesc = $('#newDesc')[0].value;
	var action 	= 'updateTable';
	var params  = newTableName+'-:-'+newDesc;
	SchemaEdit(action, service, table, params);
}

function addNewField() {
	var service = $('#add-serviceName')[0].value;
	var table 	= $('#add-tableName')[0].value;
	var newFieldName = $('#newFieldName')[0].value;
    var fieldType = $('#fieldType')[0].value;
    var referencedField = $('#refField')[0].value;
    var addDefault = $('#addDefault')[0].value;
	var action 	= 'addField';
    var params = newFieldName + '-:-' + fieldType + '-:-' + referencedField + '-:-' +addDefault;
	SchemaEdit(action, service, table, params);
}

function updateFieldName(id) {
	var service = $('#ef-serviceName')[0].value;
	var table 	= $('#ef-tableName')[0].value;
	var newFieldName = $("input[name="+id+"]").val();
	var oldFieldName = id;
	var action 	= 'updateFieldName';
	var params  = oldFieldName+'-:-'+newFieldName;
	SchemaEdit(action, service, table, params);
}

function deleteFieldName(id) {
	var service = $('#ef-serviceName')[0].value;
	var table 	= $('#ef-tableName')[0].value;
	var fieldName = id;
	var action 	= 'deleteField';
	var params  = fieldName;
	SchemaEdit(action, service, table, params);
}
function displayAllFields(service, table) {
	var comb_tableName = service+'_'+table;
  var url = window.location.origin;
	$('#ef-serviceName')[0].value = service;
	$('#ef-tableName')[0].value = table;
  $.get(url+'/datatable/'+service+'_'+table+'/metas',
		function(response){
      $('#fieldList')[0].textContent = '';
      response = response.reverse();
			for(var i = 0; response.length > i; i++) {
				if(response[i] !== 'devless_user_id' && response[i] !== 'id') {
					var field = $('#fieldTemplate')[0].cloneNode(true, true);
					field.id = Math.random();
					$(field).find("input[name=user_bets]")[0].value = response[i];
          $(field).find("input[name=user_bets]")[0].readOnly = false;
          $(field).find("input[name=user_bets]")[0].name = response[i];

					$.each($(field).find("#user_bets"), function(key, field) {
							field.id = response[i];
              field.disabled = false;
					});
					$('#fieldList')[0].append(field);
				}

			}

	});
}

function SchemaEdit(action, service, table, params) {
	var url = window.location.origin;
	var settings = {
  "async": true,
  "crossDomain": true,
  "url": url+"/edit-table/"+action+"/"+service+"/"+table+"/"+params,
  "method": "GET",
  "headers": {
    "content-type": "application/json",
    "cache-control": "no-cache",
  },
  "processData": false
}

$.ajax(settings).done(function (response) {
  if( typeof response == 'string') {
  	response = JSON.parse(response);
  }
  if(response.status == 'ok') {
  	window.location.href = window.devless_edit_url;
  } else {
  	alert('Field/Table could not be modified'+'       '+response.message);
  }
});
}

<commit_msg>fix default field value<commit_after>//page init function
    function init(){
        window.count = 0;
        window.main_old_fields =  $('.removeIndicator').clone();
        window.schema_json = {"resource":[{"name":"","description":"","field":[]}]  }
    }
    //destroy table
    function destroy_table(table_name, service_name){
        if(confirm('Are you sure you want to delete '+table_name+' table?')){
            var settings = {
           "async": true,
           "crossDomain": true,
           "url": "/api/v1/service/"+service_name+"/db",
           "method": "DELETE",
           "headers": {
             "content-type": "application/json",
             "cache-control": "no-cache",
           },
           "processData": false,
            "data": "{\"resource\":[{\"name\":\""+table_name+"\",\"params\":[{\"drop\":\"true\"}]}]}"
           }
         $(".delete-"+table_name)[0].innerText = "...";
         $.ajax(settings).done(function (response) {
             console.log(response)
           status_code = response.status_code;
           if (status_code != 613) {
             alert('could not delete table ');
           }
           partialUpdate(['service-tables']);

         });}
    }
  function append_field(){
    field_names = ['name', 'description', 'field-name', 'field-type', 'field-reference',
                'default','required', 'validate', 'unique'];
    old_fields = window.main_old_fields.clone();
          field_names.forEach(
    function(i){
              field_name = i+window.count;
              old_fields.find('#'+i).attr('name', field_name ).attr('id', field_name );
         }
    )
    new_fields = old_fields;
    $( ".dynamic-space").append(new_fields);
    old_fields.attr('class', 'fields'+window.count);
    old_fields.contents().each(function () {
        if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/removeIndicator/g, "fields"+window.count)
        if (this.nodeType === 1) $(this).html( $(this).html().replace(/removeIndicator/g, "fields"+window.count) )
        })
    window.count = window.count + 1 ;

    }

    function create_table(service_name){
         $('#crt-tbl').prop('disabled', true);
         $.fn.serializeObject = function()
        {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
        object = $('#form').serializeObject();
        var array = $.map(object, function(value, index) {
        return [value];
        });
        count = 0
        jQuery(
            function($)
            {
              count = 0 ;
              form_array = [];
              $.each($('#form')[0].elements,
                     function(i,o)
                     {
                      var _this=$(o);
                      field_id = _this.attr('id');
                       if(typeof field_id == "string" && field_id.indexOf("validate")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }
                       else if(typeof field_id == "string" && field_id.indexOf("required")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }
                       else if(typeof field_id == "string" && field_id.indexOf("unique")>= 0){
                           form_array[count] = $('#'+_this.attr('id')).is(':checked');
                       }else{
                           form_array[count] = $('#'+_this.attr('id')).val();
                       }
                    count++;
                     })
            }
          );
            if(form_array.length > 4){
                function trim(str){
                    console.log(str);
                    if(typeof str == "string"){

                        return str.replace(/\s+/g, '').toLowerCase();
                    }else{
                        return str;
                    }
                }
                window.schema_json.resource[0].name = trim(form_array[0]);
                window.schema_json.resource[0].description = form_array[1]  ;
                var len = ((form_array.length)-4)/8;

                for (var i = 1; i <= len; i++) {
                    position = ((len-i)*8)
                    if(form_array[6+position] == ""){ _default = null;}else{_default = form_array[6+position]; }
                    console.log("field tpe", trim(form_array[4+position]));
                    if(trim(form_array[4+position]) == "reference")
                    {
                        console.log('appended service')
                        referenced_table_name = service_name+'_'+trim(form_array[5+position])+'_id';

                    }else{
                        referenced_table_name = trim(form_array[3+position]);
                        console.log('went for else instead')
                    }
                    console.log('ref after passing', referenced_table_name);
                    window.schema_json.resource[0].field[i-1] = {
                        "name":    referenced_table_name,
                        "field_type":trim(form_array[4+position]),
                        "ref_table":trim(form_array[5+position]),
                        "default":_default,
                        "required":trim(form_array[7+position]),
                        "validation":trim(form_array[8+position]),
                        "is_unique":trim(form_array[9+position]),
                     };
                }

                if (len => 1) {
                   table_schema =   JSON.stringify(window.schema_json);
                   var settings = {
                    "async": true,
                    "crossDomain": true,
                    "url": "/api/v1/service/"+service_name+"/schema",
                    "method": "POST",
                    "headers": {
                      "content-type": "application/json",
                      "cache-control": "no-cache",
                    },
                    "processData": false,
                    "data": table_schema
                  }
                $.ajax(settings).done(function (response) {
                  console.log(response);
                  if(typeof(response) == "string")
                  {
                      response = JSON.parse(response);
                  }
                  var status_code = response.status_code;
                  var message = response.message;
                  var payload = response.payload;

                  if(status_code == 700){
                      console.log(message)
                      alert(message);
                      $('#crt-tbl').prop('disabled', false);
                  }
                  else if(status_code == 606){
                          window.location.href = window.devless_edit_url;
//                        partialUpdate(['service-tables']);
//                        $('#schema-table').click()
                  }else{
                        alert(message);

                  }
                });} else {

                     alert('Please add at least a field');
                     $('#crt-tbl').prop('disabled', false);
                }
            }
            else{
                alert('Sorry seems like you have no fields set ');
                $('#crt-tbl').prop('disabled', false);
            }

    }
   function destroy_field(field_id){
       $('.'+field_id).remove();
   }
   function set_script(){
       setTimeout(function(){
          $('.code-box').ace({ theme: 'github', lang: 'php',

        });
        var editor = $('.code-box').data('ace');
        // var aceInstance = editor.editor.ace;
        // console.log(aceInstance);

       }, 1);
   }
   function run_script(){
       var form = new FormData();
form.append("call_type", "solo");
form.append("script", $('.code-box').val());
form.append("_method", "PUT");
var script_url = $('#script_url')[0].textContent;
var settings = {
  "async": true,
  "crossDomain": true,
  "url": script_url,
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
  },
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}
$('#saving')[0].style.display = 'block';
$.ajax(settings).done(function (response) {
  result = JSON.parse(response);
    $('#saving')[0].style.display = 'none';
   (result.status_code == 626)?$('.code-console').css('color','green')
 : $('.code-console').css('color','red');
  $('.code-console').html(''+result.message+'');
  if(result.status_code == 626){
      setTimeout(function(){
        $('.code-console').html('');
    }, 950);
  }

});
   }

//save script
document.addEventListener("keydown", function(e) {
    if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
        e.preventDefault();
        run_script();
    }
});

function partialUpdate(ids) {
    $.each(ids, function(index, id){
        $('#'+id).load(document.URL +  ' #'+id);
    });

}

function tableFieldPopulation(fields) {
	for (var i=0; fields.length > i; i++) {
		$('#'+fields[i].name)[0].value = fields[i].value;
	}
}

function updateTable() {
	var service = $('#edit-serviceName')[0].value;
	var table 	= $('#edit-tableName')[0].value;
	var newTableName = $('#newTableName')[0].value;
	var newDesc = $('#newDesc')[0].value;
	var action 	= 'updateTable';
	var params  = newTableName+'-:-'+newDesc;
	SchemaEdit(action, service, table, params);
}

function addNewField() {
	var service = $('#add-serviceName')[0].value;
	var table 	= $('#add-tableName')[0].value;
	var newFieldName = $('#newFieldName')[0].value;
    var fieldType = $('#fieldType')[0].value;
    var referencedField = $('#refField')[0].value;
    var addDefault ='' //$('#addDefault')[0].value;
	var action 	= 'addField';
    var params = newFieldName + '-:-' + fieldType + '-:-' + referencedField + '-:-' +addDefault;
	SchemaEdit(action, service, table, params);
}

function updateFieldName(id) {
	var service = $('#ef-serviceName')[0].value;
	var table 	= $('#ef-tableName')[0].value;
	var newFieldName = $("input[name="+id+"]").val();
	var oldFieldName = id;
	var action 	= 'updateFieldName';
	var params  = oldFieldName+'-:-'+newFieldName;
	SchemaEdit(action, service, table, params);
}

function deleteFieldName(id) {
	var service = $('#ef-serviceName')[0].value;
	var table 	= $('#ef-tableName')[0].value;
	var fieldName = id;
	var action 	= 'deleteField';
	var params  = fieldName;
	SchemaEdit(action, service, table, params);
}
function displayAllFields(service, table) {
	var comb_tableName = service+'_'+table;
  var url = window.location.origin;
	$('#ef-serviceName')[0].value = service;
	$('#ef-tableName')[0].value = table;
  $.get(url+'/datatable/'+service+'_'+table+'/metas',
		function(response){
      $('#fieldList')[0].textContent = '';
      response = response.reverse();
			for(var i = 0; response.length > i; i++) {
				if(response[i] !== 'devless_user_id' && response[i] !== 'id') {
					var field = $('#fieldTemplate')[0].cloneNode(true, true);
					field.id = Math.random();
					$(field).find("input[name=user_bets]")[0].value = response[i];
          $(field).find("input[name=user_bets]")[0].readOnly = false;
          $(field).find("input[name=user_bets]")[0].name = response[i];

					$.each($(field).find("#user_bets"), function(key, field) {
							field.id = response[i];
              field.disabled = false;
					});
					$('#fieldList')[0].append(field);
				}

			}

	});
}

function SchemaEdit(action, service, table, params) {
	var url = window.location.origin;
	var settings = {
  "async": true,
  "crossDomain": true,
  "url": url+"/edit-table/"+action+"/"+service+"/"+table+"/"+params,
  "method": "GET",
  "headers": {
    "content-type": "application/json",
    "cache-control": "no-cache",
  },
  "processData": false
}

$.ajax(settings).done(function (response) {
  if( typeof response == 'string') {
  	response = JSON.parse(response);
  }
  if(response.status == 'ok') {
  	window.location.href = window.devless_edit_url;
  } else {
  	alert('Field/Table could not be modified'+'       '+response.message);
  }
});
}

<|endoftext|>