<commit_before>/*
 * Copyright (c) 2016, Inversoft Inc., All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
var Prime = Prime || {};

/**
 * The Prime.Data namespace.
 *
 * @namespace Prime.Data
 */
Prime.Data = Prime.Data || {};

/**
 * Queue implementation modeled after java.util.Deque interface.
 * @constructor
 */
Prime.Data.Queue = function() {
  this._elements = {};
  this._head = 0;
  this._tail = 0;
  this._cursor = 0;
};

Prime.Data.Queue.constructor = Prime.Data.Queue;
Prime.Data.Queue.prototype = {

  /**
   * Add the element to the tail of the queue.
   *
   * @param {Object} element An object to store in the queue.
   * @returns {Prime.Data.Queue} This Element.
   */
  add: function(element) {
    this._elements[this._head] = element;
    this._head++;

    return this;
  },

  /**
   * Move the cursor back by one.
   *
   * @returns {Number} The value of the cursor after it has been decremented;
   */
  decrementCursor: function() {
    return --this._cursor;
  },

  /**
   * Return the index of the cursor position in the queue.
   * @returns {Number}
   */
  getCursor: function() {
    return this._cursor;
  },

  /**
   * Return the head index of the queue.
   *
   * @returns {Number} The index position of the head.
   */
  getHeadIndex: function() {
    return this._head;
  },

  /**
   * Return the tail index of the queue.
   * @returns {Number} The index position of the tail.
   */
  getTailIndex: function() {
    return this._tail;
  },

  /**
   * Advance the cursor by one.
   *
   * @returns {Number} The value of the cursor after it has been incremented.
   */
  incrementCursor: function() {
    return ++this._cursor;
  },

  /**
   * Return true if the queue is empty.
   *
   * @returns {boolean} True if the queue is empty, false if not.
   */
  isEmpty: function() {
    return this._head === this._tail;
  },

  /**
   * Return but do not remove the head of the queue.
   *
   * @returns {Object} The object at the head of the queue, or null if empty.
   */
  peek: function() {
    if (this.isEmpty()) {
      return null;
    }

    return this._elements[this._tail];
  },

  /**
   * Return but do not remove the element at the position of the cursor.
   *
   * @param {Number} index The index to peek.
   * @returns {Object} the object at the current position in the queue as determined by the provided index. Null if the cursor is not in bounds.
   */
  peekAtPosition: function(index) {
    if (this.isEmpty()) {
      return null;
    }

    if (index < this._tail || index > (this._head - 1)) {
      throw new Error('The cursor is out of bounds.');
    }

    return this._elements[index];
  },

  /**
   * Return and remove the head of the queue.
   *
   * @returns {Object} the object at the head of the queue, or null if empty.
   */
  poll: function() {
    if (this.isEmpty()) {
      return null;
    }

    var object = this._elements[this._tail];
    delete this._elements[this._tail];
    this._tail++;

    // The cursor should not go off the end of the queue
    if (this._cursor < this._tail) {
      this._cursor = this._tail;
    }

    return object;
  },

  /**
   * Set the cursor position.
   *
   * @param {Number} index The index to set the cursor position.
   * @returns {Prime.Data.Queue} This Element.
   */
  setCursor: function(index) {
    if (index < this._tail || index > (this._head - 1)) {
      throw new Error('The cursor is out of bounds.');
    }

    this._cursor = index;
    return this;
  },

  /**
   * Return the size of the queue.
   *
   * @returns {Number} The size of the queue.
   */
  size: function() {
    return this._head - this._tail;
  }
};<commit_msg>Fix some JSDoc.<commit_after>/*
 * Copyright (c) 2016, Inversoft Inc., All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
var Prime = Prime || {};

/**
 * The Prime.Data namespace.
 *
 * @namespace Prime.Data
 */
Prime.Data = Prime.Data || {};

/**
 * First-In-First-Out Queue implementation modeled after java.util.Deque interface.
 * @constructor
 */
Prime.Data.Queue = function() {
  this._elements = {};
  this._head = 0;
  this._tail = 0;
  this._cursor = 0;
};

Prime.Data.Queue.constructor = Prime.Data.Queue;
Prime.Data.Queue.prototype = {

  /**
   * Add the element to the head of the queue.
   *
   * @param {Object} element An object to store in the queue.
   * @returns {Prime.Data.Queue} This Element.
   */
  add: function(element) {
    this._elements[this._head] = element;
    this._head++;

    return this;
  },

  /**
   * Move the cursor back by one.
   *
   * @returns {Number} The value of the cursor after it has been decremented;
   */
  decrementCursor: function() {
    return --this._cursor;
  },

  /**
   * Return the index of the cursor position in the queue.
   *
   * @returns {Number} The index position of the cursor.
   */
  getCursor: function() {
    return this._cursor;
  },

  /**
   * Return the head index of the queue.
   *
   * @returns {Number} The index position of the head.
   */
  getHeadIndex: function() {
    return this._head;
  },

  /**
   * Return the tail index of the queue.
   *
   * @returns {Number} The index position of the tail.
   */
  getTailIndex: function() {
    return this._tail;
  },

  /**
   * Advance the cursor by one.
   *
   * @returns {Number} The value of the cursor after it has been incremented.
   */
  incrementCursor: function() {
    return ++this._cursor;
  },

  /**
   * Return true if the queue is empty.
   *
   * @returns {boolean} True if the queue is empty, false if not.
   */
  isEmpty: function() {
    return this._head === this._tail;
  },

  /**
   * Return but do not remove the tail of the queue. This is the oldest element in the queue.
   *
   * @returns {Object} The object at the head of the queue, or null if empty.
   */
  peek: function() {
    if (this.isEmpty()) {
      return null;
    }

    return this._elements[this._tail];
  },

  /**
   * Return but do not remove the element at the position of the cursor.
   *
   * @param {Number} index The index to peek.
   * @returns {Object} the object at the current position in the queue as determined by the provided index. Null if the cursor is not in bounds.
   */
  peekAtPosition: function(index) {
    if (this.isEmpty()) {
      return null;
    }

    if (index < this._tail || index > (this._head - 1)) {
      throw new Error('The cursor is out of bounds.');
    }

    return this._elements[index];
  },

  /**
   * Return and remove the tail of the queue. This is the oldest element in the queue.
   *
   * @returns {Object} the object at the tail of the queue, or null if the queue is empty.
   */
  poll: function() {
    if (this.isEmpty()) {
      return null;
    }

    var object = this._elements[this._tail];
    delete this._elements[this._tail];
    this._tail++;

    // The cursor should not go off the end of the queue
    if (this._cursor < this._tail) {
      this._cursor = this._tail;
    }

    return object;
  },

  /**
   * Set the cursor position.
   *
   * @param {Number} index The index to set the cursor position.
   * @returns {Prime.Data.Queue} This Element.
   */
  setCursor: function(index) {
    if (index < this._tail || index > (this._head - 1)) {
      throw new Error('The cursor is out of bounds.');
    }

    this._cursor = index;
    return this;
  },

  /**
   * Return the size of the queue.
   *
   * @returns {Number} The size of the queue.
   */
  size: function() {
    return this._head - this._tail;
  }
};<|endoftext|>


<commit_before>module.exports = {
  meetupParams: {
    key: process.env.MEETUP_API_KEY,
    country: 'SG',
    state: 'SG',
    city: 'Singapore',
    category_id: 34, //Tech category
    page: 500,
    fields: 'next_event'
  },
  blacklistGroups: [
    9319232,
    13903282,
    15867652,
    15237742,
    10989282,
    13917282,
    12117622,
    17604562,
    4280832,
    14995732,
    15750332
  ],
  blacklistWords: [
    'business',
    'networking',
    'UNICOM'
  ],
  auth0: {
    domain: 'webuildsg.auth0.com',
    clientId: process.env.WEBUILD_AUTH0_CLIENT_ID,
    clientSecret: process.env.WEBUILD_AUTH0_CLIENT_SECRET
  },
  eventbrite: {
    token: process.env.EVENTBRITE_TOKEN,
    blacklistOrganiserId: [
      4456586249,
      7875748007,
      7872992855,
      7606683649,
      7554720435,
      7598389997,
      7877801280,
      2263972645,
      7637890579,
      7356770417,
      4435944763,
      7174588005,
      6692116179
    ]
  }
};
<commit_msg>data: remove group for paid events<commit_after>module.exports = {
  meetupParams: {
    key: process.env.MEETUP_API_KEY,
    country: 'SG',
    state: 'SG',
    city: 'Singapore',
    category_id: 34, //Tech category
    page: 500,
    fields: 'next_event'
  },
  blacklistGroups: [
    9319232,
    13903282,
    15867652,
    15237742,
    10989282,
    13917282,
    12117622,
    17604562,
    4280832,
    14995732,
    15750332,
    18312857
  ],
  blacklistWords: [
    'business',
    'networking',
    'UNICOM'
  ],
  auth0: {
    domain: 'webuildsg.auth0.com',
    clientId: process.env.WEBUILD_AUTH0_CLIENT_ID,
    clientSecret: process.env.WEBUILD_AUTH0_CLIENT_SECRET
  },
  eventbrite: {
    token: process.env.EVENTBRITE_TOKEN,
    blacklistOrganiserId: [
      4456586249,
      7875748007,
      7872992855,
      7606683649,
      7554720435,
      7598389997,
      7877801280,
      2263972645,
      7637890579,
      7356770417,
      4435944763,
      7174588005,
      6692116179
    ]
  }
};
<|endoftext|>


<commit_before>// @flow
/* eslint-disable */
import { Directory, Disposable, GitRepository, TextEditor } from 'atom'

type CommandListenerFunction = (event: any) => void
type CommandListenerDescriptor = {
  didDispatch: CommandListenerFunction,
  description?: string,
  displayName?: string,
  hiddenInCommandPalette?: boolean
}
type CommandListener = CommandListenerFunction | CommandListenerDescriptor
type CommandListeners = {
  [name: string]: CommandListenerFunction
}

type PanelOptions = {
  item: HTMLElement | mixed,
  visible?: boolean,
  priority?: number,
  autoFocus?: boolean
}

type Panel = {
  destroy(): void
}

type NotificationButtonOptions = {
  className?: string,
  onDidClick?: Function,
  text: string
}
type NotificationOptions = {
  buttons?: NotificationButtonOptions[],
  description?: string,
  detail?: string,
  dismissable?: boolean,
  icon?: string
}
type ErrorNotificationOptions = NotificationOptions & { stack?: string }
type Notification = {}

type WorkspaceCenter = {
  getActiveTextEditor(): TextEditor | void
}

type ScopeDescriptor = {}

type ConfigQueryOptions = {
  sources?: string[],
  excludedSources?: string[],
  scope?: ScopeDescriptor
}

type OpenUriOptions = {}

interface Dock {
  show(): void;
}

type URI = string
interface ViewItem { element: HTMLElement }

type Bindings = {
  [selector: string]: {
    [key: string]: string
  }
}

type Atom = {
  clipboard: {
    write(string): void,
    read(): string
  },
  commands: {
    add(target: string, commands: CommandListeners): Disposable,
    add(target: string, commandName: string, listener: CommandListener): Disposable
  },
  config: {
    get(keyPath: string, options?: ConfigQueryOptions): string | boolean | number
  },
  keymaps: {
    add(source: string, bindings: Bindings, priority?: number): void,
    removeBindingsFromSource(string): void
  },
  notifications: {
    addInfo(message: string, ?NotificationOptions): Notification,
    addSuccess(message: string, ?NotificationOptions): Notification,
    addError(message: string, ?ErrorNotificationOptions): Notification
  },
  project: {
    getDirectories(): Directory[],
    repositoryForDirectory(Directory): Promise<GitRepository>
  },
  workspace: {
    addModalPanel(PanelOptions): Panel,
    getBottomDock(): Dock,
    getCenter(): WorkspaceCenter,
    getActiveTextEditor(): TextEditor | void,
    getTextEditors(): TextEditor[],
    hide(ViewItem | URI): boolean,
    observeActiveTextEditor(callback: (editor: TextEditor | void) => any): Disposable,
    open(?URI | ?ViewItem, ?OpenUriOptions): Promise<TextEditor>,
    toggle(URI | ViewItem): void
  }
}

declare var atom: Atom
<commit_msg>:memo:<commit_after>// @flow
/* eslint-disable */
import { Directory, Disposable, GitRepository, TextEditor } from 'atom'

type CommandListenerFunction = (event: any) => void
type CommandListenerDescriptor = {
  didDispatch: CommandListenerFunction,
  description?: string,
  displayName?: string,
  hiddenInCommandPalette?: boolean
}
type CommandListener = CommandListenerFunction | CommandListenerDescriptor
type CommandListeners = {
  [name: string]: CommandListenerFunction
}

type PanelOptions = {
  item: HTMLElement | mixed,
  visible?: boolean,
  priority?: number,
  autoFocus?: boolean
}

type Panel = {
  destroy(): void
}

type NotificationButtonOptions = {
  className?: string,
  onDidClick?: Function,
  text: string
}
type NotificationOptions = {
  buttons?: NotificationButtonOptions[],
  description?: string,
  detail?: string,
  dismissable?: boolean,
  icon?: string
}
type ErrorNotificationOptions = NotificationOptions & { stack?: string }
type Notification = {
  dismiss: () => void
}

type WorkspaceCenter = {
  getActiveTextEditor(): TextEditor | void
}

type ScopeDescriptor = {}

type ConfigQueryOptions = {
  sources?: string[],
  excludedSources?: string[],
  scope?: ScopeDescriptor
}

type OpenUriOptions = {}

interface Dock {
  show(): void;
}

type URI = string
interface ViewItem { element: HTMLElement }

type Bindings = {
  [selector: string]: {
    [key: string]: string
  }
}

type Atom = {
  clipboard: {
    write(string): void,
    read(): string
  },
  commands: {
    add(target: string, commands: CommandListeners): Disposable,
    add(target: string, commandName: string, listener: CommandListener): Disposable
  },
  config: {
    get(keyPath: string, options?: ConfigQueryOptions): string | boolean | number
  },
  keymaps: {
    add(source: string, bindings: Bindings, priority?: number): void,
    removeBindingsFromSource(string): void
  },
  notifications: {
    addInfo(message: string, ?NotificationOptions): Notification,
    addSuccess(message: string, ?NotificationOptions): Notification,
    addError(message: string, ?ErrorNotificationOptions): Notification
  },
  project: {
    getDirectories(): Directory[],
    repositoryForDirectory(Directory): Promise<GitRepository>
  },
  workspace: {
    addModalPanel(PanelOptions): Panel,
    getBottomDock(): Dock,
    getCenter(): WorkspaceCenter,
    getActiveTextEditor(): TextEditor | void,
    getTextEditors(): TextEditor[],
    hide(ViewItem | URI): boolean,
    observeActiveTextEditor(callback: (editor: TextEditor | void) => any): Disposable,
    open(?URI | ?ViewItem, ?OpenUriOptions): Promise<TextEditor>,
    toggle(URI | ViewItem): void
  }
}

declare var atom: Atom
<|endoftext|>


<commit_before>;(function (jQuery) {
    jQuery.extend({
        fm: function (custom_options) {

            var defaults = {
                debug: false,
                create_button_selector: ".fm-create",
                update_button_selector: ".fm-update",
                delete_button_selector: ".fm-delete",
                modal_selector: '#fm-modal',
                modal_wrapper_selector: '.modal-wrapper',
                modal_head_selector: '.modal-head',
                modal_body_selector: '.modal-body',
                modal_buttons_selector: '.modal-buttons',
                modal_loader_selector: '.modal-loader',
                modal_load_error: "Error occurred while loading",
                delegate_target: 'body',
                trigger_event_name: 'fm.success',
                ready_event_name: 'fm.ready'
            };

            var global_options = jQuery.extend(defaults, custom_options);

            // using jQuery
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

            function sameOrigin(url) {
                // test that a given url is a same-origin URL
                // url could be relative or scheme relative or absolute
                var host = document.location.host; // host + port
                var protocol = document.location.protocol;
                var sr_origin = '//' + host;
                var origin = protocol + sr_origin;
                // Allow absolute or scheme relative URLs to same origin
                return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                    // or any other URL that isn't scheme relative or absolute i.e relative.
                    !(/^(\/\/|http:|https:).*/.test(url));
            }

            $.ajaxPrefilter(function(options, originalOptions, jqXHR){
                var request_method = options['type'].toLowerCase();
                if ((request_method === "post" || request_method === "delete") && sameOrigin(options.url)) {
                    jqXHR.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
                }
            });

            var delegate_target = $(global_options.delegate_target);
            var modal = $(global_options.modal_selector);
            var modal_loader = $(global_options.modal_loader_selector);
            var modal_wrapper = $(global_options.modal_wrapper_selector);
            var modal_head = $(global_options.modal_head_selector);
            var modal_body = $(global_options.modal_body_selector);
            var modal_buttons = $(global_options.modal_buttons_selector);

            function debug(data) {
                if (global_options.debug === true) {
                    console.log(data);
                }
            }

            function load_content(options) {
                if (!options.url) {
                    debug("no URL found to load data from");
                    return;
                }
                modal_loader.show();
                $.ajax({
                    url: options.url,
                    type: "GET",
                    dataType: "html",
                    error: function () {
                        debug("error occurred while loading modal body from URL");
                        modal_body.text(global_options.modal_load_error);
                    },
                    success: function (data) {
                        debug("modal body successfully loaded");
                        modal_body.html(data);
                        show_modal_wrapper();
                        var form = modal.find('form');
                        form.on('submit', function () {
                            submit_form(form, options);
                            return false;
                        });
                        modal.trigger(global_options.ready_event_name);
                    }
                }).done(function(){
                    modal_head.html(options.modal_head);
                    modal_loader.hide();
                });
            }

            function clear_modal() {
                hide_modal_wrapper();
                modal_head.html('');
                modal_body.html('');
            }

            function show_modal(element, action) {
                debug("showing modal");
                var options = extract_modal_options(element, action);
                debug("options:");
                debug(options);
                modal.modal('show');
                modal_buttons.find('[type="submit"]').unbind('click').bind("click", function () {
                    var form = modal.find('form');
                    submit_form(form, options);
                });
                load_content(options);
            }

            function show_delete_modal(element) {
                debug("showing delete modal");
                var options = extract_modal_options(element, 'delete');
                debug(options);
                modal.modal('show');
                modal_head.html(options.modal_head);
                modal_wrapper.show();
                modal_buttons.find('[type="submit"]').unbind('click').bind("click", function () {
                    var url = options.url;
                    disable_modal_buttons();
                    $.ajax({
                        url: url,
                        type: 'DELETE',
                        dataType: "json",
                        success: function(data) {
                            debug(data);
                            process_response_data(data, options);
                        }
                    });
                });
            }

            function extract_modal_options(element, action) {
                return {
                    url: element.attr('href'),
                    action: action,
                    modal_head: element.attr('data-fm-head'),
                    modal_callback: element.attr('data-fm-callback'),
                    modal_target: element.attr('data-fm-target')
                };
            }

            function submit_form(form, options) {

                var params = {
                    url: options.url,
                    type: form.attr('method').toUpperCase(),
                    dataType: "json"
                };

                var data;
                if (!window.FormData) {
                    // for old browsers - do not support forms with file input fields.
                    data = form.serialize();
                } else {
                    data = new FormData(form[0]);
                    params['processData'] = false;
                    params['contentType'] = false;
                }
                params['data'] = data;
                disable_modal_buttons();
                $.ajax(params).success(function (data) {
                    process_response_data(data, options);
                }).error(function () {
                    enable_modal_buttons();
                    modal_body.text(global_options.modal_load_error);
                });
                return false;
            }

            function process_response_data(data, options) {
                if (data.status === 'ok') {
                    modal.modal("hide");
                    if (options.modal_callback === null || options.modal_callback === undefined) {
                        $.noop();
                    } else if (options.modal_callback === 'reload') {
                        window.location.reload();
                    } else if (options.modal_callback === 'redirect') {
                        window.location = options.modal_target;
                    } else if (options.modal_callback === 'remove' || options.modal_callback === 'delete') {
                        $(options.modal_target).remove();
                    } else if (options.modal_callback === 'append') {
                        $(options.modal_target).append(data.message);
                    } else if (options.modal_callback === 'prepend') {
                        $(options.modal_target).prepend(data.message);
                    } else if (options.modal_callback === 'replace') {
                        $(options.modal_target).replaceWith(data.message);
                    } else if (options.modal_callback === 'redirect_from_response') {
                        window.location = data.message;
                    } else if (options.modal_callback === 'trigger') {
                        delegate_target.trigger(global_options.trigger_event_name, {
                            data: data,
                            options: options
                        });
                    } else {
                        debug("unknown action " + data.action);
                    }
                } else {
                    modal_body.html(data.message);
                    // Also reinstate bindings on submit buttons (in case a
                    // form is invalid, subsequent invalid submissions should
                    // keep the user on the form):
                    var form = modal.find('form');
                    form.on('submit', function () {
                            submit_form(form, options);
                            return false;
                    });
                    // and set event ready:
                    modal.trigger(global_options.ready_event_name);
                }
                enable_modal_buttons();
            }

            function hide_modal_wrapper() {
                modal_wrapper.hide();
            }

            function show_modal_wrapper() {
                modal_wrapper.show();
            }

            function disable_modal_buttons() {
                modal_buttons.find('[type="submit"]').attr('disabled', true);
            }

            function enable_modal_buttons() {
                modal_buttons.find('[type="submit"]').attr('disabled', false);
            }

            function init() {

                modal.on('hidden.bs.modal', function () {
                    debug("modal hidden event fired");
                    clear_modal();
                });

                delegate_target.on('click', global_options.create_button_selector, function () {
                    var self = $(this);
                    show_modal(self, 'create');
                    return false;
                });

                delegate_target.on('click', global_options.update_button_selector, function () {
                    var self = $(this);
                    show_modal(self, 'update');
                    return false;
                });

                delegate_target.on('click', global_options.delete_button_selector, function () {
                    var self = $(this);
                    show_delete_modal(self);
                    return false;
                });
            }

            return init();

        }
    });
})(jQuery);

<commit_msg>custom_callbacks option to provide custom callback functions<commit_after>;(function (jQuery) {
    jQuery.extend({
        fm: function (custom_options) {

            var defaults = {
                debug: false,
                create_button_selector: ".fm-create",
                update_button_selector: ".fm-update",
                delete_button_selector: ".fm-delete",
                modal_selector: '#fm-modal',
                modal_wrapper_selector: '.modal-wrapper',
                modal_head_selector: '.modal-head',
                modal_body_selector: '.modal-body',
                modal_buttons_selector: '.modal-buttons',
                modal_loader_selector: '.modal-loader',
                modal_load_error: "Error occurred while loading",
                delegate_target: 'body',
                trigger_event_name: 'fm.success',
                ready_event_name: 'fm.ready',
                custom_callbacks : {}
            };

            var global_options = jQuery.extend(defaults, custom_options);

            var delegate_target = $(global_options.delegate_target);
            var modal = $(global_options.modal_selector);
            var modal_loader = $(global_options.modal_loader_selector);
            var modal_wrapper = $(global_options.modal_wrapper_selector);
            var modal_head = $(global_options.modal_head_selector);
            var modal_body = $(global_options.modal_body_selector);
            var modal_buttons = $(global_options.modal_buttons_selector);

            var default_callbacks = {
                "reload": function() {
                    window.location.reload();
                },
                "redirect": function(data, options) {
                    window.location = options.modal_target;
                },
                "remove": function(data, options) {
                    $(options.modal_target).remove();
                },
                "delete": function(data, options) {
                    $(options.modal_target).remove();
                },
                "append": function(data, options) {
                    $(options.modal_target).append(data.message);
                },
                "prepend": function(data, options) {
                    $(options.modal_target).prepend(data.message);
                },
                "replace": function(data, options) {
                    $(options.modal_target).replaceWith(data.message);
                },
                "redirect_from_response": function(data) {
                    window.location = data.message;
                },
                "trigger": function(data, options) {
                    delegate_target.trigger(global_options.trigger_event_name, {
                        data: data,
                        options: options
                    });
                }
            };

            var global_callbacks = jQuery.extend(default_callbacks, global_options.custom_callbacks);

            // using jQuery
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }

            function sameOrigin(url) {
                // test that a given url is a same-origin URL
                // url could be relative or scheme relative or absolute
                var host = document.location.host; // host + port
                var protocol = document.location.protocol;
                var sr_origin = '//' + host;
                var origin = protocol + sr_origin;
                // Allow absolute or scheme relative URLs to same origin
                return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                    // or any other URL that isn't scheme relative or absolute i.e relative.
                    !(/^(\/\/|http:|https:).*/.test(url));
            }

            $.ajaxPrefilter(function(options, originalOptions, jqXHR){
                var request_method = options['type'].toLowerCase();
                if ((request_method === "post" || request_method === "delete") && sameOrigin(options.url)) {
                    jqXHR.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
                }
            });

            function debug(data) {
                if (global_options.debug === true) {
                    console.log(data);
                }
            }

            function load_content(options) {
                if (!options.url) {
                    debug("no URL found to load data from");
                    return;
                }
                modal_loader.show();
                $.ajax({
                    url: options.url,
                    type: "GET",
                    dataType: "html",
                    error: function () {
                        debug("error occurred while loading modal body from URL");
                        modal_body.text(global_options.modal_load_error);
                    },
                    success: function (data) {
                        debug("modal body successfully loaded");
                        modal_body.html(data);
                        show_modal_wrapper();
                        var form = modal.find('form');
                        form.on('submit', function () {
                            submit_form(form, options);
                            return false;
                        });
                        modal.trigger(global_options.ready_event_name);
                    }
                }).done(function(){
                    modal_head.html(options.modal_head);
                    modal_loader.hide();
                });
            }

            function clear_modal() {
                hide_modal_wrapper();
                modal_head.html('');
                modal_body.html('');
            }

            function show_modal(element, action) {
                debug("showing modal");
                var options = extract_modal_options(element, action);
                debug("options:");
                debug(options);
                modal.modal('show');
                modal_buttons.find('[type="submit"]').unbind('click').bind("click", function () {
                    var form = modal.find('form');
                    submit_form(form, options);
                });
                load_content(options);
            }

            function show_delete_modal(element) {
                debug("showing delete modal");
                var options = extract_modal_options(element, 'delete');
                debug(options);
                modal.modal('show');
                modal_head.html(options.modal_head);
                modal_wrapper.show();
                modal_buttons.find('[type="submit"]').unbind('click').bind("click", function () {
                    var url = options.url;
                    disable_modal_buttons();
                    $.ajax({
                        url: url,
                        type: 'DELETE',
                        dataType: "json",
                        success: function(data) {
                            debug(data);
                            process_response_data(data, options);
                        }
                    });
                });
            }

            function extract_modal_options(element, action) {
                return {
                    url: element.attr('href'),
                    action: action,
                    modal_head: element.attr('data-fm-head'),
                    modal_callback: element.attr('data-fm-callback'),
                    modal_target: element.attr('data-fm-target')
                };
            }

            function submit_form(form, options) {

                var params = {
                    url: options.url,
                    type: form.attr('method').toUpperCase(),
                    dataType: "json"
                };

                var data;
                if (!window.FormData) {
                    // for old browsers - do not support forms with file input fields.
                    data = form.serialize();
                } else {
                    data = new FormData(form[0]);
                    params['processData'] = false;
                    params['contentType'] = false;
                }
                params['data'] = data;
                disable_modal_buttons();
                $.ajax(params).success(function (data) {
                    process_response_data(data, options);
                }).error(function () {
                    enable_modal_buttons();
                    modal_body.text(global_options.modal_load_error);
                });
                return false;
            }

            function process_response_data(data, options) {
                if (data.status === 'ok') {
                    modal.modal("hide");
                    var callback = options.modal_callback;
                    if (options.modal_callback === null || options.modal_callback === undefined) {
                        $.noop();
                    } else if (callback in global_callbacks) {
                        var cb = global_callbacks[callback];
                        cb(data, options);
                    } else {
                        debug("unknown action " + data.action);
                    }
                } else {
                    modal_body.html(data.message);
                    // Also reinstate bindings on submit buttons (in case a
                    // form is invalid, subsequent invalid submissions should
                    // keep the user on the form):
                    var form = modal.find('form');
                    form.on('submit', function () {
                            submit_form(form, options);
                            return false;
                    });
                    // and set event ready:
                    modal.trigger(global_options.ready_event_name);
                }
                enable_modal_buttons();
            }

            function hide_modal_wrapper() {
                modal_wrapper.hide();
            }

            function show_modal_wrapper() {
                modal_wrapper.show();
            }

            function disable_modal_buttons() {
                modal_buttons.find('[type="submit"]').attr('disabled', true);
            }

            function enable_modal_buttons() {
                modal_buttons.find('[type="submit"]').attr('disabled', false);
            }

            function init() {

                modal.on('hidden.bs.modal', function () {
                    debug("modal hidden event fired");
                    clear_modal();
                });

                delegate_target.on('click', global_options.create_button_selector, function () {
                    var self = $(this);
                    show_modal(self, 'create');
                    return false;
                });

                delegate_target.on('click', global_options.update_button_selector, function () {
                    var self = $(this);
                    show_modal(self, 'update');
                    return false;
                });

                delegate_target.on('click', global_options.delete_button_selector, function () {
                    var self = $(this);
                    show_delete_modal(self);
                    return false;
                });
            }

            return init();

        }
    });
})(jQuery);

<|endoftext|>


<commit_before>var browser = browser || chrome; // eslint-disable-line no-undef

browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages', 'textsize', 'font', 'bold' ], function ( r ) {
	var  m = r.messages || 'Breathe';

	m = m.split( '\n' );
	m = m[ Math.floor( Math.random() * m.length ) ];

	if ( r.font !== '' ) {
		document.querySelector( 'h1' ).style.fontFamily = r.font;
	}

	if ( r.bold === false ) {
		document.querySelector( 'h1' ).style.fontWeight = 400;
	}

	document.querySelector( 'h1' ).textContent = m;
	document.querySelector( 'h1' ).style.fontSize = r.textsize + 'px' || '30px';
	document.body.style.backgroundColor = r.bgcolor || '#fff';
	document.body.style.color = r.textcolor || '#b3b3b3';
} );
<commit_msg>fix: load default font when nothing is set<commit_after>var browser = browser || chrome; // eslint-disable-line no-undef

browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages', 'textsize', 'font', 'bold' ], function ( r ) {
	var  m = r.messages || 'Breathe';

	m = m.split( '\n' );
	m = m[ Math.floor( Math.random() * m.length ) ];

	if ( r.font !== undefined && r.font !== '' ) {
		document.querySelector( 'h1' ).style.fontFamily = r.font;
	}

	if ( r.bold === false ) {
		document.querySelector( 'h1' ).style.fontWeight = 400;
	}

	document.querySelector( 'h1' ).textContent = m;
	document.querySelector( 'h1' ).style.fontSize = r.textsize + 'px' || '30px';
	document.body.style.backgroundColor = r.bgcolor || '#fff';
	document.body.style.color = r.textcolor || '#b3b3b3';
} );
<|endoftext|>


<commit_before>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');

var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

module.exports.dataplan = [];
/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: false,
    bikeShare: false,
    bus: true,
    car: false,
    parkRide: false,
    date: moment().format('MM:DD:YYYY'),
    arriveBy: false,
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    dataplan: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours(),
    minute: moment().minute(),
    to: '',
    to_valid: false,
    train: true,
    walk: true,
    fast: true,
    safe: true,
    flat: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('parkRide')
  .attr('days')
  .attr('date')
  .attr('arriveBy')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('minute')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk')
  .attr('fast')
  .attr('safe')
  .attr('flat');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with sessionStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in sessionStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
  this.dataplan = updateRoutes.dataplan;
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey

  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {
  callback = callback || function() {}; // noop callback
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

  if (isCoordinate) {
    var callbackAmigo = function (err, reverse) {
      var changes = {};
      if (reverse) {
        var geocode_features = reverse.features;
        changes[name] = name;
        if (isCoordinate) {
          if (!(extra === undefined)) {
            changes[name] = extra.properties.label;
          } else {
            changes[name] = geocode_features[0].properties.label;
          }
        } else {
          if (!(extra === undefined)) {
            changes[name] = extra.properties.label;
          } else {
            changes[name] = geocode_features[0].properties.label;
          }
        }
        changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])};
        changes[name + '_id'] = geocode_features[0].properties.id;
        changes[name + '_valid'] = true;

        plan.set(changes);
        callback(null, reverse);
      } else {
        if (isCoordinate) {
          changes[name] = extra.properties.label;
          changes[name + '_ll'] = { lat: parseFloat(c[1]),lng: parseFloat(c[0])};
          changes[name + '_valid'] = true;
          plan.set(changes);
          callback(null, extra);
        } else {
          callback(err);
        }
      }
    };
    geocode.reverseAmigo(c, callbackAmigo);
  } else {
    plan.setAddress('', '', callback);
  }
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

Plan.prototype.triangulateBikeOptions = function () {
  var totalOpts = 0,
      opts = [this.flat(), this.safe(), this.fast()];

  opts.forEach(function (opt) {
    totalOpts += opt ? 1 : 0;
  });

  if (!totalOpts) {
    return [0.333, 0.333, 0.334];
  } else {
    return opts.map(function (opt) {
      return opt ? +(1 / totalOpts).toFixed(3) : 0;
    });
  }
}

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) {
    modes.push('BICYCLE_RENT');
  }

  if (this.car()) {
    modes.push('CAR');
  }

  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }

  if (this.parkRide()) {
    modes.push('CAR');
    modes.push('BUSISH');
    modes.push('TRAINISH');
  } else {
    if (this.bus()) {
      modes.push('BUSISH');
    }
    if (this.train()) {
      modes.push('TRAINISH');
    }
  }

  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();
  var arriveBy = this.arriveBy();
  var triangleFactors = this.triangulateBikeOptions();

  // Get correct hour, add minutes and convert to string
  var time = arriveBy ? endTime : startTime;
  time += ':' + this.minute()

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: time,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 5000,
      bikeSpeed: 10,
//      bikeBoardCost: 15,
//      walkReluctance: 10,
//      clampInitialWait: 60,
//      bikeBoardCost: 40,
//      walkBoardCost: 30,
      walkReluctance: 15,
//      clampInitialWait: 60,
      maxTransfers: 5,
//      waitAtBeginningFactor: 0.5,
      triangleSlopeFactor: triangleFactors[0],
      triangleSafetyFactor: triangleFactors[1],
      triangleTimeFactor: (triangleFactors[2] === 0.333) ? triangleFactors[2] + 0.001 : triangleFactors[2], // must add to one
      optimize: 'TRIANGLE',
      arriveBy: arriveBy
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear sessionStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {
  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days(),
    date: this.date(),
    minute: this.minute()
  });
};
<commit_msg>fixed geocoding for when the user does not select an option from the suggestions<commit_after>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');

var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

module.exports.dataplan = [];
/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: false,
    bikeShare: false,
    bus: true,
    car: false,
    parkRide: false,
    date: moment().format('MM:DD:YYYY'),
    arriveBy: false,
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    dataplan: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours(),
    minute: moment().minute(),
    to: '',
    to_valid: false,
    train: true,
    walk: true,
    fast: true,
    safe: true,
    flat: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('parkRide')
  .attr('days')
  .attr('date')
  .attr('arriveBy')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('minute')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk')
  .attr('fast')
  .attr('safe')
  .attr('flat');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with sessionStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in sessionStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
  this.dataplan = updateRoutes.dataplan;
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey

  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {
  callback = callback || function() {}; // noop callback
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

  if (isCoordinate) {
    var callbackAmigo = function (err, reverse) {
      var changes = {};
      if (reverse) {
        var geocode_features = reverse.features;
        changes[name] = name;
        if (isCoordinate) {
          if (!(extra === undefined)) {
            changes[name] = extra.properties.label;
          } else {
            changes[name] = geocode_features[0].properties.label;
          }
        } else {
          if (!(extra === undefined)) {
            changes[name] = extra.properties.label;
          } else {
            changes[name] = geocode_features[0].properties.label;
          }
        }
        changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])};
        changes[name + '_id'] = geocode_features[0].properties.id;
        changes[name + '_valid'] = true;

        plan.set(changes);
        callback(null, reverse);
      } else {
        if (isCoordinate) {
          changes[name] = extra.properties.label;
          changes[name + '_ll'] = { lat: parseFloat(c[1]),lng: parseFloat(c[0])};
          changes[name + '_valid'] = true;
          plan.set(changes);
          callback(null, extra);
        } else {
          callback(err);
        }
      }
    };
    geocode.reverseAmigo(c, callbackAmigo);
  } else {
    var cb_amigo =  function(err, suggestions){
      if (suggestions && suggestions.length > 0){
        var lat_lng = suggestions[0].geometry.coordinates[0]+','+suggestions[0].geometry.coordinates[1];
        plan.setAddress(name, lat_lng, callback);
      } else {
        console.log('no ejecuta nada', {'err':err,'suggestions':suggestions})
        plan.setAddress('', '', callback);
      }
    }
    geocode.suggestAmigo(address, cb_amigo);
  }
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

Plan.prototype.triangulateBikeOptions = function () {
  var totalOpts = 0,
      opts = [this.flat(), this.safe(), this.fast()];

  opts.forEach(function (opt) {
    totalOpts += opt ? 1 : 0;
  });

  if (!totalOpts) {
    return [0.333, 0.333, 0.334];
  } else {
    return opts.map(function (opt) {
      return opt ? +(1 / totalOpts).toFixed(3) : 0;
    });
  }
}

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) {
    modes.push('BICYCLE_RENT');
  }

  if (this.car()) {
    modes.push('CAR');
  }

  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }

  if (this.parkRide()) {
    modes.push('CAR');
    modes.push('BUSISH');
    modes.push('TRAINISH');
  } else {
    if (this.bus()) {
      modes.push('BUSISH');
    }
    if (this.train()) {
      modes.push('TRAINISH');
    }
  }

  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();
  var arriveBy = this.arriveBy();
  var triangleFactors = this.triangulateBikeOptions();

  // Get correct hour, add minutes and convert to string
  var time = arriveBy ? endTime : startTime;
  time += ':' + this.minute()

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: time,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 5000,
      bikeSpeed: 10,
//      bikeBoardCost: 15,
//      walkReluctance: 10,
//      clampInitialWait: 60,
//      bikeBoardCost: 40,
//      walkBoardCost: 30,
      walkReluctance: 15,
//      clampInitialWait: 60,
      maxTransfers: 5,
//      waitAtBeginningFactor: 0.5,
      triangleSlopeFactor: triangleFactors[0],
      triangleSafetyFactor: triangleFactors[1],
      triangleTimeFactor: (triangleFactors[2] === 0.333) ? triangleFactors[2] + 0.001 : triangleFactors[2], // must add to one
      optimize: 'TRIANGLE',
      arriveBy: arriveBy
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear sessionStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {
  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days(),
    date: this.date(),
    minute: this.minute()
  });
};
<|endoftext|>


<commit_before>app.Idea = React.createClass({

  getInitialState: function() {
    // set initial editing state to false
    return {
      displaying: true,
      editing: false
    };
  },

  componentDidMount: function() {
    // add a change listener on the IdeaStore
    // this is needed when the edit comes back and emits a change
    // that will force the component to re-render
    app.IdeaStore.addChangeListener(function() {
      if(this.isMounted()) {
        this.setState({editing: false});
      }
    }.bind(this));
  },

  show: function () {
    if (this.isMounted()) {
      this.setState({ displaying: !this.state.displaying });
    }
  },

  addInterest: function(e){
    e.preventDefault();

    var ideaId = this.props._id;

    app.InterestActions.add(ideaId);

    // Todo: Change state/class to indicate the interest

    return;
  },

  render: function() {
    var ideaContent;
    var editForm;
    // if editing render edit form otherwise render "Edit Idea" button
    if (this.state.editing) {
      editForm = <app.IdeaForm editing="true" name={this.props.name} key={this.props._id} _id={this.props._id} />
    }

    if (this.state.displaying) {
      ideaContent = (

{this.props.name}

          <form className="pure-form" >
            {editForm}
            <button className="button-small pure-button pure-button-primary" onClick={this.edit}>{ this.state.editing ? 'Cancel' : 'Edit Idea'}</button>
            <button className="button-small pure-button pure-button-primary" onClick={this.delete}>Delete Idea</button>
            <button className="button-small pure-button pure-button-primary" onClick={this.addInterest}>Watch</button>
            <app.Comments idea_id={idea_id} />
          </form>

      );
    }

    return (

        {ideaContent}

    );
  },

  edit: function(e) {
    e.preventDefault();
    if (this.isMounted()) {
      this.setState({ editing: !this.state.editing });
    }
  },

  delete: function(e) {
    e.preventDefault();
    if (this.isMounted()) {
      app.IdeaActions.delete({ id: this.props._id });
    }
  }
});
<commit_msg>Fix incorrect reference to an Idea's id in Idea component.<commit_after>app.Idea = React.createClass({

  getInitialState: function() {
    // set initial editing state to false
    return {
      displaying: true,
      editing: false
    };
  },

  componentDidMount: function() {
    // add a change listener on the IdeaStore
    // this is needed when the edit comes back and emits a change
    // that will force the component to re-render
    app.IdeaStore.addChangeListener(function() {
      if(this.isMounted()) {
        this.setState({editing: false});
      }
    }.bind(this));
  },

  show: function () {
    if (this.isMounted()) {
      this.setState({ displaying: !this.state.displaying });
    }
  },

  addInterest: function(e){
    e.preventDefault();

    var ideaId = this.props._id;

    app.InterestActions.add(ideaId);

    // Todo: Change state/class to indicate the interest

    return;
  },

  render: function() {
    var ideaContent;
    var editForm;
    // if editing render edit form otherwise render "Edit Idea" button
    if (this.state.editing) {
      editForm = <app.IdeaForm editing="true" name={this.props.name} key={this.props._id} _id={this.props._id} />
    }

    if (this.state.displaying) {
      ideaContent = (

{this.props.name}

          <form className="pure-form" >
            {editForm}
            <button className="button-small pure-button pure-button-primary" onClick={this.edit}>{ this.state.editing ? 'Cancel' : 'Edit Idea'}</button>
            <button className="button-small pure-button pure-button-primary" onClick={this.delete}>Delete Idea</button>
            <button className="button-small pure-button pure-button-primary" onClick={this.addInterest}>Watch</button>
            <app.Comments idea_id={this.props._id} />
          </form>

      );
    }

    return (

        {ideaContent}

    );
  },

  edit: function(e) {
    e.preventDefault();
    if (this.isMounted()) {
      this.setState({ editing: !this.state.editing });
    }
  },

  delete: function(e) {
    e.preventDefault();
    if (this.isMounted()) {
      app.IdeaActions.delete({ id: this.props._id });
    }
  }
});
<|endoftext|>


<commit_before>
/**
 * Possible states of a subscription to a YouTube channel or playlist.
 *
 * @enum {string}
 */
export default Object.freeze({
  /**
   * The subscription is enabled, videos are fetched from the playlist.
   */
  ACTIVE: "ACTIVE",

  /**
   * The subscription is disabled. This is only used with incognito
   * subscriptions.
   */
  DISABLED: "DISABLED",

  /**
   * The subscription is reporting an error.
   */
  ERROR: "ERROR"
})
<commit_msg>documentation clarification<commit_after>
/**
 * Possible states of a subscription to a YouTube channel or playlist.
 *
 * @enum {string}
 */
export default Object.freeze({
  /**
   * The subscription is enabled, videos are fetched from the playlist.
   */
  ACTIVE: "ACTIVE",

  /**
   * The subscription is disabled. This is only used with incognito
   * subscriptions.
   */
  DISABLED: "DISABLED",

  /**
   * The subscription is enabled, but reporting an error.
   */
  ERROR: "ERROR"
})
<|endoftext|>


<commit_before>import { app } from 'hyperapp'
import actions from './actions'
import state from './state'
import view from './view'

import { hyperlog } from "./utils/logger";
import core from './core'

const main = hyperlog(app)(state, actions, view, document.body)

document.onreadystatechange = function() {
    if (document.readyState === "complete") {
        main.setBootScreenState(false);
        console.log(main);
    }
};

core(main);
<commit_msg>disable bouncing in ios webkit<commit_after>import { app } from 'hyperapp'
import actions from './actions'
import state from './state'
import view from './view'

import { hyperlog } from "./utils/logger";
import core from './core'

const main = hyperlog(app)(state, actions, view, document.body)

document.onreadystatechange = function() {
    if (document.readyState === "complete") {
        main.setBootScreenState(false);
        console.log(main);
    }
};

core(main);

// This disables bouncing
// https://bugs.webkit.org/show_bug.cgi?id=182521
// https://stackoverflow.com/a/50856621/1589989
window.addEventListener("touchmove", (event) => event.preventDefault(), {passive: false} );<|endoftext|>


<commit_before>/**
 * Copyright (c) 2009-2014, rultor.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met: 1) Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following
 * disclaimer. 2) Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution. 3) Neither the name of the rultor.com nor
 * the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*globals $:false, document:false, window:false */

$(document).ready(
  function () {
    "use strict";
    var $div = $('#pulse');
    window.setInterval(
      function () {
        $div.load($div.attr('data-href'));
      },
      3000
    );
  }
);
<commit_msg>ajax every second<commit_after>/**
 * Copyright (c) 2009-2014, rultor.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met: 1) Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following
 * disclaimer. 2) Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution. 3) Neither the name of the rultor.com nor
 * the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*globals $:false, document:false, window:false */

$(document).ready(
  function () {
    "use strict";
    var $div = $('#pulse');
    window.setInterval(
      function () {
        $div.load($div.attr('data-href'));
      },
      1000
    );
  }
);
<|endoftext|>


<commit_before>/*
 * Copyright 1998-2015 Linux.org.ru
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

function initNextPrevKeys() {
  $script.ready('plugins', function () {
    $(function () {
      function jump(link) {
        if (link && link.href) {
          document.location = link.href;
        }
      }

      if (typeof  jQuery.hotkeys !== 'undefined') {
        $(document).bind('keydown', {combi: 'Ctrl+left', disableInInput: true}, function () {
          jump(document.getElementById('PrevLink'))
        });
        $(document).bind('keydown', {combi: 'Ctrl+right', disableInInput: true}, function () {
          jump(document.getElementById('NextLink'))
        });
      }
    })
  });
}

function initStarPopovers() {
  $script.ready('plugins', function () {
    $(function () {
      $("#favs_button").click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        $("#memories_button").popover('hide');
        $("#favs_button").popover('show');
      });
      $("#favs_button").popover({
        content: "Для добавления в избранное надо залогиниться!",
        autoReposition: false,
        trigger: 'manual'
      });

      $("#memories_button").click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        $("#favs_button").popover('hide');
        $("#memories_button").popover('show');
      });
      $("#memories_button").popover({
        content: "Для добавления в отслеживаемое надо залогиниться!",
        autoReposition: false,
        trigger: 'manual'
      });
    })
  });
}

function init_interpage_adv(ads) {
    $(function() {
        var ad = ads[Math.floor(Math.random() * ads.length)];

        if (ad.type==='flash') {
            $script('/js/jquery.swfobject.1-1-1.min.js', function() {
                $('#interpage-adv').flash({
                    "swf": ad.src,
                    "width": 728,
                    "height": 90
                });
            });
        }

        if (ad.type==='img') {
            var anchor = $('<a>');
            anchor.attr('href', ad.href);
            anchor.attr('target', '_blank');

            var img = $('<img>');
            img.attr('src', ad.src);
            if ('width' in ad) {
                img.attr('width', ad.width);
            } else {
                img.attr('width', 728);
            }

            if ('height' in ad) {
                img.attr('height', ad.height);
            } else {
                img.attr('height', 90);
            }

            anchor.append(img);
            $('#interpage-adv').append(anchor);
        }

        if (ad.type==='rimg') {
            var anchor = $('<a>');
            anchor.attr('href', ad.href);
            anchor.attr('target', '_blank');

            var img = $('<img>');

            if (window.matchMedia("(min-width: 768px").matches) {
                img.attr('width', 728);
                img.attr('height', 90);
                img.attr('src', ad.img728);
            } else if (window.matchMedia("(min-width: 500px").matches) {
                img.attr('width', 468);
                img.attr('height', 60);
                img.attr('src', ad.img468);
            } else {
                img.attr('width', 320);
                img.attr('height', 100);
                img.attr('src', ad.img320);
            }

            anchor.append(img);
            $('#interpage-adv').append(anchor);
        }
    });
}

function topic_memories_form_setup(memId, watch, msgid, csrf) {
  function memories_add(event) {
    event.preventDefault();

    $.ajax({
      url: "/memories.jsp",
      type: "POST",
      data: { msgid : msgid, add: "add", watch: event.data.watch, csrf: csrf }
    }).done(function(t) {
       form_setup(t['id'], event.data.watch);
       if (event.data.watch) {
         $('#memories_count').text(t['count']);
       } else {
         $('#favs_count').text(t['count']);
       }
    });
  }

  function memories_remove(event) {
    event.preventDefault();

    $.ajax({
      url: "/memories.jsp",
      type: "POST",
      data: { id : event.data.id, remove: "remove", csrf: csrf }
    }).done(function(t) {
      form_setup(0, event.data.watch);
      if (t>=0) {
        if (event.data.watch) {
          $('#memories_count').text(t);
        } else {
          $('#favs_count').text(t);
        }
      }
    });
  }

  function form_setup(memId, watch) {
    var el;

    if (watch) {
      el = $('#memories_button');
    } else {
      el = $('#favs_button');
    }

    if (memId==0) {
      el.removeClass('selected');
      el.attr('title', watch?"Отслеживать":"В избранное");

      el.unbind("click", memories_remove);
      el.bind("click", {watch: watch}, memories_add);
    } else {
      el.addClass('selected');
      el.attr('title', watch?"Не отслеживать":"Удалить из избранного");

      el.unbind("click", memories_add);
      el.bind("click", {watch: watch, id: memId}, memories_remove);
    }
  }

  $(function () {
    form_setup(memId, watch);
  });
}

function tag_memories_form_setup(tag, csrf_token) {
  $script.ready('plugins', function() {
    $(function() {
      $("#tagFavNoth").click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        $("#tagFavNoth").popover('show');
      }).popover({
        content: "Для добавления в избранное надо залогиниться!"
      });

      $("#tagIgnNoth").click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        $("#tagIgnNoth").popover('show');
      }).popover({
        content: "Для добавления в список игнорирования надо залогиниться!"
      });
    });
  });

  $(function() {
    function tag_filter(event) {
      event.preventDefault();

      var data = { tagName: tag};

      var el = $('#tagFavAdd');
      var add = !el.hasClass("selected");

      if (add) {
        data['add'] = 'add';
      } else {
        data['del'] = 'del';
      }

      data['csrf'] = csrf_token;

      $.ajax({
        url: "/user-filter/favorite-tag",
        type: "POST",
        dataType: "json",
        data: data
      }).done(function (t) {
            if (t.error) {
              alert(t.error);
            } else {
              el.attr('title', add ? "Удалить из избранного" : "В избранное");

              $('#favsCount').text(t['count']);

              if (add) {
                el.addClass("selected");
              } else {
                el.removeClass("selected");
              }
            }
          });
    }

    $("#tagFavAdd").bind("click", tag_filter);
  });

  $(function() {
    function tag_ignore(event) {
      event.preventDefault();

      var data = { tagName: tag};

      var el = $('#tagIgnore');
      var add = !el.hasClass("selected");

      if (add) {
        data['add'] = 'add';
      } else {
        data['del'] = 'del';
      }

      data['csrf'] = csrf_token;

      $.ajax({
        url: "/user-filter/ignore-tag",
        type: "POST",
        dataType: "json",
        data: data
      }).done(function (t) {
            if (t.error) {
              alert(t.error);
            } else {
              el.attr('title', add ? "Перестать игнорировать" : "Игнорировать");

              $('#ignoreCount').text(t['count']);

              if (add) {
                el.addClass("selected");
              } else {
                el.removeClass("selected");
              }
            }
          });
    }

    $("#tagIgnore").bind("click", tag_ignore);
  });

}

$script.ready('plugins', function() {
  function initLoginForm() {
    var options = {
      type:"post",
      dataType:"json",
      xhrFields: {
        withCredentials: true
      },
      success:function (response, status) {
        if (response.loggedIn) {
          window.location.reload();
        } else {
          alert("Ошибка авторизации. Неправильное имя пользователя, e-mail или пароль.");
          window.location = "/login.jsp";
        }
      },
      error:function (response, status) {
        alert("Ошибка авторизации. Неправильное имя пользователя, e-mail или пароль.");
        window.location = "/login.jsp";
      }
    };

    if (location.protocol === 'https:') {
      $('#regform').ajaxForm(options);

      $('#loginbutton').bind('click', function(e) {
        $("#regmenu").fadeOut("fast", function() {
          $("#regform").fadeIn("fast", function() {
            $("#regform input[name='nick']").focus();
          });
        });
        return false;
      });

      $('#hide_loginbutton').bind('click', function(e) {
        $("#regform").fadeOut("fast", function() {
          $("#regmenu").fadeIn("fast");
        });
        return false;
      });
    }
  }

  $(function() {
    initLoginForm();
  });
});

$(document).ready(function() {
  function initCtrlEnter() {
    function ctrl_enter(e, form) {
        if (((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey||e.metaKey)) {
          window.onbeforeunload = null;

          $(form).submit();

          return false;
        }
    }

    $('textarea').bind('keypress', function(e) {
      ctrl_enter(e, e.target.form);
    });
  }

  function initSamepageCommentNavigation() {
    $("article.msg .title a[data-samepage]").click(function(event) {
      event.preventDefault();
      location.hash = "comment-" + this.search.substr(5);
    })
  }

  function initScollupButton() {
    var backButton = $('<button id="ft-back-button">');

    backButton.text("Вверх");

    backButton.click(function() {
      $("html, body").animate({ scrollTop: 0 });
    });

    $('#ft').prepend(backButton);
  }

  function initUpdateEventsCount() {
    function update_count() {
      $.ajax({
        url: "/notifications-count",
        cache: false
      }).success(function(data) {
        var value = data==0 ? "" : ("("+data+")" );

        $('#main_events_count').text(value);
      });
    }

    $(function() {
      if ($('#main_events_count').length>0) {
        update_count();
      }
    });
  }

  initCtrlEnter();
  initUpdateEventsCount();

  initSamepageCommentNavigation();
  initScollupButton();
});

<commit_msg>fix ios media query<commit_after>/*
 * Copyright 1998-2015 Linux.org.ru
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

function initNextPrevKeys() {
  $script.ready('plugins', function () {
    $(function () {
      function jump(link) {
        if (link && link.href) {
          document.location = link.href;
        }
      }

      if (typeof  jQuery.hotkeys !== 'undefined') {
        $(document).bind('keydown', {combi: 'Ctrl+left', disableInInput: true}, function () {
          jump(document.getElementById('PrevLink'))
        });
        $(document).bind('keydown', {combi: 'Ctrl+right', disableInInput: true}, function () {
          jump(document.getElementById('NextLink'))
        });
      }
    })
  });
}

function initStarPopovers() {
  $script.ready('plugins', function () {
    $(function () {
      $("#favs_button").click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        $("#memories_button").popover('hide');
        $("#favs_button").popover('show');
      });
      $("#favs_button").popover({
        content: "Для добавления в избранное надо залогиниться!",
        autoReposition: false,
        trigger: 'manual'
      });

      $("#memories_button").click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        $("#favs_button").popover('hide');
        $("#memories_button").popover('show');
      });
      $("#memories_button").popover({
        content: "Для добавления в отслеживаемое надо залогиниться!",
        autoReposition: false,
        trigger: 'manual'
      });
    })
  });
}

function init_interpage_adv(ads) {
    $(function() {
        var ad = ads[Math.floor(Math.random() * ads.length)];

        if (ad.type==='flash') {
            $script('/js/jquery.swfobject.1-1-1.min.js', function() {
                $('#interpage-adv').flash({
                    "swf": ad.src,
                    "width": 728,
                    "height": 90
                });
            });
        }

        if (ad.type==='img') {
            var anchor = $('<a>');
            anchor.attr('href', ad.href);
            anchor.attr('target', '_blank');

            var img = $('<img>');
            img.attr('src', ad.src);
            if ('width' in ad) {
                img.attr('width', ad.width);
            } else {
                img.attr('width', 728);
            }

            if ('height' in ad) {
                img.attr('height', ad.height);
            } else {
                img.attr('height', 90);
            }

            anchor.append(img);
            $('#interpage-adv').append(anchor);
        }

        if (ad.type==='rimg') {
            var anchor = $('<a>');
            anchor.attr('href', ad.href);
            anchor.attr('target', '_blank');

            var img = $('<img>');

            if (window.matchMedia("(min-width: 768px)").matches) {
                img.attr('width', 728);
                img.attr('height', 90);
                img.attr('src', ad.img728);
            } else if (window.matchMedia("(min-width: 500px)").matches) {
                img.attr('width', 468);
                img.attr('height', 60);
                img.attr('src', ad.img468);
            } else {
                img.attr('width', 320);
                img.attr('height', 100);
                img.attr('src', ad.img320);
            }

            anchor.append(img);
            $('#interpage-adv').append(anchor);
        }
    });
}

function topic_memories_form_setup(memId, watch, msgid, csrf) {
  function memories_add(event) {
    event.preventDefault();

    $.ajax({
      url: "/memories.jsp",
      type: "POST",
      data: { msgid : msgid, add: "add", watch: event.data.watch, csrf: csrf }
    }).done(function(t) {
       form_setup(t['id'], event.data.watch);
       if (event.data.watch) {
         $('#memories_count').text(t['count']);
       } else {
         $('#favs_count').text(t['count']);
       }
    });
  }

  function memories_remove(event) {
    event.preventDefault();

    $.ajax({
      url: "/memories.jsp",
      type: "POST",
      data: { id : event.data.id, remove: "remove", csrf: csrf }
    }).done(function(t) {
      form_setup(0, event.data.watch);
      if (t>=0) {
        if (event.data.watch) {
          $('#memories_count').text(t);
        } else {
          $('#favs_count').text(t);
        }
      }
    });
  }

  function form_setup(memId, watch) {
    var el;

    if (watch) {
      el = $('#memories_button');
    } else {
      el = $('#favs_button');
    }

    if (memId==0) {
      el.removeClass('selected');
      el.attr('title', watch?"Отслеживать":"В избранное");

      el.unbind("click", memories_remove);
      el.bind("click", {watch: watch}, memories_add);
    } else {
      el.addClass('selected');
      el.attr('title', watch?"Не отслеживать":"Удалить из избранного");

      el.unbind("click", memories_add);
      el.bind("click", {watch: watch, id: memId}, memories_remove);
    }
  }

  $(function () {
    form_setup(memId, watch);
  });
}

function tag_memories_form_setup(tag, csrf_token) {
  $script.ready('plugins', function() {
    $(function() {
      $("#tagFavNoth").click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        $("#tagFavNoth").popover('show');
      }).popover({
        content: "Для добавления в избранное надо залогиниться!"
      });

      $("#tagIgnNoth").click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        $("#tagIgnNoth").popover('show');
      }).popover({
        content: "Для добавления в список игнорирования надо залогиниться!"
      });
    });
  });

  $(function() {
    function tag_filter(event) {
      event.preventDefault();

      var data = { tagName: tag};

      var el = $('#tagFavAdd');
      var add = !el.hasClass("selected");

      if (add) {
        data['add'] = 'add';
      } else {
        data['del'] = 'del';
      }

      data['csrf'] = csrf_token;

      $.ajax({
        url: "/user-filter/favorite-tag",
        type: "POST",
        dataType: "json",
        data: data
      }).done(function (t) {
            if (t.error) {
              alert(t.error);
            } else {
              el.attr('title', add ? "Удалить из избранного" : "В избранное");

              $('#favsCount').text(t['count']);

              if (add) {
                el.addClass("selected");
              } else {
                el.removeClass("selected");
              }
            }
          });
    }

    $("#tagFavAdd").bind("click", tag_filter);
  });

  $(function() {
    function tag_ignore(event) {
      event.preventDefault();

      var data = { tagName: tag};

      var el = $('#tagIgnore');
      var add = !el.hasClass("selected");

      if (add) {
        data['add'] = 'add';
      } else {
        data['del'] = 'del';
      }

      data['csrf'] = csrf_token;

      $.ajax({
        url: "/user-filter/ignore-tag",
        type: "POST",
        dataType: "json",
        data: data
      }).done(function (t) {
            if (t.error) {
              alert(t.error);
            } else {
              el.attr('title', add ? "Перестать игнорировать" : "Игнорировать");

              $('#ignoreCount').text(t['count']);

              if (add) {
                el.addClass("selected");
              } else {
                el.removeClass("selected");
              }
            }
          });
    }

    $("#tagIgnore").bind("click", tag_ignore);
  });

}

$script.ready('plugins', function() {
  function initLoginForm() {
    var options = {
      type:"post",
      dataType:"json",
      xhrFields: {
        withCredentials: true
      },
      success:function (response, status) {
        if (response.loggedIn) {
          window.location.reload();
        } else {
          alert("Ошибка авторизации. Неправильное имя пользователя, e-mail или пароль.");
          window.location = "/login.jsp";
        }
      },
      error:function (response, status) {
        alert("Ошибка авторизации. Неправильное имя пользователя, e-mail или пароль.");
        window.location = "/login.jsp";
      }
    };

    if (location.protocol === 'https:') {
      $('#regform').ajaxForm(options);

      $('#loginbutton').bind('click', function(e) {
        $("#regmenu").fadeOut("fast", function() {
          $("#regform").fadeIn("fast", function() {
            $("#regform input[name='nick']").focus();
          });
        });
        return false;
      });

      $('#hide_loginbutton').bind('click', function(e) {
        $("#regform").fadeOut("fast", function() {
          $("#regmenu").fadeIn("fast");
        });
        return false;
      });
    }
  }

  $(function() {
    initLoginForm();
  });
});

$(document).ready(function() {
  function initCtrlEnter() {
    function ctrl_enter(e, form) {
        if (((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey||e.metaKey)) {
          window.onbeforeunload = null;

          $(form).submit();

          return false;
        }
    }

    $('textarea').bind('keypress', function(e) {
      ctrl_enter(e, e.target.form);
    });
  }

  function initSamepageCommentNavigation() {
    $("article.msg .title a[data-samepage]").click(function(event) {
      event.preventDefault();
      location.hash = "comment-" + this.search.substr(5);
    })
  }

  function initScollupButton() {
    var backButton = $('<button id="ft-back-button">');

    backButton.text("Вверх");

    backButton.click(function() {
      $("html, body").animate({ scrollTop: 0 });
    });

    $('#ft').prepend(backButton);
  }

  function initUpdateEventsCount() {
    function update_count() {
      $.ajax({
        url: "/notifications-count",
        cache: false
      }).success(function(data) {
        var value = data==0 ? "" : ("("+data+")" );

        $('#main_events_count').text(value);
      });
    }

    $(function() {
      if ($('#main_events_count').length>0) {
        update_count();
      }
    });
  }

  initCtrlEnter();
  initUpdateEventsCount();

  initSamepageCommentNavigation();
  initScollupButton();
});

<|endoftext|>