<commit_before>var window_rails = {alert: {}, info: {}, confirm: {action: {}}, loading: {}, configuration: {}};

/**
 * Access configuration
 *
 * @param key [String] configuration name
 * @param default_value [Object] default value if no value found
 * @return [Object]
 **/
window_rails.config = function(key, default_value){
  if(window_rails.configuration[key] == undefined){
    return default_value;
  } else {
    return window_rails.configuration[key];
  }
}

/**
 * Generate internal name
 *
 * @param name [String]
 * @return [String] internal name
 **/
window_rails.namer = function(name){
  return 'window-rails-' + name;
}

/**
 * Generate DOM ID for name
 *
 * @param name [String]
 * @return [String] DOM ID
 **/
window_rails.dom_ider = function(name){
  return '#' + window_rails.namer(name);
}

/**
 * Provide window DOM element for name
 *
 * @param name [String]
 * @return [jQuery Element]
 **/
window_rails.window_for = function(name){
  return $(window_rails.dom_ider(name));
}

/**
 * Create a new window
 *
 * @param args [Hash]
 * @option args [String] :name window name
 * @option args [String] :title
 * @option args [String] :content
 * @option args [String] :size size of window (large or small)
 **/
window_rails.create_window = function(args){
  if(window_rails.window_for(args.name).length == 0){
    window_rails.initialize_window(args);
  }
}

/**
 * Open a window
 *
 * @param name [String] window name
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 * @option args [true,false] :esc_close allow escape key window close
 * @option args [true,false] :show show by default
 * @option args [true,false] :backdrop show backdrop
 * @option args [true,false] :static_backdrop do not allow backdrop click close
 **/
window_rails.open_window = function(name, args){
  if(args){
    if(args.title){
      $(window_rails.dom_ider(name) + ' .modal-title').html(args.title);
    }
    if(args.content){
      $(window_rails.dom_ider(name) + ' .modal-body').html(args.content);
    }
  }

  backdrop = args.backdrop == undefined ? true : args.backdrop;
  if(backdrop && args.static_backdrop){
    backdrop = 'static';
  }

  window_rails.window_for(name).modal({
    keyboard: args.esc_close == undefined ? window_rails.config('default_esc_close', true) : args.esc_close,
    show: args.show == undefined ? window_rails.config('default_open_show', true) : args.show,
    backdrop: backdrop
  });
}

/**
 * Close window
 *
 * @param name [String] window name
 **/
window_rails.close_window = function(name){
  window_rails.window_for(name).modal('hide');
}

/**
 * Open alert window
 *
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 **/
window_rails.alert.open = function(args){
  args.static_backdrop = true;
  window_rails.open_window('alert', args);
}

/**
 * Close alert window
 **/
window_rails.alert.close = function(){
  window_rails.close_window('alert');
}

/**
 * Open info window
 *
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 * @option args [Integer] :auto_close close info after given seconds
 **/
window_rails.info.open = function(args){
  window_rails.open_window('info', args);
  if(args.auto_close){
    setTimeout(
      function(){ window_rails.info.close(); },
      args.auto_close * 1000
    )
  }
}

/**
 * Close info window
 **/
window_rails.info.close = function(){
  window_rails.close_window('info');
}

/**
 * Open confirm window
 *
 * @param args [Hash]
 * @option args [String] :title content for title
 * @option args [String] :content content for content
 * @option args [String] :url URL to load on acceptance
 * @option args [String] :ajax AJAX method to use (get, post, etc)
 * @option args [String] :progress title for loading window while in progres
 * @option args [String] :complete content for info window upon completion
 **/
window_rails.confirm.open = function(args){
  window_rails.confirm.action = args;
  args.static_backdrop = true;
  window_rails.open_window('confirm', args);
}

/**
 * Close confirm window
 **/
window_rails.confirm.close = function(){
  window_rails.close_window('confirm');
}

/**
 * Execute defined action for confirmation
 **/
window_rails.confirm.execute = function(){
  args = window_rails.confirm.action;
  window_rails.confirm.close();
  window_rails.confirm.action = {};
  window_rails.loading.open({
    title: args.progress
  });
  if(args.ajax){
    $.ajax({
      url: args.url,
      type: args.ajax.toUpperCase()
    }).error(function(data, status){
      window_rails.loading.close();
      if(args.error){
        msg = args.error;
      } else {
        msg = data.responseText;
      }
      window_rails.alert.open({
        title: args.title,
        content: msg
      });
    }).success(function(data){
      window_rails.loading.close();
      window_rails.info.open({
        title: args.title,
        content: args.complete || 'Action complete',
        auto_close: window_rails.config('confirm_info_auto_close', 5)
      });
    });
  } else {
    document.location = args.url;
  }
}

/**
 * Open loading window
 *
 * @param style [String] style of spinner (valid class in csspinner or progress)
 * @param title [String] title of window
 **/
window_rails.loading.open = function(style, title){
  if(style){
    if(typeof style === 'object'){
      title = style.title;
      style = style.style;
    }
  }
  if(!style){
    style = 'standard';
  }
  if(style == 'progress'){
    content = '

';
  } else {
    content = '
';
  }
  window_rails.open_window('loading', {
    esc_close: false,
    title: title,
    static_backdrop: true,
    content: content
  });
  if(style == 'progress'){
    window_rails.loading.progress_look_busy();
  }
}

/**
 * Start progress bar busy action on loading display
 **/
window_rails.loading.progress_look_busy = function(){
  $('body').data(
    'window-rails-loading-progress',
    window_rails.config('loading_progress_increments', 3)
  );
  window_rails.loading.run_look_busy();
}

/**
 * Perform busy action
 * @note this should generally not be called directly
 * @see window_rails.loading.progress_look_busy
 **/
window_rails.loading.run_look_busy = function(){
  setTimeout(function(){
    allowed_max = window_rails.config('loading_progress_max', 90);
    elm = $('#window-rails-loading .progress-bar-info');
    if(elm.length > 0){
      completed = Number(elm.attr('aria-valuenow'));
      busy_by = $('body').data('window-rails-loading-progress');
      addition = (100 - completed) / busy_by;
      if(busy_by < 9){
        $('body').data('window-rails-loading-progress', busy_by / 0.75);
      }
      completed_now = completed + addition;
      if(completed_now > allowed_max){
        completed_now = allowed_max;
      }
      elm.attr('aria-valuenow', completed_now);
      elm.attr('style', 'width: ' + completed_now + '%');
      window_rails.loading.run_look_busy();
    }
  }, 2500);
}

/**
 * Close loading window
 **/
window_rails.loading.close = function(){
  window_rails.close_window('loading');
}

/**
 * Initialize a new window. Creates DOM elements required for modal.
 *
 * @param args [Hash]
 * @option args [String] :name window name
 * @option args [String] :size large or small
 * @option args [String] :title
 * @option args [String] :content
 * @option args [String] :footer
 **/
window_rails.initialize_window = function(args){
  if(!args.name){
    throw new Error('Name must be set when initializing a new window!');
  }
  name = window_rails.namer(args.name);
  if(args.size == 'large'){
    size = 'lg';
  } else {
    size = window_rails.config('default_size', 'sm');
  }
  if(args.footer){
    footer = '\

\
        ' + args.footer + '\

\
    ';
  } else {
    footer = '';
  }
  $('#window-rails-container').append('\

\

\

\

\
            <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
              ×\
            </button>\

' + args.title + '
\

\

\
            ' + args.content + '\

\

\

\

\
  ');
}

/**
 * Initialize the document for window rails
 **/
window_rails.init = function(){
  if(!window_rails.initialized){
    $('body').append('\

\

\

\

\

\
                <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
                  ×\
                </button>\

Alert
\

\

\
                Alert message\

\

\

\

\

\

\

\

\
                <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
                  ×\
                </button>\

Info
\

\

\
                Information message\

\

\

\

\

\

\

\

\

Confirm
\

\

\
                Please confirm!\

\

\
                <button type="button" class="btn btn-danger window-rails-confirm-cancel">Cancel</button>\
                <button type="button" class="btn btn-success window-rails-confirm-ok">OK</button>\

\

\

\

\

\

\

\

\

\
                Loading...\

\

\

\

\

\

\

\

\
    ');
    window_rails.hooks();
    window_rails.initialized = true
  }
}

/**
 * Hook into interesting events
 **/
window_rails.hooks = function(){
  $('.window-rails').on('click', function(){
    window_rails.confirm.open({
      title: $(this).attr('window-rails-title'),
      content: $(this).attr('window-rails-confirm'),
      ajax: $(this).attr('window-rails-ajax'),
      url: $(this).attr('window-rails-url'),
      progress: $(this).attr('window-rails-progress'),
      complete: $(this).attr('window-rails-complete'),
      error: $(this).attr('window-rails-error')
    });
  });
  $('.window-rails-confirm-cancel').on('click', function(){
    window_rails.confirm.action = {};
    window_rails.confirm.close();
  });
  $('.window-rails-confirm-ok').on('click', window_rails.confirm.execute);
}

// Initialize once page has loaded
$(document).ready(window_rails.init);<commit_msg>If no title is provided, default so we don't persist previous title<commit_after>var window_rails = {alert: {}, info: {}, confirm: {action: {}}, loading: {}, configuration: {}};

/**
 * Access configuration
 *
 * @param key [String] configuration name
 * @param default_value [Object] default value if no value found
 * @return [Object]
 **/
window_rails.config = function(key, default_value){
  if(window_rails.configuration[key] == undefined){
    return default_value;
  } else {
    return window_rails.configuration[key];
  }
}

/**
 * Generate internal name
 *
 * @param name [String]
 * @return [String] internal name
 **/
window_rails.namer = function(name){
  return 'window-rails-' + name;
}

/**
 * Generate DOM ID for name
 *
 * @param name [String]
 * @return [String] DOM ID
 **/
window_rails.dom_ider = function(name){
  return '#' + window_rails.namer(name);
}

/**
 * Provide window DOM element for name
 *
 * @param name [String]
 * @return [jQuery Element]
 **/
window_rails.window_for = function(name){
  return $(window_rails.dom_ider(name));
}

/**
 * Create a new window
 *
 * @param args [Hash]
 * @option args [String] :name window name
 * @option args [String] :title
 * @option args [String] :content
 * @option args [String] :size size of window (large or small)
 **/
window_rails.create_window = function(args){
  if(window_rails.window_for(args.name).length == 0){
    window_rails.initialize_window(args);
  }
}

/**
 * Open a window
 *
 * @param name [String] window name
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 * @option args [true,false] :esc_close allow escape key window close
 * @option args [true,false] :show show by default
 * @option args [true,false] :backdrop show backdrop
 * @option args [true,false] :static_backdrop do not allow backdrop click close
 **/
window_rails.open_window = function(name, args){
  if(args){
    if(args.title){
      $(window_rails.dom_ider(name) + ' .modal-title').html(args.title);
    }
    if(args.content){
      $(window_rails.dom_ider(name) + ' .modal-body').html(args.content);
    }
  }

  backdrop = args.backdrop == undefined ? true : args.backdrop;
  if(backdrop && args.static_backdrop){
    backdrop = 'static';
  }

  window_rails.window_for(name).modal({
    keyboard: args.esc_close == undefined ? window_rails.config('default_esc_close', true) : args.esc_close,
    show: args.show == undefined ? window_rails.config('default_open_show', true) : args.show,
    backdrop: backdrop
  });
}

/**
 * Close window
 *
 * @param name [String] window name
 **/
window_rails.close_window = function(name){
  window_rails.window_for(name).modal('hide');
}

/**
 * Open alert window
 *
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 **/
window_rails.alert.open = function(args){
  args.static_backdrop = true;
  window_rails.open_window('alert', args);
}

/**
 * Close alert window
 **/
window_rails.alert.close = function(){
  window_rails.close_window('alert');
}

/**
 * Open info window
 *
 * @param args [Hash]
 * @option args [String] :title
 * @option args [String] :content
 * @option args [Integer] :auto_close close info after given seconds
 **/
window_rails.info.open = function(args){
  window_rails.open_window('info', args);
  if(args.auto_close){
    setTimeout(
      function(){ window_rails.info.close(); },
      args.auto_close * 1000
    )
  }
}

/**
 * Close info window
 **/
window_rails.info.close = function(){
  window_rails.close_window('info');
}

/**
 * Open confirm window
 *
 * @param args [Hash]
 * @option args [String] :title content for title
 * @option args [String] :content content for content
 * @option args [String] :url URL to load on acceptance
 * @option args [String] :ajax AJAX method to use (get, post, etc)
 * @option args [String] :progress title for loading window while in progres
 * @option args [String] :complete content for info window upon completion
 **/
window_rails.confirm.open = function(args){
  window_rails.confirm.action = args;
  args.static_backdrop = true;
  window_rails.open_window('confirm', args);
}

/**
 * Close confirm window
 **/
window_rails.confirm.close = function(){
  window_rails.close_window('confirm');
}

/**
 * Execute defined action for confirmation
 **/
window_rails.confirm.execute = function(){
  args = window_rails.confirm.action;
  window_rails.confirm.close();
  window_rails.confirm.action = {};
  window_rails.loading.open({
    title: args.progress
  });
  if(args.ajax){
    $.ajax({
      url: args.url,
      type: args.ajax.toUpperCase()
    }).error(function(data, status){
      window_rails.loading.close();
      if(args.error){
        msg = args.error;
      } else {
        msg = data.responseText;
      }
      window_rails.alert.open({
        title: args.title,
        content: msg
      });
    }).success(function(data){
      window_rails.loading.close();
      window_rails.info.open({
        title: args.title,
        content: args.complete || 'Action complete',
        auto_close: window_rails.config('confirm_info_auto_close', 5)
      });
    });
  } else {
    document.location = args.url;
  }
}

/**
 * Open loading window
 *
 * @param style [String] style of spinner (valid class in csspinner or progress)
 * @param title [String] title of window
 **/
window_rails.loading.open = function(style, title){
  if(style){
    if(typeof style === 'object'){
      title = style.title;
      style = style.style;
    }
  }
  if(!style){
    style = 'standard';
  }
  if(!title){
    title = 'Loading...';
  }
  if(style == 'progress'){
    content = '

';
  } else {
    content = '
';
  }
  window_rails.open_window('loading', {
    esc_close: false,
    title: title,
    static_backdrop: true,
    content: content
  });
  if(style == 'progress'){
    window_rails.loading.progress_look_busy();
  }
}

/**
 * Start progress bar busy action on loading display
 **/
window_rails.loading.progress_look_busy = function(){
  $('body').data(
    'window-rails-loading-progress',
    window_rails.config('loading_progress_increments', 3)
  );
  window_rails.loading.run_look_busy();
}

/**
 * Perform busy action
 * @note this should generally not be called directly
 * @see window_rails.loading.progress_look_busy
 **/
window_rails.loading.run_look_busy = function(){
  setTimeout(function(){
    allowed_max = window_rails.config('loading_progress_max', 90);
    elm = $('#window-rails-loading .progress-bar-info');
    if(elm.length > 0){
      completed = Number(elm.attr('aria-valuenow'));
      busy_by = $('body').data('window-rails-loading-progress');
      addition = (100 - completed) / busy_by;
      if(busy_by < 9){
        $('body').data('window-rails-loading-progress', busy_by / 0.75);
      }
      completed_now = completed + addition;
      if(completed_now > allowed_max){
        completed_now = allowed_max;
      }
      elm.attr('aria-valuenow', completed_now);
      elm.attr('style', 'width: ' + completed_now + '%');
      window_rails.loading.run_look_busy();
    }
  }, 2500);
}

/**
 * Close loading window
 **/
window_rails.loading.close = function(){
  window_rails.close_window('loading');
}

/**
 * Initialize a new window. Creates DOM elements required for modal.
 *
 * @param args [Hash]
 * @option args [String] :name window name
 * @option args [String] :size large or small
 * @option args [String] :title
 * @option args [String] :content
 * @option args [String] :footer
 **/
window_rails.initialize_window = function(args){
  if(!args.name){
    throw new Error('Name must be set when initializing a new window!');
  }
  name = window_rails.namer(args.name);
  if(args.size == 'large'){
    size = 'lg';
  } else {
    size = window_rails.config('default_size', 'sm');
  }
  if(args.footer){
    footer = '\

\
        ' + args.footer + '\

\
    ';
  } else {
    footer = '';
  }
  $('#window-rails-container').append('\

\

\

\

\
            <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
              ×\
            </button>\

' + args.title + '
\

\

\
            ' + args.content + '\

\

\

\

\
  ');
}

/**
 * Initialize the document for window rails
 **/
window_rails.init = function(){
  if(!window_rails.initialized){
    $('body').append('\

\

\

\

\

\
                <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
                  ×\
                </button>\

Alert
\

\

\
                Alert message\

\

\

\

\

\

\

\

\
                <button class="close" type="button" data-dismiss="modal" aria-hidden="true">\
                  ×\
                </button>\

Info
\

\

\
                Information message\

\

\

\

\

\

\

\

\

Confirm
\

\

\
                Please confirm!\

\

\
                <button type="button" class="btn btn-danger window-rails-confirm-cancel">Cancel</button>\
                <button type="button" class="btn btn-success window-rails-confirm-ok">OK</button>\

\

\

\

\

\

\

\

\

\
                Loading...\

\

\

\

\

\

\

\

\
    ');
    window_rails.hooks();
    window_rails.initialized = true
  }
}

/**
 * Hook into interesting events
 **/
window_rails.hooks = function(){
  $('.window-rails').on('click', function(){
    window_rails.confirm.open({
      title: $(this).attr('window-rails-title'),
      content: $(this).attr('window-rails-confirm'),
      ajax: $(this).attr('window-rails-ajax'),
      url: $(this).attr('window-rails-url'),
      progress: $(this).attr('window-rails-progress'),
      complete: $(this).attr('window-rails-complete'),
      error: $(this).attr('window-rails-error')
    });
  });
  $('.window-rails-confirm-cancel').on('click', function(){
    window_rails.confirm.action = {};
    window_rails.confirm.close();
  });
  $('.window-rails-confirm-ok').on('click', window_rails.confirm.execute);
}

// Initialize once page has loaded
$(document).ready(window_rails.init);<|endoftext|>


<commit_before>'use strict';

const PSQL = require('cartodb-psql');
const copyTo = require('pg-copy-streams').to;
const copyFrom = require('pg-copy-streams').from;

const ACTION_TO = 'to';
const ACTION_FROM = 'from';
const DEFAULT_TIMEOUT = "'5h'";

const cancelQuery = pid => `SELECT pg_cancel_backend(${pid}) as cancelled`;
const terminateQuery = pid => `SELECT pg_terminate_backend(${pid}) as terminated`;
const timeoutQuery = timeout => `SET statement_timeout=${timeout}`;

module.exports = class StreamCopy {
    constructor(sql, userDbParams, logger) {
        this.dbParams = Object.assign({}, userDbParams, {
            port: global.settings.db_batch_port || userDbParams.port
        });
        this.sql = sql;
        this.stream = null;
        this.timeout = global.settings.copy_timeout || DEFAULT_TIMEOUT;
        this.logger = logger;
    }

    static get ACTION_TO() {
        return ACTION_TO;
    }

    static get ACTION_FROM() {
        return ACTION_FROM;
    }

    getPGStream(action, callback) {
        this.action = action;
        const pg = new PSQL(this.dbParams);

        pg.connect((err, client, done) => {
            if (err) {
                return callback(err);
            }

            client.query(timeoutQuery(this.timeout), (err) => {
                if (err) {
                    return callback(err);
                }

                this.clientProcessID = client.processID;

                this.stream = action === ACTION_TO ? copyTo(this.sql) : copyFrom(this.sql);

                const pgstream = client.query(this.stream);

                if (action === ACTION_TO) {
                    pgstream.on('end', () => done());
                } else if (action === ACTION_FROM) {
                    pgstream.on('finish', () => done());
                }

                pgstream.on('error', err => {
                    this._cancel(client.processID, action);
                    done(err);
                });

                callback(null, pgstream);
            });
        });
    }

    getRowCount() {
        return this.stream.rowCount;
    }

    _cancel (pid, action) {
        const pg = new PSQL(this.dbParams);
        const actionType = action === ACTION_TO ? ACTION_TO : ACTION_FROM;

        pg.query(cancelQuery(pid), (err, result) => {
            if (err) {
                return this.logger.error(err);
            }

            const isCancelled = result.rows.length && result.rows[0].cancelled;

            if (isCancelled) {
                return this.logger.info(`Canceled "copy ${actionType}" stream query successfully (pid: ${pid})`);
            }

            return pg.query(terminateQuery(pid), (err, result) => {
                if (err) {
                    return this.logger.error(err);
                }

                const isTerminated = result.rows.length && result.rows[0].terminated;

                if (!isTerminated) {
                    return this.logger.error(
                        new Error(`Unable to terminate "copy ${actionType}" stream query (pid: ${pid})`)
                    );
                }

                return this.logger.info(`Terminated "copy ${actionType}" stream query successfully (pid: ${pid})`);
            });
        });
    }
};
<commit_msg>Remove unused reference<commit_after>'use strict';

const PSQL = require('cartodb-psql');
const copyTo = require('pg-copy-streams').to;
const copyFrom = require('pg-copy-streams').from;

const ACTION_TO = 'to';
const ACTION_FROM = 'from';
const DEFAULT_TIMEOUT = "'5h'";

const cancelQuery = pid => `SELECT pg_cancel_backend(${pid}) as cancelled`;
const terminateQuery = pid => `SELECT pg_terminate_backend(${pid}) as terminated`;
const timeoutQuery = timeout => `SET statement_timeout=${timeout}`;

module.exports = class StreamCopy {
    constructor(sql, userDbParams, logger) {
        this.dbParams = Object.assign({}, userDbParams, {
            port: global.settings.db_batch_port || userDbParams.port
        });
        this.sql = sql;
        this.stream = null;
        this.timeout = global.settings.copy_timeout || DEFAULT_TIMEOUT;
        this.logger = logger;
    }

    static get ACTION_TO() {
        return ACTION_TO;
    }

    static get ACTION_FROM() {
        return ACTION_FROM;
    }

    getPGStream(action, callback) {
        const pg = new PSQL(this.dbParams);

        pg.connect((err, client, done) => {
            if (err) {
                return callback(err);
            }

            client.query(timeoutQuery(this.timeout), (err) => {
                if (err) {
                    return callback(err);
                }

                this.clientProcessID = client.processID;

                this.stream = action === ACTION_TO ? copyTo(this.sql) : copyFrom(this.sql);

                const pgstream = client.query(this.stream);

                if (action === ACTION_TO) {
                    pgstream.on('end', () => done());
                } else if (action === ACTION_FROM) {
                    pgstream.on('finish', () => done());
                }

                pgstream.on('error', err => {
                    this._cancel(client.processID, action);
                    done(err);
                });

                callback(null, pgstream);
            });
        });
    }

    getRowCount() {
        return this.stream.rowCount;
    }

    _cancel (pid, action) {
        const pg = new PSQL(this.dbParams);
        const actionType = action === ACTION_TO ? ACTION_TO : ACTION_FROM;

        pg.query(cancelQuery(pid), (err, result) => {
            if (err) {
                return this.logger.error(err);
            }

            const isCancelled = result.rows.length && result.rows[0].cancelled;

            if (isCancelled) {
                return this.logger.info(`Canceled "copy ${actionType}" stream query successfully (pid: ${pid})`);
            }

            return pg.query(terminateQuery(pid), (err, result) => {
                if (err) {
                    return this.logger.error(err);
                }

                const isTerminated = result.rows.length && result.rows[0].terminated;

                if (!isTerminated) {
                    return this.logger.error(
                        new Error(`Unable to terminate "copy ${actionType}" stream query (pid: ${pid})`)
                    );
                }

                return this.logger.info(`Terminated "copy ${actionType}" stream query successfully (pid: ${pid})`);
            });
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

/* Widget directives */
angular.module('arachne.widgets.directives')

/**
 * @author: Sebastian Cuy
 */
.directive('con10tTree', ['Query', 'Entity', '$location', function(Query, Entity, $location) {
    return {
        restrict: 'E',
        templateUrl: 'partials/widgets/con10t-tree.html',
        scope: {},
        link: function(scope, element, attrs) {
            scope.staticFacets = [];
            if (!attrs.fq) return;

            var fq_facets = attrs.fq.split(',');
            for (var i = 0; i < fq_facets.length; i++) {
                scope.staticFacets.push(fq_facets[i].split(':'));
            }
            scope.wildcardFacet = attrs.wildcardFacet;
            scope.hierarchyFacets = [];

            if (attrs.hierarchyFacets)
                scope.hierarchyFacets = attrs.hierarchyFacets.split(',');

            // in the UI, the tree starts with the last provided static facet's name
            scope.treeRoot = [{
                name: scope.staticFacets[scope.staticFacets.length - 1][1],
                depth: 0,
                children: [],
                facet: null,
                parent: null,
                id: "0"
            }];
            scope.isShown = {};

            scope.getNodeChildren = function(node) {

                // TODO add proper object check
                if (node.children != 0) {
                    return;
                }

                var treeQuery = new Query();

                for (var i = 0; i < scope.staticFacets.length; i++) {
                    treeQuery = treeQuery.addFacet(scope.staticFacets[i][0], scope.staticFacets[i][1]);
                }

                var collectedFacets = this.collectAllFacets(node);

                for (var i = 0; i < collectedFacets.length; i++) {
                    treeQuery = treeQuery.addFacet(collectedFacets[i][0], collectedFacets[i][1]);
                }

                treeQuery.q = "*";
                treeQuery.limit = 0;

                // sorting of facet values
                if (scope.hierarchyFacets.length > 0) {
                    treeQuery.sf = scope.hierarchyFacets[node.depth];
                } else if (scope.wildcardFacet && collectedFacets.length > 0) {
                    var lastFacet = collectedFacets[0][0];
                    var lvl = parseInt(lastFacet[lastFacet.length-1]) + 1;
                    treeQuery.sf = lastFacet.substr(0, lastFacet.length-1) + lvl;
                }

                Entity.query(treeQuery.toFlatObject(), function(response) {

                    if (!response.facets) {
                        console.error('[con10t_tree.js] No facets in response because of missing user rights or wrong facet query.');
                        return false;
                    }

                    for (var i = 0; i < response.facets.length; i++) {

                        var currentResultFacet = response.facets[i];

                        console.log(currentResultFacet)
                        // try to find custom hierarchy-facet or wildcard
                        if ((scope.hierarchyFacets.length > 0 && currentResultFacet.name == (scope.hierarchyFacets[node.depth]))
                                || (scope.wildcardFacet && currentResultFacet.name.indexOf(scope.wildcardFacet) > -1)) {

                            console.log(currentResultFacet)

                            for (var j = 0; j < currentResultFacet.values.length; j++) {
                                var value = currentResultFacet.values[j].value;
                                var child = {
                                    name: value,
                                    depth: node.depth + 1,
                                    children: [],
                                    facet: [currentResultFacet.name, value],
                                    parent: node,
                                    id: node.id + "_" + j
                                };
                                node.children.push(child);
                            }
                        }
                    }
                    if (node.children == 0) {
                        node.isLeaf = true;
                    }
                    scope.isShown[node.id] = true;
                });
            };

            scope.collectAllFacets = function(node) {
                var result = [];
                if (node.parent != null) {
                    result.push(node.facet);
                    result = result.concat(this.collectAllFacets(node.parent));
                    return result;
                }
                return result;
            };

            scope.toggleCollapse = function(node) {
                scope.isShown[node.id] = !scope.isShown[node.id];
                if (scope.isShown[node.id]) {
                    this.getNodeChildren(node);
                }
            };
            scope.checkIfShown = function(node) {
                return scope.isShown[node.id]; // at first load -> undefined, so it gets hidden but: ugly?
            };

            scope.closeAll = function() {
                for (var key in scope.isShown)
                    scope.isShown[key] = false;
            };

            scope.startFacetedSearch = function(node) {
                var facets = this.collectAllFacets(node);

                facets = facets.concat(scope.staticFacets);

                var url = "search/?q=*";

                for (var i = 0; i < facets.length; i++) {
                    url += "&fq=" + facets[i][0] + ':"' + facets[i][1] + '"';
                }

                $location.url(url);
            };

            scope.toggleCollapse(scope.treeRoot[0]);

        }
    }
}]);<commit_msg>Fix fckng wrong assembly of search url in con10 tree widget (closes #2764).<commit_after>'use strict';

/* Widget directives */
angular.module('arachne.widgets.directives')

/**
 * @author: Sebastian Cuy
 */
.directive('con10tTree', ['Query', 'Entity', '$location', function(Query, Entity, $location) {
    return {
        restrict: 'E',
        templateUrl: 'partials/widgets/con10t-tree.html',
        scope: {},
        link: function(scope, element, attrs) {
            scope.staticFacets = [];
            if (!attrs.fq) return;

            var fq_facets = attrs.fq.split(',');
            for (var i = 0; i < fq_facets.length; i++) {
                scope.staticFacets.push(fq_facets[i].split(':'));
            }
            scope.wildcardFacet = attrs.wildcardFacet;
            scope.hierarchyFacets = [];

            if (attrs.hierarchyFacets)
                scope.hierarchyFacets = attrs.hierarchyFacets.split(',');

            // in the UI, the tree starts with the last provided static facet's name
            scope.treeRoot = [{
                name: scope.staticFacets[scope.staticFacets.length - 1][1],
                depth: 0,
                children: [],
                facet: null,
                parent: null,
                id: "0"
            }];
            scope.isShown = {};

            scope.getNodeChildren = function(node) {

                // TODO add proper object check
                if (node.children != 0) {
                    return;
                }

                var treeQuery = new Query();

                for (var i = 0; i < scope.staticFacets.length; i++) {
                    treeQuery = treeQuery.addFacet(scope.staticFacets[i][0], scope.staticFacets[i][1]);
                }

                var collectedFacets = this.collectAllFacets(node);

                for (var i = 0; i < collectedFacets.length; i++) {
                    treeQuery = treeQuery.addFacet(collectedFacets[i][0], collectedFacets[i][1]);
                }

                treeQuery.q = "*";
                treeQuery.limit = 0;

                // sorting of facet values
                if (scope.hierarchyFacets.length > 0) {
                    treeQuery.sf = scope.hierarchyFacets[node.depth];
                } else if (scope.wildcardFacet && collectedFacets.length > 0) {
                    var lastFacet = collectedFacets[0][0];
                    var lvl = parseInt(lastFacet[lastFacet.length-1]) + 1;
                    treeQuery.sf = lastFacet.substr(0, lastFacet.length-1) + lvl;
                }

                Entity.query(treeQuery.toFlatObject(), function(response) {

                    if (!response.facets) {
                        console.error('[con10t_tree.js] No facets in response because of missing user rights or wrong facet query.');
                        return false;
                    }

                    for (var i = 0; i < response.facets.length; i++) {

                        var currentResultFacet = response.facets[i];

                        // try to find custom hierarchy-facet or wildcard
                        if ((scope.hierarchyFacets.length > 0 && currentResultFacet.name == (scope.hierarchyFacets[node.depth]))
                                || (scope.wildcardFacet && currentResultFacet.name.indexOf(scope.wildcardFacet) > -1)) {

                            for (var j = 0; j < currentResultFacet.values.length; j++) {
                                var value = currentResultFacet.values[j].value;
                                var child = {
                                    name: value,
                                    depth: node.depth + 1,
                                    children: [],
                                    facet: [currentResultFacet.name, value],
                                    parent: node,
                                    id: node.id + "_" + j
                                };
                                node.children.push(child);
                            }
                        }
                    }
                    if (node.children == 0) {
                        node.isLeaf = true;
                    }
                    scope.isShown[node.id] = true;
                });
            };

            scope.collectAllFacets = function(node) {
                var result = [];
                if (node.parent != null) {
                    result.push(node.facet);
                    result = result.concat(this.collectAllFacets(node.parent));
                    return result;
                }
                return result;
            };

            scope.toggleCollapse = function(node) {
                scope.isShown[node.id] = !scope.isShown[node.id];
                if (scope.isShown[node.id]) {
                    this.getNodeChildren(node);
                }
            };
            scope.checkIfShown = function(node) {
                return scope.isShown[node.id]; // at first load -> undefined, so it gets hidden but: ugly?
            };

            scope.closeAll = function() {
                for (var key in scope.isShown)
                    scope.isShown[key] = false;
            };

            scope.startFacetedSearch = function(node) {
                var facets = this.collectAllFacets(node);

                facets = facets.concat(scope.staticFacets);

                var url = "search?q=";

                for (var i = 0; i < facets.length; i++) {
                    url += "&fq=" + facets[i][0] + ':"' + facets[i][1] + '"';
                }
                $location.url(url);
            };

            scope.toggleCollapse(scope.treeRoot[0]);

        }
    }
}]);<|endoftext|>


<commit_before>/*
  p.js
*/

var ip_is_in_range = function(val, range){
  if( range[0] <= val && range[1] >= val )
    return true;
  else
    return false;
}

var ip_darken = function(dst, val){
  var roi = ip_get_roi( dst );
  var ch_mask = [];

  console.log( roi );
  console.log(dst);

  for(i=0;i<4;i++){
    ch_mask[i] = ip_get_channel_mask( dst, i );
    console.log( ch_mask[i] );
  }

  for(i=roi[0];i<roi[2];i++){
    for(j=roi[1];j<roi[3];j++){
      var idx = (j * dst.width + i) * 4;

      for(k=IP_R;k<=IP_B;k++){
        if( ip_is_in_range( dst.data[idx+k], ch_mask[k] ) ){
          dst.data[idx+k] = Math.min( dst.data[idx+k]+val, 255 );
        }
      }
    }
  }
}
<commit_msg>Update ip_p.js<commit_after>/*
  p.js
*/

var ip_is_in_range = function(val, range){
  if( range[0] <= val && range[1] >= val )
    return true;
  else
    return false;
}

var ip_lighten = function(dst, val){
  var roi = ip_get_roi( dst );
  var ch_mask = [];

  console.log( roi );
  console.log(dst);

  for(i=0;i<4;i++){
    ch_mask[i] = ip_get_channel_mask( dst, i );
    console.log( ch_mask[i] );
  }

  for(i=roi[0];i<roi[2];i++){
    for(j=roi[1];j<roi[3];j++){
      var idx = (j * dst.width + i) * 4;

      for(k=IP_R;k<=IP_B;k++){
        if( ip_is_in_range( dst.data[idx+k], ch_mask[k] ) ){
          dst.data[idx+k] = Math.min( dst.data[idx+k]+val, 255 );
        }
      }
    }
  }
}
var ip_darken = function(dst, val){
  ip_lighten( dst, -val );
}
<|endoftext|>


<commit_before>(function() {
	window.Customer = function(customerId) {
		this.customerId = customerId;
		this.visitorId = customerId;
		this.users = new Array();
		this.id = null; //Used for socket Id.
		this.webrtcCall = new Call(customerId);
		var self = this;
		this.presenceIndicator = function() {
			heartbeat(self);
			setTimeout(self.presenceIndicator,CUSTOMER_HEARTBEAT);
		}
		this.onMessage = function(message) {
			console.log(message);
		};

		this.onChat = function(message) {
			console.log(message);
			addToChatMessageBox(message.sender,message.sender,message.message);
		};

		this.onPresence = function (message) {
			console.log(message);
			var presenceUser = message.data;
			console.log(self.users);
			for(i in self.users) {
				user=self.users[i];
				if(user.visitorId == presenceUser.visitorId) {
					//currently return.
					//In future we will update that visitor.
					console.log("User already in the list!");
					self.users[i].lastOnline = new Date().getTime();
					if(self.users[i].location == null) {
						console.log('Updating location for visitor' + presenceUser.visitorId);
						self.users[i].location=presenceUser.location;
						$('#'+presenceUser.visitorId).detach();
						$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
						$("#flagIcon"+presenceUser.visitorId).tooltip();
						$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geoplugin_longitude)});
					}
					if(self.users[i].id == null) {
						self.users[i].id = presenceUser.id;
						$('#'+presenceUser.visitorId).detach();
						$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
						$("#flagIcon"+presenceUser.visitorId).tooltip();
						$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geoplugin_longitude)});
					}
					return;
				}
			}
			console.log("Adding new user!");
			presenceUser.lastOnline = new Date().getTime();
			self.users.push(presenceUser);
			$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
			$("#flagIcon"+presenceUser.visitorId).tooltip();
			if(presenceUser.location != null ) {
				$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geolugin_longitude)});
			}
			customer.sendChatMessage(presenceUser.id,presenceUser.visitorId,"We are launching beta on 1/1/14.");
			customer.sendChatMessage(presenceUser.id,presenceUser.visitorId,"To be part of beta launch mail to biplav.saraf@gmail.com");

		};

		this.onCall = function(message) {
			console.log(message);
			self.webrtcCall.onCall(message);
		};

		this.sendChatMessage = function(id,visitorId, chatText) {
			socket.chat(chatText,id);
			console.log('sending chat message to ' + visitorId +' with message ' + chatText);
			$('#chatMsg'+visitorId).val('');
			addToChatMessageBox(visitorId,customerId,chatText);
		};

		this.init = function() {
			initializeSocket(self);
			//self.presenceIndicator();
			self.visitorMonitor();
			//initialize_calling();
		}
		this.visitorMonitor = function() {
			console.log('VISITOR MONITOR');
			for(i in self.users) {
				var user = self.users[i];
				var now = new Date().getTime();
				var timeDiff = now - user.lastOnline;
				//Give a lag in timeDiff for production
				if(timeDiff > VISITOR_MONITOR) {
						console.log("Visitor went offline " + user.visitorId + " at " + now);
						$('#'+user.visitorId).detach();
						self.users.splice(i,1);
					}
			}
			setTimeout(self.visitorMonitor,VISITOR_MONITOR);
		}

		this.audioCall = function(id) {
			self.webrtcCall.call(id,true);
		}
	};
})();<commit_msg>Extra welcome message<commit_after>(function() {
	window.Customer = function(customerId) {
		this.customerId = customerId;
		this.visitorId = customerId;
		this.users = new Array();
		this.id = null; //Used for socket Id.
		this.webrtcCall = new Call(customerId);
		var self = this;
		this.presenceIndicator = function() {
			heartbeat(self);
			setTimeout(self.presenceIndicator,CUSTOMER_HEARTBEAT);
		}
		this.onMessage = function(message) {
			console.log(message);
		};

		this.onChat = function(message) {
			console.log(message);
			addToChatMessageBox(message.sender,message.sender,message.message);
		};

		this.onPresence = function (message) {
			console.log(message);
			var presenceUser = message.data;
			console.log(self.users);
			for(i in self.users) {
				user=self.users[i];
				if(user.visitorId == presenceUser.visitorId) {
					//currently return.
					//In future we will update that visitor.
					console.log("User already in the list!");
					self.users[i].lastOnline = new Date().getTime();
					if(self.users[i].location == null) {
						console.log('Updating location for visitor' + presenceUser.visitorId);
						self.users[i].location=presenceUser.location;
						$('#'+presenceUser.visitorId).detach();
						$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
						$("#flagIcon"+presenceUser.visitorId).tooltip();
						$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geoplugin_longitude)});
					}
					if(self.users[i].id == null) {
						self.users[i].id = presenceUser.id;
						$('#'+presenceUser.visitorId).detach();
						$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
						$("#flagIcon"+presenceUser.visitorId).tooltip();
						$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geoplugin_longitude)});
					}
					return;
				}
			}
			console.log("Adding new user!");
			presenceUser.lastOnline = new Date().getTime();
			self.users.push(presenceUser);
			$("#UserListTemplate").tmpl(presenceUser).appendTo("#userList");
			$("#flagIcon"+presenceUser.visitorId).tooltip();
			if(presenceUser.location != null ) {
				$("#map"+presenceUser.visitorId).popover({content : getMapContent(presenceUser.location.geoplugin_city,presenceUser.location.geoplugin_latitude,presenceUser.location.geolugin_longitude)});
			}
			customer.sendChatMessage(presenceUser.id,presenceUser.visitorId,"Good Morning! OCC Member.");
			customer.sendChatMessage(presenceUser.id,presenceUser.visitorId,"We are launching beta on 1/1/14.");
			customer.sendChatMessage(presenceUser.id,presenceUser.visitorId,"To be part of beta launch mail to biplav.saraf@gmail.com");

		};

		this.onCall = function(message) {
			console.log(message);
			self.webrtcCall.onCall(message);
		};

		this.sendChatMessage = function(id,visitorId, chatText) {
			socket.chat(chatText,id);
			console.log('sending chat message to ' + visitorId +' with message ' + chatText);
			$('#chatMsg'+visitorId).val('');
			addToChatMessageBox(visitorId,customerId,chatText);
		};

		this.init = function() {
			initializeSocket(self);
			//self.presenceIndicator();
			self.visitorMonitor();
			//initialize_calling();
		}
		this.visitorMonitor = function() {
			console.log('VISITOR MONITOR');
			for(i in self.users) {
				var user = self.users[i];
				var now = new Date().getTime();
				var timeDiff = now - user.lastOnline;
				//Give a lag in timeDiff for production
				if(timeDiff > VISITOR_MONITOR) {
						console.log("Visitor went offline " + user.visitorId + " at " + now);
						$('#'+user.visitorId).detach();
						self.users.splice(i,1);
					}
			}
			setTimeout(self.visitorMonitor,VISITOR_MONITOR);
		}

		this.audioCall = function(id) {
			self.webrtcCall.call(id,true);
		}
	};
})();<|endoftext|>


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

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

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var currentPatients;
var newPatientIndex;

var beginDispatching = function () {

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

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

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

    // Update current address
    updateCurrentAddress(currentLocation);

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

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

    // add new patient form entry
    addPatientForm(newPatientIndex);

}

var endDispatching = function () {

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

    markersGroup.clearLayers();

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

}

var removeFromDispatchingList = function(ambulance) {

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

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

}

var addToDispatchingList = function(ambulance) {

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

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

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

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

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

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

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

var updateCurrentLocation = function(location) {

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

    // set currentLocation
    currentLocation = location;

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

    // remove existing marker
    markersGroup.clearLayers();

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

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

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

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

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

    })

}

var updateCurrentAddress = function(location) {

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

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

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

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

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

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

    });

}

var updateCoordinates = function() {

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

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

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

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

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

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

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

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

        });
}

function dispatchCall() {

    var form = {};

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

    // checks
    if (form["priority"] === undefined) {
        bsalert("Please select the priority level.");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        bsalert("Please dispatch at least one ambulance.");
        return;
    }

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

    // Has the user modified the street address?
    if (street_address != currentAddress['street_address']) {

        // parse street address
        var address = geocoder.parse_street_address(street_address, form['country']);

        form['number'] = address['number'];
        form['street'] = address['street'];
        form['unit'] = address['unit'];

    } else {

        form['number'] = currentAddress['number'];
        form['street'] = currentAddress['street'];
        form['unit'] = currentAddress['unit'];

    }

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

    // patients
    var patients = [];
    for (var index in currentPatients)
        if (currentPatients.hasOwnProperty(index)) {
            var patient = currentPatients[index];
            var obj = { 'name': patient[0] };
            if (patient[1])
                // add age
                obj['age'] = patient[1];
            patients.push(obj);
        }
    form['patients'] = patients;

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

    var CSRFToken = getCookie('csrftoken');

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

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

            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

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

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

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

            endDispatching();
        }
    });
}

// patient functions

var addPatient = function(index) {

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

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

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

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

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

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

    // add new form
    addPatientForm(newPatientIndex);

}

var removePatient = function(index) {

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

    // remove from storage
    delete currentPatients[index];

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

}

var addPatientForm = function(index) {

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

    // bind addPatient to click
    $('#patients')
        .on('click',
            '#patient-' + index + '-button',
            function(e) { addPatient(index); });

}

var newPatientForm = function(index, symbol) {

    var html =
        '
' +
            '
' +
                '<input id="patient-' + index + '-name" ' +
                       'type="text" ' +
                       'class="form-control" ' +
                       'placeholder="Name">' +
            '
' +
            '
' +
                '<input id="patient-' + index + '-age" ' +
                       'type="number" min="0" ' +
                       'class="form-control" ' +
                       'placeholder="Age">' +
            '
' +
            '
' +
                '<button class="btn btn-default new-patient" ' +
                       ' type="button" ' +
                       ' id="patient-' + index + '-button">' +
                    '' +
                '</button>' +
            '
' +
        '
';

    // console.log('html = "' + html + '"');

    return html;

}

// Ready function
$(function() {

    // connect actions to inputs

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

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

    });

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

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

    });

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

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

    });

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

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

        // dispatch call
        dispatchCall();

    });

});

// CSRF functions

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

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

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

var dispatchingAmbulances = {};
var numberOfDispatchingAmbulances = 0;

var currentAddress;
var currentLocation;
var currentPatients;
var newPatientIndex;

var beginDispatching = function () {

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

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

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

    // Update current address
    updateCurrentAddress(currentLocation);

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

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

    // add new patient form entry
    addPatientForm(newPatientIndex);

}

var endDispatching = function () {

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

    markersGroup.clearLayers();

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

}

var removeFromDispatchingList = function(ambulance) {

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

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

}

var addToDispatchingList = function(ambulance) {

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

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

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

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

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

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

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

var updateCurrentLocation = function(location) {

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

    // set currentLocation
    currentLocation = location;

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

    // remove existing marker
    markersGroup.clearLayers();

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

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

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

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

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

    })

}

var updateCurrentAddress = function(location) {

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

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

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

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

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

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

    });

}

var updateCoordinates = function() {

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

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

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

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

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

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

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

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

        });
}

function dispatchCall() {

    var form = {};

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

    // checks
    if (form["priority"] === undefined) {
        bsalert("Please select the priority level.");
        return;
    }
    if (numberOfDispatchingAmbulances == 0) {
        bsalert("Please dispatch at least one ambulance.");
        return;
    }

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

    // Has the user modified the street address?
    if (street_address != currentAddress['street_address']) {

        // parse street address
        var address = geocoder.parse_street_address(street_address, form['country']);

        form['number'] = address['number'];
        form['street'] = address['street'];
        form['unit'] = address['unit'];

    } else {

        form['number'] = currentAddress['number'];
        form['street'] = currentAddress['street'];
        form['unit'] = currentAddress['unit'];

    }

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

    // patients
    var patients = [];
    for (var index in currentPatients)
        if (currentPatients.hasOwnProperty(index)) {
            var patient = currentPatients[index];
            var obj = { 'name': patient[0] };
            if (patient[1])
                // add age
                obj['age'] = patient[1];
            patients.push(obj);
        }
    form['patients'] = patients;

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

    var CSRFToken = getCookie('csrftoken');

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

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

            var successMsg = 'Success
' +
                +'Ambulance: ' + data['ambulance']
                + ' dispatched to
' + data['residential_unit']
                + ', ' + data['stmain_number'] + ', ' + data['latitude'] + ', ' + data['longitude'];

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

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

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

            endDispatching();
        }
    });
}

// patient functions

var addPatient = function(index) {

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

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

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

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

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

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

    // add new form
    addPatientForm(newPatientIndex);

}

var removePatient = function(index) {

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

    // remove from storage
    delete currentPatients[index];

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

}

var addPatientForm = function(index) {

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

    // bind addPatient to click
    $('#patients')
        .on('click',
            '#patient-' + index + '-button',
            function(e) { addPatient(index); });

}

var newPatientForm = function(index, symbol) {

    var html =
        '
' +
            '
' +
                '<input id="patient-' + index + '-name" ' +
                       'type="text" ' +
                       'class="form-control" ' +
                       'placeholder="Name">' +
            '
' +
            '
' +
                '<input id="patient-' + index + '-age" ' +
                       'type="number" min="0" ' +
                       'class="form-control" ' +
                       'placeholder="Age">' +
            '
' +
            '
' +
                '<button class="btn btn-default new-patient" ' +
                       ' type="button" ' +
                       ' id="patient-' + index + '-button">' +
                    '' +
                '</button>' +
            '
' +
        '
';

    // console.log('html = "' + html + '"');

    return html;

}

// Ready function
$(function() {

    // connect actions to inputs

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

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

    });

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

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

    });

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

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

    });

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

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

        // dispatch call
        dispatchCall();

    });

});

// CSRF functions

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

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


<commit_before>/**
 *  @create 2013/06/11
 *  @version 0.2
 *  @author: chenwenli <kapa2robert@gmail.com>, Unknown <joe2010xtmf@163.com>
 */

(function () {
    // Fit navbar padding.
    Responsive();
    $(window).resize(function () {
        Responsive();
    });

    function Responsive() {
        var navbarFrame = document.getElementById("navbar_frame");
        var body = document.getElementById("body");
        var delta = document.body.clientWidth - 1050;

        if (delta >= 0) {
            if (document.getElementById("sidebar") == null) {
                navbarFrame.className = "navbar navbar-default navbar-fixed-top";
                body.style.paddingTop = "60px";
            } else {
                navbarFrame.className = "navbar navbar-default";
                body.style.paddingTop = "0px";
            }

        } else {
            navbarFrame.className = "navbar navbar-default";
            body.style.paddingTop = "0px";
        }
    }

    var $backToTopTxt = "Back to Top", $backToTopEle = $('

').appendTo($("body")).attr("title", $backToTopTxt).click(function () {
        $("html, body").animate({ scrollTop: 0 }, 120);
    }), $backToTopFun = function () {
        var st = $(document).scrollTop(), winh = $(window).height();
        (st > 0) ? $backToTopEle.show() : $backToTopEle.hide();
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
    $backToTopFun();

    if (document.body.clientWidth > 1500 && document.getElementById("sidebar") != null) {
        document.getElementById("sidebar").className = "span3"
    }

    var _ep = $('#search_exports');
    if (_ep.length != 0) {
        _ep.modal({ keyboard: false, show: false }); // for export modal

        $('#search_form').submit(function () {
            var input = $.trim(document.getElementById("search_export_box").value)
            if (input.length > 0) {
                _ep.modal('hide');
                var anchor = "#".concat(input.replace(".", "_"));
                location.hash = anchor;
            }
            _ep.find('input[type=text]').val("");
            return false;
        });
    } else {
        _ep = null;
    }

    // For label modal.
    var _tf = $('#label_modal');
    if (_tf.length != 0) {
        _tf.modal({ keyboard: false, show: false }); // For tags modal.

        $('#label_form').submit(function () {
            var _tf = $('#label_modal');
            _tf.modal('hide');
            _tf.find('input[type=text]').val("");
            return false;
        });
    } else {
        _tf = null;
    }

    // For example modal.
    var _ex = $('#example_modal');
    if (_ex.length != 0) {

    } else {
        _ex = null;
    }

    // For global modal.
    var _modal = $("#_keyshortcut");
    _modal.modal({ keyboard: true, show: false });
    var isProjectPage = 0;
    var preKeyG = 0;
    if (document.getElementById("sidebar") != null) {
        isProjectPage = 1;

    } else {
        // Mute options in control panel.
        _modal.find('tbody > tr').each(function (i, ele) {
            if (i == 2 || i == 5 || i == 6 || i == 7) {
                $(ele).addClass("muted");
            }
        })
    }

    function GkeyCb(callback) {
        if (preKeyG == 1) {
            callback();
        }
        preKeyG = 0;
    }

    $(document).keypress(function (event) {
        if ($('input:focus').length != 0) {
            return true;
        }
        var code = event.keyCode ? event.keyCode : event.charCode;
        if (code == 63) {// for '?'  equal as  63
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('show');
        } else if (code == 47) { //for '/'    forward slash code:47
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            //site search focus
            $('input[name=q]').first().focus();
            return false;
        } else if (code == 46 && isProjectPage) { //for '.'    comma as 46   'go to export'
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            if (_ep) {
                _ep.modal('show');
                _ep.on('shown', function () {
                    $(this).find('#search_export_box').focus();
                })
            }
        } else if (code == 103) {// for 'g then g'   g 103
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            if (preKeyG == 0) {
                preKeyG = 1;
                setTimeout(function () {
                    preKeyG = 0
                }, 2000);
                return false;
            }
            //                           console.log(preKeyG);
            GkeyCb(function () {
                $("html,body").animate({ scrollTop: 0 }, 120);
            });

        } else if (code == 98) {//for 'g then b'    b 98
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            GkeyCb(function () {
                $("html,body").animate({ scrollTop: $("body").height() }, 120);
            });

        } else if (code == 105) {//for 'g then i'     i  105
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            GkeyCb(function () {
                location.hash = "#_index";
            });
        } else if (code == 116) { // for `g then t`	t 	116
            if (_ep) _ep.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            if (_tf) {
                _tf.modal('show');
                _tf.on('shown', function () {
                    $(this).find('#label_box').focus();
                })
            }
        } else if (code == 101) {// for 'g then e'   e 101
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            _modal.modal('hide');
            if (_ex) {
                _ex.modal('show');
                _ex.on('shown', function () {
                    $(this).find('#example_box').focus();
                })
            }
        }
    })
    //end
})();

// Add tag.
function AddLabelSubmit(obj) {
    var input = $.trim(document.getElementById("label_box").value);
    if (input.length > 0) {
        var anchor;
        if (window.location.href.indexOf("?") > -1) {
            anchor = window.location.href.replace("?", ":l=" + input + "?");
        } else {
            anchor = window.location.href + ":l=" + input;
        }
        window.location.href = anchor;
        return false;
    }
}

// Remove tag.
function RemoveLabelSubmit(obj) {
    var input = $.trim(document.getElementById("label_box").value);
    if (input.length > 0) {
        var anchor;
        if (window.location.href.indexOf("?") > -1) {
            anchor = window.location.href.replace("?", ":rl=" + input + "?");
        } else {
            anchor = window.location.href + ":rl=" + input;
        }
        window.location.href = anchor;
        return false;
    }
}

function showExample(name) {
    var ex = document.getElementById("_ex_" + name);
    ex.className = "accordion-body collapse in";
    ex.style.height = "auto";
}

function TransToChinese(node) {
    switch (node.attr("id")) {
        case "_index":
            node.html(node.html().toString().replace("Index", "索引"));
            break;
        case "_exams":
            node.html("示例");
            break;
        default:
            node.html(node.html().toString().replace("View Code", "查看代码"));
    }
}

function viewCode(name) {
    var decl = document.getElementById(name.replace("|||", "_"));
    if (decl.style.borderBottom == "0") {
        decl.style.borderBottom = "1px";
    } else {
        decl.style.borderBottom = "0px";
    }
}<commit_msg>Update gwserver.js<commit_after>/**
 *  @create 2013/06/11
 *  @version 0.2
 *  @author: chenwenli <kapa2robert@gmail.com>, Unknown <joe2010xtmf@163.com>
 */

(function () {
    // Fit navbar padding.
    Responsive();
    $(window).resize(function () {
        Responsive();
    });

    function Responsive() {
        var navbarFrame = document.getElementById("navbar_frame");
        var body = document.getElementById("body");
        var delta = document.body.clientWidth - 1050;

        if (delta >= 0) {
            if (document.getElementById("sidebar") == null) {
                navbarFrame.className = "navbar navbar-default navbar-fixed-top";
                body.style.paddingTop = "60px";
            } else {
                navbarFrame.className = "navbar navbar-default";
                body.style.paddingTop = "0px";
            }

        } else {
            navbarFrame.className = "navbar navbar-default";
            body.style.paddingTop = "0px";
        }
    }

    var $backToTopTxt = "Back to Top", $backToTopEle = $('

').appendTo($("body")).attr("title", $backToTopTxt).click(function () {
        $("html, body").animate({ scrollTop: 0 }, 120);
    }), $backToTopFun = function () {
        var st = $(document).scrollTop(), winh = $(window).height();
        (st > 0) ? $backToTopEle.show() : $backToTopEle.hide();
        //IE6下的定位
        if (!window.XMLHttpRequest) {
            $backToTopEle.css("top", st + winh - 166);
        }
    };
    $(window).bind("scroll", $backToTopFun);
    $backToTopFun();

    if (document.body.clientWidth > 1500 && document.getElementById("sidebar") != null) {
        document.getElementById("sidebar").className = "span3"
    }

    var _ep = $('#search_exports');
    if (_ep.length != 0) {
        _ep.modal({ keyboard: false, show: false }); // for export modal

        $('#search_form').submit(function () {
            var input = $.trim(document.getElementById("search_export_box").value)
            if (input.length > 0) {
                _ep.modal('hide');
                var anchor = "#".concat(input.replace(".", "_"));
                location.hash = anchor;
            }
            _ep.find('input[type=text]').val("");
            return false;
        });
    } else {
        _ep = null;
    }

    // For label modal.
    var _tf = $('#label_modal');
    if (_tf.length != 0) {
        _tf.modal({ keyboard: false, show: false }); // For tags modal.

        $('#label_form').submit(function () {
            var _tf = $('#label_modal');
            _tf.modal('hide');
            _tf.find('input[type=text]').val("");
            return false;
        });
    } else {
        _tf = null;
    }

    // For example modal.
    var _ex = $('#example_modal');
    if (_ex.length != 0) {

    } else {
        _ex = null;
    }

    // For global modal.
    var _modal = $("#_keyshortcut");
    _modal.modal({ keyboard: true, show: false });
    var isProjectPage = 0;
    var preKeyG = 0;
    if (document.getElementById("sidebar") != null) {
        isProjectPage = 1;

    } else {
        // Mute options in control panel.
        _modal.find('tbody > tr').each(function (i, ele) {
            if (i == 2 || i == 5 || i == 6 || i == 7) {
                $(ele).addClass("muted");
            }
        })
    }

    function GkeyCb(callback) {
        if (preKeyG == 1) {
            callback();
        }
        preKeyG = 0;
    }

    $(document).keypress(function (event) {
        if ($('input:focus').length != 0) {
            return true;
        }
        var code = event.keyCode ? event.keyCode : event.charCode;
        if (code == 63) {// for '?'  equal as  63
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('show');
        } else if (code == 47) { //for '/'    forward slash code:47
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            //site search focus
            $('input[name=q]').first().focus();
            return false;
        } else if (code == 46 && isProjectPage) { //for '.'    comma as 46   'go to export'
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            if (_ep) {
                _ep.modal('show');
                _ep.on('shown', function () {
                    $(this).find('#search_export_box').focus();
                })
            }
        } else if (code == 103) {// for 'g then g'   g 103
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            if (preKeyG == 0) {
                preKeyG = 1;
                setTimeout(function () {
                    preKeyG = 0
                }, 2000);
                return false;
            }
            //                           console.log(preKeyG);
            GkeyCb(function () {
                $("html,body").animate({ scrollTop: 0 }, 120);
            });

        } else if (code == 98) {//for 'g then b'    b 98
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            GkeyCb(function () {
                $("html,body").animate({ scrollTop: $("body").height() }, 120);
            });

        } else if (code == 105) {//for 'g then i'     i  105
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            GkeyCb(function () {
                location.hash = "#_index";
            });
        } else if (code == 116) { // for `g then t`	t 	116
            if (_ep) _ep.modal('hide');
            if (_ex) _ex.modal('hide');
            _modal.modal('hide');
            GkeyCb( function(){
                    if (_tf) {
                        _tf.modal('show');
                        _tf.on('shown', function () {
                        $(this).find('#label_box').focus();
                    })
                }
            });
        } else if (code == 101) {// for 'g then e'   e 101
            if (_ep) _ep.modal('hide');
            if (_tf) _tf.modal('hide');
            _modal.modal('hide');
            GkeyCb( function() {
                if (_ex) {
                    _ex.modal('show');
                    _ex.on('shown', function () {
                        $(this).find('#example_box').focus();
                    })
                }
            });
        }
    })
    //end
})();

// Add tag.
function AddLabelSubmit(obj) {
    var input = $.trim(document.getElementById("label_box").value);
    if (input.length > 0) {
        var anchor;
        if (window.location.href.indexOf("?") > -1) {
            anchor = window.location.href.replace("?", ":l=" + input + "?");
        } else {
            anchor = window.location.href + ":l=" + input;
        }
        window.location.href = anchor;
        return false;
    }
}

// Remove tag.
function RemoveLabelSubmit(obj) {
    var input = $.trim(document.getElementById("label_box").value);
    if (input.length > 0) {
        var anchor;
        if (window.location.href.indexOf("?") > -1) {
            anchor = window.location.href.replace("?", ":rl=" + input + "?");
        } else {
            anchor = window.location.href + ":rl=" + input;
        }
        window.location.href = anchor;
        return false;
    }
}

function showExample(name) {
    var ex = document.getElementById("_ex_" + name);
    ex.className = "accordion-body collapse in";
    ex.style.height = "auto";
}

function TransToChinese(node) {
    switch (node.attr("id")) {
        case "_index":
            node.html(node.html().toString().replace("Index", "索引"));
            break;
        case "_exams":
            node.html("示例");
            break;
        default:
            node.html(node.html().toString().replace("View Code", "查看代码"));
    }
}

function viewCode(name) {
    var decl = document.getElementById(name.replace("|||", "_"));
    if (decl.style.borderBottom == "0") {
        decl.style.borderBottom = "1px";
    } else {
        decl.style.borderBottom = "0px";
    }
}
<|endoftext|>


<commit_before>import { mount } from 'enzyme';
import assert from 'assert';
import counterpart from 'counterpart';
import React from 'react';
import Summary from './summary';
import { workflow } from '../../../pages/dev-classifier/mock-data';
import enLocale from '../../../locales/en';

counterpart.registerTranslations('en', enLocale);

const annotation = {
  value: [{
    "choice": "ar",
    "answers": {
      "ho": "two",
      "be": [
        "mo",
        "ea"
      ]
    },
    "filters": {}
  }]
};
const task = workflow.tasks.survey
const expectedSummary = 'Armadillo: 2; Moving, Eating';

describe('Survey task summary, not expanded', function() {
  const wrapper = mount(<Summary annotation={annotation} task={task} />);
  const answers = wrapper.find('.answers .answer');

  it('should show one answer node', function(){
    assert.equal(answers.length, 1);
  });

  it('should summarise the number of identifications', function() {
    assert.equal(answers.text(), '1 identification');
  });
});

describe('Survey task summary, expanded', function() {
  const wrapper = mount(<Summary annotation={annotation} task={task} expanded={true} />);
  const answers = wrapper.find('.answers .answer');

  it('should show two answer nodes', function(){
    assert.equal(answers.length, 2);
  });

  it('should summarise the identification and questions', function() {
    assert.equal(answers.last().text(), expectedSummary);
  });
})<commit_msg>Add a test for the 'Survey of…' summary<commit_after>import { mount } from 'enzyme';
import assert from 'assert';
import counterpart from 'counterpart';
import React from 'react';
import Summary from './summary';
import { workflow } from '../../../pages/dev-classifier/mock-data';
import enLocale from '../../../locales/en';

counterpart.registerTranslations('en', enLocale);

const annotation = {
  value: [{
    "choice": "ar",
    "answers": {
      "ho": "two",
      "be": [
        "mo",
        "ea"
      ]
    },
    "filters": {}
  }]
};
const task = workflow.tasks.survey
const expectedSummary = 'Armadillo: 2; Moving, Eating';

describe('Survey task summary, not expanded', function() {
  const wrapper = mount(<Summary annotation={annotation} task={task} />);
  const question = wrapper.find('.question span').first();
  const answers = wrapper.find('.answers .answer');

  it('should summarise the survey task', function(){
    const count = task.choicesOrder.length;
    assert.equal(`Survey of ${count}`, question.text());
  });

  it('should show one answer node', function(){
    assert.equal(answers.length, 1);
  });

  it('should summarise the number of identifications', function() {
    assert.equal(answers.text(), '1 identification');
  });
});

describe('Survey task summary, expanded', function() {
  const wrapper = mount(<Summary annotation={annotation} task={task} expanded={true} />);
  const question = wrapper.find('.question span').first();
  const answers = wrapper.find('.answers .answer');

  it('should summarise the survey task', function(){
    const count = task.choicesOrder.length;
    assert.equal(`Survey of ${count}`, question.text());
  });

  it('should show two answer nodes', function(){
    assert.equal(answers.length, 2);
  });

  it('should summarise the identification and questions', function() {
    assert.equal(answers.last().text(), expectedSummary);
  });
})<|endoftext|>