<commit_before>// Disabling websites messing with pasting passwords:
// https://www.cyberciti.biz/linux-news/google-chrome-extension-to-removes-password-paste-blocking-on-website/

// Pale moon pref list:
// https://forum.palemoon.org/viewtopic.php?f=24&t=3357&p=19126

// Bogus pref detection:
// 1. Change a pref in about:config.
// 2. Quit browser.
// 3. Look for Invalidprefs.js file in profile directory.
// Or, run jslint on this file before using it.

// Uncomment for jslint:
// var user_pref = function () { 1; };

user_pref('devtools.selfxss.count', 10000);

// backspace goes back in history
user_pref('browser.backspace_action', 0);
// hide tab bar when only one tab is open
user_pref('browser.tabs.autoHide', true);
// fit more tabs on screen simultaneously
user_pref('browser.tabs.tabMinWidth', 30);
// updates are not handled by brower
user_pref('app.update.auto', false);
user_pref('app.update.enabled', false);
user_pref('browser.search.update', false);
user_pref('extensions.update.enabled', false);
user_pref('lightweightThemes.update.enabled', false);
// don't want even more google phoning
user_pref('browser.safebrowsing.enabled', false);
user_pref('browser.safebrowsing.malware.enabled', false);
user_pref('browser.safebrowsing.remoteLookups', false);
// start with blank page?
user_pref('browser.startup.page', 0);
// how many autocompletion results to show
user_pref('browser.urlbar.maxRichResults', 100);
// search history only?
user_pref('browser.urlbar.default.behavior', 1);
// match only at word boundaries
user_pref('browser.urlbar.matchBehavior', 2);
// javascript cannot move/resize windows
user_pref('dom.disable_window_move_resize', true);
// javascsript cannot disable context menus
// this affects google maps
user_pref('dom.event.contextmenu.enabled', false);
// pre-set exclude urls in livehttpheaders
user_pref('extensions.livehttpheaders.excludeRegexp', '.gif$|.jpg$|.ico$|.css$|.js$|.png$|google');
// disable about:config scare warning
user_pref('general.warnOnAboutConfig', false);
// use more memory for caching pages in memory
// http://blog.pluron.com/2008/07/why-you-should.html
// http://kb.mozillazine.org/Browser.cache.memory.capacity
user_pref('browser.cache.memory.enable', true);
user_pref('browser.cache.memory.capacity', 10000);
// cache ssl pages to disk
// http://blog.pluron.com/2008/07/why-you-should.html
user_pref('browser.cache.disk_cache_ssl', true);
// kill animation in gifs
// http://www.glump.net/howto/disable_animation_in_your_web_browser#disable_animation_in_firefox_and_other_mozilla-based_browsers
user_pref('image.animation_mode', 'once');
// Disable blinking text
// http://www.mozilla.org/unix/customizing.html
user_pref("browser.blink_allowed", false);
// ship less data to google when searching,
// specifically entering stuff in url bar that is a word, not a url
user_pref('keyword.URL', 'http://www.google.com/search?ie=UTF-8&oe=UTF-8&q=');
// disable geo location reporting
user_pref('geo.enabled', false);
// http://kb.mozillazine.org/Disabling_yellow_plugin_bar_-_Firefox
user_pref('plugins.hide_infobar_for_missing_plugin', true);
user_pref('plugins.hide_infobar_for_blocked_plugin', true);
user_pref('plugins.hide_infobar_for_outdated_plugin', true);
// not documented, and still does not do it
user_pref('plugin.default_plugin_disabled', false);
// stop stupid dns dumbness
user_pref('network.dnsCacheExpiration', 0);
// disable smooth sliding (chrome?)
user_pref('alerts.disableSlidingEffect', true);
// disable smooth scrolling
user_pref('general.smoothScroll', false);
// disable smooth scrolling of tabs
user_pref('toolkit.scrollbox.smoothScroll', false);
user_pref('layout.css.scroll-behavior.enabled', false);
user_pref('layout.css.scroll-behavior.property-enabled', false);
// for good measure
user_pref('social.active', false);
user_pref('social.enabled', false);
// Blank page be blank
// https://support.mozilla.org/en-US/questions/926778
user_pref('browser.newtab.url', 'about:blank');
// Disable status bar delay - this is completely retarded
// a delay of 0 is not working?
// also: https://bugzilla.mozilla.org/show_bug.cgi?id=632365
user_pref('browser.overlink-delay', 1);
user_pref('status4evar.status.linkOver.delay.show', 0);
user_pref('status4evar.status.linkOver.delay.hide', 0);
user_pref('toolkit.cosmeticAnimations.enabled', false);
user_pref('browser.stopReloadAnimation.enabled', false);
user_pref('browser.suppress_first_window_animation', true);
// don't know what this does but probably don't want it
user_pref('status4evar.download.notify.animate', false);
// and these too
user_pref('layout.css.prefixes.animations', false);
user_pref('dom.animations-api.element-animate.enabled', false);
user_pref('browser.fullscreen.animateUp', 0);
user_pref('browser.fullscreen.animate', false);
user_pref('browser.panorama.animate_zoom', false);
user_pref('browser.preferences.animateFadeIn', false);
// what does this do that is useful
user_pref('browser.download.manager.scanWhenDone', false);
// is this the obnoxious download button explosion?
user_pref('browser.download.manager.showAlertOnComplete', false);
// do not track
user_pref('privacy.donottrackheader.enabled', true);
// reject third-party cookies
user_pref('network.cookie.cookieBehavior', 1);
// load all tabs when restoring session
// https://bugzilla.mozilla.org/show_bug.cgi?id=648683
user_pref('browser.sessionstore.restore_on_demand', false);

// experimental
user_pref('browser.download.manager.showWhenStarting', false);
user_pref('browser.tabs.animate', false);
user_pref('browser.download.animateNotifications', false);
user_pref('browser.zoom.updateBackgroundTabs', false);
user_pref('browser.fullscreen.autohide', false);
user_pref('browser.preferences.animateFadeIn', false);
// https://bugzilla.mozilla.org/show_bug.cgi?id=649671
user_pref('toolkit.scrollbox.smoothScroll', false);

user_pref('browser.xul.error_pages.enabled', false);
user_pref('browser.xul.error_pages.expert_bad_cert', true);

// totally cretinous behavior
// firefox 17 doorhanger idiocy is enough to never remember passwords
user_pref('signon.rememberSignons', false);

// firefox health report bs
user_pref('datareporting.healthreport.about.reportUrl', 'http://localhost');
user_pref('datareporting.healthreport.documentServerURI', 'http://localhost');
user_pref('datareporting.healthreport.uploadEnabled', false);
user_pref('datareporting.healthreport.service.enabled', false);
user_pref('datareporting.healthreport.logging.dumpEnabled', false);

user_pref('datareporting.policy.dataSubmissionPolicyAccepted', false);
user_pref('datareporting.policy.dataSubmissionEnabled', false);

// https://www.agwa.name/blog/post/verisigns_broken_name_servers_slow_down_https_for_google_and_others
user_pref('security.OCSP.enabled', 0);

// stop html5 videos from automatically playing
// https://support.mozilla.org/en-US/questions/961940
user_pref('plugins.click_to_play', true);

// Disable: On GTK, we now default to showing the menubar only when alt is pressed:
user_pref("ui.key.menuAccessKeyFocuses", false);

// useless
user_pref("browser.uitour.enabled", false);

// disable reader popup
// https://support.mozilla.org/en-US/questions/1065151
user_pref('reader.parse-on-load.enabled', false);

// disable url bar search suggestions prompt
user_pref('browser.urlbar.userMadeSearchSuggestionsChoice', true);
user_pref('browser.search.suggest.enabled', false);
user_pref('browser.urlbar.timesBeforeHidingSuggestionsHint', 0);

// do not fill top search result into url bar
// https://support.mozilla.org/en-US/questions/976885
//user_pref('browser.urlbar.autoFill', false);

// http://www.palemoon.org/faq.shtml#Preference:_I_prefer_the_old_Ctrl-Tab
user_pref('browser.ctrlTab.previews', false)

user_pref('extensions.pocket.enabled', false)

// disable switch to tab in pale moon
// https://forum.palemoon.org/viewtopic.php?t=10186
// all values:
// https://forum.palemoon.org/viewtopic.php?f=3&t=8757&p=58089&hilit=Browser.urlbar.default.behavior#p58089
user_pref('browser.urlbar.default.behavior', 128)

// https://superuser.com/questions/1539855/how-can-i-disable-address-bar-animation-in-mozilla-firefox-75

// https://support.mozilla.org/en-US/questions/1157121
user_pref("network.captive-portal-service.enabled", false);

// https://support.mozilla.org/en-US/questions/1285537
user_pref("media.videocontrols.picture-in-picture.video-toggle.enabled", false);

// Do not check whether browser is the default one because I have many browsers.
user_pref('browser.shell.checkDefaultBrowser', false);

user_pref('browser.urlbar.delay', 0)
<commit_msg>disable update<commit_after>// Disabling websites messing with pasting passwords:
// https://www.cyberciti.biz/linux-news/google-chrome-extension-to-removes-password-paste-blocking-on-website/

// Pale moon pref list:
// https://forum.palemoon.org/viewtopic.php?f=24&t=3357&p=19126

// Bogus pref detection:
// 1. Change a pref in about:config.
// 2. Quit browser.
// 3. Look for Invalidprefs.js file in profile directory.
// Or, run jslint on this file before using it.

// Uncomment for jslint:
// var user_pref = function () { 1; };

user_pref('devtools.selfxss.count', 10000);

// backspace goes back in history
user_pref('browser.backspace_action', 0);
// hide tab bar when only one tab is open
user_pref('browser.tabs.autoHide', true);
// fit more tabs on screen simultaneously
user_pref('browser.tabs.tabMinWidth', 30);
// updates are not handled by brower
user_pref('app.update.auto', false);
user_pref('app.update.enabled', false);
user_pref('app.update.doorhanger', false);
user_pref('browser.search.update', false);
user_pref('extensions.update.enabled', false);
user_pref('lightweightThemes.update.enabled', false);
// don't want even more google phoning
user_pref('browser.safebrowsing.enabled', false);
user_pref('browser.safebrowsing.malware.enabled', false);
user_pref('browser.safebrowsing.remoteLookups', false);
// start with blank page?
user_pref('browser.startup.page', 0);
// how many autocompletion results to show
user_pref('browser.urlbar.maxRichResults', 100);
// search history only?
user_pref('browser.urlbar.default.behavior', 1);
// match only at word boundaries
user_pref('browser.urlbar.matchBehavior', 2);
// javascript cannot move/resize windows
user_pref('dom.disable_window_move_resize', true);
// javascsript cannot disable context menus
// this affects google maps
user_pref('dom.event.contextmenu.enabled', false);
// pre-set exclude urls in livehttpheaders
user_pref('extensions.livehttpheaders.excludeRegexp', '.gif$|.jpg$|.ico$|.css$|.js$|.png$|google');
// disable about:config scare warning
user_pref('general.warnOnAboutConfig', false);
// use more memory for caching pages in memory
// http://blog.pluron.com/2008/07/why-you-should.html
// http://kb.mozillazine.org/Browser.cache.memory.capacity
user_pref('browser.cache.memory.enable', true);
user_pref('browser.cache.memory.capacity', 10000);
// cache ssl pages to disk
// http://blog.pluron.com/2008/07/why-you-should.html
user_pref('browser.cache.disk_cache_ssl', true);
// kill animation in gifs
// http://www.glump.net/howto/disable_animation_in_your_web_browser#disable_animation_in_firefox_and_other_mozilla-based_browsers
user_pref('image.animation_mode', 'once');
// Disable blinking text
// http://www.mozilla.org/unix/customizing.html
user_pref("browser.blink_allowed", false);
// ship less data to google when searching,
// specifically entering stuff in url bar that is a word, not a url
user_pref('keyword.URL', 'http://www.google.com/search?ie=UTF-8&oe=UTF-8&q=');
// disable geo location reporting
user_pref('geo.enabled', false);
// http://kb.mozillazine.org/Disabling_yellow_plugin_bar_-_Firefox
user_pref('plugins.hide_infobar_for_missing_plugin', true);
user_pref('plugins.hide_infobar_for_blocked_plugin', true);
user_pref('plugins.hide_infobar_for_outdated_plugin', true);
// not documented, and still does not do it
user_pref('plugin.default_plugin_disabled', false);
// stop stupid dns dumbness
user_pref('network.dnsCacheExpiration', 0);
// disable smooth sliding (chrome?)
user_pref('alerts.disableSlidingEffect', true);
// disable smooth scrolling
user_pref('general.smoothScroll', false);
// disable smooth scrolling of tabs
user_pref('toolkit.scrollbox.smoothScroll', false);
user_pref('layout.css.scroll-behavior.enabled', false);
user_pref('layout.css.scroll-behavior.property-enabled', false);
// for good measure
user_pref('social.active', false);
user_pref('social.enabled', false);
// Blank page be blank
// https://support.mozilla.org/en-US/questions/926778
user_pref('browser.newtab.url', 'about:blank');
// Disable status bar delay - this is completely retarded
// a delay of 0 is not working?
// also: https://bugzilla.mozilla.org/show_bug.cgi?id=632365
user_pref('browser.overlink-delay', 1);
user_pref('status4evar.status.linkOver.delay.show', 0);
user_pref('status4evar.status.linkOver.delay.hide', 0);
user_pref('toolkit.cosmeticAnimations.enabled', false);
user_pref('browser.stopReloadAnimation.enabled', false);
user_pref('browser.suppress_first_window_animation', true);
// don't know what this does but probably don't want it
user_pref('status4evar.download.notify.animate', false);
// and these too
user_pref('layout.css.prefixes.animations', false);
user_pref('dom.animations-api.element-animate.enabled', false);
user_pref('browser.fullscreen.animateUp', 0);
user_pref('browser.fullscreen.animate', false);
user_pref('browser.panorama.animate_zoom', false);
user_pref('browser.preferences.animateFadeIn', false);
// what does this do that is useful
user_pref('browser.download.manager.scanWhenDone', false);
// is this the obnoxious download button explosion?
user_pref('browser.download.manager.showAlertOnComplete', false);
// do not track
user_pref('privacy.donottrackheader.enabled', true);
// reject third-party cookies
user_pref('network.cookie.cookieBehavior', 1);
// load all tabs when restoring session
// https://bugzilla.mozilla.org/show_bug.cgi?id=648683
user_pref('browser.sessionstore.restore_on_demand', false);

// experimental
user_pref('browser.download.manager.showWhenStarting', false);
user_pref('browser.tabs.animate', false);
user_pref('browser.download.animateNotifications', false);
user_pref('browser.zoom.updateBackgroundTabs', false);
user_pref('browser.fullscreen.autohide', false);
user_pref('browser.preferences.animateFadeIn', false);
// https://bugzilla.mozilla.org/show_bug.cgi?id=649671
user_pref('toolkit.scrollbox.smoothScroll', false);

user_pref('browser.xul.error_pages.enabled', false);
user_pref('browser.xul.error_pages.expert_bad_cert', true);

// totally cretinous behavior
// firefox 17 doorhanger idiocy is enough to never remember passwords
user_pref('signon.rememberSignons', false);

// firefox health report bs
user_pref('datareporting.healthreport.about.reportUrl', 'http://localhost');
user_pref('datareporting.healthreport.documentServerURI', 'http://localhost');
user_pref('datareporting.healthreport.uploadEnabled', false);
user_pref('datareporting.healthreport.service.enabled', false);
user_pref('datareporting.healthreport.logging.dumpEnabled', false);

user_pref('datareporting.policy.dataSubmissionPolicyAccepted', false);
user_pref('datareporting.policy.dataSubmissionEnabled', false);

// https://www.agwa.name/blog/post/verisigns_broken_name_servers_slow_down_https_for_google_and_others
user_pref('security.OCSP.enabled', 0);

// stop html5 videos from automatically playing
// https://support.mozilla.org/en-US/questions/961940
user_pref('plugins.click_to_play', true);

// Disable: On GTK, we now default to showing the menubar only when alt is pressed:
user_pref("ui.key.menuAccessKeyFocuses", false);

// useless
user_pref("browser.uitour.enabled", false);

// disable reader popup
// https://support.mozilla.org/en-US/questions/1065151
user_pref('reader.parse-on-load.enabled', false);

// disable url bar search suggestions prompt
user_pref('browser.urlbar.userMadeSearchSuggestionsChoice', true);
user_pref('browser.search.suggest.enabled', false);
user_pref('browser.urlbar.timesBeforeHidingSuggestionsHint', 0);

// do not fill top search result into url bar
// https://support.mozilla.org/en-US/questions/976885
//user_pref('browser.urlbar.autoFill', false);

// http://www.palemoon.org/faq.shtml#Preference:_I_prefer_the_old_Ctrl-Tab
user_pref('browser.ctrlTab.previews', false)

user_pref('extensions.pocket.enabled', false)

// disable switch to tab in pale moon
// https://forum.palemoon.org/viewtopic.php?t=10186
// all values:
// https://forum.palemoon.org/viewtopic.php?f=3&t=8757&p=58089&hilit=Browser.urlbar.default.behavior#p58089
user_pref('browser.urlbar.default.behavior', 128)

// https://superuser.com/questions/1539855/how-can-i-disable-address-bar-animation-in-mozilla-firefox-75

// https://support.mozilla.org/en-US/questions/1157121
user_pref("network.captive-portal-service.enabled", false);

// https://support.mozilla.org/en-US/questions/1285537
user_pref("media.videocontrols.picture-in-picture.video-toggle.enabled", false);

// Do not check whether browser is the default one because I have many browsers.
user_pref('browser.shell.checkDefaultBrowser', false);

user_pref('browser.urlbar.delay', 0)
<|endoftext|>


<commit_before>/*
 * Copyright 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.api.rest.views',
    dependencies: ['og.api.common', 'og.api.rest'],
    obj: function () {
        var common = og.api.common, api = og.api.rest, str = common.str, check = common.check, STALL = common.STALL;
        return { // all requests that begin with /views
            root: 'views',
            get: common.not_available_get,
            put: function (config, promise) {
                config = config || {};
                var promise = promise || new common.Promise,
                    root = this.root, method = [root], data = {}, meta,
                    fields = [
                        'viewdefinition', 'aggregators', 'providers', 'valuation', 'version', 'correction', 'blotter'
                    ],
                    api_fields = [
                        'viewDefinitionId', 'aggregators', 'marketDataProviders', 'valuationTime',
                        'portfolioVersionTime', 'portfolioCorrectionTime', 'blotter'
                    ];
                if (!api.id) return setTimeout((function (context) {                    // if handshake isn't
                    return function () {api.views.put.call(context, config, promise);}; // complete, return a
                })(this), STALL), promise;                                              // promise and try again
                meta = check({
                    bundle: {method: root + '#put', config: config},
                    required: [{all_of: ['viewdefinition', 'providers']}]
                });
                meta.type = 'POST';
                promise.ignore = true; // this request will be answered in fire_updates NOT in ajax handler
                fields.forEach(function (val, idx) {
                    var is_object = typeof config[val] === 'object';
                    if (is_object ? val = JSON.stringify(config[val]) : val = str(config[val])) // is truthy
                        data[api_fields[idx]] = val;
                });
                data['requestId'] = promise.id;
                data['aggregators'] = config.aggregators; // send traditional form array and not JSON
                data['clientId'] = api.id;
                return api.request(method, {data: data, meta: meta}, promise);
            },
            del: function (config) {
                config = config || {};
                var root = this.root, method = [root], meta, view_id = config.view_id;
                meta = check({
                    bundle: {method: root + '#del', config: config},
                    required: [{all_of: ['view_id']}]
                });
                meta.type = 'DELETE';
                method = method.concat(view_id);
                return api.request(method, {data: {}, meta: meta});
            },
            status: {
                root: 'views/{{view_id}}/pauseOrResume',
                pause_or_resume: function (config) {
                    config = config || {};
                    var root = this.root, method = root.split('/'), data = {state: config.state}, meta;
                    meta = check({
                        bundle: {method: root + '#put', config: config},
                        required: [{all_of: ['state']}]
                    });
                    method[1] = config.view_id;
                    meta.type = 'PUT';
                    return api.request(method, {data: data, meta: meta});
                }
            },
            csv: function (config) {
                    window.open('/jax/views/' + config.view_id + '/' + config.grid_type + '/data', '_blank');
            },
            grid: {
                depgraphs: {
                    root: 'views/{{view_id}}/{{grid_type}}/depgraphs',
                    del: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#del', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'graph_id']}]
                        });
                        meta.type = 'DELETE';
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.graph_id);
                        return api.request(method, {data: {}, meta: meta});
                    },
                    get: common.not_available_get,
                    structure: {
                        root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#get', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id']}]
                            });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: common.not_available_put,
                        del: common.not_available_del
                    },
                    put: function (config) {
                        config = config || {};
                        var promise = new common.Promise, root = this.root, method = root.split('/'),
                            data = {}, meta, fields = ['view_id', 'grid_type', 'row', 'col'],
                        meta = check({
                            bundle: {method: root + '#put', config: config}, required: [{all_of: fields}]
                        });
                        meta.type = 'POST';
                        promise.ignore = true; // this request will be answered in fire_updates NOT in ajax handler
                        data['requestId'] = promise.id;
                        data['clientId'] = api.id;
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        fields.forEach(function (val, idx) {
                            if (val = str(config[val])) {
                                data[fields[idx]] = val;
                            }
                        });
                        return api.request(method, {data: data, meta: meta}, promise);
                    },
                    viewports: {
                        structure: {
                            root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}/viewports/{{viewport_id}}/structure',
                            get: function (config) {
                                config = config || {};
                                var root = this.root, method = root.split('/'), data = {}, meta;
                                meta = check({
                                    bundle: {method: root + '#get', config: config},
                                    required: [{all_of: ['view_id', 'grid_type', 'viewport_id', 'graph_id']}]
                                });
                                method[1] = config.view_id;
                                method[2] = config.grid_type;
                                method[4] = config.graph_id;
                                method[6] = config.viewport_id;
                                return api.request(method, {data: data, meta: meta});
                            },
                            put: common.not_available_put,
                            del: common.not_available_del
                        },
                        root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}/viewports',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#get', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id', 'viewport_id']}]
                            });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            method.push(config.viewport_id);
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: function (config) {
                            config = config || {};
                            var promise = new common.Promise, root = this.root, method = root.split('/'),
                                data = {}, meta, fields = ['cells', 'rows', 'cols', 'format', 'log'],
                                api_fields = ['cells', 'rows', 'columns', 'format', 'enableLogging'];
                            meta = check({
                                bundle: {method: root + '#put', config: config},
                                required: [
                                    {all_of: ['view_id', 'graph_id']},
                                    {either: ['rows', 'cols'], or: ['cells']}
                                ]
                            });
                            meta.type = 'POST';
                            fields.forEach(function (key, idx) {data[api_fields[idx]] = config[key];});
                            data['clientId'] = api.id;
                            data['enableLogging'] = !!data['enableLogging'];
                            data.version = promise.id;
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            if (config.viewport_id) // use the promise id as viewport_version
                                (meta.type = 'PUT'), method.push(config.viewport_id);
                            else // the response will come back in fire_updates
                                (promise.ignore = true), (data['requestId'] = promise.id);
                            return api.request(method, {data: data, meta: meta}, promise);
                        },
                        del: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#del', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id', 'viewport_id']}]
                            });
                            meta.type = 'DELETE';
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            method.push(config.viewport_id);
                            return api.request(method, {data: {}, meta: meta});
                        }
                    }
                },
                structure: {
                    root: 'views/{{view_id}}/{{grid_type}}',
                    get: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#get', config: config},
                            required: [{all_of: ['view_id', 'grid_type']}]
                        });
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        return api.request(method, {data: data, meta: meta});
                    },
                    put: common.not_available_put,
                    del: common.not_available_del
                },
                viewports: {
                    structure: {
                        root: 'views/{{view_id}}/{{grid_type}}/viewports/{{viewport_id}}/structure',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                 bundle: {method: root + '#get', config: config},
                                 required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                             });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.viewport_id;
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: common.not_available_put,
                        del: common.not_available_del
                    },
                    root: 'views/{{view_id}}/{{grid_type}}/viewports',
                    get: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#get', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                        });
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.viewport_id);
                        return api.request(method, {data: data, meta: meta});
                    },
                    put: function (config) {
                        config = config || {};
                        var promise = new common.Promise, root = this.root, method = root.split('/'),
                            data = {}, meta, fields = ['cells', 'rows', 'cols', 'format', 'log'],
                            api_fields = ['cells', 'rows', 'columns', 'format', 'enableLogging'];
                        meta = check({
                            bundle: {method: root + '#put', config: config},
                            required: [
                                {all_of: ['view_id']},
                                {either: ['rows', 'cols'], or: ['cells']}
                            ]
                        });
                        meta.type = 'POST';
                        fields.forEach(function (key, idx) {data[api_fields[idx]] = config[key];});
                        data['clientId'] = api.id;
                        data['enableLogging'] = !!data['enableLogging'];
                        data.version = promise.id;
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        if (config.viewport_id) {// use the promise id as viewport_version
                            meta.type = 'PUT';
                            method.push(config.viewport_id);
                        }
                        else {// the response will come back in fire_updates
                            promise.ignore = true;
                            data['requestId'] = promise.id;
                        }
                        return api.request(method, {data: data, meta: meta}, promise);
                    },
                    del: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#del', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                        });
                        meta.type = 'DELETE';
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.viewport_id);
                        return api.request(method, {data: {}, meta: meta});
                    }
                }
            }
        };
    }
});
<commit_msg>[PLAT-4507] new views errors path for rest api<commit_after>/*
 * Copyright 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 * Please see distribution for license.
 */
$.register_module({
    name: 'og.api.rest.views',
    dependencies: ['og.api.common', 'og.api.rest'],
    obj: function () {
        var common = og.api.common, api = og.api.rest, str = common.str, check = common.check, STALL = common.STALL;
        return { // all requests that begin with /views
            root: 'views',
            get: common.not_available_get,
            put: function (config, promise) {
                config = config || {};
                var promise = promise || new common.Promise,
                    root = this.root, method = [root], data = {}, meta,
                    fields = [
                        'viewdefinition', 'aggregators', 'providers', 'valuation', 'version', 'correction', 'blotter'
                    ],
                    api_fields = [
                        'viewDefinitionId', 'aggregators', 'marketDataProviders', 'valuationTime',
                        'portfolioVersionTime', 'portfolioCorrectionTime', 'blotter'
                    ];
                if (!api.id) return setTimeout((function (context) {                    // if handshake isn't
                    return function () {api.views.put.call(context, config, promise);}; // complete, return a
                })(this), STALL), promise;                                              // promise and try again
                meta = check({
                    bundle: {method: root + '#put', config: config},
                    required: [{all_of: ['viewdefinition', 'providers']}]
                });
                meta.type = 'POST';
                promise.ignore = true; // this request will be answered in fire_updates NOT in ajax handler
                fields.forEach(function (val, idx) {
                    var is_object = typeof config[val] === 'object';
                    if (is_object ? val = JSON.stringify(config[val]) : val = str(config[val])) // is truthy
                        data[api_fields[idx]] = val;
                });
                data['requestId'] = promise.id;
                data['aggregators'] = config.aggregators; // send traditional form array and not JSON
                data['clientId'] = api.id;
                return api.request(method, {data: data, meta: meta}, promise);
            },
            del: function (config) {
                config = config || {};
                var root = this.root, method = [root], meta, view_id = config.view_id;
                meta = check({
                    bundle: {method: root + '#del', config: config},
                    required: [{all_of: ['view_id']}]
                });
                meta.type = 'DELETE';
                method = method.concat(view_id);
                return api.request(method, {data: {}, meta: meta});
            },
            error : {
                root: 'views/{{view_id}}/errors',
                get: function (config) {
                    config = config || {};
                    var root = this.root, method = root.split('/'), data = {}, meta;
                    meta = check({
                    bundle: {method: root + '#get', config: config},
                    required: [{all_of: ['view_id']}]
                    });
                    method[1] = config.view_id;
                    return api.request(method, {data: data, meta: meta});
                },
                put: common.not_available_put,
                del: common.not_available_del
            },
            status: {
                root: 'views/{{view_id}}/pauseOrResume',
                pause_or_resume: function (config) {
                    config = config || {};
                    var root = this.root, method = root.split('/'), data = {state: config.state}, meta;
                    meta = check({
                        bundle: {method: root + '#put', config: config},
                        required: [{all_of: ['state']}]
                    });
                    method[1] = config.view_id;
                    meta.type = 'PUT';
                    return api.request(method, {data: data, meta: meta});
                }
            },
            csv: function (config) {
                    window.open('/jax/views/' + config.view_id + '/' + config.grid_type + '/data', '_blank');
            },
            grid: {
                depgraphs: {
                    root: 'views/{{view_id}}/{{grid_type}}/depgraphs',
                    del: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#del', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'graph_id']}]
                        });
                        meta.type = 'DELETE';
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.graph_id);
                        return api.request(method, {data: {}, meta: meta});
                    },
                    get: common.not_available_get,
                    structure: {
                        root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#get', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id']}]
                            });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: common.not_available_put,
                        del: common.not_available_del
                    },
                    put: function (config) {
                        config = config || {};
                        var promise = new common.Promise, root = this.root, method = root.split('/'),
                            data = {}, meta, fields = ['view_id', 'grid_type', 'row', 'col'],
                        meta = check({
                            bundle: {method: root + '#put', config: config}, required: [{all_of: fields}]
                        });
                        meta.type = 'POST';
                        promise.ignore = true; // this request will be answered in fire_updates NOT in ajax handler
                        data['requestId'] = promise.id;
                        data['clientId'] = api.id;
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        fields.forEach(function (val, idx) {
                            if (val = str(config[val])) {
                                data[fields[idx]] = val;
                            }
                        });
                        return api.request(method, {data: data, meta: meta}, promise);
                    },
                    viewports: {
                        structure: {
                            root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}/viewports/{{viewport_id}}/structure',
                            get: function (config) {
                                config = config || {};
                                var root = this.root, method = root.split('/'), data = {}, meta;
                                meta = check({
                                    bundle: {method: root + '#get', config: config},
                                    required: [{all_of: ['view_id', 'grid_type', 'viewport_id', 'graph_id']}]
                                });
                                method[1] = config.view_id;
                                method[2] = config.grid_type;
                                method[4] = config.graph_id;
                                method[6] = config.viewport_id;
                                return api.request(method, {data: data, meta: meta});
                            },
                            put: common.not_available_put,
                            del: common.not_available_del
                        },
                        root: 'views/{{view_id}}/{{grid_type}}/depgraphs/{{graph_id}}/viewports',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#get', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id', 'viewport_id']}]
                            });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            method.push(config.viewport_id);
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: function (config) {
                            config = config || {};
                            var promise = new common.Promise, root = this.root, method = root.split('/'),
                                data = {}, meta, fields = ['cells', 'rows', 'cols', 'format', 'log'],
                                api_fields = ['cells', 'rows', 'columns', 'format', 'enableLogging'];
                            meta = check({
                                bundle: {method: root + '#put', config: config},
                                required: [
                                    {all_of: ['view_id', 'graph_id']},
                                    {either: ['rows', 'cols'], or: ['cells']}
                                ]
                            });
                            meta.type = 'POST';
                            fields.forEach(function (key, idx) {data[api_fields[idx]] = config[key];});
                            data['clientId'] = api.id;
                            data['enableLogging'] = !!data['enableLogging'];
                            data.version = promise.id;
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            if (config.viewport_id) // use the promise id as viewport_version
                                (meta.type = 'PUT'), method.push(config.viewport_id);
                            else // the response will come back in fire_updates
                                (promise.ignore = true), (data['requestId'] = promise.id);
                            return api.request(method, {data: data, meta: meta}, promise);
                        },
                        del: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                bundle: {method: root + '#del', config: config},
                                required: [{all_of: ['view_id', 'grid_type', 'graph_id', 'viewport_id']}]
                            });
                            meta.type = 'DELETE';
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.graph_id;
                            method.push(config.viewport_id);
                            return api.request(method, {data: {}, meta: meta});
                        }
                    }
                },
                structure: {
                    root: 'views/{{view_id}}/{{grid_type}}',
                    get: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#get', config: config},
                            required: [{all_of: ['view_id', 'grid_type']}]
                        });
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        return api.request(method, {data: data, meta: meta});
                    },
                    put: common.not_available_put,
                    del: common.not_available_del
                },
                viewports: {
                    structure: {
                        root: 'views/{{view_id}}/{{grid_type}}/viewports/{{viewport_id}}/structure',
                        get: function (config) {
                            config = config || {};
                            var root = this.root, method = root.split('/'), data = {}, meta;
                            meta = check({
                                 bundle: {method: root + '#get', config: config},
                                 required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                             });
                            method[1] = config.view_id;
                            method[2] = config.grid_type;
                            method[4] = config.viewport_id;
                            return api.request(method, {data: data, meta: meta});
                        },
                        put: common.not_available_put,
                        del: common.not_available_del
                    },
                    root: 'views/{{view_id}}/{{grid_type}}/viewports',
                    get: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#get', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                        });
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.viewport_id);
                        return api.request(method, {data: data, meta: meta});
                    },
                    put: function (config) {
                        config = config || {};
                        var promise = new common.Promise, root = this.root, method = root.split('/'),
                            data = {}, meta, fields = ['cells', 'rows', 'cols', 'format', 'log'],
                            api_fields = ['cells', 'rows', 'columns', 'format', 'enableLogging'];
                        meta = check({
                            bundle: {method: root + '#put', config: config},
                            required: [
                                {all_of: ['view_id']},
                                {either: ['rows', 'cols'], or: ['cells']}
                            ]
                        });
                        meta.type = 'POST';
                        fields.forEach(function (key, idx) {data[api_fields[idx]] = config[key];});
                        data['clientId'] = api.id;
                        data['enableLogging'] = !!data['enableLogging'];
                        data.version = promise.id;
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        if (config.viewport_id) {// use the promise id as viewport_version
                            meta.type = 'PUT';
                            method.push(config.viewport_id);
                        }
                        else {// the response will come back in fire_updates
                            promise.ignore = true;
                            data['requestId'] = promise.id;
                        }
                        return api.request(method, {data: data, meta: meta}, promise);
                    },
                    del: function (config) {
                        config = config || {};
                        var root = this.root, method = root.split('/'), data = {}, meta;
                        meta = check({
                            bundle: {method: root + '#del', config: config},
                            required: [{all_of: ['view_id', 'grid_type', 'viewport_id']}]
                        });
                        meta.type = 'DELETE';
                        method[1] = config.view_id;
                        method[2] = config.grid_type;
                        method.push(config.viewport_id);
                        return api.request(method, {data: {}, meta: meta});
                    }
                }
            }
        };
    }
});
<|endoftext|>


<commit_before>ace.define("ace/snippets/razor",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText = "snippet if\n\
(${1} == ${2}) {\n\
	${3}\n\
}";
exports.scope = "razor";

});
<commit_msg>Update public/libs/bower_components/ace-builds/src-noconflict/snippets/razor.js<commit_after><|endoftext|>


<commit_before>var renderer = new marked.Renderer();
var toc = []; // Table of contents as a list
var nameCounter = 0;

renderer.heading = function(text, level) {
    // Use number to avoid issues with Chinese
    var escapedText = 'toc_' + nameCounter++;
    var textHtml = escapeHtml(text);
    toc.push({
        level: level,
        anchor: escapedText,
        title: textHtml
    });
    return '<h' + level + ' id="' + escapedText + '">' + textHtml + '</h' + level + '>';
};

// Highlight.js to highlight code block
marked.setOptions({
    highlight: function(code, lang) {
        if (lang && (!specialCodeBlock(lang) || highlightSpecialBlocks)) {
            if (hljs.getLanguage(lang)) {
                return hljs.highlight(lang, code, true).value;
            } else {
                return hljs.highlightAuto(code).value;
            }
        } else {
            return code;
        }
    }
});

var markdownToHtml = function(markdown, needToc) {
    toc = [];
    nameCounter = 0;
    var html = marked(markdown, { renderer: renderer });
    if (needToc) {
        return html.replace(/
\[TOC\]<\/p>/ig, '

');
    } else {
        return html;
    }
};

var mdHasTocSection = function(markdown) {
    var n = markdown.search(/(\n|^)\[toc\]/i);
    return n != -1;
};

var updateText = function(text) {
    if (VAddTOC) {
        text = "[TOC]\n\n" + text;
    }

    startFreshRender();

    // There is at least one async job for MathJax.
    asyncJobsCount = 1;

    var needToc = mdHasTocSection(text);
    var html = markdownToHtml(text, needToc);
    contentDiv.innerHTML = html;
    handleToc(needToc);
    insertImageCaption();
    setupImageView();
    renderMermaid('lang-mermaid');
    renderFlowchart(['lang-flowchart', 'lang-flow']);
    renderPlantUML('lang-puml');
    renderGraphviz('lang-dot');
    addClassToCodeBlock();
    renderCodeBlockLineNumber();

    // If you add new logics after handling MathJax, please pay attention to
    // finishLoading logic.
    if (VEnableMathjax) {
        try {
            MathJax.Hub.Queue(["Typeset", MathJax.Hub, contentDiv, postProcessMathJax]);
        } catch (err) {
            content.setLog("err: " + err);
            finishOneAsyncJob();
        }
    } else {
        finishOneAsyncJob();
    }
};

var highlightText = function(text, id, timeStamp) {
    highlightSpecialBlocks = true;
    var html = marked(text);
    highlightSpecialBlocks = false;
    content.highlightTextCB(html, id, timeStamp);
}

var textToHtml = function(identifier, id, timeStamp, text, inlineStyle) {
    var html = marked(text);
    if (inlineStyle) {
        var container = textHtmlDiv;
        container.innerHTML = html;
        html = getHtmlWithInlineStyles(container);
        container.innerHTML = "";
    }

    content.textToHtmlCB(identifier, id, timeStamp, html);
}
<commit_msg>marked: upgrade of the Marked break the language keyword of code block<commit_after>var renderer = new marked.Renderer();
var toc = []; // Table of contents as a list
var nameCounter = 0;

renderer.heading = function(text, level) {
    // Use number to avoid issues with Chinese
    var escapedText = 'toc_' + nameCounter++;
    var textHtml = escapeHtml(text);
    toc.push({
        level: level,
        anchor: escapedText,
        title: textHtml
    });
    return '<h' + level + ' id="' + escapedText + '">' + textHtml + '</h' + level + '>';
};

// Highlight.js to highlight code block
marked.setOptions({
    highlight: function(code, lang) {
        if (lang && (!specialCodeBlock(lang) || highlightSpecialBlocks)) {
            if (hljs.getLanguage(lang)) {
                return hljs.highlight(lang, code, true).value;
            } else {
                return hljs.highlightAuto(code).value;
            }
        } else {
            return code;
        }
    }
});

var markdownToHtml = function(markdown, needToc) {
    toc = [];
    nameCounter = 0;
    var html = marked(markdown, { renderer: renderer });
    if (needToc) {
        return html.replace(/
\[TOC\]<\/p>/ig, '

');
    } else {
        return html;
    }
};

var mdHasTocSection = function(markdown) {
    var n = markdown.search(/(\n|^)\[toc\]/i);
    return n != -1;
};

var updateText = function(text) {
    if (VAddTOC) {
        text = "[TOC]\n\n" + text;
    }

    startFreshRender();

    // There is at least one async job for MathJax.
    asyncJobsCount = 1;

    var needToc = mdHasTocSection(text);
    var html = markdownToHtml(text, needToc);
    contentDiv.innerHTML = html;
    handleToc(needToc);
    insertImageCaption();
    setupImageView();
    renderMermaid('language-mermaid');
    renderFlowchart(['language-flowchart', 'language-flow']);
    renderPlantUML('language-puml');
    renderGraphviz('language-dot');
    addClassToCodeBlock();
    renderCodeBlockLineNumber();

    // If you add new logics after handling MathJax, please pay attention to
    // finishLoading logic.
    if (VEnableMathjax) {
        try {
            MathJax.Hub.Queue(["Typeset", MathJax.Hub, contentDiv, postProcessMathJax]);
        } catch (err) {
            content.setLog("err: " + err);
            finishOneAsyncJob();
        }
    } else {
        finishOneAsyncJob();
    }
};

var highlightText = function(text, id, timeStamp) {
    highlightSpecialBlocks = true;
    var html = marked(text);
    highlightSpecialBlocks = false;
    content.highlightTextCB(html, id, timeStamp);
}

var textToHtml = function(identifier, id, timeStamp, text, inlineStyle) {
    var html = marked(text);
    if (inlineStyle) {
        var container = textHtmlDiv;
        container.innerHTML = html;
        html = getHtmlWithInlineStyles(container);
        container.innerHTML = "";
    }

    content.textToHtmlCB(identifier, id, timeStamp, html);
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
});

$('.menu .item').tab();

/*$('.blog-list li').map(function(currentValue, index){
 console.log('ooooo')
 });*/

var DateDiff = {

    inMinutes: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(60*1000))
    },

    inHours: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(3600*1000))
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    },

    getDesc: function(d1, d2) {
        var minutes = this.inMinutes(d1,d2);
        var hours = this.inHours(d1,d2);
        if (minutes < 2) {
            return "刚刚发表"
        } else if (minutes < 60) {
            return  minutes + "分钟之前";
        } else {
            if (hours < 24) {
                return hours + "小时之前";
            } else {
                var days = this.inDays(d1, d2);
                if (days < 30) {
                    return days + "天之前";
                } else {
                    var months = this.inMonths(d1, d2);
                    if (months < 12) {
                        return months + "月之前";
                    } else {
                        var years = this.inYears(d1, d2);
                        return years + "年之前";
                    }
                }
            }
        }
    }
};

function doTimeAction() {
    $('.blog-list li').each(function(){
        var spanPlug = $(this).find('.list-top>span');
        var publishTime = new Date(spanPlug.attr('data-shared-at'));
        var currentTime = new Date();
        spanPlug.html(DateDiff.getDesc(publishTime, currentTime));
    });
}

function timer() {
    doTimeAction()
    setTimeout("timer()",1000);
}

timer();
<commit_msg>update js<commit_after>$(document).ready(function() {
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
});

$('.menu .item').tab();

/*$('.blog-list li').map(function(currentValue, index){
 console.log('ooooo')
 });*/

var DateDiff = {

    inMinutes: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(60*1000))
    },

    inHours: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(3600*1000))
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    },

    getDesc: function(d1, d2) {
        var minutes = this.inMinutes(d1,d2);
        var hours = this.inHours(d1,d2);
        if (minutes < 2) {
            return "刚刚发表"
        } else if (minutes < 60) {
            return  minutes + "分钟之前";
        } else {
            if (hours < 24) {
                return hours + "小时之前";
            } else {
                var days = this.inDays(d1, d2);
                if (days < 30) {
                    return days + "天之前";
                } else {
                    var months = this.inMonths(d1, d2);
                    if (months < 12) {
                        return months + "月之前";
                    } else {
                        var years = this.inYears(d1, d2);
                        return years + "年之前";
                    }
                }
            }
        }
    }
};

function doTimeAction() {
    $('.blog-list li').each(function(){
        var spanPlug = $(this).find('.list-top>span');
        var publishTime = new Date(spanPlug.attr('data-shared-at'));
        var currentTime = new Date();
        spanPlug.html(DateDiff.getDesc(publishTime, currentTime));
    });
}

function timer() {
    doTimeAction()
    setTimeout("timer()",1000);
}

timer();

$('.popup').popup();
<|endoftext|>


<commit_before>/* eslint-env mocha */
import Vue from 'vue-test';
import assert from 'assert';
import progressBar from '../src/views/progress-bar';

const ProgressBarComponent = Vue.extend(progressBar);

describe('progressBar Component', () => {
  describe('`percent` computed property', () => {
    let vm;
    beforeEach(() => {
      vm = new ProgressBarComponent({
        propsData: {
          progress: 0,
        },
      }).$mount();
    });
    it('should give 0 percent for progress of < 0', () => {
      vm.progress = -0.0000000001;
      assert.equal(vm.percent, 0);
    });
    it('should give 10 percent for progress of 0.1', () => {
      vm.progress = 0.1;
      assert.equal(vm.percent, 10);
    });
    it('should give 100 percent for progress of 1.0', () => {
      vm.progress = 1.0;
      assert.equal(vm.percent, 100);
    });
    it('should give 100 percent for progress of > 1.0', () => {
      vm.progress = 1.0000000001;
      assert.equal(vm.percent, 100);
    });
  });
});
<commit_msg>Rewrite progress bar test with avoriaz<commit_after>/* eslint-env mocha */
import assert from 'assert';
import { shallow } from 'avoriaz';
import ProgressBar from '../src/views/progress-bar';

function testProgressBar(wrapper, expected) {
  const { text, width } = expected;
  assert.equal(wrapper.first('.progress-bar-complete').text(), text);
  assert(wrapper.first('.progress-bar-text').hasStyle('width', width));
}

describe('ProgressBar Component', () => {
  it('should give 0 percent for progress of < 0', () => {
    const wrapper = shallow(ProgressBar, {
      propsData: {
        progress: -0.0000001,
      },
    });
    // The negative still shows up...
    testProgressBar(wrapper, { text: '-0%', width: '0%' });
  });

  it('should give 10 percent for progress of 0.1', () => {
    const wrapper = shallow(ProgressBar, {
      propsData: {
        progress: 0.1,
      },
    });
    testProgressBar(wrapper, { text: '10%', width: '10%' });
  });

  it('should give 100 percent for progress of 1.0', () => {
    const wrapper = shallow(ProgressBar, {
      propsData: {
        progress: 1.0,
      },
    });
    testProgressBar(wrapper, { text: '100%', width: '100%' });
  });

  it('should give 100 percent for progress of > 1.0', () => {
    const wrapper = shallow(ProgressBar, {
      propsData: {
        progress: 1.0000001,
      },
    });
    testProgressBar(wrapper, { text: '100%', width: '100%' });
  });
});
<|endoftext|>


<commit_before>// jQuery plugin modalAjaxForm
(function($, jQuery) {
    jQuery.fn.modalAjaxForm = function(options) {
        options = jQuery.extend({}, jQuery.fn.modalAjaxForm.defaults, options);
        return $(this).each(function() {
            $(this).click(function(e) {
                e.preventDefault();

                var url = $(this).attr('href');
                jQuery.fn.modalAjaxForm.showModal(url, {}, options.onComplete, "GET");
            });
        });
    };
    jQuery.fn.modalAjaxForm.defaults = {
        onComplete: function (){}
    };

    jQuery.fn.modalAjaxForm.showModal = function(url, data, complete, method){

        $.ajax(url, {
            dataType: 'html',
            data: data,
            type: method,
            success: function(data, textStatus, jqXHR) {

                if (jqXHR.status == 201) {
                    window.location.reload();
                    return;
                }

                $('#ajax-form-modal').remove();
                var $modal = $('
');

                $modal.appendTo('body');

                $modal.modal();
                $modal.html(data);

                complete($modal);

                $modal.find('form').submit(function(e) {

                    e.preventDefault();

                    jQuery.fn.modalAjaxForm.showModal(
                        $(this).attr('action'),
                        $(this).serialize(),
                        complete,
                        "POST"
                    );
                });
            }
        });
    };
})(jQuery, jQuery);

<commit_msg>prevent caching of add link form<commit_after>// jQuery plugin modalAjaxForm
(function($, jQuery) {
    jQuery.fn.modalAjaxForm = function(options) {
        options = jQuery.extend({}, jQuery.fn.modalAjaxForm.defaults, options);
        return $(this).each(function() {
            $(this).click(function(e) {
                e.preventDefault();

                var d = new Date();
                var seconds = d.getTime() / 1000;

                var url = $(this).attr('href') + '?t=' + seconds;
                jQuery.fn.modalAjaxForm.showModal(url, {}, options.onComplete, "GET");
            });
        });
    };
    jQuery.fn.modalAjaxForm.defaults = {
        onComplete: function (){}
    };

    jQuery.fn.modalAjaxForm.showModal = function(url, data, complete, method){

        $.ajax(url, {
            dataType: 'html',
            data: data,
            type: method,
            success: function(data, textStatus, jqXHR) {

                if (jqXHR.status == 201) {
                    window.location.reload();
                    return;
                }

                $('#ajax-form-modal').remove();
                var $modal = $('
');

                $modal.appendTo('body');

                $modal.modal();
                $modal.html(data);

                complete($modal);

                $modal.find('form').submit(function(e) {

                    e.preventDefault();

                    jQuery.fn.modalAjaxForm.showModal(
                        $(this).attr('action'),
                        $(this).serialize(),
                        complete,
                        "POST"
                    );
                });
            }
        });
    };
})(jQuery, jQuery);

<|endoftext|>


<commit_before>/**
 * Configuration for the left hand tree
 */
if(typeof SiteTreeHandlers == 'undefined') SiteTreeHandlers = {};
SiteTreeHandlers.parentChanged_url = 'admin/assets/ajaxupdateparent';
SiteTreeHandlers.orderChanged_url = 'admin/assets/ajaxupdatesort';
SiteTreeHandlers.loadPage_url = 'admin/assets/getitem';
SiteTreeHandlers.loadTree_url = 'admin/assets/getsubtree';
SiteTreeHandlers.showRecord_url = 'admin/assets/show/';
SiteTreeHandlers.controller_url = 'admin/assets';

var _HANDLER_FORMS = {
	addpage : 'Form_AddForm',
	deletepage : 'Form_DeleteItemsForm',
	sortitems : 'sortitems_options'
};

(function($) {
	$('.AssetAdmin').concrete('ss', function($) {
		return {
			onmatch: function() {

				this._super();
			}
		};
	});

	/**
	 * Delete selected folders through "batch actions" tab.
	 */
	$('#Form_BatchActionsForm').concrete('ss').register(
		'admin/assets/batchactions/delete',
		function(ids) {
			var confirmed = confirm(
				ss.i18n.sprintf(
					ss.i18n._t(
						'AssetAdmin.BATCHACTIONSDELETECONFIRM',
						"Do you really want to delete %d folders?"
					),
					ids.length
				)
			);
			return (confirmed) ? ids : false;
		}
	);

	/**
	 * @class Simple form with a page type dropdown
	 * which creates a new page through #Form_EditForm and adds a new tree node.
	 * @name ss.Form_AddForm
	 * @requires ss.i18n
	 * @requires ss.Form_EditForm
	 */
	$('#Form_AddForm').concrete(function($) {
	  return/** @lends ss.Form_AddForm */{
			/**
			 * @type DOMElement
			 */
			Tree: null,

			/**
			 * @type Array Internal counter to create unique page identifiers prior to ajax saving
			 */
			_NewPages: [],

			onmatch: function() {
				var self = this;

				this.bind('submit', function(e) {
				  return self._submit(e);
				});

				Observable.applyTo(this[0]);

				var tree = jQuery('#sitetree')[0];
				this.setTree(tree);
			},

			_submit: function(e) {
				var newPages = this._NewPages();
				var tree = this.Tree();
				var parentID = (tree.firstSelected()) ? tree.getIdxOf(tree.firstSelected()) : 0;

				// TODO: Remove 'new-' code http://open.silverstripe.com/ticket/875
				if(parentID && parentID.substr(0,3) == 'new') {
					alert(ss.i18n._t('CMSMAIN.WARNINGSAVEPAGESBEFOREADDING'));
				}

				if(tree.firstSelected() && jQuery(tree.firstSelected()).hasClass("nochildren")) {
					alert(ss.i18n._t('CMSMAIN.CANTADDCHILDREN') );
				}

				// Optionally initalize the new pages tracker
				if(!newPages[parentID] ) newPages[parentID] = 1;

				// default to first button
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');

				// collect data and submit the form
				var data = jQuery(this).serializeArray();
				data.push({name:'Suffix',value:newPages[parentID]++});
				data.push({name:button.attr('name'),value:button.val()});
				jQuery('#Form_EditForm').concrete('ss').loadForm(
					jQuery(this).attr('action'),
					function() {
						button.removeClass('loading');
					},
					{type: 'POST', data: data}
				);

				this.set_NewPages(newPages);

				return false;
			}
		};
	});

	$('#Form_SyncForm').concrete('ss', function($) {
		return {
			onmatch: function() {
				this.bind('submit', this._onsubmit);
				this._super();
			},
			_onsubmit: function(e) {
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');
				$.get(
					jQuery(this).attr('action'),
					function() {
						button.removeClass('loading');
					}
				);

				return false;
			}
		};
	});

	$('#Form_DeleteItemsForm').concrete('ss', function($) {
		return {
			onmatch: function() {
				$('#TreeActions').bind('tabsselect', function(e, ui) {
					if($(ui.tab).attr('id') == 'TreeActions-delete-btn') {

					}
				});
			},
			/**
			 * @param {Boolean}
			 */
			toggleTree: function(bool) {
				if(bool) {
					deletefolder.o1 = $('sitetree').observeMethod('SelectionChanged', deletefolder.treeSelectionChanged);
					deletefolder.o2 = $('Form_DeleteItemsForm').observeMethod('Close', deletefolder.popupClosed);

					jQuery('#sitetree').addClass('multiselect');

					deletefolder.selectedNodes = { };

					var sel = $('sitetree').firstSelected()
					if(sel) {
						var selIdx = $('sitetree').getIdxOf(sel);
						deletefolder.selectedNodes[selIdx] = true;
						sel.removeNodeClass('current');
						sel.addNodeClass('selected');
					}
				}
			}

		};
	});
}(jQuery));

/**
 * Delete folder action
 */
deletefolder = {
	button_onclick : function() {

		return false;
	},

	treeSelectionChanged : function(selectedNode) {
		var idx = $('sitetree').getIdxOf(selectedNode);

		if(selectedNode.selected) {
			selectedNode.removeNodeClass('selected');
			selectedNode.selected = false;
			deletefolder.selectedNodes[idx] = false;

		} else {
			selectedNode.addNodeClass('selected');
			selectedNode.selected = true;
			deletefolder.selectedNodes[idx] = true;
		}

		return false;
	},

	popupClosed : function() {
		jQuery('#sitetree').removeClass('multiselect');
		$('sitetree').stopObserving(deletefolder.o1);
		$('Form_DeleteItemsForm').stopObserving(deletefolder.o2);

		for(var idx in deletefolder.selectedNodes) {
			if(deletefolder.selectedNodes[idx]) {
				node = $('sitetree').getTreeNodeByIdx(idx);
				if(node) {
					node.removeNodeClass('selected');
					node.selected = false;
				}
			}
		}
	},

	form_submit : function() {
		var csvIDs = "";
		for(var idx in deletefolder.selectedNodes) {
			var selectedNode = $('sitetree').getTreeNodeByIdx(idx);
			var link = selectedNode.getElementsByTagName('a')[0];

			if(deletefolder.selectedNodes[idx] && ( !Element.hasClassName( link, 'contents' ) || confirm( "'" + link.firstChild.nodeValue + "' contains files. Would you like to delete the files and folder?" ) ) )
				csvIDs += (csvIDs ? "," : "") + idx;
		}

		if(csvIDs) {
			$('Form_DeleteItemsForm').elements.csvIDs.value = csvIDs;

			statusMessage('deleting pages');

			Ajax.SubmitForm('Form_DeleteItemsForm', null, {
				onSuccess : deletefolder.submit_success,
				onFailure : function(response) {
					errorMessage('Error deleting pages', response);
				}
			});

			$('deletepage').getElementsByTagName('button')[0].onclick();

		} else {
			alert("Please select at least 1 page.");
		}

		return false;
	},

	submit_success: function(response) {
		Ajax.Evaluator(response);
		treeactions.closeSelection($('deletepage'));
	}
}

Behaviour.register({
	'#Form_EditForm_Files': {
		removeFile : function(fileID) {
			var record;
			if(record = $('record-' + fileID)) {
				record.parentNode.removeChild(record);
			}
		}
	},

	'#Form_EditForm_Files a.deletelink' : {
		onclick : function(event) {
			// Send request
			new Ajax.Request(this.href + (this.href.indexOf("?") == -1 ? "?" : "&") + "ajax=1", {
				method : 'get',
				onSuccess : Ajax.Evaluator,
				onFailure : function(response) {errorMessage('Server Error', response);}
			});
			Event.stop(event);
			return false;
		}
	},

	'#Form_EditForm' : {
		changeDetection_fieldsToIgnore : {
			'Files[]' : true
		}
	}
});

/**
 * We don't want hitting the enter key in the name field
 * to submit the form.
 */
 Behaviour.register({
 	'#Form_EditForm_Name' : {
 		onkeypress : function(event) {
 			event = (event) ? event : window.event;
 			var kc = event.keyCode ? event.keyCode : event.charCode;
 			if(kc == 13) {
 				return false;
 			}
 		}
 	}
 });

/**
 * Initialisation function to set everything up
 */
jQuery(document).ready(function() {
	// Set up delete page
	Observable.applyTo($('Form_DeleteItemsForm'));
	if($('deletepage')) {
		$('deletepage').onclick = deletefolder.button_onclick;
		$('deletepage').getElementsByTagName('button')[0].onclick = function() { return false; };
		$('Form_DeleteItemsForm').onsubmit = deletefolder.form_submit;
		Element.hide('Form_DeleteItemsForm');
	}

});<commit_msg>MINOR Removed deletefolder javascript in AssetAdmin.js, superseded by LeftAndMain.BatchActions.js<commit_after>/**
 * Configuration for the left hand tree
 */
if(typeof SiteTreeHandlers == 'undefined') SiteTreeHandlers = {};
SiteTreeHandlers.parentChanged_url = 'admin/assets/ajaxupdateparent';
SiteTreeHandlers.orderChanged_url = 'admin/assets/ajaxupdatesort';
SiteTreeHandlers.loadPage_url = 'admin/assets/getitem';
SiteTreeHandlers.loadTree_url = 'admin/assets/getsubtree';
SiteTreeHandlers.showRecord_url = 'admin/assets/show/';
SiteTreeHandlers.controller_url = 'admin/assets';

var _HANDLER_FORMS = {
	addpage : 'Form_AddForm',
	deletepage : 'Form_DeleteItemsForm',
	sortitems : 'sortitems_options'
};

(function($) {
	$('.AssetAdmin').concrete('ss', function($) {
		return {
			onmatch: function() {

				this._super();
			}
		};
	});

	/**
	 * Delete selected folders through "batch actions" tab.
	 */
	$('#Form_BatchActionsForm').concrete('ss').register(
		'admin/assets/batchactions/delete',
		function(ids) {
			var confirmed = confirm(
				ss.i18n.sprintf(
					ss.i18n._t(
						'AssetAdmin.BATCHACTIONSDELETECONFIRM',
						"Do you really want to delete %d folders?"
					),
					ids.length
				)
			);
			return (confirmed) ? ids : false;
		}
	);

	/**
	 * @class Simple form with a page type dropdown
	 * which creates a new page through #Form_EditForm and adds a new tree node.
	 * @name ss.Form_AddForm
	 * @requires ss.i18n
	 * @requires ss.Form_EditForm
	 */
	$('#Form_AddForm').concrete(function($) {
	  return/** @lends ss.Form_AddForm */{
			/**
			 * @type DOMElement
			 */
			Tree: null,

			/**
			 * @type Array Internal counter to create unique page identifiers prior to ajax saving
			 */
			_NewPages: [],

			onmatch: function() {
				var self = this;

				this.bind('submit', function(e) {
				  return self._submit(e);
				});

				Observable.applyTo(this[0]);

				var tree = jQuery('#sitetree')[0];
				this.setTree(tree);
			},

			_submit: function(e) {
				var newPages = this._NewPages();
				var tree = this.Tree();
				var parentID = (tree.firstSelected()) ? tree.getIdxOf(tree.firstSelected()) : 0;

				// TODO: Remove 'new-' code http://open.silverstripe.com/ticket/875
				if(parentID && parentID.substr(0,3) == 'new') {
					alert(ss.i18n._t('CMSMAIN.WARNINGSAVEPAGESBEFOREADDING'));
				}

				if(tree.firstSelected() && jQuery(tree.firstSelected()).hasClass("nochildren")) {
					alert(ss.i18n._t('CMSMAIN.CANTADDCHILDREN') );
				}

				// Optionally initalize the new pages tracker
				if(!newPages[parentID] ) newPages[parentID] = 1;

				// default to first button
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');

				// collect data and submit the form
				var data = jQuery(this).serializeArray();
				data.push({name:'Suffix',value:newPages[parentID]++});
				data.push({name:button.attr('name'),value:button.val()});
				jQuery('#Form_EditForm').concrete('ss').loadForm(
					jQuery(this).attr('action'),
					function() {
						button.removeClass('loading');
					},
					{type: 'POST', data: data}
				);

				this.set_NewPages(newPages);

				return false;
			}
		};
	});

	$('#Form_SyncForm').concrete('ss', function($) {
		return {
			onmatch: function() {
				this.bind('submit', this._onsubmit);
				this._super();
			},
			_onsubmit: function(e) {
				var button = jQuery(this).find(':submit:first');
				button.addClass('loading');
				$.get(
					jQuery(this).attr('action'),
					function() {
						button.removeClass('loading');
					}
				);

				return false;
			}
		};
	});
}(jQuery));

Behaviour.register({
	'#Form_EditForm_Files': {
		removeFile : function(fileID) {
			var record;
			if(record = $('record-' + fileID)) {
				record.parentNode.removeChild(record);
			}
		}
	},

	'#Form_EditForm_Files a.deletelink' : {
		onclick : function(event) {
			// Send request
			new Ajax.Request(this.href + (this.href.indexOf("?") == -1 ? "?" : "&") + "ajax=1", {
				method : 'get',
				onSuccess : Ajax.Evaluator,
				onFailure : function(response) {errorMessage('Server Error', response);}
			});
			Event.stop(event);
			return false;
		}
	},

	'#Form_EditForm' : {
		changeDetection_fieldsToIgnore : {
			'Files[]' : true
		}
	}
});

/**
 * We don't want hitting the enter key in the name field
 * to submit the form.
 */
 Behaviour.register({
 	'#Form_EditForm_Name' : {
 		onkeypress : function(event) {
 			event = (event) ? event : window.event;
 			var kc = event.keyCode ? event.keyCode : event.charCode;
 			if(kc == 13) {
 				return false;
 			}
 		}
 	}
 });
<|endoftext|>


<commit_before>(function($){
	"use strict";

	/**
	 * Filters the records by the date range inputted.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterDateRange', function(e, records) {
		function convertDateToTime(date, dateFormat) {
			if (date && dateFormat) {
				// Convert from specific other date formats
				var dateBits;
				if (dateFormat === 'd/m/Y') {
					dateBits = date.split('/');
					date = dateBits[2]+'-'+dateBits[1]+'-'+dateBits[0];
				} else if (dateFormat === 'd-m-Y') {
					dateBits = date.split('-');
					date = dateBits[2]+'-'+dateBits[1]+'-'+dateBits[0];
				} else {
					console.log('ListFilterDateRange: Unsupported dateFormat "'+dateFormat+'" configured.');
				}
			}
			return Date.parse(date);
		}

		var filterStartDate = null;
		var filterEndDate = null;
		var dateFormat = null;

		// getStartDateAndEndDateFromInptus
		var $inputs = $(this).find('input');
		$inputs.each(function() {
			var $input = $(this);
			var name = $input.attr('name');
			if (name.indexOf('StartDate') != -1) {
				filterStartDate = $input.val();
				dateFormat = $input.data('dateformat');
			} else if (name.indexOf('EndDate') != -1) {
				filterEndDate = $input.val();
				if (!dateFormat) {
					dateFormat = $input.data('dateformat');
				}
			}
		});
		if (!filterStartDate && !filterEndDate) {
			return;
		}

		// Convert filter format to time()
		filterStartDate = convertDateToTime(filterStartDate, dateFormat);
		filterEndDate = convertDateToTime(filterEndDate, dateFormat);

		var fieldGroupID = $(this).data('fieldgroup-id');
		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('ListFilterDateRange: Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var values = fieldGroupIDs[fieldGroupID].value;
			if (values.StartDate.length != values.EndDate.length) {
				console.log('ListFilterDateRange: Invalid start date and end dates, mismatching array sizes.');
				return;
			}

			var isInFilter = false;
			var startEndDateCount = values.StartDate.length;
			for (var i = 0; i < startEndDateCount; ++i) {
				var startDate = values.StartDate[i];
				startDate = convertDateToTime(startDate);
				var endDate = values.EndDate[i];
				endDate = convertDateToTime(endDate);
				if (filterStartDate && filterEndDate) {
					isInFilter = isInFilter || ((startDate <= filterStartDate && endDate >= filterEndDate) ||
								(startDate >= filterStartDate && startDate <= filterEndDate) ||
								(endDate >= filterStartDate && endDate <= filterEndDate));
				} else if (filterStartDate) {
					isInFilter = isInFilter || (startDate >= filterStartDate || endDate > filterStartDate);
				}  else if (filterEndDate) {
					isInFilter = isInFilter || (endDate <= filterEndDate || startDate < filterEndDate);
				}
			}
			if (isInFilter) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by the IDs returned from the backend
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterGroupIDs', function(e, records, backendFilter) {
		if (!backendFilter) {
			return null;
		}
		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			if (typeof backendFilter[record.ID] !== 'undefined') {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by the selected tags.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterTags', function(e, records) {
		var selectedFilters = null;
		var fieldGroupID = $(this).data('fieldgroup-id');
		var $inputs = $(this).find('input[type="checkbox"]');
		$inputs.each(function() {
			var matches = $(this).attr('name').match(/\[(.*?)\]/);
			var tagID = matches[1];
			if ($(this).prop('checked')) {
				if (selectedFilters === null) {
					selectedFilters = {};
				}
				if (typeof selectedFilters[fieldGroupID] === 'undefined') {
					selectedFilters[fieldGroupID] = {};
				}
				selectedFilters[fieldGroupID][tagID] = true;
			}
		});
		if (selectedFilters === null) {
			return null;
		}

		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (!fieldGroupIDs || typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var isInFilter = false;
			var values = fieldGroupIDs[fieldGroupID].value;
			for (var i = 0; i < values.length; ++i) {
				var value = values[i];
				isInFilter = isInFilter || (selectedFilters !== null && typeof selectedFilters[fieldGroupID][value] !== 'undefined');
			}
			if (isInFilter) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by whether or not their in range of the provided latitude
	 * or longitude.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterLatLngRadius', function(e, records) {
		function getDistanceInKmFromLatLngRadians(latitude1, longitude1, latitude2, longitude2) {
			// Reference: http://stackoverflow.com/questions/12439801/how-to-check-if-a-certain-coordinates-fall-to-another-coordinates-radius-using-p
		    var dLat = latitude2 - latitude1;
		    var dLon = longitude2 - longitude1;

		    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(dLon/2) * Math.sin(dLon/2);
		    var c = 2 * Math.asin(Math.sqrt(a));
		    var result = 6371 * c;

		    return result;
		}

		var fieldGroupID = $(this).data('fieldgroup-id');
		var config = $(this).data('fieldgroup-config');
		if (typeof config.Radius === 'undefined') {
			console.log('"Radius" config variable is missing.');
		}
		var radiusInKm = parseInt(config.Radius, 10);

		var userLat = 0,
			userLng = 0;
		var result = $(this).triggerHandler('getUserLatLng');
		if (typeof result !== 'undefined' && result) {
			userLat = result.Lat;
			userLng = result.Lng;
		} else {
			if (result === false) {
				// Allow the user-code to disable filtering by returning false with 'getUserLatLng'
				return null;
			}
			if (typeof config.Lat !== 'undefined' && typeof config.Lng !== 'undefined' && config.Lat && config.Lng) {
				userLat = config.Lat;
				userLng = config.Lng;
			}
		}

		if (userLat === 0 || userLng === 0) {
			return null;
		}

		// Degrees to Radians
		userLat *= 0.017453292519943295;
		userLng *= 0.017453292519943295;

		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var values = fieldGroupIDs[fieldGroupID].value;
			var distanceInKm = getDistanceInKmFromLatLngRadians(userLat, userLng, values.Lat, values.Lng);
			if (distanceInKm < radiusInKm) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});
})(jQuery);<commit_msg>fix(ListFilterDateRange): Fix conversion from date formats in JavaScript<commit_after>(function($){
	"use strict";

	/**
	 * Filters the records by the date range inputted.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterDateRange', function(e, records) {
		function convertDateToTime(date, dateFormat) {
			if (date && dateFormat) {
				// Convert from specific other date formats
				var dateBits;
				date = date.replace(/\//g, '-');
				dateFormat = dateFormat.replace(/\//g, '-');

				if (dateFormat === 'yyyy-MM-dd') {
					dateBits = date.split('-');
					date = dateBits[0]+'-'+dateBits[1]+'-'+dateBits[2];
				} else if (dateFormat === 'd-MM-yyyy' || dateFormat === 'dd-MM-yyyy') {
					dateBits = date.split('-');
					date = dateBits[2]+'-'+dateBits[1]+'-'+dateBits[0];
				} else {
					console.log('ListFilterDateRange: Unsupported dateFormat "'+dateFormat+'" configured.');
				}
			}
			return Date.parse(date);
		}

		var filterStartDate = null;
		var filterEndDate = null;
		var dateFormat = null;

		// getStartDateAndEndDateFromInputs
		var $inputs = $(this).find('input');
		$inputs.each(function() {
			var $input = $(this);
			var name = $input.attr('name');
			if (name.indexOf('StartDate') != -1) {
				filterStartDate = $input.val();
				dateFormat = $input.data('isodateformat');
			} else if (name.indexOf('EndDate') != -1) {
				filterEndDate = $input.val();
				if (!dateFormat) {
					dateFormat = $input.data('isodateformat');
				}
			}
		});
		if (!filterStartDate && !filterEndDate) {
			return;
		}

		// Convert filter format to time()
		filterStartDate = convertDateToTime(filterStartDate, dateFormat);
		filterEndDate = convertDateToTime(filterEndDate, dateFormat);

		var fieldGroupID = $(this).data('fieldgroup-id');
		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('ListFilterDateRange: Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var values = fieldGroupIDs[fieldGroupID].value;
			if (values.StartDate.length != values.EndDate.length) {
				console.log('ListFilterDateRange: Invalid start date and end dates, mismatching array sizes.');
				return;
			}

			var isInFilter = false;
			var startEndDateCount = values.StartDate.length;
			for (var i = 0; i < startEndDateCount; ++i) {
				var startDate = values.StartDate[i];
				startDate = convertDateToTime(startDate);
				var endDate = values.EndDate[i];
				endDate = convertDateToTime(endDate);
				if (filterStartDate && filterEndDate) {
					isInFilter = isInFilter || ((startDate <= filterStartDate && endDate >= filterEndDate) ||
								(startDate >= filterStartDate && startDate <= filterEndDate) ||
								(endDate >= filterStartDate && endDate <= filterEndDate));
				} else if (filterStartDate) {
					isInFilter = isInFilter || (startDate >= filterStartDate || endDate > filterStartDate);
				}  else if (filterEndDate) {
					isInFilter = isInFilter || (endDate <= filterEndDate || startDate < filterEndDate);
				}
			}
			if (isInFilter) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by the IDs returned from the backend
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterGroupIDs', function(e, records, backendFilter) {
		if (!backendFilter) {
			return null;
		}
		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			if (typeof backendFilter[record.ID] !== 'undefined') {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by the selected tags.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterTags', function(e, records) {
		var selectedFilters = null;
		var fieldGroupID = $(this).data('fieldgroup-id');
		var $inputs = $(this).find('input[type="checkbox"]');
		$inputs.each(function() {
			var matches = $(this).attr('name').match(/\[(.*?)\]/);
			var tagID = matches[1];
			if ($(this).prop('checked')) {
				if (selectedFilters === null) {
					selectedFilters = {};
				}
				if (typeof selectedFilters[fieldGroupID] === 'undefined') {
					selectedFilters[fieldGroupID] = {};
				}
				selectedFilters[fieldGroupID][tagID] = true;
			}
		});
		if (selectedFilters === null) {
			return null;
		}

		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (!fieldGroupIDs || typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var isInFilter = false;
			var values = fieldGroupIDs[fieldGroupID].value;
			for (var i = 0; i < values.length; ++i) {
				var value = values[i];
				isInFilter = isInFilter || (selectedFilters !== null && typeof selectedFilters[fieldGroupID][value] !== 'undefined');
			}
			if (isInFilter) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});

	/**
	 * Filters the records by whether or not their in range of the provided latitude
	 * or longitude.
	 *
	 * @return {array}
	 */
	$('.js-listfilter-filter').bind('ListFilterLatLngRadius', function(e, records) {
		function getDistanceInKmFromLatLngRadians(latitude1, longitude1, latitude2, longitude2) {
			// Reference: http://stackoverflow.com/questions/12439801/how-to-check-if-a-certain-coordinates-fall-to-another-coordinates-radius-using-p
		    var dLat = latitude2 - latitude1;
		    var dLon = longitude2 - longitude1;

		    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(dLon/2) * Math.sin(dLon/2);
		    var c = 2 * Math.asin(Math.sqrt(a));
		    var result = 6371 * c;

		    return result;
		}

		var fieldGroupID = $(this).data('fieldgroup-id');
		var config = $(this).data('fieldgroup-config');
		if (typeof config.Radius === 'undefined') {
			console.log('"Radius" config variable is missing.');
		}
		var radiusInKm = parseInt(config.Radius, 10);

		var userLat = 0,
			userLng = 0;
		var result = $(this).triggerHandler('getUserLatLng');
		if (typeof result !== 'undefined' && result) {
			userLat = result.Lat;
			userLng = result.Lng;
		} else {
			if (result === false) {
				// Allow the user-code to disable filtering by returning false with 'getUserLatLng'
				return null;
			}
			if (typeof config.Lat !== 'undefined' && typeof config.Lng !== 'undefined' && config.Lat && config.Lng) {
				userLat = config.Lat;
				userLng = config.Lng;
			}
		}

		if (userLat === 0 || userLng === 0) {
			return null;
		}

		// Degrees to Radians
		userLat *= 0.017453292519943295;
		userLng *= 0.017453292519943295;

		var visibleRecords = {};
		for (var r = 0; r < records.length; ++r) {
			var record = records[r];
			var fieldGroupIDs = record.FilterGroups;
			if (typeof fieldGroupIDs[fieldGroupID] === 'undefined') {
				console.log('Feature is missing FilterGroups['+fieldGroupID+'] data.');
				return;
			}
			var values = fieldGroupIDs[fieldGroupID].value;
			var distanceInKm = getDistanceInKmFromLatLngRadians(userLat, userLng, values.Lat, values.Lng);
			if (distanceInKm < radiusInKm) {
				visibleRecords[record.ID] = record;
			}
		}
		return visibleRecords;
	});
})(jQuery);<|endoftext|>