<commit_before>// finding out keyCode:
// http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

function addShortcut(keyCode, mods, callback) {
    mods = mods || {};
    listenTo(document, 'keydown', function(e) {
        var modsMatched = ((e.ctrlKey  == !!mods.ctrl) &&
                           (e.shiftKey == !!mods.shift) &&
                           (e.altKey   == !!mods.alt) &&
                           (e.metaKey  == !!mods.meta));
        var received = e.keyCode !== undefined ? e.keyCode : e.which;
        if (modsMatched && received == keyCode) {
            callback(e);
            e.preventDefault();
        }
    });
}

var $id = function(x) { return document.getElementById(x); };
var $qs = function(x) { return document.querySelector(x); };
var $qsa = function(x) { return document.querySelectorAll(x); };
var forEach = function (array, callback, scope) {
    for (var i = 0; i < array.length; i++) {
        callback.call(scope || array, array[i], i);
    }
};

function listenTo(els, type, fn) {
    if (!els) return;
    if (els && els.nodeType) return listenTo([els], type, fn);

    for (var i = 0; i < els.length; i++) {
        els[i].addEventListener(type, fn);
    }
}

function absHeight(el) {
    if (el == document.body)
        return Math.max(document.body.offsetHeight,
                        document.documentElement.offsetHeight);
    return parseInt(window.getComputedStyle(el).height, 10);
}

function selectHotLang() {
    var selected = $qs('.hot.selected'),
        next = $qs('.hot[rel=' + lexers.value + ']');
    selected && selected.classList.remove('selected');
    next && next.classList.add('selected');
}

document.addEventListener('DOMContentLoaded', function() {
    var lexers = $id('lexers');
    var text = $id('text');

    lexers.addEventListener('change', selectHotLang);
    selectHotLang();

    listenTo($qsa('.hot'), 'click', function(e) {
        e.preventDefault();
        lexers.value = e.target.rel;
        selectHotLang();
        text.focus();
    });

    listenTo($id('wrap'), 'click', function(e) {
        e.preventDefault();
        $id('content').classList.toggle('wrap');
    });

    // resize textarea to fill maximum area without adding a scrollbar
    if (text) {
        var newheight = window.innerHeight - absHeight(document.body) + absHeight(text);
        if (newheight > absHeight(text)) {
            text.style.height = newheight + 'px';
        }
    }

    addShortcut(13, {ctrl: true}, function(e) { // ctrl+enter
        if (!text.value.replace(/^\s+|\s+$/g, '')) { return; }
        $qs('form') && $qs('form').submit();
    });
    addShortcut(74, {ctrl: true}, function() { // ctrl+j
        lexers.focus();
    });
    addShortcut(78, {ctrl: true}, function() { // ctrl+n
        document.location.href = '/';
    });

    hlter.run();

    // highlight hovered lines
    listenTo($qsa('.linenos a'), 'mouseover', function(e) {
        $id(e.target.rel).classList.add('over');
    });
    listenTo($qsa('.linenos a'), 'mouseout', function(e) {
        $id(e.target.rel).classList.remove('over');
    });
});

hlter = {
    last_location: null,    // which location we're following right now
    run_interval_every: 50, // time in ms that the URL is queried for changes
    selecting: null,        // if user is selecting lines, first line
    current: null,          // current line or line number if any
    modifier: 0,            // if ctrl or shift is pressed
    // shift - 16, ctrl - 17
    isModifier: function(code) { return [16].indexOf(code) + 1; },
    bit: function(code) { return 1 << (code - 16); },

    run: function() {
        var app = this;
        this.lineselection(true);
        this._interval = setInterval(function() {
            app.check.apply(app);
        }, this.run_interval_every);

        listenTo($qsa('.linenos a'), 'mousedown', function(e) {
            if (e.which == 1) app.selectStart(this.rel);
        });
        listenTo($qsa('.linenos a'), 'mouseup', function(e) {
            app.selectEnd(this.rel);
        });
        listenTo($qsa('.line'), 'mouseup', function(e) {
            app.selectEnd(this.id);
        });

        listenTo($qsa('.line'), 'mousemove', function() { app.current = this.id; });
        listenTo($qsa('.linenos a'), 'mousemove', function() { app.current = this.rel; });

        // yay bitwise :P
        listenTo(document, 'keydown', function(e) {
            if (app.isModifier(e.keyCode)) {
                app.modifier |= app.bit(e.keyCode);
            }
        });
        listenTo(document, 'keyup', function(e) {
            if (app.isModifier(e.keyCode)) {
                app.modifier ^= app.bit(e.keyCode);
            }
        });
    },

    selectStart: function(id) { this.selecting = id; },
    selectEnd: function(id) { this.select(id); },

    select: function(end) {
        if (!this.selecting) { return; }

        var range = this.selecting;
        if (end && end != this.selecting) {
            range += ':' + end;
        }

        if (this.modifier && window.location.hash) {
            window.location.hash += ',' + range;
        } else {
            window.location.hash = range;
        }

        this.selecting = null;
    },

    ongoingselection: function() {
        forEach($qsa('.selecting'), function(el) {
            el.classList.remove('selecting');
        });
        if (!(this.selecting && this.current)) { return; }

        var range = this.range(this.selecting, this.current, 'a-');
        forEach(range, function(id) {
            $id(id).classList.add('selecting');
        });
    },

    lineselection: function(onload) {
        forEach($qsa('.selected'), function(el) {
            el.classList.remove('selected');
        });
        var specifiers = this.location().split(',');
        var first;
        for (var i = 0, l = specifiers.length; i < l; i++) {
            var pair = this.getPair(specifiers[i]);
            var range = this.range(pair[0], pair[1], '');
            forEach(range, function(id) {
                $id(id).classList.add('selected');
            });

            if (onload && (!first || first > pair[0])) {
                first = pair[0];
            }
        }

        if (onload && first) {
            document.body.scrollTop += $id('' + first).getBoundingClientRect().top;
        }
    },

    int: function(v) { return parseInt(v, 10); },

    getPair: function(x) {
        var pair = x.split(':').map(this.int);
        if (pair[0] > pair[1]) {
            return [pair[1], pair[0]];
        }
        return pair;
    },

    range: function(start, end, prefix) {
        start = parseInt(start, 10);
        end = parseInt(end, 10);
        if (!start) { return []; }
        if (!end) { end = start; }
        if (prefix == undefined) { prefix = '#'; }

        if (start > end) {
            end += start;
            start = end - start;
            end = end - start;
        }

        var range = [];
        for (var i = start; i <= end; i++) {
            range.push(prefix + i);
        }
        return range;
    },

    location: function() {
        return window.location.hash.slice(1);
    },

    check: function() {
        this.ongoingselection();
        var location = this.location();
        if (location != this.last_location) {
            this.last_location = location;
            this.lineselection();
        }
    }
};
<commit_msg>add cmd+enter to submit<commit_after>// finding out keyCode:
// http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

function addShortcut(keyCode, mods, callback) {
    mods = mods || {};
    listenTo(document, 'keydown', function(e) {
        var modsMatched = ((e.ctrlKey  == !!mods.ctrl) &&
                           (e.shiftKey == !!mods.shift) &&
                           (e.altKey   == !!mods.alt) &&
                           (e.metaKey  == !!mods.meta));
        var received = e.keyCode !== undefined ? e.keyCode : e.which;
        if (modsMatched && received == keyCode) {
            callback(e);
            e.preventDefault();
        }
    });
}

var $id = function(x) { return document.getElementById(x); };
var $qs = function(x) { return document.querySelector(x); };
var $qsa = function(x) { return document.querySelectorAll(x); };
var forEach = function (array, callback, scope) {
    for (var i = 0; i < array.length; i++) {
        callback.call(scope || array, array[i], i);
    }
};

function listenTo(els, type, fn) {
    if (!els) return;
    if (els && els.nodeType) return listenTo([els], type, fn);

    for (var i = 0; i < els.length; i++) {
        els[i].addEventListener(type, fn);
    }
}

function absHeight(el) {
    if (el == document.body)
        return Math.max(document.body.offsetHeight,
                        document.documentElement.offsetHeight);
    return parseInt(window.getComputedStyle(el).height, 10);
}

function selectHotLang() {
    var selected = $qs('.hot.selected'),
        next = $qs('.hot[rel=' + lexers.value + ']');
    selected && selected.classList.remove('selected');
    next && next.classList.add('selected');
}

document.addEventListener('DOMContentLoaded', function() {
    var lexers = $id('lexers');
    var text = $id('text');

    lexers.addEventListener('change', selectHotLang);
    selectHotLang();

    listenTo($qsa('.hot'), 'click', function(e) {
        e.preventDefault();
        lexers.value = e.target.rel;
        selectHotLang();
        text.focus();
    });

    listenTo($id('wrap'), 'click', function(e) {
        e.preventDefault();
        $id('content').classList.toggle('wrap');
    });

    // resize textarea to fill maximum area without adding a scrollbar
    if (text) {
        var newheight = window.innerHeight - absHeight(document.body) + absHeight(text);
        if (newheight > absHeight(text)) {
            text.style.height = newheight + 'px';
        }
    }

    function submit(e) {
        if (!text.value.replace(/^\s+|\s+$/g, '')) { return; }
        $qs('form') && $qs('form').submit();
    };

    addShortcut(13, {ctrl: true}, submit); // ctrl+enter
    addShortcut(13, {meta: true}, submit); // cmd+enter
    addShortcut(74, {ctrl: true}, function() { // ctrl+j
        lexers.focus();
    });
    addShortcut(78, {ctrl: true}, function() { // ctrl+n
        document.location.href = '/';
    });

    hlter.run();

    // highlight hovered lines
    listenTo($qsa('.linenos a'), 'mouseover', function(e) {
        $id(e.target.rel).classList.add('over');
    });
    listenTo($qsa('.linenos a'), 'mouseout', function(e) {
        $id(e.target.rel).classList.remove('over');
    });
});

hlter = {
    last_location: null,    // which location we're following right now
    run_interval_every: 50, // time in ms that the URL is queried for changes
    selecting: null,        // if user is selecting lines, first line
    current: null,          // current line or line number if any
    modifier: 0,            // if ctrl or shift is pressed
    // shift - 16, ctrl - 17
    isModifier: function(code) { return [16].indexOf(code) + 1; },
    bit: function(code) { return 1 << (code - 16); },

    run: function() {
        var app = this;
        this.lineselection(true);
        this._interval = setInterval(function() {
            app.check.apply(app);
        }, this.run_interval_every);

        listenTo($qsa('.linenos a'), 'mousedown', function(e) {
            if (e.which == 1) app.selectStart(this.rel);
        });
        listenTo($qsa('.linenos a'), 'mouseup', function(e) {
            app.selectEnd(this.rel);
        });
        listenTo($qsa('.line'), 'mouseup', function(e) {
            app.selectEnd(this.id);
        });

        listenTo($qsa('.line'), 'mousemove', function() { app.current = this.id; });
        listenTo($qsa('.linenos a'), 'mousemove', function() { app.current = this.rel; });

        // yay bitwise :P
        listenTo(document, 'keydown', function(e) {
            if (app.isModifier(e.keyCode)) {
                app.modifier |= app.bit(e.keyCode);
            }
        });
        listenTo(document, 'keyup', function(e) {
            if (app.isModifier(e.keyCode)) {
                app.modifier ^= app.bit(e.keyCode);
            }
        });
    },

    selectStart: function(id) { this.selecting = id; },
    selectEnd: function(id) { this.select(id); },

    select: function(end) {
        if (!this.selecting) { return; }

        var range = this.selecting;
        if (end && end != this.selecting) {
            range += ':' + end;
        }

        if (this.modifier && window.location.hash) {
            window.location.hash += ',' + range;
        } else {
            window.location.hash = range;
        }

        this.selecting = null;
    },

    ongoingselection: function() {
        forEach($qsa('.selecting'), function(el) {
            el.classList.remove('selecting');
        });
        if (!(this.selecting && this.current)) { return; }

        var range = this.range(this.selecting, this.current, 'a-');
        forEach(range, function(id) {
            $id(id).classList.add('selecting');
        });
    },

    lineselection: function(onload) {
        forEach($qsa('.selected'), function(el) {
            el.classList.remove('selected');
        });
        var specifiers = this.location().split(',');
        var first;
        for (var i = 0, l = specifiers.length; i < l; i++) {
            var pair = this.getPair(specifiers[i]);
            var range = this.range(pair[0], pair[1], '');
            forEach(range, function(id) {
                $id(id).classList.add('selected');
            });

            if (onload && (!first || first > pair[0])) {
                first = pair[0];
            }
        }

        if (onload && first) {
            document.body.scrollTop += $id('' + first).getBoundingClientRect().top;
        }
    },

    int: function(v) { return parseInt(v, 10); },

    getPair: function(x) {
        var pair = x.split(':').map(this.int);
        if (pair[0] > pair[1]) {
            return [pair[1], pair[0]];
        }
        return pair;
    },

    range: function(start, end, prefix) {
        start = parseInt(start, 10);
        end = parseInt(end, 10);
        if (!start) { return []; }
        if (!end) { end = start; }
        if (prefix == undefined) { prefix = '#'; }

        if (start > end) {
            end += start;
            start = end - start;
            end = end - start;
        }

        var range = [];
        for (var i = start; i <= end; i++) {
            range.push(prefix + i);
        }
        return range;
    },

    location: function() {
        return window.location.hash.slice(1);
    },

    check: function() {
        this.ongoingselection();
        var location = this.location();
        if (location != this.last_location) {
            this.last_location = location;
            this.lineselection();
        }
    }
};
<|endoftext|>


<commit_before>Ext.fly(window).on('beforeunload', function() {
    Kwf.Connection.isLeavingPage = true;
});
Kwf.Connection = Ext.extend(Ext.data.Connection, {
    _progressData    : { },

    /**
     * Options:
     * - mask (true für body, sonst element)
     * - maskText (default Loading...)
     * - progress
     * - progressTitle (default Progress)
     * - ignoreErrors (don't show error messages, but call failure callback)
     */
    request: function(options)
    {

        Kwf.requestSentSinceLastKeepAlive = true;
        Kwf.Connection.runningRequests++;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.mask(options.maskText || trlKwf('Loading...'));
            } else {
                if (Kwf.Connection.masks == 0) {
                    if (Ext.get('loading')) {
                        Ext.getBody().mask();
                    } else {
                        Ext.getBody().mask(options.maskText || trlKwf('Loading...'));
                    }
                }
                Kwf.Connection.masks++;
            }
        }

        if (options.url.match(/[\/a-zA-Z0-9]*\/json[a-zA-Z0-9\-]+(\/|\?|)/)) {
            options.kwfCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.kwfJsonSuccess;
            options.failure = this.kwfJsonFailure;
            options.callback = this.kwfCallback;
            options.scope = this;
        } else {
            options.kwfCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.kwfNoJsonSuccess;
            options.failure = this.kwfNoJsonFailure;
            options.callback = this.kwfCallback;
            options.scope = this;
        }
        if (!options.params) options.params = {};
        if (Kwf.isApp) {
            options.params.applicationAssetsVersion = Kwf.application.assetsVersion;
        }
        if (Kwf.sessionToken) options.params.kwfSessionToken = Kwf.sessionToken;
        if (!options.url.match(':\/\/')) {
            //absolute url incl. http:// erstellen
            //wird benötigt wenn fkt über mozrepl aufgerufen wird
            var u = location.protocol + '/'+'/' + location.host;
            if (options.url.substr(0, 1) == '/') {
                options.url = u + options.url;
            } else {
                options.url = u + '/' + options.url;
            }
        }

        if (options.progress) {
            var progressNum = Math.floor(Math.random() * 1000000000) + 1;
            options.params.progressNum = progressNum;
        }

        var ret = Kwf.Connection.superclass.request.call(this, options);

        if (options.progress) {
            this._showProgress(options);
        }

        return ret;
    },

    _showProgress: function(options)
    {
        var progressNum = options.params.progressNum;

        this._progressData[progressNum] = {
            progressBar: this._createProgressDialog({
                title: options.progressTitle || trlKwf('Progress'),
                transId: this.transId,
                requestOptions: options,
                showCancel: options.showCancel
            }),
            breakStatusRequests: false
        };
        this._progressData[progressNum].progressBar.updateProgress(0, '0%', '');

        this._doProgressStatusRequest.defer(1500, this, [ progressNum ]);
    },

    _doProgressStatusRequest: function(progressNum)
    {
        this.request({
            url: '/kwf/json-progress-status',
            params: { progressNum: progressNum },
            success: function(response, options, r) {
                var progressNum = options.params.progressNum;
                if (!this._progressData[progressNum]) return;

                if (typeof r.finished != 'undefined') {
                    if (r.finished) {
                        this._progressData[progressNum].progressBar.updateProgress(
                            1, '100%', trlKwf('Finished')
                        );
                        return;
                    }

                    this._progressData[progressNum].progressBar.updateProgress(
                        r.percent / 100,
                        Math.floor(r.percent)+'%',
                        r.text ? r.text : ''
                    );
                }

                if (!this._progressData[progressNum].breakStatusRequests) {
                    // recursing
                    this._doProgressStatusRequest.defer(500, this, [ progressNum ]);
                }
            },
            scope: this
        });
    },

    _createProgressDialog: function(cfg)
    {
        var progressBar = new Ext.ProgressBar({
            text:'0%',
            animate: true
        });
        cfg = Ext.applyIf(cfg, {
            title: trlKwf('Progress'),
            autoCreate : true,
            resizable:false,
            constrain:true,
            constrainHeader:true,
            minimizable : false,
            maximizable : false,
            stateful: false,
            modal: true,
            shim:true,
            buttonAlign:"center",
            width:400,
            plain:true,
            footer:true,
            closable:false
        });
        var dlg = new Ext.Window(cfg);

        if (typeof cfg.showCancel == 'undefined' || cfg.showCancel) {
            dlg.addButton(
                { text: trlKwf('Cancel') },
                (function(dialog) {
                    Ext.Ajax.abort(dialog.transId);

                    var responseObject = Ext.lib.Ajax.createExceptionObject(
                        dialog.transId, null, true
                    );
                    Ext.callback(
                        dialog.requestOptions.kwfCallback.failure,
                        dialog.requestOptions.kwfCallback.scope,
                        [responseObject, dialog.requestOptions]
                    );
                    dialog.requestOptions.callback.call(
                        this,
                        dialog.requestOptions,
                        false,
                        responseObject
                    );
                }).createDelegate(this, [ dlg ])
            );
        }

        dlg.render(document.body);
        dlg.myEls = { };
        dlg.myEls.bodyEl = dlg.body.createChild({
            html:'

'
        });
        dlg.myEls.bodyEl.addClass('kwf-progress-window');
        dlg.myEls.msgEl = Ext.get(dlg.myEls.bodyEl.dom.childNodes[0].firstChild);

        dlg.progressBar = new Ext.ProgressBar({
            renderTo:dlg.myEls.bodyEl,
            text: '0%',
            animate: true
        });
        dlg.myEls.bodyEl.createChild({cls:'x-clear'});

        dlg.updateProgress = function(num, progressBarText, text)
        {
            this.progressBar.updateProgress(num, progressBarText, true);
            this.myEls.msgEl.update(text || ' ');
        };

        dlg.show();
        return dlg;
    },

    repeatRequest: function(options) {
        Kwf.Connection.runningRequests++;
        delete options.kwfIsSuccess;
        delete options.kwfLogin;

        //session token might have changed if user had to login -> update it
        if (Kwf.sessionToken) options.params.kwfSessionToken = Kwf.sessionToken;

        Kwf.Connection.superclass.request.call(this, options);
        if (options.progress) {
            this._showProgress(options);
        }
    },
    kwfJsonSuccess: function(response, options)
    {
        options.kwfIsSuccess = false;
        options.kwfLogin = false;

        var errorMsg = false;

        var encParams;
        if (typeof options.params == "string") {
            encParams = options.params;
        } else {
            encParams = Ext.urlEncode(options.params);
        }
        try {
            if (!response.responseText) {
                errorMsg = 'response is empty';
            } else {
                var r = Ext.decode(response.responseText);
            }
        } catch(e) {
            errorMsg = e.toString()+':
'+response.responseText;
            var errorMsgTitle = 'Javascript Parse Exception';
        }
        if (errorMsg) {
            errorMsg = 'request-url
' + errorMsg;
            var sendMail = !r || !r.exception;
            if (options.errorText) {
                errorText = options.errorText;
            } else {
                errorText = null;
            }
            if (options.ignoreErrors) {
                Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
            } else {
                Kwf.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    mail: sendMail,
                    errorText: errorText,
                    checkRetry: false,
                    retry: function() {
                        this.connection.repeatRequest(this.options);
                    },
                    abort: function() {
                        Ext.callback(this.options.kwfCallback.failure, this.options.kwfCallback.scope, [this.response, this.options]);
                    },
                    scope: { connection: this, options: options, response: response }
                });
            }
            return;
        }

        if (!r.success && !options.ignoreErrors) {
            if (r.error) {
                Ext.Msg.alert(trlKwf('Error'), r.error);
            } else {
                Ext.Msg.alert(trlKwf('Error'), trlKwf("A Server failure occured."));
            }
            Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
            return;
        }
        options.kwfIsSuccess = true;
        if (options.kwfCallback.success) {
            options.kwfCallback.success.call(options.kwfCallback.scope, response, options, r);
        }
    },
    kwfNoJsonSuccess: function(response, options)
    {
        options.kwfIsSuccess = true;
        if (options.kwfCallback.success) {
            options.kwfCallback.success.call(options.kwfCallback.scope, response, options);
        }
    },
    kwfNoJsonFailure: function(response, options)
    {
        options.kwfIsSuccess = false;
        if (options.kwfCallback.failure) {
            options.kwfCallback.failure.call(options.kwfCallback.scope, response, options);
        }
    },
    kwfJsonFailure: function(response, options)
    {
        if (Kwf.Connection.isLeavingPage) return; //when user leaves page all requests are stopped. Don't show errors in that case.

        options.kwfIsSuccess = false;

        var r = Ext.decode(response.responseText);

        if (r && r.wrongversion && !options.ignoreErrors) {
            var dlg = new Ext.Window({
                autoCreate : true,
                title: trlKwf('Error - wrong version'),
                resizable: false,
                modal: true,
                buttonAlign:"center",
                width:250,
                height:100,
                plain:true,
                closable: false,
                html: trlKwf('Because of an application update the application has to be reloaded.'),
                buttons: [{
                    text: trlKwf('OK'),
                    handler: function() {
                        location.reload();
                    },
                    scope: this
                }, {
                    text: trlKwf('Ignore'),
                    handler: function() {
                        Kwf.application.assetsVersion = r.assetsVersion;
                        options.params.applicationAssetsVersion = Kwf.application.assetsVersion;
                        this.repeatRequest(options);
                        dlg.hide();
                    },
                    scope: this
                }]
            });
            dlg.show();
            dlg.getEl().addClass('x-window-dlg');
            return;
        }
        if (r && r.login && !options.ignoreErrors) {
            options.kwfLogin = true;
            if (!Kwf.Connection._loginDialog) {
                Kwf.Connection._afterLoginRequests = [];
                Kwf.Connection._loginDialog = new Kwf.User.Login.Dialog({
                    message: r.message,
                    success: function() {

                        Kwf.Connection._loginDialog.destroy();
                        delete Kwf.Connection._loginDialog;

                        //redo requests...
                        Kwf.Connection._afterLoginRequests.each(function(i) {
                            this.repeatRequest(i);
                        }, this);

                        Kwf.Connection._afterLoginRequests.length = 0;
                    },
                    scope: this
                });
                Ext.getBody().unmask();
                Kwf.Connection._loginDialog.showLogin();
            }
            Kwf.Connection._afterLoginRequests.push(options); //redo after login
            return;
        }

        var errorText, errorMsg;
        var errorMsgTitle = trlKwf('Error');
        if (options.errorText) {
            errorText = options.errorText;
            errorMsg = options.errorText;
        } else if (r.exception) {
            errorMsg = '
'+r.exception.join('\n')+'
';
            errorMsgTitle = 'PHP Exception';
        } else if (r.error) {
            errorMsg = r.error;
            errorMsgTitle = 'PHP Exception';
        } else {
            errorMsg = trlKwf("A connection problem occured.");
            errorText = null;
        }
        var checkRetry = false;
        if (response.status == -1) {
            //request failed not beause of error response (eg 500) but because of eg. timeout
            //allow the user to retry the request
            retry = true;
        } else {
            //request failed because of error response (eg 500), don't allow the user to
            //retry as it would result in the same error again
            //however if displayErrors is enabled (during development) retry is possible (this is handled in Kwf.handleError)
        }
        if (options.ignoreErrors) {
            Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
        } else {
            Kwf.handleError({
                url: options.url,
                message: errorMsg,
                title: errorMsgTitle,
                errorText: errorText,
                mail: false,
                checkRetry: retry,
                retry: function() {
                    this.repeatRequest(options);
                },
                abort: function() {
                    Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
                },
                scope: this
            });
        }
    },

    kwfCallback: function(options, success, response)
    {
        //wenn login-fenster angezeigt wird keinen callback aufrufen - weil der request
        //wird ja erneut gesendet und da dann der callback aufgerufen.
        if (options.kwfLogin) return;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.unmask();
            } else {
                Kwf.Connection.masks--;
                if (Kwf.Connection.masks == 0) {
                    Ext.getBody().unmask();
                    if (Ext.get('loading')) {
                        Ext.get('loading').fadeOut({remove: true});
                    }
                }
            }
        }

        if (options.progress) {
            this._progressData[options.params.progressNum].progressBar.hide();
            delete this._progressData[options.params.progressNum];
        }

        if(success && !options.kwfIsSuccess) {
            success = false;
        }
        Ext.callback(options.kwfCallback.callback, options.kwfCallback.scope, [options, success, response]);
        Kwf.Connection.runningRequests--;
    }
});
Kwf.Connection.masks = 0; //static var that hols number of masked requests
Kwf.Connection.runningRequests = 0;

Ext.Ajax = new Kwf.Connection({
    /**
     * The timeout in milliseconds to be used for requests. (defaults
     * to 30000)
     * @type Number
     * @property  timeout
     */
    autoAbort : false,

    /**
     * Serialize the passed form into a url encoded string
     * @return {String}
     */
    serializeForm : function(form){
        return Ext.lib.Ajax.serializeForm(form);
    }
});

<commit_msg>fix connection: typo in retry variable<commit_after>Ext.fly(window).on('beforeunload', function() {
    Kwf.Connection.isLeavingPage = true;
});
Kwf.Connection = Ext.extend(Ext.data.Connection, {
    _progressData    : { },

    /**
     * Options:
     * - mask (true für body, sonst element)
     * - maskText (default Loading...)
     * - progress
     * - progressTitle (default Progress)
     * - ignoreErrors (don't show error messages, but call failure callback)
     */
    request: function(options)
    {

        Kwf.requestSentSinceLastKeepAlive = true;
        Kwf.Connection.runningRequests++;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.mask(options.maskText || trlKwf('Loading...'));
            } else {
                if (Kwf.Connection.masks == 0) {
                    if (Ext.get('loading')) {
                        Ext.getBody().mask();
                    } else {
                        Ext.getBody().mask(options.maskText || trlKwf('Loading...'));
                    }
                }
                Kwf.Connection.masks++;
            }
        }

        if (options.url.match(/[\/a-zA-Z0-9]*\/json[a-zA-Z0-9\-]+(\/|\?|)/)) {
            options.kwfCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.kwfJsonSuccess;
            options.failure = this.kwfJsonFailure;
            options.callback = this.kwfCallback;
            options.scope = this;
        } else {
            options.kwfCallback = {
                success: options.success,
                failure: options.failure,
                callback: options.callback,
                scope: options.scope
            };
            options.success = this.kwfNoJsonSuccess;
            options.failure = this.kwfNoJsonFailure;
            options.callback = this.kwfCallback;
            options.scope = this;
        }
        if (!options.params) options.params = {};
        if (Kwf.isApp) {
            options.params.applicationAssetsVersion = Kwf.application.assetsVersion;
        }
        if (Kwf.sessionToken) options.params.kwfSessionToken = Kwf.sessionToken;
        if (!options.url.match(':\/\/')) {
            //absolute url incl. http:// erstellen
            //wird benötigt wenn fkt über mozrepl aufgerufen wird
            var u = location.protocol + '/'+'/' + location.host;
            if (options.url.substr(0, 1) == '/') {
                options.url = u + options.url;
            } else {
                options.url = u + '/' + options.url;
            }
        }

        if (options.progress) {
            var progressNum = Math.floor(Math.random() * 1000000000) + 1;
            options.params.progressNum = progressNum;
        }

        var ret = Kwf.Connection.superclass.request.call(this, options);

        if (options.progress) {
            this._showProgress(options);
        }

        return ret;
    },

    _showProgress: function(options)
    {
        var progressNum = options.params.progressNum;

        this._progressData[progressNum] = {
            progressBar: this._createProgressDialog({
                title: options.progressTitle || trlKwf('Progress'),
                transId: this.transId,
                requestOptions: options,
                showCancel: options.showCancel
            }),
            breakStatusRequests: false
        };
        this._progressData[progressNum].progressBar.updateProgress(0, '0%', '');

        this._doProgressStatusRequest.defer(1500, this, [ progressNum ]);
    },

    _doProgressStatusRequest: function(progressNum)
    {
        this.request({
            url: '/kwf/json-progress-status',
            params: { progressNum: progressNum },
            success: function(response, options, r) {
                var progressNum = options.params.progressNum;
                if (!this._progressData[progressNum]) return;

                if (typeof r.finished != 'undefined') {
                    if (r.finished) {
                        this._progressData[progressNum].progressBar.updateProgress(
                            1, '100%', trlKwf('Finished')
                        );
                        return;
                    }

                    this._progressData[progressNum].progressBar.updateProgress(
                        r.percent / 100,
                        Math.floor(r.percent)+'%',
                        r.text ? r.text : ''
                    );
                }

                if (!this._progressData[progressNum].breakStatusRequests) {
                    // recursing
                    this._doProgressStatusRequest.defer(500, this, [ progressNum ]);
                }
            },
            scope: this
        });
    },

    _createProgressDialog: function(cfg)
    {
        var progressBar = new Ext.ProgressBar({
            text:'0%',
            animate: true
        });
        cfg = Ext.applyIf(cfg, {
            title: trlKwf('Progress'),
            autoCreate : true,
            resizable:false,
            constrain:true,
            constrainHeader:true,
            minimizable : false,
            maximizable : false,
            stateful: false,
            modal: true,
            shim:true,
            buttonAlign:"center",
            width:400,
            plain:true,
            footer:true,
            closable:false
        });
        var dlg = new Ext.Window(cfg);

        if (typeof cfg.showCancel == 'undefined' || cfg.showCancel) {
            dlg.addButton(
                { text: trlKwf('Cancel') },
                (function(dialog) {
                    Ext.Ajax.abort(dialog.transId);

                    var responseObject = Ext.lib.Ajax.createExceptionObject(
                        dialog.transId, null, true
                    );
                    Ext.callback(
                        dialog.requestOptions.kwfCallback.failure,
                        dialog.requestOptions.kwfCallback.scope,
                        [responseObject, dialog.requestOptions]
                    );
                    dialog.requestOptions.callback.call(
                        this,
                        dialog.requestOptions,
                        false,
                        responseObject
                    );
                }).createDelegate(this, [ dlg ])
            );
        }

        dlg.render(document.body);
        dlg.myEls = { };
        dlg.myEls.bodyEl = dlg.body.createChild({
            html:'

'
        });
        dlg.myEls.bodyEl.addClass('kwf-progress-window');
        dlg.myEls.msgEl = Ext.get(dlg.myEls.bodyEl.dom.childNodes[0].firstChild);

        dlg.progressBar = new Ext.ProgressBar({
            renderTo:dlg.myEls.bodyEl,
            text: '0%',
            animate: true
        });
        dlg.myEls.bodyEl.createChild({cls:'x-clear'});

        dlg.updateProgress = function(num, progressBarText, text)
        {
            this.progressBar.updateProgress(num, progressBarText, true);
            this.myEls.msgEl.update(text || ' ');
        };

        dlg.show();
        return dlg;
    },

    repeatRequest: function(options) {
        Kwf.Connection.runningRequests++;
        delete options.kwfIsSuccess;
        delete options.kwfLogin;

        //session token might have changed if user had to login -> update it
        if (Kwf.sessionToken) options.params.kwfSessionToken = Kwf.sessionToken;

        Kwf.Connection.superclass.request.call(this, options);
        if (options.progress) {
            this._showProgress(options);
        }
    },
    kwfJsonSuccess: function(response, options)
    {
        options.kwfIsSuccess = false;
        options.kwfLogin = false;

        var errorMsg = false;

        var encParams;
        if (typeof options.params == "string") {
            encParams = options.params;
        } else {
            encParams = Ext.urlEncode(options.params);
        }
        try {
            if (!response.responseText) {
                errorMsg = 'response is empty';
            } else {
                var r = Ext.decode(response.responseText);
            }
        } catch(e) {
            errorMsg = e.toString()+':
'+response.responseText;
            var errorMsgTitle = 'Javascript Parse Exception';
        }
        if (errorMsg) {
            errorMsg = 'request-url
' + errorMsg;
            var sendMail = !r || !r.exception;
            if (options.errorText) {
                errorText = options.errorText;
            } else {
                errorText = null;
            }
            if (options.ignoreErrors) {
                Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
            } else {
                Kwf.handleError({
                    url: options.url,
                    message: errorMsg,
                    title: errorMsgTitle,
                    mail: sendMail,
                    errorText: errorText,
                    checkRetry: false,
                    retry: function() {
                        this.connection.repeatRequest(this.options);
                    },
                    abort: function() {
                        Ext.callback(this.options.kwfCallback.failure, this.options.kwfCallback.scope, [this.response, this.options]);
                    },
                    scope: { connection: this, options: options, response: response }
                });
            }
            return;
        }

        if (!r.success && !options.ignoreErrors) {
            if (r.error) {
                Ext.Msg.alert(trlKwf('Error'), r.error);
            } else {
                Ext.Msg.alert(trlKwf('Error'), trlKwf("A Server failure occured."));
            }
            Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
            return;
        }
        options.kwfIsSuccess = true;
        if (options.kwfCallback.success) {
            options.kwfCallback.success.call(options.kwfCallback.scope, response, options, r);
        }
    },
    kwfNoJsonSuccess: function(response, options)
    {
        options.kwfIsSuccess = true;
        if (options.kwfCallback.success) {
            options.kwfCallback.success.call(options.kwfCallback.scope, response, options);
        }
    },
    kwfNoJsonFailure: function(response, options)
    {
        options.kwfIsSuccess = false;
        if (options.kwfCallback.failure) {
            options.kwfCallback.failure.call(options.kwfCallback.scope, response, options);
        }
    },
    kwfJsonFailure: function(response, options)
    {
        if (Kwf.Connection.isLeavingPage) return; //when user leaves page all requests are stopped. Don't show errors in that case.

        options.kwfIsSuccess = false;

        var r = Ext.decode(response.responseText);

        if (r && r.wrongversion && !options.ignoreErrors) {
            var dlg = new Ext.Window({
                autoCreate : true,
                title: trlKwf('Error - wrong version'),
                resizable: false,
                modal: true,
                buttonAlign:"center",
                width:250,
                height:100,
                plain:true,
                closable: false,
                html: trlKwf('Because of an application update the application has to be reloaded.'),
                buttons: [{
                    text: trlKwf('OK'),
                    handler: function() {
                        location.reload();
                    },
                    scope: this
                }, {
                    text: trlKwf('Ignore'),
                    handler: function() {
                        Kwf.application.assetsVersion = r.assetsVersion;
                        options.params.applicationAssetsVersion = Kwf.application.assetsVersion;
                        this.repeatRequest(options);
                        dlg.hide();
                    },
                    scope: this
                }]
            });
            dlg.show();
            dlg.getEl().addClass('x-window-dlg');
            return;
        }
        if (r && r.login && !options.ignoreErrors) {
            options.kwfLogin = true;
            if (!Kwf.Connection._loginDialog) {
                Kwf.Connection._afterLoginRequests = [];
                Kwf.Connection._loginDialog = new Kwf.User.Login.Dialog({
                    message: r.message,
                    success: function() {

                        Kwf.Connection._loginDialog.destroy();
                        delete Kwf.Connection._loginDialog;

                        //redo requests...
                        Kwf.Connection._afterLoginRequests.each(function(i) {
                            this.repeatRequest(i);
                        }, this);

                        Kwf.Connection._afterLoginRequests.length = 0;
                    },
                    scope: this
                });
                Ext.getBody().unmask();
                Kwf.Connection._loginDialog.showLogin();
            }
            Kwf.Connection._afterLoginRequests.push(options); //redo after login
            return;
        }

        var errorText, errorMsg;
        var errorMsgTitle = trlKwf('Error');
        if (options.errorText) {
            errorText = options.errorText;
            errorMsg = options.errorText;
        } else if (r.exception) {
            errorMsg = '
'+r.exception.join('\n')+'
';
            errorMsgTitle = 'PHP Exception';
        } else if (r.error) {
            errorMsg = r.error;
            errorMsgTitle = 'PHP Exception';
        } else {
            errorMsg = trlKwf("A connection problem occured.");
            errorText = null;
        }
        var retry = false;
        if (response.status == -1) {
            //request failed not beause of error response (eg 500) but because of eg. timeout
            //allow the user to retry the request
            retry = true;
        } else {
            //request failed because of error response (eg 500), don't allow the user to
            //retry as it would result in the same error again
            //however if displayErrors is enabled (during development) retry is possible (this is handled in Kwf.handleError)
        }
        if (options.ignoreErrors) {
            Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
        } else {
            Kwf.handleError({
                url: options.url,
                message: errorMsg,
                title: errorMsgTitle,
                errorText: errorText,
                mail: false,
                checkRetry: retry,
                retry: function() {
                    this.repeatRequest(options);
                },
                abort: function() {
                    Ext.callback(options.kwfCallback.failure, options.kwfCallback.scope, [response, options]);
                },
                scope: this
            });
        }
    },

    kwfCallback: function(options, success, response)
    {
        //wenn login-fenster angezeigt wird keinen callback aufrufen - weil der request
        //wird ja erneut gesendet und da dann der callback aufgerufen.
        if (options.kwfLogin) return;

        if (options.mask) {
            if (options.mask instanceof Ext.Element) {
                options.mask.unmask();
            } else {
                Kwf.Connection.masks--;
                if (Kwf.Connection.masks == 0) {
                    Ext.getBody().unmask();
                    if (Ext.get('loading')) {
                        Ext.get('loading').fadeOut({remove: true});
                    }
                }
            }
        }

        if (options.progress) {
            this._progressData[options.params.progressNum].progressBar.hide();
            delete this._progressData[options.params.progressNum];
        }

        if(success && !options.kwfIsSuccess) {
            success = false;
        }
        Ext.callback(options.kwfCallback.callback, options.kwfCallback.scope, [options, success, response]);
        Kwf.Connection.runningRequests--;
    }
});
Kwf.Connection.masks = 0; //static var that hols number of masked requests
Kwf.Connection.runningRequests = 0;

Ext.Ajax = new Kwf.Connection({
    /**
     * The timeout in milliseconds to be used for requests. (defaults
     * to 30000)
     * @type Number
     * @property  timeout
     */
    autoAbort : false,

    /**
     * Serialize the passed form into a url encoded string
     * @return {String}
     */
    serializeForm : function(form){
        return Ext.lib.Ajax.serializeForm(form);
    }
});

<|endoftext|>


<commit_before>/**
 *  File: L.SimpleGraticule.js
 *  Desc: A graticule for Leaflet maps in the L.CRS.Simple coordinate system.
 *  Auth: Andrew Blakey (ablakey@gmail.com)
 */
L.SimpleGraticule = L.LayerGroup.extend({
    options: {
        interval: 20,
        showOriginLabel: true,
        redraw: 'move',
        hidden: false,
        zoomIntervals : []
    },

    lineStyle: {
        stroke: true,
        color: '#111',
        opacity: 0.6,
        weight: 1,
        clickable: false
    },

    initialize: function(options) {
        L.LayerGroup.prototype.initialize.call(this);
        L.Util.setOptions(this, options);
    },

    onAdd: function(map) {
        this._map = map;

        var graticule = this.redraw();
        this._map.on('viewreset ' + this.options.redraw, graticule.redraw, graticule);

        this.eachLayer(map.addLayer, map);
    },

    onRemove: function(map) {
        map.off('viewreset '+ this.options.redraw, this.map);
        this.eachLayer(this.removeLayer, this);
    },

    hide: function() {
        this.options.hidden = true;
        this.redraw();
    },

    show: function() {
        this.options.hidden = false;
        this.redraw();
    },

    redraw: function() {
        this._bounds = this._map.getBounds().pad(0.5);

        this.clearLayers();

        if (!this.options.hidden) {

            var currentZoom = this._map.getZoom();

            for(var i = 0 ; i < this.options.zoomIntervals.length ; i++) {
                if(currentZoom >= this.options.zoomIntervals[i].start && currentZoom <= this.options.zoomIntervals[i].end){
                    this.options.interval = this.options.zoomIntervals[i].interval;
                    break;
                }
            }

            this.constructLines(this.getMins(), this.getLineCounts());

            if (this.options.showOriginLabel) {
                this.addLayer(this.addOriginLabel());
            }
        }

        return this;
    },

    getLineCounts: function() {
        return {
            x: Math.ceil((this._bounds.getEast() - this._bounds.getWest()) /
                this.options.interval),
            y: Math.ceil((this._bounds.getNorth() - this._bounds.getSouth()) /
                this.options.interval)
        };
    },

    getMins: function() {
        //rounds up to nearest multiple of x
        var s = this.options.interval;
        return {
            x: Math.floor(this._bounds.getWest() / s) * s,
            y: Math.floor(this._bounds.getSouth() / s) * s
        };
    },

    constructLines: function(mins, counts) {
        var lines = new Array(counts.x + counts.y);
        var labels = new Array(counts.x + counts.y);

        //for horizontal lines
        for (var i = 0; i <= counts.x; i++) {
            var x = mins.x + i * this.options.interval;
            lines[i] = this.buildXLine(x);
            labels[i] = this.buildLabel('gridlabel-horiz', x);
        }

        //for vertical lines
        for (var j = 0; j <= counts.y; j++) {
            var y = mins.y + j * this.options.interval;
            lines[j + i] = this.buildYLine(y);
            labels[j + i] = this.buildLabel('gridlabel-vert', y);
        }

        lines.forEach(this.addLayer, this);
        labels.forEach(this.addLayer, this);
    },

    buildXLine: function(x) {
        var bottomLL = new L.LatLng(this._bounds.getSouth(), x);
        var topLL = new L.LatLng(this._bounds.getNorth(), x);

        return new L.Polyline([bottomLL, topLL], this.lineStyle);
    },

    buildYLine: function(y) {
        var leftLL = new L.LatLng(y, this._bounds.getWest());
        var rightLL = new L.LatLng(y, this._bounds.getEast());

        return new L.Polyline([leftLL, rightLL], this.lineStyle);
    },

    buildLabel: function(axis, val) {
        var bounds = this._map.getBounds().pad(-0.003);
        var latLng;
        if (axis == 'gridlabel-horiz') {
            latLng = new L.LatLng(bounds.getNorth(), val);
        } else {
            latLng = new L.LatLng(val, bounds.getWest());
        }

        return L.marker(latLng, {
            clickable: false,
            icon: L.divIcon({
                iconSize: [0, 0],
                className: 'leaflet-grid-label',
                html: '
' + val + '
'
            })
        });
    },

    addOriginLabel: function() {
        return L.marker([0, 0], {
            clickable: false,
            icon: L.divIcon({
                iconSize: [0, 0],
                className: 'leaflet-grid-label',
                html: '
(0,0)
'
            })
        });
    }
});

L.simpleGraticule = function(options) {
    return new L.SimpleGraticule(options);
};
<commit_msg>1.0 support<commit_after>/**
 *  File: L.SimpleGraticule.js
 *  Desc: A graticule for Leaflet maps in the L.CRS.Simple coordinate system.
 *  Auth: Andrew Blakey (ablakey@gmail.com)
 */
L.SimpleGraticule = L.LayerGroup.extend({
    options: {
        interval: 20,
        showOriginLabel: true,
        redraw: 'move',
        hidden: false,
        zoomIntervals : []
    },

    lineStyle: {
        stroke: true,
        color: '#111',
        opacity: 0.6,
        weight: 1,
        interactive: false,
        clickable: false//legacy support
    },

    initialize: function(options) {
        L.LayerGroup.prototype.initialize.call(this);
        L.Util.setOptions(this, options);
    },

    onAdd: function(map) {
        this._map = map;

        var graticule = this.redraw();
        this._map.on('viewreset ' + this.options.redraw, graticule.redraw, graticule);

        this.eachLayer(map.addLayer, map);
    },

    onRemove: function(map) {
        map.off('viewreset '+ this.options.redraw, this.map);
        this.eachLayer(this.removeLayer, this);
    },

    hide: function() {
        this.options.hidden = true;
        this.redraw();
    },

    show: function() {
        this.options.hidden = false;
        this.redraw();
    },

    redraw: function() {
        this._bounds = this._map.getBounds().pad(0.5);

        this.clearLayers();

        if (!this.options.hidden) {

            var currentZoom = this._map.getZoom();

            for(var i = 0 ; i < this.options.zoomIntervals.length ; i++) {
                if(currentZoom >= this.options.zoomIntervals[i].start && currentZoom <= this.options.zoomIntervals[i].end){
                    this.options.interval = this.options.zoomIntervals[i].interval;
                    break;
                }
            }

            this.constructLines(this.getMins(), this.getLineCounts());

            if (this.options.showOriginLabel) {
                this.addLayer(this.addOriginLabel());
            }
        }

        return this;
    },

    getLineCounts: function() {
        return {
            x: Math.ceil((this._bounds.getEast() - this._bounds.getWest()) /
                this.options.interval),
            y: Math.ceil((this._bounds.getNorth() - this._bounds.getSouth()) /
                this.options.interval)
        };
    },

    getMins: function() {
        //rounds up to nearest multiple of x
        var s = this.options.interval;
        return {
            x: Math.floor(this._bounds.getWest() / s) * s,
            y: Math.floor(this._bounds.getSouth() / s) * s
        };
    },

    constructLines: function(mins, counts) {
        var lines = new Array(counts.x + counts.y);
        var labels = new Array(counts.x + counts.y);

        //for horizontal lines
        for (var i = 0; i <= counts.x; i++) {
            var x = mins.x + i * this.options.interval;
            lines[i] = this.buildXLine(x);
            labels[i] = this.buildLabel('gridlabel-horiz', x);
        }

        //for vertical lines
        for (var j = 0; j <= counts.y; j++) {
            var y = mins.y + j * this.options.interval;
            lines[j + i] = this.buildYLine(y);
            labels[j + i] = this.buildLabel('gridlabel-vert', y);
        }

        lines.forEach(this.addLayer, this);
        labels.forEach(this.addLayer, this);
    },

    buildXLine: function(x) {
        var bottomLL = new L.LatLng(this._bounds.getSouth(), x);
        var topLL = new L.LatLng(this._bounds.getNorth(), x);

        return new L.Polyline([bottomLL, topLL], this.lineStyle);
    },

    buildYLine: function(y) {
        var leftLL = new L.LatLng(y, this._bounds.getWest());
        var rightLL = new L.LatLng(y, this._bounds.getEast());

        return new L.Polyline([leftLL, rightLL], this.lineStyle);
    },

    buildLabel: function(axis, val) {
        var bounds = this._map.getBounds().pad(-0.003);
        var latLng;
        if (axis == 'gridlabel-horiz') {
            latLng = new L.LatLng(bounds.getNorth(), val);
        } else {
            latLng = new L.LatLng(val, bounds.getWest());
        }

        return L.marker(latLng, {
            clickable: false,
            icon: L.divIcon({
                iconSize: [0, 0],
                className: 'leaflet-grid-label',
                html: '
' + val + '
'
            })
        });
    },

    addOriginLabel: function() {
        return L.marker([0, 0], {
            clickable: false,
            icon: L.divIcon({
                iconSize: [0, 0],
                className: 'leaflet-grid-label',
                html: '
(0,0)
'
            })
        });
    }
});

L.simpleGraticule = function(options) {
    return new L.SimpleGraticule(options);
};
<|endoftext|>


<commit_before>/*
  The following comments are parsed by Gulp include
  (https://www.npmjs.com/package/gulp-include) which uses
  Sprockets-style (https://github.com/sstephenson/sprockets)
  directives to concatenate multiple Javascript files into one.
*/
//= require ../../../node_modules/jquery/dist/jquery.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/list-entry.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/word-counter.js
//= require ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/selection-buttons.js
//= require ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/shim-links-with-button-role.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/shim-links-with-button-role.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/show-hide-content.js
; // Hack needed because show-hide-content.js does not have a closing ";"
//= require ../../../node_modules/digitalmarketplace-govuk-frontend/govuk-frontend/all.js
//= require _selection-buttons.js
//= require _analytics.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/module-loader.js

GOVUKFrontend.initAll()
<commit_msg>Exclude analytics code from application.js<commit_after>/*
  The following comments are parsed by Gulp include
  (https://www.npmjs.com/package/gulp-include) which uses
  Sprockets-style (https://github.com/sstephenson/sprockets)
  directives to concatenate multiple Javascript files into one.
*/
//= require ../../../node_modules/jquery/dist/jquery.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/list-entry.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/word-counter.js
//= require ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/selection-buttons.js
//= require ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/shim-links-with-button-role.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/shim-links-with-button-role.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/show-hide-content.js
; // Hack needed because show-hide-content.js does not have a closing ";"
//= require ../../../node_modules/digitalmarketplace-govuk-frontend/govuk-frontend/all.js
//= require _selection-buttons.js
//= require ../../../node_modules/digitalmarketplace-frontend-toolkit/toolkit/javascripts/module-loader.js

GOVUKFrontend.initAll()
<|endoftext|>


<commit_before>//= require foundation/js/vendor/jquery
//= require foundation/js/vendor/modernizr
//= require foundation/js/foundation

//= require lodash/lodash.min

//= require angular/angular
//= require ngFx/dist/ngFx.min
//= require angular-busy/dist/angular-busy.min
//= require angular-ui-router/release/angular-ui-router
//= require angularjs-rails-resource/angularjs-rails-resource

//= require angular-rails-templates
//= require_tree ../templates

//= require ./ng-app/app.module
//= require ./ng-app/app.config
//= require_tree ./ng-app/services
//= require_tree ./ng-app/controllers
<commit_msg>not use minified<commit_after>//= require foundation/js/vendor/jquery
//= require foundation/js/vendor/modernizr
//= require foundation/js/foundation

//= require lodash/lodash

//= require angular/angular
//= require ngFx/dist/ngFx
//= require angular-busy/dist/angular-busy
//= require angular-ui-router/release/angular-ui-router
//= require angularjs-rails-resource/angularjs-rails-resource

//= require angular-rails-templates
//= require_tree ../templates

//= require ./ng-app/app.module
//= require ./ng-app/app.config
//= require_tree ./ng-app/services
//= require_tree ./ng-app/controllers
<|endoftext|>


<commit_before>//= require miq_global
//= require es6-shim
//= require array-includes
//= require fetch
//= require jquery
//= require jquery_overrides
//= require i18n
//= require patternfly
//= require jquery-ujs
//= require angular
//= require angular-patternfly-sass/dist/angular-patternfly
//= require angular-ui-bootstrap
//= require angular-ui-bootstrap-tpls
//= require angular-sanitize
//= require angular.validators
//= require moment
//= require moment-strftime/build/moment-strftime.min
//= require moment-timezone
//= require sprintf
//= require numeral
//= require cable
//= require miq_api
//= require rxjs/dist/rx.all
//= require miq_angular_application
//= require_tree ./angular_modules/
//= require_tree ./controllers/
//= require_tree ./directives/
//= require_tree ./services/
//= require d3
//= require c3
//= require lodash
//= require kubernetes-topology-graph/dist/topology-graph
//= require miq_browser_detect
//= require miq_application
//= require miq_change_stored_password
//= require miq_qe
//= require automate_import_export
//= require dialog_field_refresh
//= require excanvas
//= require jquery.jqplot
//= require jqplot-plugins/jqplot.pieRenderer
//= require jqplot-plugins/jqplot.donutRenderer
//= require jqplot-plugins/jqplot.barRenderer
//= require jqplot-plugins/jqplot.categoryAxisRenderer
//= require jqplot-plugins/jqplot.highlighter
//= require jqplot-plugins/jqplot.cursor
//= require jqplot-plugins/jqplot.enhancedLegendRenderer
//= require jqplot-plugins/jqplot.canvasAxisTickRenderer
//= require jqplot-plugins/jqplot.canvasTextRenderer
//= require miq_jqplot
//= require miq_c3_config
//= require jquery-ui
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap-filestyle
//= require bootstrap-select
//= require bootstrap-hover-dropdown
//= require bootstrap-switch
//= require angular-bootstrap-switch
//= require patternfly-bootstrap-treeview
//= require jquery.observe_field
//= require miq_ujs_bindings
//= require miq_tree
//= require codemirror
//= require codemirror/mode/css/css
//= require codemirror/mode/htmlmixed/htmlmixed
//= require codemirror/mode/javascript/javascript
//= require codemirror/mode/ruby/ruby
//= require codemirror/mode/shell/shell
//= require codemirror/mode/xml/xml
//= require codemirror/mode/yaml/yaml
//= require spin.js/spin
//= require spin.js/jquery.spin
//= require jquery-hotkeys
//= require miq_formatters
//= require miq_grid
//= require miq_list_grid
//= require miq_toolbar
//= require resizable_sidebar
//= require xml_display
//= require miq_c3
//= require miq_explorer
//= require qs
//= require miq_timeline
// Bower packages
//= require manageiq-ui-components/dist/js/ui-components
//= require rx-angular/dist/rx.angular
//= require patternfly-timeline/dist/timeline<commit_msg>Removed require of miq_qe to fix issue with drop downs in UI<commit_after>//= require miq_global
//= require es6-shim
//= require array-includes
//= require fetch
//= require jquery
//= require jquery_overrides
//= require i18n
//= require patternfly
//= require jquery-ujs
//= require angular
//= require angular-patternfly-sass/dist/angular-patternfly
//= require angular-ui-bootstrap
//= require angular-ui-bootstrap-tpls
//= require angular-sanitize
//= require angular.validators
//= require moment
//= require moment-strftime/build/moment-strftime.min
//= require moment-timezone
//= require sprintf
//= require numeral
//= require cable
//= require miq_api
//= require rxjs/dist/rx.all
//= require miq_angular_application
//= require_tree ./angular_modules/
//= require_tree ./controllers/
//= require_tree ./directives/
//= require_tree ./services/
//= require d3
//= require c3
//= require lodash
//= require kubernetes-topology-graph/dist/topology-graph
//= require miq_browser_detect
//= require miq_application
//= require miq_change_stored_password
//= require automate_import_export
//= require dialog_field_refresh
//= require excanvas
//= require jquery.jqplot
//= require jqplot-plugins/jqplot.pieRenderer
//= require jqplot-plugins/jqplot.donutRenderer
//= require jqplot-plugins/jqplot.barRenderer
//= require jqplot-plugins/jqplot.categoryAxisRenderer
//= require jqplot-plugins/jqplot.highlighter
//= require jqplot-plugins/jqplot.cursor
//= require jqplot-plugins/jqplot.enhancedLegendRenderer
//= require jqplot-plugins/jqplot.canvasAxisTickRenderer
//= require jqplot-plugins/jqplot.canvasTextRenderer
//= require miq_jqplot
//= require miq_c3_config
//= require jquery-ui
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap-filestyle
//= require bootstrap-select
//= require bootstrap-hover-dropdown
//= require bootstrap-switch
//= require angular-bootstrap-switch
//= require patternfly-bootstrap-treeview
//= require jquery.observe_field
//= require miq_ujs_bindings
//= require miq_tree
//= require codemirror
//= require codemirror/mode/css/css
//= require codemirror/mode/htmlmixed/htmlmixed
//= require codemirror/mode/javascript/javascript
//= require codemirror/mode/ruby/ruby
//= require codemirror/mode/shell/shell
//= require codemirror/mode/xml/xml
//= require codemirror/mode/yaml/yaml
//= require spin.js/spin
//= require spin.js/jquery.spin
//= require jquery-hotkeys
//= require miq_formatters
//= require miq_grid
//= require miq_list_grid
//= require miq_toolbar
//= require resizable_sidebar
//= require xml_display
//= require miq_c3
//= require miq_explorer
//= require qs
//= require miq_timeline
// Bower packages
//= require manageiq-ui-components/dist/js/ui-components
//= require rx-angular/dist/rx.angular
//= require patternfly-timeline/dist/timeline
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require fotorama
//= require retina
//= require jquery_ujs
//= require ink-all
//= require autoload
//= require html5shiv
//= require leaflet
//= require jquery.dynatable
//= require_tree .

$(document).ready(function () {
    $('.fotorama').on('fotorama:showend', function (e, fotorama, extra) {
        var images = document.getElementsByTagName('img'),
            retinaImages = [],
            i, image;
        for (i = 0; i < images.length; i += 1) {
            image = images[i];
            if (!!!image.getAttributeNode('data-no-retina')) {
                retinaImages.push(new RetinaImage(image));
            }
        }
    });

    map = L.map('map');

    map.setView([-35.30, 149.12], 4);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/doconnor.ionk423c/{z}/{x}/{y}.png', {
        attribution: 'Terms & Feedback'
    }).addTo(map);
/*
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
*/

    $("#items-table").on("click", ".view-image", function (e) {
        e.preventDefault();
        id = $(this).data().id;
        project_id = $(this).data().project_id;
        $('#image').html(" ");
        $.getJSON('/projects/' + project_id + '/items/' + id + '/photo_links.json', function (data) {
            $.each(data, function (i, item) {
                $("").attr("src", item).appendTo("#image");
            });
        });

        $.getJSON('/projects/' + project_id + '/items/' + id + '.geojson', function (data) {
            map.setView(data.coordinates, 15);
            L.geoJson(data.properties).addTo(map);
        });
    });
});
<commit_msg>On success, scroll to the map!<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require fotorama
//= require retina
//= require jquery_ujs
//= require ink-all
//= require autoload
//= require html5shiv
//= require leaflet
//= require jquery.dynatable
//= require_tree .

$(document).ready(function () {
    $('.fotorama').on('fotorama:showend', function (e, fotorama, extra) {
        var images = document.getElementsByTagName('img'),
            retinaImages = [],
            i, image;
        for (i = 0; i < images.length; i += 1) {
            image = images[i];
            if (!!!image.getAttributeNode('data-no-retina')) {
                retinaImages.push(new RetinaImage(image));
            }
        }
    });

    map = L.map('map');

    map.setView([-35.30, 149.12], 4);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/doconnor.ionk423c/{z}/{x}/{y}.png', {
        attribution: 'Terms & Feedback'
    }).addTo(map);
/*
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
*/

    $("#items-table").on("click", ".view-image", function (e) {
        e.preventDefault();
        id = $(this).data().id;
        project_id = $(this).data().project_id;
        $('#image').html(" ");
        $.getJSON('/projects/' + project_id + '/items/' + id + '/photo_links.json', function (data) {
            $.each(data, function (i, item) {
                $("").attr("src", item).appendTo("#image");
            });
        });

        $.getJSON('/projects/' + project_id + '/items/' + id + '.geojson', function (data) {
            map.setView(data.coordinates, 15);
            L.geoJson(data.properties).addTo(map);

            window.location.href="#map";
        });
    });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
$(function () {
  $(document).foundation();
  (function replaceEmojiWithImages(root) {
    var REGIONAL_INDICATOR_A = parseInt('1f1e6', 16), REGIONAL_INDICATOR_Z = parseInt('1f1ff', 16), IMAGE_HOST = 'assets.github.com', IMAGE_PATH = '/images/icons/emoji/unicode/', IMAGE_EXT = '.png';
    // String.fromCodePoint is super helpful
    if (!String.fromCodePoint) {
      /*!
     * ES6 Unicode Shims 0.1
     * (c) 2012 Steven Levithan <http://slevithan.com/>
     * MIT License
     **/
      String.fromCodePoint = function fromCodePoint() {
        var chars = [], point, offset, units, i;
        for (i = 0; i < arguments.length; ++i) {
          point = arguments[i];
          offset = point - 65536;
          units = point > 65535 ? [
            55296 + (offset >> 10),
            56320 + (offset & 1023)
          ] : [point];
          chars.push(String.fromCharCode.apply(null, units));
        }
        return chars.join('');
      };
    }
    /**
   * Create a treewalker to walk an element and return an Array of Text Nodes.
   * This function is (hopefully) smart enough to exclude unwanted text nodes
   * like whitespace and script tags.
   * https://gist.github.com/mwunsch/4693383
   */
    function getLegitTextNodes(element) {
      if (!document.createTreeWalker)
        return [];
      var blacklist = [
          'SCRIPT',
          'OPTION',
          'TEXTAREA'
        ], textNodes = [], walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, function excludeBlacklistedNodes(node) {
          if (blacklist.indexOf(node.parentElement.nodeName.toUpperCase()) >= 0)
            return NodeFilter.FILTER_REJECT;
          if (String.prototype.trim && !node.nodeValue.trim().length)
            return NodeFilter.FILTER_SKIP;
          return NodeFilter.FILTER_ACCEPT;
        }, false);
      while (walker.nextNode())
        textNodes.push(walker.currentNode);
      return textNodes;
    }
    /**
   * Determine if this browser supports emoji.
   */
    function doesSupportEmoji() {
      var context, smiley;
      if (!document.createElement('canvas').getContext)
        return;
      context = document.createElement('canvas').getContext('2d');
      if (typeof context.fillText != 'function')
        return;
      smile = String.fromCodePoint(128516);
      // :smile: String.fromCharCode(55357) + String.fromCharCode(56835)
      context.textBaseline = 'top';
      context.font = '32px Arial';
      context.fillText(smile, 0, 0);
      return context.getImageData(16, 16, 1, 1).data[0] !== 0;
    }
    /**
   * For a UTF-16 (JavaScript's preferred encoding...kinda) surrogate pair,
   * return a Unicode codepoint.
   */
    function surrogatePairToCodepoint(lead, trail) {
      return (lead - 55296) * 1024 + (trail - 56320) + 65536;
    }
    /**
   * Get an Image element for an emoji codepoint (in hex).
   */
    function getImageForCodepoint(hex) {
      var img = document.createElement('IMG');
      img.style.width = '1.4em';
      img.style.verticalAlign = 'top';
      img.src = '//' + IMAGE_HOST + IMAGE_PATH + hex + IMAGE_EXT;
      return img;
    }
    /**
   * Convert an HTML string into a DocumentFragment, for insertion into the dom.
   */
    function fragmentForString(htmlString) {
      var tmpDoc = document.createElement('DIV'), fragment = document.createDocumentFragment(), childNode;
      tmpDoc.innerHTML = htmlString;
      while (childNode = tmpDoc.firstChild) {
        fragment.appendChild(childNode);
      }
      return fragment;
    }
    /**
   * Iterate through a list of nodes, find emoji, replace with images.
   */
    function emojiReplace(nodes) {
      var PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/g;
      nodes.forEach(function (node) {
        var replacement, value = node.nodeValue, matches = value.match(PATTERN);
        if (matches) {
          replacement = value.replace(PATTERN, function (match, p1, p2) {
            var codepoint = surrogatePairToCodepoint(p1.charCodeAt(0), p2.charCodeAt(0)), img = getImageForCodepoint(codepoint.toString(16));
            return img.outerHTML;
          });
          node.parentNode.replaceChild(fragmentForString(replacement), node);
        }
      });
    }
    // Call everything we've defined
    if (!doesSupportEmoji()) {
      emojiReplace(getLegitTextNodes(document.body));
    }
  }(this));
});
<commit_msg>limit emoji/image replacement to rendered markdown<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
$(function () {
  $(document).foundation();
  (function replaceEmojiWithImages(root) {
    var REGIONAL_INDICATOR_A = parseInt('1f1e6', 16), REGIONAL_INDICATOR_Z = parseInt('1f1ff', 16), IMAGE_HOST = 'assets.github.com', IMAGE_PATH = '/images/icons/emoji/unicode/', IMAGE_EXT = '.png';
    // String.fromCodePoint is super helpful
    if (!String.fromCodePoint) {
      /*!
     * ES6 Unicode Shims 0.1
     * (c) 2012 Steven Levithan <http://slevithan.com/>
     * MIT License
     **/
      String.fromCodePoint = function fromCodePoint() {
        var chars = [], point, offset, units, i;
        for (i = 0; i < arguments.length; ++i) {
          point = arguments[i];
          offset = point - 65536;
          units = point > 65535 ? [
            55296 + (offset >> 10),
            56320 + (offset & 1023)
          ] : [point];
          chars.push(String.fromCharCode.apply(null, units));
        }
        return chars.join('');
      };
    }
    /**
   * Create a treewalker to walk an element and return an Array of Text Nodes.
   * This function is (hopefully) smart enough to exclude unwanted text nodes
   * like whitespace and script tags.
   * https://gist.github.com/mwunsch/4693383
   */
    function getLegitTextNodes(element) {
      if (!document.createTreeWalker)
        return [];
      var blacklist = [
          'SCRIPT',
          'OPTION',
          'TEXTAREA'
        ], textNodes = [], walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, function excludeBlacklistedNodes(node) {
          if (blacklist.indexOf(node.parentElement.nodeName.toUpperCase()) >= 0)
            return NodeFilter.FILTER_REJECT;
          if (String.prototype.trim && !node.nodeValue.trim().length)
            return NodeFilter.FILTER_SKIP;
          return NodeFilter.FILTER_ACCEPT;
        }, false);
      while (walker.nextNode())
        textNodes.push(walker.currentNode);
      return textNodes;
    }
    /**
   * Determine if this browser supports emoji.
   */
    function doesSupportEmoji() {
      var context, smiley;
      if (!document.createElement('canvas').getContext)
        return;
      context = document.createElement('canvas').getContext('2d');
      if (typeof context.fillText != 'function')
        return;
      smile = String.fromCodePoint(128516);
      // :smile: String.fromCharCode(55357) + String.fromCharCode(56835)
      context.textBaseline = 'top';
      context.font = '32px Arial';
      context.fillText(smile, 0, 0);
      return context.getImageData(16, 16, 1, 1).data[0] !== 0;
    }
    /**
   * For a UTF-16 (JavaScript's preferred encoding...kinda) surrogate pair,
   * return a Unicode codepoint.
   */
    function surrogatePairToCodepoint(lead, trail) {
      return (lead - 55296) * 1024 + (trail - 56320) + 65536;
    }
    /**
   * Get an Image element for an emoji codepoint (in hex).
   */
    function getImageForCodepoint(hex) {
      var img = document.createElement('IMG');
      img.style.width = '1.4em';
      img.style.verticalAlign = 'top';
      img.src = '//' + IMAGE_HOST + IMAGE_PATH + hex + IMAGE_EXT;
      return img;
    }
    /**
   * Convert an HTML string into a DocumentFragment, for insertion into the dom.
   */
    function fragmentForString(htmlString) {
      var tmpDoc = document.createElement('DIV'), fragment = document.createDocumentFragment(), childNode;
      tmpDoc.innerHTML = htmlString;
      while (childNode = tmpDoc.firstChild) {
        fragment.appendChild(childNode);
      }
      return fragment;
    }
    /**
   * Iterate through a list of nodes, find emoji, replace with images.
   */
    function emojiReplace(nodes) {
      var PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/g;
      nodes.forEach(function (node) {
        var replacement, value = node.nodeValue, matches = value.match(PATTERN);
        if (matches) {
          replacement = value.replace(PATTERN, function (match, p1, p2) {
            var codepoint = surrogatePairToCodepoint(p1.charCodeAt(0), p2.charCodeAt(0)), img = getImageForCodepoint(codepoint.toString(16));
            return img.outerHTML;
          });
          node.parentNode.replaceChild(fragmentForString(replacement), node);
        }
      });
    }
    // Call everything we've defined
    if (!doesSupportEmoji()) {
      emojiReplace(getLegitTextNodes(document.querySelector("#md_rendered")));
    }
  }(this));
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>cleaning up<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require jquery.easing.1.3
//= require jquery-ui-1.8.20.custom.min
//= require wax.g.min-6.0.4
//= require cartodb-gmapsv3
//= require cartodb-infowindow-min
//= require jquery.history
//= require jstorage.min
//= require lodash.min
//= require backbone-min
//= require class
//= require backbone.cartodb
//= require d3.v2.min
//= require_tree .

// Map needs to be a global var or
// CapybaraHelpers#draw_polygon won't work

var
map           = null,
previousState = null;

function initialize() {

  var
  State = History.getState(),
  hash  = parseHash(State.hash);

  if (hash) {
    config.mapOptions.center = hash.center;
    config.mapOptions.zoom   = hash.zoom;
  }

  // Initialise the google map
  map = new google.maps.Map(document.getElementById("map"), config.mapOptions);

  var map_style = {};

  GFW(function(env) {

    GFW.app = new env.app.Instance(map, {
      user       : 'wri-01',
      layerTable : 'layerinfo',
      logging    : true
    });

    GFW.app.run();
    GFW.env = env;

  });

}

(function(window,undefined){

  // Prepare
  var History = window.History; // Note: We are using a capital H instead of a lower h

  if ( !History.enabled ) {
    // History.js is disabled for this browser.
    // This is because we can optionally choose to support HTML4 browsers or not.
    return false;
  }

  // Bind to StateChange Event
  History.Adapter.bind(window,'statechange', function(){ // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state

    //History.log(State.data, State.title, State.url);
    if (previousState != State.title) {
      if (State.title === 'Home') {
        Navigation.showState("home");
      } else if (State.title === 'Map') {
        Navigation.showState("map");
      }

      previousState = State.title;
    }
  });

  $("nav .home.ajax").on("click", function(e) {
    e.preventDefault();
    History.pushState({ state: 2 }, "Home", "/");

    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });

  });

  $("nav .countries.ajax").on("click", function(e) {
    e.preventDefault();
    Navigation.showState('countries');
  });

  $(".share_link").on("click", function(e) {
    e.preventDefault();
    $("#content").append('
');
    $(".backdrop").fadeIn(250, function() {

      var top = ( $(window).height() - $("#share").height() ) / 2+$(window).scrollTop() + "px",
      left = ( $(window).width() - $("#share").width() ) / 2+$(window).scrollLeft() + "px";

      $("#share").css({top: top, left:left});
      $("#share").fadeIn(250);
    });
  });

  $(".close_icon").on("click", function(e) {
    e.preventDefault();
    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
    $("#share").fadeOut(250);
  });

  $(".subscribe_link").on("click", function(e) {
    e.preventDefault();
    $("#content").append('
');
    $(".backdrop").fadeIn(250, function() {

      var top = ( $(window).height() - $("#subscribe").height() ) / 2+$(window).scrollTop() + "px",
      left = ( $(window).width() - $("#subscribe").width() ) / 2+$(window).scrollLeft() + "px";

      $("#subscribe").css({top: top, left:left});
      $("#subscribe").fadeIn(250);
    });
  });

  $("#subscribe").on("click", function(e) {
    e.preventDefault();
    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
    $("#subscribe").fadeOut(250);
  });

  $("nav .map.ajax").on("click", function(e) {
    e.preventDefault();
    History.pushState({ state: 1 }, "Map", "/map");

    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
  });

  return false;

})(window);

$(function(){

  var
  renderPolygonListener = null,
  polygon               = null,
  polygonPath           = [],
  resizePID;

  $(document).keyup(function(e) {
    if (e.keyCode == 27) {
      if ($("#share:visible").length > 0) {
        $("#share").fadeOut(250);
        $(".backdrop").fadeOut(250);
      }
      if ($("#subscribe:visible").length > 0) {
        $("#subscribe").fadeOut(250);
        $(".backdrop").fadeOut(250);
      }

    } // esc
  });

  $(window).resize(function() {
    clearTimeout(resizePID);
    resizePID = setTimeout(function() { resizeWindow(); }, 100);
  });

  function resizeWindow(e) {
    if (showMap) {
      GFW.app.open();
      Filter.calcFiltersPosition();
    }
  }

  if ($("div[data-load]:visible").length > 0) {
    updateFeed({countryCode: countryCode, n: 4});
    addCircle("forest", "bars", { legendUnit: "m", countryCode: countryCode, width: 300, title: "Height", subtitle:"Tree height distribution", legend:"with {{n}} tall trees", hoverColor: "#427C8D", color: "#75ADB5", unit: "km2" });
    addCircle("forma", "lines", { countryCode: countryCode, width: 300, title: "FORMA", subtitle:"Forest clearing alerts", legend:"In the last month", hoverColor: "#F2B357", color: "#F2B357" });
  }
});
<commit_msg>Adds drawing function<commit_after>//= require jquery
//= require jquery_ujs
//= require jquery.easing.1.3
//= require jquery-ui-1.8.20.custom.min
//= require wax.g.min-6.0.4
//= require cartodb-gmapsv3
//= require cartodb-infowindow-min
//= require jquery.history
//= require jstorage.min
//= require lodash.min
//= require backbone-min
//= require class
//= require backbone.cartodb
//= require d3.v2.min
//= require_tree .

// Map needs to be a global var or
// CapybaraHelpers#draw_polygon won't work

var
map           = null,
previousState = null;

function initialize() {

  var
  State = History.getState(),
  hash  = parseHash(State.hash);

  if (hash) {
    config.mapOptions.center = hash.center;
    config.mapOptions.zoom   = hash.zoom;
  }

  // Initialise the google map
  map = new google.maps.Map(document.getElementById("map"), config.mapOptions);

  var map_style = {};

  GFW(function(env) {

    GFW.app = new env.app.Instance(map, {
      user       : 'wri-01',
      layerTable : 'layerinfo',
      logging    : true
    });

    GFW.app.run();
    GFW.env = env;

  });

}

(function(window,undefined){

  // Prepare
  var History = window.History; // Note: We are using a capital H instead of a lower h

  if ( !History.enabled ) {
    // History.js is disabled for this browser.
    // This is because we can optionally choose to support HTML4 browsers or not.
    return false;
  }

  // Bind to StateChange Event
  History.Adapter.bind(window,'statechange', function(){ // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state

    //History.log(State.data, State.title, State.url);
    if (previousState != State.title) {
      if (State.title === 'Home') {
        Navigation.showState("home");
      } else if (State.title === 'Map') {
        Navigation.showState("map");
      }

      previousState = State.title;
    }
  });

  $("nav .home.ajax").on("click", function(e) {
    e.preventDefault();
    History.pushState({ state: 2 }, "Home", "/");

    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });

  });

  $("nav .countries.ajax").on("click", function(e) {
    e.preventDefault();
    Navigation.showState('countries');
  });

  $(".share_link").on("click", function(e) {
    e.preventDefault();
    $("#content").append('
');
    $(".backdrop").fadeIn(250, function() {

      var top = ( $(window).height() - $("#share").height() ) / 2+$(window).scrollTop() + "px",
      left = ( $(window).width() - $("#share").width() ) / 2+$(window).scrollLeft() + "px";

      $("#share").css({top: top, left:left});
      $("#share").fadeIn(250);
    });
  });

  $(".close_icon").on("click", function(e) {
    e.preventDefault();
    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
    $("#share").fadeOut(250);
  });

  $(".subscribe_link").on("click", function(e) {
    e.preventDefault();
    $("#content").append('
');
    $(".backdrop").fadeIn(250, function() {

      var top = ( $(window).height() - $("#subscribe").height() ) / 2+$(window).scrollTop() + "px",
      left = ( $(window).width() - $("#subscribe").width() ) / 2+$(window).scrollLeft() + "px";

      $("#subscribe").css({top: top, left:left});
      $("#subscribe").fadeIn(250);
    });
  });

  $("#subscribe").on("click", function(e) {
    e.preventDefault();
    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
    $("#subscribe").fadeOut(250);
  });

  $("nav .map.ajax").on("click", function(e) {
    e.preventDefault();
    History.pushState({ state: 1 }, "Map", "/map");

    $(".backdrop").fadeOut(250, function() {
      $(this).remove();
    });
  });

  return false;

})(window);

$(function(){

  var
  renderPolygonListener = null,
  polygon               = null,
  polygonPath           = [],
  resizePID;

  $(document).keyup(function(e) {
    if (e.keyCode == 27) {
      if ($("#share:visible").length > 0) {
        $("#share").fadeOut(250);
        $(".backdrop").fadeOut(250);
      }
      if ($("#subscribe:visible").length > 0) {
        $("#subscribe").fadeOut(250);
        $(".backdrop").fadeOut(250);
      }

    } // esc
  });

  $(window).resize(function() {
    clearTimeout(resizePID);
    resizePID = setTimeout(function() { resizeWindow(); }, 100);
  });

  function resizeWindow(e) {
    if (showMap) {
      GFW.app.open();
      Filter.calcFiltersPosition();
    }
  }

  if ($("div[data-load]:visible").length > 0) {
    updateFeed({countryCode: countryCode, n: 4});
    addCircle("forest", "bars", { legendUnit: "m", countryCode: countryCode, width: 300, title: "Height", subtitle:"Tree height distribution", legend:"with {{n}} tall trees", hoverColor: "#427C8D", color: "#75ADB5", unit: "km2" });
    addCircle("forma", "lines", { countryCode: countryCode, width: 300, title: "FORMA", subtitle:"Forest clearing alerts", legend:"In the last month", hoverColor: "#F2B357", color: "#F2B357" });
  }

    // Enables map editing mode. When activated, each click in the map draws a polyline
    $('#map-container').find('.draw-area').click(function(){
      $(this).closest('#map-container').toggleClass('editing-mode');

      if (renderPolygonListener) return;

      polygonPath = [];

      polygon = new google.maps.Polygon({
        paths: [],
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: "#FF0000",
        fillOpacity: 0.35
      });

      polygon.setMap(map);

      renderPolygonListener = google.maps.event.addListener(map, 'click', function(e){
        polygonPath.push(e.latLng);
        polygon.setPath(polygonPath);
      });
    });

    // Disables editing mode. Sends the created polygon to cartodb.
    $('#map-container').find('.save-area').submit(function(e){
      e.preventDefault();
      $(this).closest('#map-container').toggleClass('editing-mode');
      $(this).find('#area_the_geom').val(JSON.stringify({
        "type": "MultiPolygon",
        "coordinates": [
          [
            $.map(polygonPath, function(latlong, index){
          return [[latlong.lng(), latlong.lat()]];
        })
        ]
        ]
      }));

      $.post($(this).attr('action'), $(this).serialize(), function(response){
        google.maps.event.removeListener(renderPolygonListener);
        renderPolygonListener = null;
      });
    });

});
<|endoftext|>