<commit_before>// This must be included before the first call to $(document).ready
// in order to be able to report exceptions that occur during their
// execution.

var blueslip = (function () {

var exports = {};

if (Error.stackTraceLimit !== undefined) {
    Error.stackTraceLimit = 100000;
}

var console = (function () {
    if (window.console !== undefined) {
        return window.console;
    }

    var proxy = {};
    var methods = ['log', 'info', 'warn', 'error', 'trace'];
    var i;
    for (i = 0; i < methods.length; i++) {
        proxy[methods[i]] = function () {};
    }
    return proxy;
}());

var reported_errors = {};
var last_report_attempt = {};
function report_error(msg, stack, opts) {
    opts = _.extend({show_ui_msg: false}, opts);

    if (stack === undefined) {
        stack = 'No stacktrace available';
    }

    var key = ':' + msg + stack;
    if (reported_errors.hasOwnProperty(key)
        || (last_report_attempt.hasOwnProperty(key)
            // Only try to report a given error once every 5 minutes
            && (Date.now() - last_report_attempt[key] <= 60 * 5 * 1000)))
    {
        return;
    }

    last_report_attempt[key] = Date.now();

    // TODO: If an exception gets thrown before we setup ajax calls
    // to include the CSRF token, our ajax call will fail.  The
    // elegant thing to do in that case is to either wait until that
    // setup is done or do it ourselves and then retry.
    $.ajax({
        type:     'POST',
        url:      '/json/report_error',
        dataType: 'json',
        data:     { message: msg,
                    stacktrace: stack,
                    ui_message: opts.show_ui_msg,
                    more_info: JSON.stringify(opts.more_info),
                    href: window.location.href,
                    user_agent: window.navigator.userAgent},
        timeout:  3*1000,
        success:  function () {
            reported_errors[key] = true;
            if (opts.show_ui_msg && ui !== undefined) {
                // There are a few races here (and below in the error
                // callback):
                // 1) The ui module or something it requires might
                //    not have been compiled or initialized yet.
                // 2) The DOM might not be ready yet and so fetching
                //    the #home-error div might fail.

                // For (1) we just don't show the message if the ui
                // hasn't been loaded yet.  The user will probably
                // get another error once it does.  We can't solve
                // (2) by using $(document).ready() because the
                // callback never gets called (I think what's going
                // on here is if the exception was raised by a
                // function that was called as a result of the DOM
                // becoming ready then the internal state of jQuery
                // gets messed up and our callback never gets
                // invoked).  In any case, it will pretty clear that
                // something is wrong with the page and the user will
                // probably try to reload anyway.
                ui.report_message("Oops.  It seems something has gone wrong. " +
                                  "The error has been reported to the fine " +
                                  "folks at Zulip, but, in the mean time, " +
                                  "please try reloading the page.",
                                  $("#home-error"), "alert-error");
            }
        },
        error: function () {
            if (opts.show_ui_msg && ui !== undefined) {
                ui.report_message("Oops.  It seems something has gone wrong. " +
                                  "Please try reloading the page.",
                                  $("#home-error"), "alert-error");
            }
        }
    });

    if (page_params.staging) {
        // Save the stacktrace so it can be examined even on local servers.
        // (N.B. This assumes you have set DEBUG = False on your local
        // server, or else this code path won't execute to begin with --
        // useful for testing (un)minification.)
        window.last_stacktrace = stack;
    }
}

function BlueslipError(msg, more_info) {
    // One can't subclass Error normally so we have to play games
    // with setting __proto__
    var self = new Error(msg);
    self.name = "BlueslipError";

    // Indirect access to __proto__ keeps jslint quiet
    var proto = '__proto__';
    self[proto] = BlueslipError.prototype;

    if (more_info !== undefined) {
        self.more_info = more_info;
    }
    return self;
}

BlueslipError.prototype = Object.create(Error.prototype);

exports.wrap_function = function blueslip_wrap_function(func) {
    if (func.blueslip_wrapper !== undefined) {
        func.blueslip_wrapper_refcnt++;
        return func.blueslip_wrapper;
    }
    var new_func = function blueslip_wrapper() {
        if (page_params.debug_mode) {
            return func.apply(this, arguments);
        }

        try {
            return func.apply(this, arguments);
        } catch (ex) {
            // Treat exceptions like a call to fatal() if they
            // weren't generated from fatal()
            if (ex instanceof BlueslipError) {
                throw ex;
            }

            var message = ex.message;
            if (ex.hasOwnProperty('fileName')) {
                message += " at " + ex.fileName;
                if (ex.hasOwnProperty('lineNumber')) {
                    message += ":" + ex.lineNumber;
                }
            }
            report_error(message, ex.stack);
            throw ex;
        }
    };
    func.blueslip_wrapper = new_func;
    func.blueslip_wrapper_refcnt = 1;
    return new_func;
};

// Catch all exceptions from jQuery event handlers, $(document).ready
// functions, and ajax success/failure continuations and funnel them
// through blueslip.
(function () {
    // This reference counting scheme can't break all the circular
    // references we create because users can remove jQuery event
    // handlers without referencing the particular handler they want
    // to remove.  We just hope this memory leak won't be too bad.
    function dec_wrapper_refcnt(func) {
        if (func.blueslip_wrapper_refcnt !== undefined) {
            func.blueslip_wrapper_refcnt--;
            if (func.blueslip_wrapper_refcnt === 0) {
                delete func.blueslip_wrapper;
                delete func.blueslip_wrapper_refcnt;
            }
        }
    }

    $.ajaxPrefilter(function (options) {
        _.each(['success', 'error', 'complete'], function (cb_name) {
            if (options[cb_name] !== undefined) {
                options[cb_name] = exports.wrap_function(options[cb_name]);
            }
        });
    });

    if (document.addEventListener) {
        var orig_on = $.fn.on;
        var orig_off = $.fn.off;
        var orig_ready = $.fn.ready;

        $.fn.on = function blueslip_jquery_on_wrapper(types, selector, data, fn, one) {
            if (typeof types === 'object') {
                // ( types-Object, selector, data)
                // We'll get called again from the recursive call in the original
                // $.fn.on
                return orig_on.call(this, types, selector, data, fn, one);
            }

            // Only one handler, but we have to figure out which
            // argument it is.  The argument munging is taken from
            // jQuery itself, so we tell jslint to ignore the style
            // issues that the jQuery code would raise.  It sucks
            // that we have to replicate the code :(
            /*jslint eqeq: true */
            if ( data == null && fn == null ) {
                // ( types, fn )
                fn = selector;
                data = selector = undefined;
            } else if ( fn == null ) {
                if ( typeof selector === "string" ) {
                // ( types, selector, fn )
                fn = data;
                data = undefined;
                } else {
                // ( types, data, fn )
                fn = data;
                data = selector;
                selector = undefined;
                }
            }
            if ( fn === false ) {
                fn = function () { return false; };
            } else if ( !fn ) {
                return this;
            }
            /*jslint eqeq: false */

            return orig_on.call(this, types, selector, data, exports.wrap_function(fn), one);
        };

        $.fn.off = function (types, selector, fn) {
            if (types && types.preventDefault && types.handleObj) {
                // (event)
                // We'll get called again through the recursive call in the original
                // $.fn.off
                return orig_off.call(this, types, selector, fn);
            }

            if (typeof types === "object" ) {
                // ( types-object [, selector] )
                // We'll get called again through the recursive call in the original
                // $.fn.off
                return orig_off.call(this, types, selector, fn);
            }

            // Only one handler, but we have to figure out which
            // argument it is.  The argument munging is taken from
            // jQuery, itself.
            if ( selector === false || typeof selector === "function" ) {
                // ( types [, fn] )
                fn = selector;
                selector = undefined;
            }
            if ( fn === false ) {
                fn = function () { return false; };
            }

            if (fn) {
                var wrapper = fn.blueslip_wrapper;
                if (wrapper !== undefined) {
                    dec_wrapper_refcnt(fn);
                    fn = wrapper;
                }
            }
            return orig_off.call(this, types, selector, fn);
        };

        $.fn.ready = function blueslip_jquery_ready_wrapper(func) {
            return orig_ready.call(this, exports.wrap_function(func));
        };
    }
}());

exports.log = function blueslip_log (msg, more_info) {
    console.log(msg);
    if (more_info !== undefined) {
        console.log("Additional information: ", more_info);
    }
};

exports.info = function blueslip_info (msg, more_info) {
    console.info(msg);
    if (more_info !== undefined) {
        console.info("Additional information: ", more_info);
    }
};

exports.warn = function blueslip_warn (msg, more_info) {
    console.warn(msg);
    if (page_params.debug_mode) {
        console.trace();
    }
    if (more_info !== undefined) {
        console.warn("Additional information: ", more_info);
    }
};

exports.error = function blueslip_error (msg, more_info) {
    if (page_params.debug_mode) {
        throw new BlueslipError(msg, more_info);
    } else {
        console.error(msg);
        if (more_info !== undefined) {
            console.error("Additional information: ", more_info);
        }
        report_error(msg, Error().stack, {more_info: more_info});
    }
};

exports.fatal = function blueslip_fatal (msg, more_info) {
    if (! page_params.debug_mode) {
        report_error(msg, Error().stack, {more_info: more_info});
    }

    throw new BlueslipError(msg, more_info);
};

return exports;
}());
<commit_msg>blueslip: Refactor log, info, warn, and error methods<commit_after>// This must be included before the first call to $(document).ready
// in order to be able to report exceptions that occur during their
// execution.

var blueslip = (function () {

var exports = {};

if (Error.stackTraceLimit !== undefined) {
    Error.stackTraceLimit = 100000;
}

var console = (function () {
    if (window.console !== undefined) {
        return window.console;
    }

    var proxy = {};
    var methods = ['log', 'info', 'warn', 'error', 'trace'];
    var i;
    for (i = 0; i < methods.length; i++) {
        proxy[methods[i]] = function () {};
    }
    return proxy;
}());

var reported_errors = {};
var last_report_attempt = {};
function report_error(msg, stack, opts) {
    opts = _.extend({show_ui_msg: false}, opts);

    if (stack === undefined) {
        stack = 'No stacktrace available';
    }

    var key = ':' + msg + stack;
    if (reported_errors.hasOwnProperty(key)
        || (last_report_attempt.hasOwnProperty(key)
            // Only try to report a given error once every 5 minutes
            && (Date.now() - last_report_attempt[key] <= 60 * 5 * 1000)))
    {
        return;
    }

    last_report_attempt[key] = Date.now();

    // TODO: If an exception gets thrown before we setup ajax calls
    // to include the CSRF token, our ajax call will fail.  The
    // elegant thing to do in that case is to either wait until that
    // setup is done or do it ourselves and then retry.
    $.ajax({
        type:     'POST',
        url:      '/json/report_error',
        dataType: 'json',
        data:     { message: msg,
                    stacktrace: stack,
                    ui_message: opts.show_ui_msg,
                    more_info: JSON.stringify(opts.more_info),
                    href: window.location.href,
                    user_agent: window.navigator.userAgent},
        timeout:  3*1000,
        success:  function () {
            reported_errors[key] = true;
            if (opts.show_ui_msg && ui !== undefined) {
                // There are a few races here (and below in the error
                // callback):
                // 1) The ui module or something it requires might
                //    not have been compiled or initialized yet.
                // 2) The DOM might not be ready yet and so fetching
                //    the #home-error div might fail.

                // For (1) we just don't show the message if the ui
                // hasn't been loaded yet.  The user will probably
                // get another error once it does.  We can't solve
                // (2) by using $(document).ready() because the
                // callback never gets called (I think what's going
                // on here is if the exception was raised by a
                // function that was called as a result of the DOM
                // becoming ready then the internal state of jQuery
                // gets messed up and our callback never gets
                // invoked).  In any case, it will pretty clear that
                // something is wrong with the page and the user will
                // probably try to reload anyway.
                ui.report_message("Oops.  It seems something has gone wrong. " +
                                  "The error has been reported to the fine " +
                                  "folks at Zulip, but, in the mean time, " +
                                  "please try reloading the page.",
                                  $("#home-error"), "alert-error");
            }
        },
        error: function () {
            if (opts.show_ui_msg && ui !== undefined) {
                ui.report_message("Oops.  It seems something has gone wrong. " +
                                  "Please try reloading the page.",
                                  $("#home-error"), "alert-error");
            }
        }
    });

    if (page_params.staging) {
        // Save the stacktrace so it can be examined even on local servers.
        // (N.B. This assumes you have set DEBUG = False on your local
        // server, or else this code path won't execute to begin with --
        // useful for testing (un)minification.)
        window.last_stacktrace = stack;
    }
}

function BlueslipError(msg, more_info) {
    // One can't subclass Error normally so we have to play games
    // with setting __proto__
    var self = new Error(msg);
    self.name = "BlueslipError";

    // Indirect access to __proto__ keeps jslint quiet
    var proto = '__proto__';
    self[proto] = BlueslipError.prototype;

    if (more_info !== undefined) {
        self.more_info = more_info;
    }
    return self;
}

BlueslipError.prototype = Object.create(Error.prototype);

exports.wrap_function = function blueslip_wrap_function(func) {
    if (func.blueslip_wrapper !== undefined) {
        func.blueslip_wrapper_refcnt++;
        return func.blueslip_wrapper;
    }
    var new_func = function blueslip_wrapper() {
        if (page_params.debug_mode) {
            return func.apply(this, arguments);
        }

        try {
            return func.apply(this, arguments);
        } catch (ex) {
            // Treat exceptions like a call to fatal() if they
            // weren't generated from fatal()
            if (ex instanceof BlueslipError) {
                throw ex;
            }

            var message = ex.message;
            if (ex.hasOwnProperty('fileName')) {
                message += " at " + ex.fileName;
                if (ex.hasOwnProperty('lineNumber')) {
                    message += ":" + ex.lineNumber;
                }
            }
            report_error(message, ex.stack);
            throw ex;
        }
    };
    func.blueslip_wrapper = new_func;
    func.blueslip_wrapper_refcnt = 1;
    return new_func;
};

// Catch all exceptions from jQuery event handlers, $(document).ready
// functions, and ajax success/failure continuations and funnel them
// through blueslip.
(function () {
    // This reference counting scheme can't break all the circular
    // references we create because users can remove jQuery event
    // handlers without referencing the particular handler they want
    // to remove.  We just hope this memory leak won't be too bad.
    function dec_wrapper_refcnt(func) {
        if (func.blueslip_wrapper_refcnt !== undefined) {
            func.blueslip_wrapper_refcnt--;
            if (func.blueslip_wrapper_refcnt === 0) {
                delete func.blueslip_wrapper;
                delete func.blueslip_wrapper_refcnt;
            }
        }
    }

    $.ajaxPrefilter(function (options) {
        _.each(['success', 'error', 'complete'], function (cb_name) {
            if (options[cb_name] !== undefined) {
                options[cb_name] = exports.wrap_function(options[cb_name]);
            }
        });
    });

    if (document.addEventListener) {
        var orig_on = $.fn.on;
        var orig_off = $.fn.off;
        var orig_ready = $.fn.ready;

        $.fn.on = function blueslip_jquery_on_wrapper(types, selector, data, fn, one) {
            if (typeof types === 'object') {
                // ( types-Object, selector, data)
                // We'll get called again from the recursive call in the original
                // $.fn.on
                return orig_on.call(this, types, selector, data, fn, one);
            }

            // Only one handler, but we have to figure out which
            // argument it is.  The argument munging is taken from
            // jQuery itself, so we tell jslint to ignore the style
            // issues that the jQuery code would raise.  It sucks
            // that we have to replicate the code :(
            /*jslint eqeq: true */
            if ( data == null && fn == null ) {
                // ( types, fn )
                fn = selector;
                data = selector = undefined;
            } else if ( fn == null ) {
                if ( typeof selector === "string" ) {
                // ( types, selector, fn )
                fn = data;
                data = undefined;
                } else {
                // ( types, data, fn )
                fn = data;
                data = selector;
                selector = undefined;
                }
            }
            if ( fn === false ) {
                fn = function () { return false; };
            } else if ( !fn ) {
                return this;
            }
            /*jslint eqeq: false */

            return orig_on.call(this, types, selector, data, exports.wrap_function(fn), one);
        };

        $.fn.off = function (types, selector, fn) {
            if (types && types.preventDefault && types.handleObj) {
                // (event)
                // We'll get called again through the recursive call in the original
                // $.fn.off
                return orig_off.call(this, types, selector, fn);
            }

            if (typeof types === "object" ) {
                // ( types-object [, selector] )
                // We'll get called again through the recursive call in the original
                // $.fn.off
                return orig_off.call(this, types, selector, fn);
            }

            // Only one handler, but we have to figure out which
            // argument it is.  The argument munging is taken from
            // jQuery, itself.
            if ( selector === false || typeof selector === "function" ) {
                // ( types [, fn] )
                fn = selector;
                selector = undefined;
            }
            if ( fn === false ) {
                fn = function () { return false; };
            }

            if (fn) {
                var wrapper = fn.blueslip_wrapper;
                if (wrapper !== undefined) {
                    dec_wrapper_refcnt(fn);
                    fn = wrapper;
                }
            }
            return orig_off.call(this, types, selector, fn);
        };

        $.fn.ready = function blueslip_jquery_ready_wrapper(func) {
            return orig_ready.call(this, exports.wrap_function(func));
        };
    }
}());

function build_arg_list(msg, more_info) {
    var args = [msg];
    if (more_info !== undefined) {
        args.push("\nAdditional information: ", more_info);
    }
    return args;
}

exports.log = function blueslip_log (msg, more_info) {
    var args = build_arg_list(msg, more_info);
    console.log.apply(console, args);
};

exports.info = function blueslip_info (msg, more_info) {
    var args = build_arg_list(msg, more_info);
    console.info.apply(console, args);
};

exports.warn = function blueslip_warn (msg, more_info) {
    var args = build_arg_list(msg, more_info);
    console.warn.apply(console, args);
    if (page_params.debug_mode) {
        console.trace();
    }
};

exports.error = function blueslip_error (msg, more_info) {
    if (page_params.debug_mode) {
        throw new BlueslipError(msg, more_info);
    } else {
        var args = build_arg_list(msg, more_info);
        console.error.apply(console, args);
        report_error(msg, Error().stack, {more_info: more_info});
    }
};

exports.fatal = function blueslip_fatal (msg, more_info) {
    if (! page_params.debug_mode) {
        report_error(msg, Error().stack, {more_info: more_info});
    }

    throw new BlueslipError(msg, more_info);
};

return exports;
}());
<|endoftext|>


<commit_before>(function ($) {
	$.fn.scrolld = function (options) {
		var scrolldCustom = 0;
		var scrolldNavBar = 'fixedNavBar';
		var scrolldMobileNavBar = 'fixedNavBar';

		var $win=$(window);var doc=document;var y=$win.scrollTop();var h=$win.height();var x=$win.width();var htmlBody=$("html, body");$win.scroll(function(a){y=$win.scrollTop();a.stopImmediatePropagation();return false});$win.resize(function(a){h=$win.height();x=$win.width();a.stopImmediatePropagation();return false});$.easing.scrolldEasing1=function(f,g,e,k,j){var i=(g/=j)*g;var a=i*g;return e+k*(-3.6*a*i+4.3*i*i+0.2*a+0.1*i)};$.easing.scrolldEasing2=function(f,g,e,k,j){var i=(g/=j)*g;var a=i*g;return e+k*(18.9925*a*i+-45.23*i*i+40.28*a+-19.89*i+6.8475*g)};$.easing.scrolldEasing3=function(e,f,a,i,g){if((f/=g)<(1.25/3)){return i*(9.5625*f*f)+a}else{if(f<(2.25/3)){return i*(8.5625*(f-=(1.5/2.75))*f+0.85)+a}else{if(f<(2.75/3)){return i*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return i*(5.5625*(f-=(2.625/2.75))*f+1)+a}}}};var speed1=100;var speed2=200;var speed3=300;var speed4=400;var speed5=500;var speed6=600;var speed7=700;var speed8=800;var speed9=900;var speed10=1000;var speed11=1100;var speed12=1200;var speed13=1300;var speed14=1400;var speed15=1500;var speed16=1600;var speed17=1700;var speed18=1800;var speed19=1900;var speed20=2000;var speedX=3000;var idScroll=$(this).attr("id");var scrolldFixed=$("#"+scrolldNavBar).outerHeight();var scrolldMobileFixed=$("#"+scrolldMobileNavBar).outerHeight();var idScrollElement=$("#"+idScroll);var idScrollString=idScroll.substr(0,idScroll.length-3);var idScrollDiv=document.getElementById(idScrollString).id;var idScrollDivElement=$("#"+idScrollDiv);var offsetDivElementTop=Math.round(idScrollDivElement.offset().top);var idScrollDivElementHeight=Math.round(idScrollDivElement.height());var scrolldTop=offsetDivElementTop+scrolldCustom;var scrolldTopFixed=Math.round(offsetDivElementTop-scrolldFixed)+scrolldCustom;var scrolldPre=offsetDivElementTop-Math.round(h/15)+scrolldCustom;var scrolldPreFixed=offsetDivElementTop-scrolldFixed-Math.round(h/20)+scrolldCustom;var scrolldCenter=offsetDivElementTop-Math.round(h/2-idScrollDivElementHeight/2);var scrolldMobileTopFixed=Math.round(offsetDivElementTop-scrolldMobileFixed)+scrolldCustom;var scrolldMobilePreFixed=offsetDivElementTop-scrolldMobileFixed-Math.round(h/20)+scrolldCustom;var scrolldDistance=scrolldTop;var scrolldDistanceMin=scrolldTop;var scrolldSpeed=speed9;var scrolldEasing="scrolldEasing1";var scrolldFixed=true;var scrolldMobile=true;var scrolldMobileWidth=979;var scrolldMobileDistance=scrolldTop;var scrolldMobileDistanceMin=scrolldTop;var scrolldMobileSpeed=speed9;var scrolldMobileEasing="scrolldEasing1";var scrolldMobileFixed=true;

		var
		defaults = {
			scrolldDistance: scrolldPre,
			scrolldDistanceMin: scrolldPre,
			scrolldSpeed: speed11,
			scrolldEasing: 'scrolldEasing1',
			scrolldFixed: 'true',

			scrolldMobile: 'true',
			scrolldMobileWidth: 979,
			scrolldMobileDistance: scrolldPre,
			scrolldMobileDistanceMin: scrolldPre,
			scrolldMobileSpeed: speed11,
			scrolldMobileEasing: 'scrolldEasing1',
			scrolldMobileFixed: 'true'
		},

		settings=$.extend({},defaults,options);this.each(function(){if($(this).attr("id")!=""){var a=$(this);if(settings.scrolldDistance){scrolldDistance=settings.scrolldDistance}if(settings.scrolldDistanceMin){scrolldDistanceMin=settings.scrolldDistanceMin}if(settings.scrolldSpeed){scrolldSpeed=settings.scrolldSpeed}if(settings.scrolldEasing){scrolldEasing=settings.scrolldEasing}if(settings.scrolldFixed==="false"){scrolldFixed=false}if(settings.scrolldMobile==="false"){scrolldMobile=false}if(settings.scrolldMobileWidth){scrolldMobileWidth=settings.scrolldMobileWidth}if(settings.scrolldMobileDistance){scrolldMobileDistance=settings.scrolldMobileDistance}if(settings.scrolldMobileDistanceMin){scrolldMobileDistanceMin=settings.scrolldMobileDistanceMin}if(settings.scrolldMobileSpeed){scrolldMobileSpeed=settings.scrolldMobileSpeed}if(settings.scrolldMobileEasing){scrolldMobileEasing=settings.scrolldMobileEasing}if(settings.scrolldMobileFixed==="false"){scrolldMobileFixed=false}if(a.hasClass("linear")){scrolldEasing="linear"}if(a.hasClass("linearMobile")){scrolldMobileEasing="linear"}if(a.hasClass("swing")){scrolldEasing="swing"}if(a.hasClass("swingMobile")){scrolldMobileEasing="swing"}if(a.hasClass("jswing")){scrolldEasing="jswing"}if(a.hasClass("jswingMobile")){scrolldMobileEasing="jswing"}if(a.hasClass("easeInQuad")){scrolldEasing="easeInQuad"}if(a.hasClass("easeInQuadMobile")){scrolldMobileEasing="easeInQuad"}if(a.hasClass("easeOutQuad")){scrolldEasing="easeOutQuad"}if(a.hasClass("easeOutQuadMobile")){scrolldMobileEasing="easeOutQuad"}if(a.hasClass("easeInOutQuad")){scrolldEasing="easeInOutQuad"}if(a.hasClass("easeInOutQuadMobile")){scrolldMobileEasing="easeInOutQuad"}if(a.hasClass("easeInCubic")){scrolldEasing="easeInCubic"}if(a.hasClass("easeInCubicMobile")){scrolldMobileEasing="easeInCubic"}if(a.hasClass("easeOutCubic")){scrolldEasing="easeOutCubic"}if(a.hasClass("easeOutCubicMobile")){scrolldMobileEasing="easeOutCubic"}if(a.hasClass("easeInOutCubic")){scrolldEasing="easeInOutCubic"}if(a.hasClass("easeInOutCubicMobile")){scrolldMobileEasing="easeInOutCubic"}if(a.hasClass("easeInQuart")){scrolldEasing="easeInQuart"}if(a.hasClass("easeInQuartMobile")){scrolldMobileEasing="easeInQuart"}if(a.hasClass("easeOutQuart")){scrolldEasing="easeOutQuart"}if(a.hasClass("easeOutQuartMobile")){scrolldMobileEasing="easeOutQuart"}if(a.hasClass("easeInOutQuart")){scrolldEasing="easeInOutQuart"}if(a.hasClass("easeInOutQuartMobile")){scrolldMobileEasing="easeInOutQuart"}if(a.hasClass("easeInQuint")){scrolldEasing="easeInQuint"}if(a.hasClass("easeInQuintMobile")){scrolldMobileEasing="easeInQuint"}if(a.hasClass("easeOutQuint")){scrolldEasing="easeOutQuint"}if(a.hasClass("easeOutQuintMobile")){scrolldMobileEasing="easeOutQuint"}if(a.hasClass("easeInOutQuint")){scrolldEasing="easeInOutQuint"}if(a.hasClass("easeInOutQuintMobile")){scrolldMobileEasing="easeInOutQuint"}if(a.hasClass("easeInSine")){scrolldEasing="easeInSine"}if(a.hasClass("easeInSineMobile")){scrolldMobileEasing="easeInSine"}if(a.hasClass("easeOutSine")){scrolldEasing="easeOutSine"}if(a.hasClass("easeOutSineMobile")){scrolldMobileEasing="easeOutSine"}if(a.hasClass("easeInOutSine")){scrolldEasing="easeInOutSine"}if(a.hasClass("easeInOutSineMobile")){scrolldMobileEasing="easeInOutSine"}if(a.hasClass("easeInExpo")){scrolldEasing="easeInExpo"}if(a.hasClass("easeInExpoMobile")){scrolldMobileEasing="easeInExpo"}if(a.hasClass("easeOutExpo")){scrolldEasing="easeOutExpo"}if(a.hasClass("easeOutExpoMobile")){scrolldMobileEasing="easeOutExpo"}if(a.hasClass("easeInOutExpo")){scrolldEasing="easeInOutExpo"}if(a.hasClass("easeInOutExpoMobile")){scrolldMobileEasing="easeInOutExpo"}if(a.hasClass("easeInCirc")){scrolldEasing="easeInCirc"}if(a.hasClass("easeInCircMobile")){scrolldMobileEasing="easeInCirc"}if(a.hasClass("easeOutCirc")){scrolldEasing="easeOutCirc"}if(a.hasClass("easeOutCircMobile")){scrolldMobileEasing="easeOutCirc"}if(a.hasClass("easeInOutCirc")){scrolldEasing="easeInOutCirc"}if(a.hasClass("easeInOutCircMobile")){scrolldMobileEasing="easeInOutCirc"}if(a.hasClass("easeInElastic")){scrolldEasing="easeInElastic"}if(a.hasClass("easeInElasticMobile")){scrolldMobileEasing="easeInElastic"}if(a.hasClass("easeOutElastic")){scrolldEasing="easeOutElastic"}if(a.hasClass("easeOutElasticMobile")){scrolldMobileEasing="easeOutElastic"}if(a.hasClass("easeInOutElastic")){scrolldEasing="easeInOutElastic"}if(a.hasClass("easeInOutElasticMobile")){scrolldMobileEasing="easeInOutElastic"}if(a.hasClass("easeInBack")){scrolldEasing="easeInBack"}if(a.hasClass("easeInBackMobile")){scrolldMobileEasing="easeInBack"}if(a.hasClass("easeOutBack")){scrolldEasing="easeOutBack"}if(a.hasClass("easeOutBackMobile")){scrolldMobileEasing="easeOutBack"}if(a.hasClass("easeInOutBack")){scrolldEasing="easeInOutBack"}if(a.hasClass("easeInOutBackMobile")){scrolldMobileEasing="easeInOutBack"}if(a.hasClass("easeInBounce")){scrolldEasing="easeInBounce"}if(a.hasClass("easeInBounceMobile")){scrolldMobileEasing="easeInBounce"}if(a.hasClass("easeOutBounce")){scrolldEasing="easeOutBounce"}if(a.hasClass("easeOutBounceMobile")){scrolldMobileEasing="easeOutBounce"}if(a.hasClass("easeInOutBounce")){scrolldEasing="easeInOutBounce"}if(a.hasClass("easeInOutBounceMobile")){scrolldMobileEasing="easeInOutBounce"}if(a.hasClass("scrolldEasing1")){scrolldEasing="scrolldEasing1"}if(a.hasClass("scrolldEasing1Mobile")){scrolldMobileEasing="scrolldEasing1"}if(a.hasClass("scrolldEasing2")){scrolldEasing="scrolldEasing2"}if(a.hasClass("scrolldEasing2Mobile")){scrolldMobileEasing="scrolldEasing2"}if(a.hasClass("scrolldEasing3")){scrolldEasing="scrolldEasing3"}if(a.hasClass("scrolldEasing3Mobile")){scrolldMobileEasing="scrolldEasing3"}if(x<scrolldMobileWidth){if(scrolldMobile===true&&scrolldMobileFixed===false){if(h<=idScrollDivElementHeight){htmlBody.stop(true).animate({scrollTop:scrolldMobileDistanceMin},scrolldMobileSpeed,scrolldMobileEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldMobileDistance},scrolldMobileSpeed,scrolldMobileEasing)}}else{if(scrolldMobile===true&&scrolldMobileFixed===true){if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldMobileSpeed,scrolldMobileEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldMobileDistance},scrolldMobileSpeed,scrolldMobileEasing)}}}}}}}else{if(scrolldMobile===false){scrolldMobileWidth=1}}}}if(x>=scrolldMobileWidth){if(scrolldFixed===false){if(h<=idScrollDivElementHeight){htmlBody.stop(true).animate({scrollTop:scrolldDistanceMin},scrolldSpeed,scrolldEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldDistance},scrolldMobileSpeed,scrolldMobileEasing)}}else{if(scrolldFixed===true){if(h<=(idScrollDivElementHeight+scrolldFixed)&&scrolldDistanceMin===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldSpeed,scrolldEasing)}else{if(h<=(idScrollDivElementHeight+scrolldFixed)&&scrolldDistanceMin===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldSpeed,scrolldEasing)}else{if(h<=(idScrollDivElementHeight+scrolldFixed*2)&&scrolldDistanceMin===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed)&&scrolldDistance===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed)&&scrolldDistance===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed*2)&&scrolldDistance===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldSpeed,scrolldEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldDistance},scrolldSpeed,scrolldEasing)}}}}}}}}}}});

        return this;
	}
})(jQuery);
<commit_msg>Replace class check if's for switch (100% Faster)<commit_after>(function ($) {
	$.fn.scrolld = function (options) {
		var scrolldCustom = 0;
		var scrolldNavBar = 'fixedNavBar';
		var scrolldMobileNavBar = 'fixedNavBar';

		var $win=$(window);var doc=document;var y=$win.scrollTop();var h=$win.height();var x=$win.width();var htmlBody=$("html, body");$win.scroll(function(a){y=$win.scrollTop();a.stopImmediatePropagation();return false});$win.resize(function(a){h=$win.height();x=$win.width();a.stopImmediatePropagation();return false});$.easing.scrolldEasing1=function(f,g,e,k,j){var i=(g/=j)*g;var a=i*g;return e+k*(-3.6*a*i+4.3*i*i+0.2*a+0.1*i)};$.easing.scrolldEasing2=function(f,g,e,k,j){var i=(g/=j)*g;var a=i*g;return e+k*(18.9925*a*i+-45.23*i*i+40.28*a+-19.89*i+6.8475*g)};$.easing.scrolldEasing3=function(e,f,a,i,g){if((f/=g)<(1.25/3)){return i*(9.5625*f*f)+a}else{if(f<(2.25/3)){return i*(8.5625*(f-=(1.5/2.75))*f+0.85)+a}else{if(f<(2.75/3)){return i*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return i*(5.5625*(f-=(2.625/2.75))*f+1)+a}}}};var speed1=100;var speed2=200;var speed3=300;var speed4=400;var speed5=500;var speed6=600;var speed7=700;var speed8=800;var speed9=900;var speed10=1000;var speed11=1100;var speed12=1200;var speed13=1300;var speed14=1400;var speed15=1500;var speed16=1600;var speed17=1700;var speed18=1800;var speed19=1900;var speed20=2000;var speedX=3000;var idScroll=$(this).attr("id");var scrolldFixed=$("#"+scrolldNavBar).outerHeight();var scrolldMobileFixed=$("#"+scrolldMobileNavBar).outerHeight();var idScrollElement=$("#"+idScroll);var idScrollString=idScroll.substr(0,idScroll.length-3);var idScrollDiv=document.getElementById(idScrollString).id;var idScrollDivElement=$("#"+idScrollDiv);var offsetDivElementTop=Math.round(idScrollDivElement.offset().top);var idScrollDivElementHeight=Math.round(idScrollDivElement.height());var scrolldTop=offsetDivElementTop+scrolldCustom;var scrolldTopFixed=Math.round(offsetDivElementTop-scrolldFixed)+scrolldCustom;var scrolldPre=offsetDivElementTop-Math.round(h/15)+scrolldCustom;var scrolldPreFixed=offsetDivElementTop-scrolldFixed-Math.round(h/20)+scrolldCustom;var scrolldCenter=offsetDivElementTop-Math.round(h/2-idScrollDivElementHeight/2);var scrolldMobileTopFixed=Math.round(offsetDivElementTop-scrolldMobileFixed)+scrolldCustom;var scrolldMobilePreFixed=offsetDivElementTop-scrolldMobileFixed-Math.round(h/20)+scrolldCustom;var scrolldDistance=scrolldTop;var scrolldDistanceMin=scrolldTop;var scrolldSpeed=speed9;var scrolldEasing="scrolldEasing1";var scrolldFixed=true;var scrolldMobile=true;var scrolldMobileWidth=979;var scrolldMobileDistance=scrolldTop;var scrolldMobileDistanceMin=scrolldTop;var scrolldMobileSpeed=speed9;var scrolldMobileEasing="scrolldEasing1";var scrolldMobileFixed=true;

		var
		defaults = {
			scrolldDistance: scrolldPre,
			scrolldDistanceMin: scrolldPre,
			scrolldSpeed: speed11,
			scrolldEasing: 'scrolldEasing1',
			scrolldFixed: 'true',
			scrolldMobile: 'true',
			scrolldMobileWidth: 979,
			scrolldMobileDistance: scrolldPre,
			scrolldMobileDistanceMin: scrolldPre,
			scrolldMobileSpeed: speed11,
			scrolldMobileEasing: 'scrolldEasing1',
			scrolldMobileFixed: 'true'
		},

		settings=$.extend({},defaults,options);this.each(function(){if($(this).attr("id")!=""){var c=$(this);if(settings.scrolldDistance){scrolldDistance=settings.scrolldDistance}if(settings.scrolldDistanceMin){scrolldDistanceMin=settings.scrolldDistanceMin}if(settings.scrolldSpeed){scrolldSpeed=settings.scrolldSpeed}if(settings.scrolldEasing){scrolldEasing=settings.scrolldEasing}if(settings.scrolldFixed==="false"){scrolldFixed=false}if(settings.scrolldMobile==="false"){scrolldMobile=false}if(settings.scrolldMobileWidth){scrolldMobileWidth=settings.scrolldMobileWidth}if(settings.scrolldMobileDistance){scrolldMobileDistance=settings.scrolldMobileDistance}if(settings.scrolldMobileDistanceMin){scrolldMobileDistanceMin=settings.scrolldMobileDistanceMin}if(settings.scrolldMobileSpeed){scrolldMobileSpeed=settings.scrolldMobileSpeed}if(settings.scrolldMobileEasing){scrolldMobileEasing=settings.scrolldMobileEasing}if(settings.scrolldMobileFixed==="false"){scrolldMobileFixed=false}var b=$(this).attr("class");var a=$(this).hasClass(b);switch(a){case"linear":scrolldEasing="linear";break;case"linearMobile":scrolldMobileEasing="linear";break;case"swing":scrolldEasing="swing";break;case"swingMobile":scrolldMobileEasing="swing";break;case"jswing":scrolldEasing="jswing";break;case"jswingMobile":scrolldMobileEasing="jswing";break;case"easeInQuad":scrolldEasing="easeInQuad";break;case"easeInQuadMobile":scrolldMobileEasing="easeInQuad";break;case"easeOutQuad":scrolldEasing="easeOutQuad";break;case"easeOutQuadMobile":scrolldMobileEasing="easeOutQuad";break;case"easeInOutQuad":scrolldEasing="easeInOutQuad";break;case"easeInOutQuadMobile":scrolldMobileEasing="easeInOutQuad";break;case"easeInCubic":scrolldEasing="easeInCubic";break;case"easeInCubicMobile":scrolldMobileEasing="easeInCubic";break;case"easeOutCubic":scrolldEasing="easeOutCubic";break;case"easeOutCubicMobile":scrolldMobileEasing="easeOutCubic";break;case"easeInOutCubic":scrolldEasing="easeInOutCubic";break;case"easeInOutCubicMobile":scrolldMobileEasing="easeInOutCubic";break;case"easeInQuart":scrolldEasing="easeInQuart";break;case"easeInQuartMobile":scrolldMobileEasing="easeInQuart";break;case"easeOutQuart":scrolldEasing="easeOutQuart";break;case"easeOutQuartMobile":scrolldMobileEasing="easeOutQuart";break;case"easeInOutQuart":scrolldEasing="easeInOutQuart";break;case"easeInOutQuartMobile":scrolldMobileEasing="easeInOutQuart";break;case"easeInQuint":scrolldEasing="easeInQuint";break;case"easeInQuintMobile":scrolldMobileEasing="easeInQuint";break;case"easeOutQuint":scrolldEasing="easeOutQuint";break;case"easeOutQuintMobile":scrolldMobileEasing="easeOutQuint";break;case"easeInOutQuint":scrolldEasing="easeInOutQuint";break;case"easeInOutQuintMobile":scrolldMobileEasing="easeInOutQuint";break;case"easeInSine":scrolldEasing="easeInSine";break;case"easeInSineMobile":scrolldMobileEasing="easeInSine";break;case"easeOutSine":scrolldEasing="easeOutSine";break;case"easeOutSineMobile":scrolldMobileEasing="easeOutSine";break;case"easeInOutSine":scrolldEasing="easeInOutSine";break;case"easeInOutSineMobile":scrolldMobileEasing="easeInOutSine";break;case"easeInExpo":scrolldEasing="easeInExpo";break;case"easeInExpoMobile":scrolldMobileEasing="easeInExpo";break;case"easeOutExpo":scrolldEasing="easeOutExpo";break;case"easeOutExpoMobile":scrolldMobileEasing="easeOutExpo";break;case"easeInOutExpo":scrolldEasing="easeInOutExpo";break;case"easeInOutExpoMobile":scrolldMobileEasing="easeInOutExpo";break;case"easeInCirc":scrolldEasing="easeInCirc";break;case"easeInCircMobile":scrolldMobileEasing="easeInCirc";break;case"easeOutCirc":scrolldEasing="easeOutCirc";break;case"easeOutCircMobile":scrolldMobileEasing="easeOutCirc";break;case"easeInOutCirc":scrolldEasing="easeInOutCirc";break;case"easeInOutCircMobile":scrolldMobileEasing="easeInOutCirc";break;case"easeInElastic":scrolldEasing="easeInElastic";break;case"easeInElasticMobile":scrolldMobileEasing="easeInElastic";break;case"easeOutElastic":scrolldEasing="easeOutElastic";break;case"easeOutElasticMobile":scrolldMobileEasing="easeOutElastic";break;case"easeInOutElastic":scrolldEasing="easeInOutElastic";break;case"easeInOutElasticMobile":scrolldMobileEasing="easeInOutElastic";break;case"easeInBack":scrolldEasing="easeInBack";break;case"easeInBackMobile":scrolldMobileEasing="easeInBack";break;case"easeOutBack":scrolldEasing="easeOutBack";break;case"easeOutBackMobile":scrolldMobileEasing="easeOutBack";break;case"easeInOutBack":scrolldEasing="easeInOutBack";break;case"easeInOutBackMobile":scrolldMobileEasing="easeInOutBack";break;case"easeInBounce":scrolldEasing="easeInBounce";break;case"easeInBounceMobile":scrolldMobileEasing="easeInBounce";break;case"easeOutBounce":scrolldEasing="easeOutBounce";break;case"easeOutBounceMobile":scrolldMobileEasing="easeOutBounce";break;case"easeInOutBounce":scrolldEasing="easeInOutBounce";break;case"easeInOutBounceMobile":scrolldMobileEasing="easeInOutBounce";break;case"scrolldEasing1":scrolldEasing="scrolldEasing1";break;case"scrolldEasing1Mobile":scrolldMobileEasing="scrolldEasing1";break;case"scrolldEasing2":scrolldEasing="scrolldEasing2";break;case"scrolldEasing2Mobile":scrolldMobileEasing="scrolldEasing2";break;case"scrolldEasing3":scrolldEasing="scrolldEasing3";break;case"scrolldEasing3Mobile":scrolldMobileEasing="scrolldEasing3";break;default:scrolldEasing=scrolldEasing;scrolldMobileEasing=scrolldMobileEasing}if(x<scrolldMobileWidth){if(scrolldMobile===true&&scrolldMobileFixed===false){if(h<=idScrollDivElementHeight){htmlBody.stop(true).animate({scrollTop:scrolldMobileDistanceMin},scrolldMobileSpeed,scrolldMobileEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldMobileDistance},scrolldMobileSpeed,scrolldMobileEasing)}}else{if(scrolldMobile===true&&scrolldMobileFixed===true){if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h<=(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistanceMin===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldMobileSpeed,scrolldMobileEasing)}else{if(h>(idScrollDivElementHeight+(scrolldMobileFixed*2))&&scrolldMobileDistance===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldMobileSpeed,scrolldMobileEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldMobileDistance},scrolldMobileSpeed,scrolldMobileEasing)}}}}}}}else{if(scrolldMobile===false){scrolldMobileWidth=1}}}}if(x>=scrolldMobileWidth){if(scrolldFixed===false){if(h<=idScrollDivElementHeight){htmlBody.stop(true).animate({scrollTop:scrolldDistanceMin},scrolldSpeed,scrolldEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldDistance},scrolldMobileSpeed,scrolldMobileEasing)}}else{if(scrolldFixed===true){if(h<=(idScrollDivElementHeight+scrolldFixed)&&scrolldDistanceMin===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldSpeed,scrolldEasing)}else{if(h<=(idScrollDivElementHeight+scrolldFixed)&&scrolldDistanceMin===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldSpeed,scrolldEasing)}else{if(h<=(idScrollDivElementHeight+scrolldFixed*2)&&scrolldDistanceMin===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed)&&scrolldDistance===scrolldTop){htmlBody.stop(true).animate({scrollTop:scrolldTopFixed},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed)&&scrolldDistance===scrolldPre){htmlBody.stop(true).animate({scrollTop:scrolldPreFixed},scrolldSpeed,scrolldEasing)}else{if(h>(idScrollDivElementHeight+scrolldFixed*2)&&scrolldDistance===scrolldCenter){htmlBody.stop(true).animate({scrollTop:scrolldCenter},scrolldSpeed,scrolldEasing)}else{htmlBody.stop(true).animate({scrollTop:scrolldDistance},scrolldSpeed,scrolldEasing)}}}}}}}}}}});

        return this;
	}
})(jQuery);<|endoftext|>


<commit_before>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
	iconUrl: '/static/icons/place_marker.png',
	iconSize: [40, 40],
	iconAnchor: [20, 40],
	popupAnchor: [0,-40]
});

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var patients;
var newPatientIndex;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    $('#start_dispatch_button').hide();

    // Update current location
    updateCurrentLocation(mymap.getCenter());

    // Update current address
    updateCurrentAddress(currentLocation);

    // Clear current patients
    patients = {};
    newPatientIndex = 0;

    // Initialize patient form
    $('#patients').empty();

    // add new patient form entry
    $('#patients').append(newPatientForm(newPatientIndex, 'fa-plus', 'addPatient(' + newPatientIndex + ')'));

}

var addPatient = function(index) {

    console.log('Adding patient index ' + index);

    var name = $('#patient-' + index + '-name').val().trim();
    var age = $('#patient-' + index + '-age').val().trim();

    // is name empty?
    if (!name) {
        alert('Empty name');
        return;
    }

    // add name
    patients[index] = [name, age];
    newPatientIndex++;

    // change button symbol
    var symbol = $('#patient-' + index + '-symbol');
    symbol.removeClass('fa-plus');
    symbol.addClass('fa-minus');

    // change button action
    $('#patient-' + index + '-button')
        .off('click')
        .on('click', function(e) { removePatient(index); });

    // add new form
    $('#patients').append(newPatientForm(newPatientIndex, 'fa-plus',
        'addPatient(' + newPatientIndex + ')'));

}

var removePatient = function(index) {

    console.log('Removing patient index ' + index);

    // remove from storage
    delete patients[index];

    // remove from form
    $('#patients').remove('#patient-' + index + '-form');

}

var newPatientForm = function(index, symbol, action) {

    return '
' +
        '
' +
        '        <input id="patient-' + index + '-name" type="text"' +
        '               class="form-control"' +
        '               placeholder="Name">' +
        '
' +
        '
' +
        '        <input id="patient-' + index + '-age" type="text"' +
        '               class="form-control"' +
        '               placeholder="Age"/>' +
        '
' +
        '
' +
        '        <button class="btn btn-default new-patient"' +
        '                type="button"' +
        '                id="patient-' + index + '-button"' +
        '                onclick="' + action + '">' +
        '            ' +
        '        </button>' +
        '
' +
        '
';

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();

    $('#start_dispatch_button').show();

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        alert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = ambulance;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

var updateCurrentLocation = function(location) {

    console.log('Setting current location to: ' + location.lat + ', ' + location.lng);

    // set currentLocation
    currentLocation = location;

    // update coordinates on form
    $('#curr-lat').html(currentLocation.lat);
    $('#curr-lng').html(currentLocation.lng);

    // remove existing marker
    markersGroup.clearLayers();

    // laydown marker
    var marker = L.marker(location,
        {
            icon: placeIcon,
            draggable: true
        })
        .addTo(markersGroup);
    markersGroup.addTo(mymap);

    // pan to location
    mymap.panTo(location);

    // events
    marker.on('dragend', function(e) {

        // update current location
        updateCurrentLocation(marker.getLatLng());

        // update address?
        if ($('#update-address').prop('checked'))
            updateCurrentAddress(currentLocation);

    })

}

var updateCurrentAddress = function(location) {

    var options = {
        types: 'address',
        limit: 1
    };
    geocoder.reverse(location, options,
        function (results, status) {

        if (status != "success") {
            alert("Could not geocode:\nError " + status + ", " + results['error']);
            return;
        }

        // quick return if found nothing
        if (results.length == 0) {
            console.log('Got nothing from geocode');
            return;
        }

        // parse features into current address
        currentAddress = geocoder.parse_feature(results[0]);

        console.log(
            'Setting currentAddress to:'
            + '\nnumber: ' + currentAddress['number']
            + '\nstreet: ' + currentAddress['street']
            + '\nunit: ' + currentAddress['unit']
            + '\nlocation: ' + currentAddress['location']['latitude']
            + ',' + currentAddress['location']['longitude']
            + '\nneighborhood: ' + currentAddress['neighborhood']
            + '\nzipcode: ' + currentAddress['zipcode']
            + '\ncity: ' + currentAddress['city']
            + '\nstate: ' + currentAddress['state']
            + '\ncountry: ' + currentAddress['country']
        );

        // set input text
        $('#street').val(currentAddress['street_address']);

    });

}

var updateCoordinates = function() {

    // when the user changes the street address
    var address =$('#street').val();

    // quick return if no address
    if (!address)
        return;

    // otherwise geocode and update
    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocoder.geocode(address, options,
        function (results, status) {

            if (status != "success") {
                alert("Could not geocode:\nError " + status + ", " + results['error']);
                return;
            }

            // quick return if found nothing
            if (results.length == 0) {
                console.log('Got nothing from geocode');
                return;
            }

            // parse features into address
            var address = geocoder.parse_feature(results[0]);

            console.log(
                'Setting currentLocation to:'
                + '\nnumber: ' + address['number']
                + '\nstreet: ' + address['street']
                + '\nunit: ' + address['unit']
                + '\nlocation: ' + address['location']['latitude']
                + ',' + address['location']['longitude']
                + '\nneighborhood: ' + address['neighborhood']
                + '\nzipcode: ' + address['zipcode']
                + '\ncity: ' + address['city']
                + '\nstate: ' + address['state']
                + '\ncountry: ' + address['country']
            );

            // set current location
            updateCurrentLocation({
                lat: address['location']['latitude'],
                lng: address['location']['longitude']
            });

        });
}

// connect actions to inputs

$("#street").change(function () {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-coordinates').change(function() {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-address').change(function() {

    // update address?
    if ($('#update-address').prop('checked'))
        updateCurrentAddress(currentLocation);

});

$('#dispatch_form_collapse').submit(function (e) {

   // prevent normal form submission
    e.preventDefault();

    // dispatch call
    dispatchCall();

});

/*
 * dispatchCall makes an ajax post request to post dispatched ambulance.
 * @param void.
 * @return void.
 */
function dispatchCall() {

    var form = {};

    // call information
    form['details'] = $('#comment').val();
    form['priority'] = $('input:radio[name=priority]:checked').val();

    // checks
    if (form["priority"] === undefined) {
        alert("Please click one of priorities");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        alert("Please dispatch at least one ambulance");
        return;
    }

    // address information
    form['number'] = currentAddress['number'];
    form['street'] = currentAddress['street'];
    form['unit'] = currentAddress['unit'];
    form['neighborbood'] = currentAddress['neighborhood'];
    form['city'] = currentAddress['city'];
    form['state'] = currentAddress['state'];
    form['country'] = currentAddress['country'];
    form['zipcode'] = currentAddress['zipcode'];
    form['location'] = currentAddress['location'];

    // ambulances
    var ambulances = [];
    for (var id in dispatchingAmbulances)
        if (dispatchingAmbulances.hasOwnProperty(id))
            ambulances.push(id);
    form['ambulances'] = ambulances;

    // TODO: patients

    // make json call
    let postJsonUrl = 'api/call/';
    console.log("Will post '" + JSON.stringify(form) + "'");

    var CSRFToken = getCookie('csrftoken');

    // retrieve csrf token
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!CSRFSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", CSRFToken);
            }
        }
    })

    // make ajax call
    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: form,
        success: function (data) {

            // alert(JSON.stringify(data));
            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

            // Show modal
            $('.modal-title').html('Success');
            $('.modal-body').html(successMsg).addClass('alert-success');
            $("#dispatchModal").modal('show');

            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {

            // Show modal
            $('.modal-title').html('Failure');
            $('.modal-body').html(textStatus + ": " + errorThrown).addClass('alert-danger');
            $("#dispatchModal").modal('show');

            endDispatching();
        }
    });
}

function CSRFSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
<commit_msg>Upgrading to Bootstrap 4.0<commit_after>/* Dispatch area - Should be eliminate after dispatching */

var markersGroup = new L.LayerGroup();
var isDispatching = false;
var placeIcon = L.icon({
	iconUrl: '/static/icons/place_marker.png',
	iconSize: [40, 40],
	iconAnchor: [20, 40],
	popupAnchor: [0,-40]
});

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var patients;
var newPatientIndex;

var beginDispatching = function () {

    isDispatching = true;
    console.log('Begin dispatching.');

    $('#start_dispatch_button').hide();

    // Update current location
    updateCurrentLocation(mymap.getCenter());

    // Update current address
    updateCurrentAddress(currentLocation);

    // Clear current patients
    patients = {};
    newPatientIndex = 0;

    // Initialize patient form
    $('#patients').empty();

    // add new patient form entry
    $('#patients').append(newPatientForm(newPatientIndex, 'fa-plus', 'addPatient(' + newPatientIndex + ')'));

}

var addPatient = function(index) {

    console.log('Adding patient index ' + index);

    var name = $('#patient-' + index + '-name').val().trim();
    var age = $('#patient-' + index + '-age').val().trim();

    // is name empty?
    if (!name) {
        alert('Empty name');
        return;
    }

    // add name
    patients[index] = [name, age];
    newPatientIndex++;

    // change button symbol
    var symbol = $('#patient-' + index + '-symbol');
    symbol.removeClass('fa-plus');
    symbol.addClass('fa-minus');

    // change button action
    $('#patient-' + index + '-button').off().on('click', function(e) { removePatient(index); });

    // add new form
    $('#patients').append(newPatientForm(newPatientIndex, 'fa-plus',
        'addPatient(' + newPatientIndex + ')'));

}

var removePatient = function(index) {

    console.log('Removing patient index ' + index);

    // remove from storage
    delete patients[index];

    // remove from form
    $('#patients').remove('#patient-' + index + '-form');

}

var newPatientForm = function(index, symbol, action) {

    return '
' +
        '
' +
        '        <input id="patient-' + index + '-name" type="text"' +
        '               class="form-control"' +
        '               placeholder="Name">' +
        '
' +
        '
' +
        '        <input id="patient-' + index + '-age" type="text"' +
        '               class="form-control"' +
        '               placeholder="Age"/>' +
        '
' +
        '
' +
        '        <button class="btn btn-default new-patient"' +
        '                type="button"' +
        '                id="patient-' + index + '-button"' +
        '                onclick="' + action + '">' +
        '            ' +
        '        </button>' +
        '
' +
        '
';

}

var endDispatching = function () {

    isDispatching = false;
    dispatchingAmbulances = {};
    console.log('End dispatching.');

    markersGroup.clearLayers();

    $('#start_dispatch_button').show();

}

var removeFromDispatchingList = function(ambulance) {

    // delete from dispatching list
    delete dispatchingAmbulances[ambulance.id];
    numberOfDispatchingAmbulances--;

    // show message if last button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').show();

}

var addToDispatchingList = function(ambulance) {

    // quick return if null or not dispatching
    if (ambulance == null || !isDispatching)
        return;

    // add ambulance to dispatching list
    console.log('Adding ambulance ' + ambulance.identifier + ' to dispatching list');

    // already in?
    if (ambulance.id in dispatchingAmbulances) {
        console.log('Already in dispatching list, skip');
        return;
    }

    // not available?
    if (ambulance.status != STATUS_AVAILABLE) {
        console.log('Ambulance is not available');
        alert('Can only dispatch available ambulances!');
        return;
    }

    // hide message if first button
    if (numberOfDispatchingAmbulances == 0)
        $('#ambulance-selection-message').hide();

    // add ambulance to list of dispatching ambulances
    dispatchingAmbulances[ambulance.id] = ambulance;
    numberOfDispatchingAmbulances++;

    // add button to ambulance dispatch grid
    $('#ambulance-selection').append(
        '<button id="dispatch-button-' + ambulance.id + '"'
        + ' value="' + ambulance.id + '"'
        + ' type="button" class="btn btn-sm btn-success"'
        + ' style="margin: 2px 2px;"'
        + ' draggable="true">'
        + ambulance.identifier
        + '</button>'
    );
    $('#dispatch-button-' + ambulance.id)
        .on('dragstart', function (e) {
            // on start of drag, copy information and fade button
            console.log('dragstart');
            this.style.opacity = '0.4';
            e.originalEvent.dataTransfer.setData("text/plain", ambulance.id);
        })
        .on('dragend', function (e) {
            console.log('dragend');
            if (e.originalEvent.dataTransfer.dropEffect == 'none') {
                // Remove button if not dropped back
                removeFromDispatchingList(ambulance);
                // Remove button
                $(this).remove();
            } else {
                // Restore opacity if dropped back in
                this.style.opacity = '1.0';
            }
        });
}

var updateCurrentLocation = function(location) {

    console.log('Setting current location to: ' + location.lat + ', ' + location.lng);

    // set currentLocation
    currentLocation = location;

    // update coordinates on form
    $('#curr-lat').html(currentLocation.lat);
    $('#curr-lng').html(currentLocation.lng);

    // remove existing marker
    markersGroup.clearLayers();

    // laydown marker
    var marker = L.marker(location,
        {
            icon: placeIcon,
            draggable: true
        })
        .addTo(markersGroup);
    markersGroup.addTo(mymap);

    // pan to location
    mymap.panTo(location);

    // events
    marker.on('dragend', function(e) {

        // update current location
        updateCurrentLocation(marker.getLatLng());

        // update address?
        if ($('#update-address').prop('checked'))
            updateCurrentAddress(currentLocation);

    })

}

var updateCurrentAddress = function(location) {

    var options = {
        types: 'address',
        limit: 1
    };
    geocoder.reverse(location, options,
        function (results, status) {

        if (status != "success") {
            alert("Could not geocode:\nError " + status + ", " + results['error']);
            return;
        }

        // quick return if found nothing
        if (results.length == 0) {
            console.log('Got nothing from geocode');
            return;
        }

        // parse features into current address
        currentAddress = geocoder.parse_feature(results[0]);

        console.log(
            'Setting currentAddress to:'
            + '\nnumber: ' + currentAddress['number']
            + '\nstreet: ' + currentAddress['street']
            + '\nunit: ' + currentAddress['unit']
            + '\nlocation: ' + currentAddress['location']['latitude']
            + ',' + currentAddress['location']['longitude']
            + '\nneighborhood: ' + currentAddress['neighborhood']
            + '\nzipcode: ' + currentAddress['zipcode']
            + '\ncity: ' + currentAddress['city']
            + '\nstate: ' + currentAddress['state']
            + '\ncountry: ' + currentAddress['country']
        );

        // set input text
        $('#street').val(currentAddress['street_address']);

    });

}

var updateCoordinates = function() {

    // when the user changes the street address
    var address =$('#street').val();

    // quick return if no address
    if (!address)
        return;

    // otherwise geocode and update
    var options = {
        types: 'address',
        limit: 1,
        autocomplete: 'true'
    };
    geocoder.geocode(address, options,
        function (results, status) {

            if (status != "success") {
                alert("Could not geocode:\nError " + status + ", " + results['error']);
                return;
            }

            // quick return if found nothing
            if (results.length == 0) {
                console.log('Got nothing from geocode');
                return;
            }

            // parse features into address
            var address = geocoder.parse_feature(results[0]);

            console.log(
                'Setting currentLocation to:'
                + '\nnumber: ' + address['number']
                + '\nstreet: ' + address['street']
                + '\nunit: ' + address['unit']
                + '\nlocation: ' + address['location']['latitude']
                + ',' + address['location']['longitude']
                + '\nneighborhood: ' + address['neighborhood']
                + '\nzipcode: ' + address['zipcode']
                + '\ncity: ' + address['city']
                + '\nstate: ' + address['state']
                + '\ncountry: ' + address['country']
            );

            // set current location
            updateCurrentLocation({
                lat: address['location']['latitude'],
                lng: address['location']['longitude']
            });

        });
}

// connect actions to inputs

$("#street").change(function () {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-coordinates').change(function() {

    // update coordinates?
    if ($('#update-coordinates').prop('checked'))
        updateCoordinates();

});

$('#update-address').change(function() {

    // update address?
    if ($('#update-address').prop('checked'))
        updateCurrentAddress(currentLocation);

});

$('#dispatch_form_collapse').submit(function (e) {

   // prevent normal form submission
    e.preventDefault();

    // dispatch call
    dispatchCall();

});

/*
 * dispatchCall makes an ajax post request to post dispatched ambulance.
 * @param void.
 * @return void.
 */
function dispatchCall() {

    var form = {};

    // call information
    form['details'] = $('#comment').val();
    form['priority'] = $('input:radio[name=priority]:checked').val();

    // checks
    if (form["priority"] === undefined) {
        alert("Please click one of priorities");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        alert("Please dispatch at least one ambulance");
        return;
    }

    // address information
    form['number'] = currentAddress['number'];
    form['street'] = currentAddress['street'];
    form['unit'] = currentAddress['unit'];
    form['neighborbood'] = currentAddress['neighborhood'];
    form['city'] = currentAddress['city'];
    form['state'] = currentAddress['state'];
    form['country'] = currentAddress['country'];
    form['zipcode'] = currentAddress['zipcode'];
    form['location'] = currentAddress['location'];

    // ambulances
    var ambulances = [];
    for (var id in dispatchingAmbulances)
        if (dispatchingAmbulances.hasOwnProperty(id))
            ambulances.push(id);
    form['ambulances'] = ambulances;

    // TODO: patients

    // make json call
    let postJsonUrl = 'api/call/';
    console.log("Will post '" + JSON.stringify(form) + "'");

    var CSRFToken = getCookie('csrftoken');

    // retrieve csrf token
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!CSRFSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", CSRFToken);
            }
        }
    })

    // make ajax call
    $.ajax({
        url: postJsonUrl,
        type: 'POST',
        dataType: 'json',
        data: form,
        success: function (data) {

            // alert(JSON.stringify(data));
            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

            // Show modal
            $('.modal-title').html('Success');
            $('.modal-body').html(successMsg).addClass('alert-success');
            $("#dispatchModal").modal('show');

            endDispatching();
        },
        error: function (jqXHR, textStatus, errorThrown) {

            // Show modal
            $('.modal-title').html('Failure');
            $('.modal-body').html(textStatus + ": " + errorThrown).addClass('alert-danger');
            $("#dispatchModal").modal('show');

            endDispatching();
        }
    });
}

function CSRFSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

/*
 * getCookie extracts the csrf token for form submit
 */
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = $.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
<|endoftext|>