<commit_before>import hock from 'hock';
import http from 'http';

import {setup, teardown} from './helpers';
import {expectRelayQuery} from '../../lib/relay-network-layer-manager';
import GitShellOutStrategy from '../../lib/git-shell-out-strategy';
import {createRepositoryResult} from '../fixtures/factories/repository-result';
import IDGenerator from '../fixtures/factories/id-generator';
import {createPullRequestsResult, createPullRequestDetailResult} from '../fixtures/factories/pull-request-result';

describe('integration: check out a pull request', function() {
  let context, wrapper, atomEnv, workspaceElement, git, idGen, repositoryID;

  beforeEach(async function() {
    context = await setup({
      initialRoots: ['three-files'],
    });
    wrapper = context.wrapper;
    atomEnv = context.atomEnv;
    workspaceElement = context.workspaceElement;
    idGen = new IDGenerator();
    repositoryID = idGen.generate('repository');

    await context.loginModel.setToken('https://api.github.com', 'good-token');

    const root = atomEnv.project.getPaths()[0];
    git = new GitShellOutStrategy(root);
    await git.exec(['remote', 'add', 'dotcom', 'https://github.com/owner/repo.git']);

    const mockGitServer = hock.createHock();

    const uploadPackAdvertisement = '001e# service=git-upload-pack\n' +
      '0000' +
      '005b66d11860af6d28eb38349ef83de475597cb0e8b4 HEAD\0multi_ack symref=HEAD:refs/heads/pr-head\n' +
      '004066d11860af6d28eb38349ef83de475597cb0e8b4 refs/heads/pr-head\n' +
      '0000';

    mockGitServer
      .get('/owner/repo.git/info/refs?service=git-upload-pack')
      .reply(200, uploadPackAdvertisement, {'Content-Type': 'application/x-git-upload-pack-advertisement'})
      .get('/owner/repo.git/info/refs?service=git-upload-pack')
      .reply(400);

    const server = http.createServer(mockGitServer.handler);
    return new Promise(resolve => {
      server.listen(0, '127.0.0.1', async () => {
        const {address, port} = server.address();
        await git.setConfig(`url.http://${address}:${port}/.insteadOf`, 'https://github.com/');

        resolve();
      });
    });
  });

  afterEach(async function() {
    await teardown(context);
  });

  function expectRepositoryQuery() {
    return expectRelayQuery({
      name: 'remoteContainerQuery',
      variables: {
        owner: 'owner',
        name: 'repo',
      },
    }, {
      repository: createRepositoryResult({id: repositoryID}),
    });
  }

  function expectCurrentPullRequestQuery() {
    return expectRelayQuery({
      name: 'currentPullRequestContainerQuery',
      variables: {
        headOwner: 'owner',
        headName: 'repo',
        headRef: 'refs/heads/pr-head',
        first: 5,
      },
    }, {
      repository: {
        id: repositoryID,
        ref: {
          id: idGen.generate('ref'),
          associatedPullRequests: {
            totalCount: 0,
            nodes: [],
          },
        },
      },
    });
  }

  function expectIssueishSearchQuery() {
    return expectRelayQuery({
      name: 'issueishSearchContainerQuery',
      variables: {
        query: 'repo:owner/repo type:pr state:open',
        first: 20,
      },
    }, {
      search: {
        issueCount: 10,
        nodes: createPullRequestsResult(
          {number: 0},
          {number: 1},
          {number: 2},
        ),
      },
    });
  }

  function expectIssueishDetailQuery() {
    const result = {
      repository: {
        id: repositoryID,
        name: 'repo',
        owner: {
          __typename: 'User',
          id: 'user0',
          login: 'owner',
        },
        issueish: createPullRequestDetailResult({
          number: 1,
          title: 'Pull Request 1',
          headRefName: 'pr-head',
          headRepositoryName: 'repo',
          headRepositoryLogin: 'owner',
        }),
      },
    };

    return expectRelayQuery({
      name: 'issueishDetailContainerQuery',
      variables: {
        repoOwner: 'owner',
        repoName: 'repo',
        issueishNumber: 1,
        timelineCount: 100,
        timelineCursor: null,
        commitCount: 100,
        commitCursor: null,
      },
    }, result);
  }

  function expectMentionableUsersQuery() {
    return expectRelayQuery({
      name: 'GetMentionableUsers',
      variables: {
        owner: 'owner',
        name: 'repo',
        first: 100,
        after: null,
      },
    }, {
      repository: {
        mentionableUsers: {
          nodes: [{login: 'smashwilson', email: 'smashwilson@github.com', name: 'Me'}],
          pageInfo: {hasNextPage: false, endCursor: 'zzz'},
        },
      },
    });
  }

  // achtung! this test is flaky
  it('opens a pane item for a pull request by clicking on an entry in the GitHub tab', async function() {
    const {resolve: resolve0, promise: promise0} = expectRepositoryQuery();
    resolve0();
    await promise0;

    const {resolve: resolve1, promise: promise1} = expectIssueishSearchQuery();
    resolve1();
    await promise1;

    const {resolve: resolve2, promise: promise2} = expectIssueishDetailQuery();
    resolve2();
    await promise2;

    const {resolve: resolve3, promise: promise3} = expectMentionableUsersQuery();
    resolve3();
    await promise3;

    const {resolve: resolve4, promise: promise4} = expectCurrentPullRequestQuery();
    resolve4();
    await promise4;

    // Open the GitHub tab and wait for results to be rendered
    await atomEnv.commands.dispatch(workspaceElement, 'github:toggle-github-tab');
    await assert.async.isTrue(wrapper.update().find('.github-IssueishList-item').exists());

    // Click on PR #1
    const prOne = wrapper.find('.github-Accordion-listItem').filterWhere(li => {
      return li.find('.github-IssueishList-item--number').text() === '#1';
    });
    prOne.simulate('click');

    // Wait for the pane item to open and fetch
    await assert.async.include(
      atomEnv.workspace.getActivePaneItem().getTitle(),
      'PR: owner/repo#1 — Pull Request 1',
    );
    assert.strictEqual(wrapper.update().find('.github-IssueishDetailView-title').text(), 'Pull Request 1');

    // Click on the "Checkout" button
    await wrapper.find('.github-IssueishDetailView-checkoutButton').prop('onClick')();

    // Ensure that the correct ref has been fetched and checked out
    const branches = await git.getBranches();
    const head = branches.find(b => b.head);
    assert.strictEqual(head.name, 'pr-1/owner/pr-head');

    await assert.async.isTrue(wrapper.update().find('.github-IssueishDetailView-checkoutButton--current').exists());
  });
});
<commit_msg>Mark that checkout PR test as flaky<commit_after>import hock from 'hock';
import http from 'http';

import {setup, teardown} from './helpers';
import {expectRelayQuery} from '../../lib/relay-network-layer-manager';
import GitShellOutStrategy from '../../lib/git-shell-out-strategy';
import {createRepositoryResult} from '../fixtures/factories/repository-result';
import IDGenerator from '../fixtures/factories/id-generator';
import {createPullRequestsResult, createPullRequestDetailResult} from '../fixtures/factories/pull-request-result';

describe('integration: check out a pull request', function() {
  let context, wrapper, atomEnv, workspaceElement, git, idGen, repositoryID;

  beforeEach(async function() {
    context = await setup({
      initialRoots: ['three-files'],
    });
    wrapper = context.wrapper;
    atomEnv = context.atomEnv;
    workspaceElement = context.workspaceElement;
    idGen = new IDGenerator();
    repositoryID = idGen.generate('repository');

    await context.loginModel.setToken('https://api.github.com', 'good-token');

    const root = atomEnv.project.getPaths()[0];
    git = new GitShellOutStrategy(root);
    await git.exec(['remote', 'add', 'dotcom', 'https://github.com/owner/repo.git']);

    const mockGitServer = hock.createHock();

    const uploadPackAdvertisement = '001e# service=git-upload-pack\n' +
      '0000' +
      '005b66d11860af6d28eb38349ef83de475597cb0e8b4 HEAD\0multi_ack symref=HEAD:refs/heads/pr-head\n' +
      '004066d11860af6d28eb38349ef83de475597cb0e8b4 refs/heads/pr-head\n' +
      '0000';

    mockGitServer
      .get('/owner/repo.git/info/refs?service=git-upload-pack')
      .reply(200, uploadPackAdvertisement, {'Content-Type': 'application/x-git-upload-pack-advertisement'})
      .get('/owner/repo.git/info/refs?service=git-upload-pack')
      .reply(400);

    const server = http.createServer(mockGitServer.handler);
    return new Promise(resolve => {
      server.listen(0, '127.0.0.1', async () => {
        const {address, port} = server.address();
        await git.setConfig(`url.http://${address}:${port}/.insteadOf`, 'https://github.com/');

        resolve();
      });
    });
  });

  afterEach(async function() {
    await teardown(context);
  });

  function expectRepositoryQuery() {
    return expectRelayQuery({
      name: 'remoteContainerQuery',
      variables: {
        owner: 'owner',
        name: 'repo',
      },
    }, {
      repository: createRepositoryResult({id: repositoryID}),
    });
  }

  function expectCurrentPullRequestQuery() {
    return expectRelayQuery({
      name: 'currentPullRequestContainerQuery',
      variables: {
        headOwner: 'owner',
        headName: 'repo',
        headRef: 'refs/heads/pr-head',
        first: 5,
      },
    }, {
      repository: {
        id: repositoryID,
        ref: {
          id: idGen.generate('ref'),
          associatedPullRequests: {
            totalCount: 0,
            nodes: [],
          },
        },
      },
    });
  }

  function expectIssueishSearchQuery() {
    return expectRelayQuery({
      name: 'issueishSearchContainerQuery',
      variables: {
        query: 'repo:owner/repo type:pr state:open',
        first: 20,
      },
    }, {
      search: {
        issueCount: 10,
        nodes: createPullRequestsResult(
          {number: 0},
          {number: 1},
          {number: 2},
        ),
      },
    });
  }

  function expectIssueishDetailQuery() {
    const result = {
      repository: {
        id: repositoryID,
        name: 'repo',
        owner: {
          __typename: 'User',
          id: 'user0',
          login: 'owner',
        },
        issueish: createPullRequestDetailResult({
          number: 1,
          title: 'Pull Request 1',
          headRefName: 'pr-head',
          headRepositoryName: 'repo',
          headRepositoryLogin: 'owner',
        }),
      },
    };

    return expectRelayQuery({
      name: 'issueishDetailContainerQuery',
      variables: {
        repoOwner: 'owner',
        repoName: 'repo',
        issueishNumber: 1,
        timelineCount: 100,
        timelineCursor: null,
        commitCount: 100,
        commitCursor: null,
      },
    }, result);
  }

  function expectMentionableUsersQuery() {
    return expectRelayQuery({
      name: 'GetMentionableUsers',
      variables: {
        owner: 'owner',
        name: 'repo',
        first: 100,
        after: null,
      },
    }, {
      repository: {
        mentionableUsers: {
          nodes: [{login: 'smashwilson', email: 'smashwilson@github.com', name: 'Me'}],
          pageInfo: {hasNextPage: false, endCursor: 'zzz'},
        },
      },
    });
  }

  // achtung! this test is flaky
  it('opens a pane item for a pull request by clicking on an entry in the GitHub tab', async function() {
    this.retries(5); // FLAKE

    const {resolve: resolve0, promise: promise0} = expectRepositoryQuery();
    resolve0();
    await promise0;

    const {resolve: resolve1, promise: promise1} = expectIssueishSearchQuery();
    resolve1();
    await promise1;

    const {resolve: resolve2, promise: promise2} = expectIssueishDetailQuery();
    resolve2();
    await promise2;

    const {resolve: resolve3, promise: promise3} = expectMentionableUsersQuery();
    resolve3();
    await promise3;

    const {resolve: resolve4, promise: promise4} = expectCurrentPullRequestQuery();
    resolve4();
    await promise4;

    // Open the GitHub tab and wait for results to be rendered
    await atomEnv.commands.dispatch(workspaceElement, 'github:toggle-github-tab');
    await assert.async.isTrue(wrapper.update().find('.github-IssueishList-item').exists());

    // Click on PR #1
    const prOne = wrapper.find('.github-Accordion-listItem').filterWhere(li => {
      return li.find('.github-IssueishList-item--number').text() === '#1';
    });
    prOne.simulate('click');

    // Wait for the pane item to open and fetch
    await assert.async.include(
      atomEnv.workspace.getActivePaneItem().getTitle(),
      'PR: owner/repo#1 — Pull Request 1',
    );
    assert.strictEqual(wrapper.update().find('.github-IssueishDetailView-title').text(), 'Pull Request 1');

    // Click on the "Checkout" button
    await wrapper.find('.github-IssueishDetailView-checkoutButton').prop('onClick')();

    // Ensure that the correct ref has been fetched and checked out
    const branches = await git.getBranches();
    const head = branches.find(b => b.head);
    assert.strictEqual(head.name, 'pr-1/owner/pr-head');

    await assert.async.isTrue(wrapper.update().find('.github-IssueishDetailView-checkoutButton--current').exists());
  });
});
<|endoftext|>


<commit_before>'use strict';

let fs    = require('fs');
let path  = require('path');
let Koa   = require('koa');
let log   = Bento.Log;
const app = new Koa();

Bento._app = function *() {
  yield Bento._bootstrap();
  yield registerMiddleware();
  yield startServer();
};

function *registerMiddleware() {
  log.title('MIDDLEWARE');
  Bento.api('middleware').forEach((target) => {
    let targetPath = path.join(Bento.ROOT_PATH, 'middleware', target + '.js');
    if (fs.existsSync(targetPath)) {
      log.silent('info')(`Loading [${ target }]`);
      require(targetPath)(app);
    }
  });
}

function *startServer() {
  log.title('STARTING SERVERS');
  log.silent('info')(`listening on server port: ${ Bento.config.api.port }`);

  yield require('./bootstrap/modules');

  app.listen(Bento.config.api.port, "127.0.0.1");
}
<commit_msg>Adding cors and listen on 0.0.0.0<commit_after>'use strict';

let fs    = require('fs');
let path  = require('path');
let Koa   = require('koa');
let log   = Bento.Log;
const app = new Koa();

const cors = require('@koa/cors');
app.use(cors());

Bento._app = function *() {
  yield Bento._bootstrap();
  yield registerMiddleware();
  yield startServer();
};

function *registerMiddleware() {
  log.title('MIDDLEWARE');
  Bento.api('middleware').forEach((target) => {
    let targetPath = path.join(Bento.ROOT_PATH, 'middleware', target + '.js');
    if (fs.existsSync(targetPath)) {
      log.silent('info')(`Loading [${ target }]`);
      require(targetPath)(app);
    }
  });
}

function *startServer() {
  log.title('STARTING SERVERS');
  log.silent('info')(`listening on server port: ${ Bento.config.api.port }`);

  yield require('./bootstrap/modules');

  app.listen(Bento.config.api.port, "0.0.0.0");
}
<|endoftext|>


<commit_before>import SelectorSet from 'selector-set';

const bubbleEvents = {};
const captureEvents = {};
const propagationStopped = new WeakMap();
const immediatePropagationStopped = new WeakMap();
const currentTargets = new WeakMap();
const currentTargetDesc = Object.getOwnPropertyDescriptor(
  Event.prototype,
  'currentTarget'
);

function before(subject, verb, fn) {
  const source = subject[verb];
  subject[verb] = function () {
    fn.apply(subject, arguments);
    return source.apply(subject, arguments);
  };
  return subject;
}

function matches(selectors, target, reverse) {
  const queue = [];
  let node = target;

  do {
    if (node.nodeType !== 1) break;
    const matches = selectors.matches(node);
    if (matches.length) {
      const matched = {node: node, observers: matches};
      if (reverse) {
        queue.unshift(matched);
      } else {
        queue.push(matched);
      }
    }
  } while ((node = node.parentElement));

  return queue;
}

function trackPropagation() {
  propagationStopped.set(this, true);
}

function trackImmediate() {
  propagationStopped.set(this, true);
  immediatePropagationStopped.set(this, true);
}

function getCurrentTarget() {
  return currentTargets.get(this) || null;
}

function defineCurrentTarget(event, getter) {
  if (!currentTargetDesc) return;

  Object.defineProperty(event, 'currentTarget', {
    configurable: true,
    enumerable: true,
    get: getter || currentTargetDesc.get
  });
}

function dispatch(event) {
  const events = event.eventPhase === 1 ? captureEvents : bubbleEvents;

  const selectors = events[event.type];
  if (!selectors) return;

  const queue = matches(selectors, event.target, event.eventPhase === 1);
  if (!queue.length) return;

  before(event, 'stopPropagation', trackPropagation);
  before(event, 'stopImmediatePropagation', trackImmediate);
  defineCurrentTarget(event, getCurrentTarget);

  for (let i = 0, len1 = queue.length; i < len1; i++) {
    if (propagationStopped.get(event)) break;
    const matched = queue[i];
    currentTargets.set(event, matched.node);

    for (let j = 0, len2 = matched.observers.length; j < len2; j++) {
      if (immediatePropagationStopped.get(event)) break;
      matched.observers[j].data.call(matched.node, event);
    }
  }

  currentTargets.delete(event);
  defineCurrentTarget(event);
}

export function on(name, selector, fn, options = {}) {
  const capture = options.capture ? true : false;
  const events = capture ? captureEvents : bubbleEvents;

  let selectors = events[name];
  if (!selectors) {
    selectors = new SelectorSet();
    events[name] = selectors;
    document.addEventListener(name, dispatch, capture);
  }
  selectors.add(selector, fn);
}

export function off(name, selector, fn, options = {}) {
  const capture = options.capture ? true : false;
  const events = capture ? captureEvents : bubbleEvents;

  const selectors = events[name];
  if (!selectors) return;
  selectors.remove(selector, fn);

  if (selectors.size) return;
  delete events[name];
  document.removeEventListener(name, dispatch, capture);
}

export function fire(target, name, detail) {
  return target.dispatchEvent(
    new CustomEvent(name, {
      bubbles: true,
      cancelable: true,
      detail: detail
    })
  );
}
<commit_msg>Permission denied to access property eventPhase<commit_after>import SelectorSet from 'selector-set';

const bubbleEvents = {};
const captureEvents = {};
const propagationStopped = new WeakMap();
const immediatePropagationStopped = new WeakMap();
const currentTargets = new WeakMap();
const currentTargetDesc = Object.getOwnPropertyDescriptor(
  Event.prototype,
  'currentTarget'
);

function before(subject, verb, fn) {
  const source = subject[verb];
  subject[verb] = function () {
    fn.apply(subject, arguments);
    return source.apply(subject, arguments);
  };
  return subject;
}

function matches(selectors, target, reverse) {
  const queue = [];
  let node = target;

  do {
    if (node.nodeType !== 1) break;
    const matches = selectors.matches(node);
    if (matches.length) {
      const matched = {node: node, observers: matches};
      if (reverse) {
        queue.unshift(matched);
      } else {
        queue.push(matched);
      }
    }
  } while ((node = node.parentElement));

  return queue;
}

function trackPropagation() {
  propagationStopped.set(this, true);
}

function trackImmediate() {
  propagationStopped.set(this, true);
  immediatePropagationStopped.set(this, true);
}

function getCurrentTarget() {
  return currentTargets.get(this) || null;
}

function defineCurrentTarget(event, getter) {
  if (!currentTargetDesc) return;

  Object.defineProperty(event, 'currentTarget', {
    configurable: true,
    enumerable: true,
    get: getter || currentTargetDesc.get
  });
}

function canDispatch(event) {
  try {
    event.eventPhase;
    return true;
  } catch (_) {
    return false;
  }
}

function dispatch(event) {
  if (!canDispatch(event)) return;

  const events = event.eventPhase === 1 ? captureEvents : bubbleEvents;
  const selectors = events[event.type];
  if (!selectors) return;

  const queue = matches(selectors, event.target, event.eventPhase === 1);
  if (!queue.length) return;

  before(event, 'stopPropagation', trackPropagation);
  before(event, 'stopImmediatePropagation', trackImmediate);
  defineCurrentTarget(event, getCurrentTarget);

  for (let i = 0, len1 = queue.length; i < len1; i++) {
    if (propagationStopped.get(event)) break;
    const matched = queue[i];
    currentTargets.set(event, matched.node);

    for (let j = 0, len2 = matched.observers.length; j < len2; j++) {
      if (immediatePropagationStopped.get(event)) break;
      matched.observers[j].data.call(matched.node, event);
    }
  }

  currentTargets.delete(event);
  defineCurrentTarget(event);
}

export function on(name, selector, fn, options = {}) {
  const capture = options.capture ? true : false;
  const events = capture ? captureEvents : bubbleEvents;

  let selectors = events[name];
  if (!selectors) {
    selectors = new SelectorSet();
    events[name] = selectors;
    document.addEventListener(name, dispatch, capture);
  }
  selectors.add(selector, fn);
}

export function off(name, selector, fn, options = {}) {
  const capture = options.capture ? true : false;
  const events = capture ? captureEvents : bubbleEvents;

  const selectors = events[name];
  if (!selectors) return;
  selectors.remove(selector, fn);

  if (selectors.size) return;
  delete events[name];
  document.removeEventListener(name, dispatch, capture);
}

export function fire(target, name, detail) {
  return target.dispatchEvent(
    new CustomEvent(name, {
      bubbles: true,
      cancelable: true,
      detail: detail
    })
  );
}
<|endoftext|>


<commit_before>var EngineJS_routerManager = {
    routes: [],
    notFoundRouter: function() {},
    defaultRouter: function() {},
    getCurrentPath: function() {
        return decodeURI(location.pathname).replace(/\/$/, '');
    },
    add: function(request, handler) {
        this.routes.push({request: "/" + request, handler: handler});
        return this;
    },
    addDefault: function(handler) {
        this.defaultRouter = handler;
        return this;
    },
    addNotFound: function(handler) {
        this.notFoundRouter = handler;
        return this;
    },
    check: function(path) {

        if (path == "") {
            this.defaultRouter();
            return;
        }

        for(var i = 0; i < this.routes.length; i++) {
            var checkRoute = this.routes[i];
            var match = path.match(new RegExp("^" + checkRoute.request + "$"));

            if(match) {
                match.shift();
                checkRoute.handler.apply({}, match);
                return;
            }
        }
        this.notFoundRouter();
    },
    listen: function() {

        if (typeof this.listenLoopFn != 'undefined') {
            return;
        }

        var self = this;
        var currentPath = self.getCurrentPath();

        this.check(currentPath);
        this.listenLoopFn = setInterval(function() {
            if(currentPath !== self.getCurrentPath()) {
                currentPath = self.getCurrentPath();
                self.check(currentPath);
            }
        }, 50);
    },
    navigate: function(path) {
        history.pushState(null, null, path);
    },
    mapLinks: function(element) {

        var self = this;

        $(element).find("a").on('click', function(e) {
            e.preventDefault();

            var href = $(this).attr('href');

            // don't make action, just igrnore it.
            if (href == "#" || href == "") {
                return;
            }

            // this is external
            if (href.match("(https?:)?\/\/")) {
                return;
            }

            self.navigate(href);
        });
    }
};
<commit_msg>Redirect the external links as usual.<commit_after>var EngineJS_routerManager = {
    routes: [],
    notFoundRouter: function() {},
    defaultRouter: function() {},
    getCurrentPath: function() {
        return decodeURI(location.pathname).replace(/\/$/, '');
    },
    add: function(request, handler) {
        this.routes.push({request: "/" + request, handler: handler});
        return this;
    },
    addDefault: function(handler) {
        this.defaultRouter = handler;
        return this;
    },
    addNotFound: function(handler) {
        this.notFoundRouter = handler;
        return this;
    },
    check: function(path) {

        if (path == "") {
            this.defaultRouter();
            return;
        }

        for(var i = 0; i < this.routes.length; i++) {
            var checkRoute = this.routes[i];
            var match = path.match(new RegExp("^" + checkRoute.request + "$"));

            if(match) {
                match.shift();
                checkRoute.handler.apply({}, match);
                return;
            }
        }
        this.notFoundRouter();
    },
    listen: function() {

        if (typeof this.listenLoopFn != 'undefined') {
            return;
        }

        var self = this;
        var currentPath = self.getCurrentPath();

        this.check(currentPath);
        this.listenLoopFn = setInterval(function() {
            if(currentPath !== self.getCurrentPath()) {
                currentPath = self.getCurrentPath();
                self.check(currentPath);
            }
        }, 50);
    },
    navigate: function(path) {
        history.pushState(null, null, path);
    },
    mapLinks: function(element) {

        var self = this;

        $(element).find("a").on('click', function(e) {
            var href = $(this).attr('href');

            // this is external link to map it.
            if (href.match("(https?:)?\/\/")) {
                return;
            }

            // don't redirect for all internal links
            e.preventDefault();

            // don't make action, just igrnore it.
            if (href == "#" || href == "") {
                return;
            }

            self.navigate(href);
        });
    }
};
<|endoftext|>


<commit_before>// Copyright (C) 2012 Kozea
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

(function ($) {
	$.fn.teddybar = function (options) {
		var config = {
			document : function () { return document /* if iframe use : document.getElementById('iframe').contentWindow.document */ },
			menu : {
				'Bold': 'bold',
				'Italic': 'italic',
				'Underline': 'underline',
				'Strikethrough': 'strikethrough',
				'-1': null,
				'Font Name': ['fontname', {'-- Font Name --': '0','Serif': 'serif', 'Sans-serif': 'sans-serif','Courier': 'courier new'}],
				'Font Size': ['fontsize', {'-- Font Size --': '0','1 (8pt)': '1', '2 (10pt)': '2','3 (12pt)': '3','4 (14pt)': '4','5 (18pt)': '5','6 (24pt)': '6','7 (36pt)': '7'}],
				'Format': ['formatblock', {'-- Block Format --': '0','Heading 1': 'h1','Heading 2': 'h2','Heading 3': 'h3','Heading 4': 'h4','Heading 5': 'h5','Heading 6': 'h6','Paragraph': 'p','Preformatted': 'pre'}],
				'-2': null,
				'Numbered List': 'insertorderedlist',
				'Unnumbered List': 'insertunorderedlist',
				'-3': null,
				'Justify Left': 'justifyleft',
				'Justify Right': 'justifyright',
				'Center': 'justifycenter',
				'Justify Full': 'justifyfull',
				'-4': null,
				'Undo': 'undo',
				'Redo': 'redo',
				//'Save': 'save'
			},
			commands : {
				// Enter your own commands here e.g. : 'save': function(){ alert('TODO') }
			}
		};
	        if (options) {
			$.extend(true, config, options);
	        }
		return this.each(function () {
			var $this=$(this);
			var block = $('<ul>').appendTo($this);
			$.each(config.menu, function (name, command) {
				if (command == null) {
					// make a separator
					block = $('<ul>').appendTo($this);
				} else if (typeof command == 'string') {
					// make a button
					$('<input>', {"title": name, "type": "button", "value": name, "class": command, "data-command": command}).appendTo(block).wrap('<li>');
				} else {
					// make a select
					$('<select>', {"title": name, "data-command": command[0]}).appendTo(block).wrap('<li>');
					$.each(command[1], function(label, value) {
						$('select[data-command='+command[0]+']').append($('<option>', {"value":value}).html(label));
					});
				}
			});

			// execCommand on select elements
			$('select').change(function() {
				var command = $(this).attr('data-command');
				var value = $(this).val();
				if (command in config.commands) {
					config.commands[command](value);
				} else {
					config.document().execCommand(command,false,value);
				}
			});

			// execCommand on input elements
			$('input[type=button]').on('click', function () {
				var command = $(this).attr('data-command');
				if (command in config.commands) {
					config.commands[command]();
				} else {
					config.document().execCommand(command,false,'');
				}
			});

			// function that always puts the toolbar above the body
			$(window).resize(function() {
				$('body').css('margin-top',$this.height());
			});
		});
	};
})(jQuery);
<commit_msg>Bug fix on select elements<commit_after>// Copyright (C) 2012 Kozea
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

(function ($) {
	$.fn.teddybar = function (options) {
		var config = {
			document : function () { return document /* if iframe use : document.getElementById('iframe').contentWindow.document */ },
			menu : {
				'Bold': 'bold',
				'Italic': 'italic',
				'Underline': 'underline',
				'Strikethrough': 'strikethrough',
				'-1': null,
				'Font Name': ['fontname', {'-- Font Name --': '0','Serif': 'serif', 'Sans-serif': 'sans-serif','Courier': 'courier new'}],
				'Font Size': ['fontsize', {'-- Font Size --': '0','1 (8pt)': '1', '2 (10pt)': '2','3 (12pt)': '3','4 (14pt)': '4','5 (18pt)': '5','6 (24pt)': '6','7 (36pt)': '7'}],
				'Format': ['formatblock', {'-- Block Format --': '0','Heading 1': 'h1','Heading 2': 'h2','Heading 3': 'h3','Heading 4': 'h4','Heading 5': 'h5','Heading 6': 'h6','Paragraph': 'p','Preformatted': 'pre'}],
				'-2': null,
				'Numbered List': 'insertorderedlist',
				'Unnumbered List': 'insertunorderedlist',
				'-3': null,
				'Justify Left': 'justifyleft',
				'Justify Right': 'justifyright',
				'Center': 'justifycenter',
				'Justify Full': 'justifyfull',
				'-4': null,
				'Undo': 'undo',
				'Redo': 'redo',
				//'Save': 'save'
			},
			commands : {
				// Enter your own commands here e.g. : 'save': function(){ alert('TODO') }
			}
		};
	        if (options) {
			$.extend(true, config, options);
	        }
		return this.each(function () {
			var $this=$(this);
			var block = $('<ul>').appendTo($this);
			$.each(config.menu, function (name, command) {
				if (command == null) {
					// make a separator
					block = $('<ul>').appendTo($this);
				} else if (typeof command == 'string') {
					// make a button
					$('<input>', {"title": name, "type": "button", "value": name, "class": command, "data-command": command}).appendTo(block).wrap('<li>');
				} else {
					// make a select
					$('<select>', {"title": name, "data-command": command[0]}).appendTo(block).wrap('<li>');
					$.each(command[1], function(label, value) {
						$('select[data-command='+command[0]+']').append($('<option>', {"value":value}).html(label));
					});
				}
			});

			// execCommand on select elements
			$('select').change(function() {
				var command = $(this).attr('data-command');
				var value = $(this).val();
				if (command in config.commands) {
					config.commands[command](value);
				} else {
					config.document().execCommand(command,false,value);
				}
				$(this).children().first().attr('selected','true');
			});

			// execCommand on input elements
			$('input[type=button]').on('click', function () {
				var command = $(this).attr('data-command');
				if (command in config.commands) {
					config.commands[command]();
				} else {
					config.document().execCommand(command,false,'');
				}
			});

			// function that always puts the toolbar above the body
			$(window).resize(function() {
				$('body').css('margin-top',$this.height());
			});
		});
	};
})(jQuery);
<|endoftext|>


<commit_before>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "sovereign-chess-restriction") {
      checkVersion(design, name, value);
  }
}

var getColors = function(design, board, val) {
  if (val === null) return {
      friend: [1],
      enemy:  []
  };
  if (val == 0) return {
      friend: [1, 2],
      enemy:  []
  };
  var ix = board.player;
  var f = board.getValue(ix);
  if (f === null) {
      f = ix;
  }
  ix = (ix == 1) ? 2 : 1;
  var e = board.getValue(ix);
  if (e === null) {
      e = ix;
  }
  return {
      friend: [f],
      enemy:  [e]
  };
}

Dagaz.Model.expandColors = function(design, board, colors, restricted) {
  for (var ix = 0; ix < colors.length; ix++) {
       _.each(design.allPositions(), function(pos) {
           var piece = board.getPiece(pos);
           if (piece === null) return;
           if (piece.player != colors[ix]) return;
           for (var player = 1; player <= 12 ; player++) {
                if ((_.indexOf(colors, player) < 0) && design.inZone(player, 1, pos) && (_.indexOf(restricted, player) < 0)) {
                    colors.push(player);
                }
           }
       });
  }
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  var v = board.getValue(0);
  var colors = getColors(design, board, v);
  Dagaz.Model.expandColors(design, board, colors.friend, colors.enemy);
  Dagaz.Model.expandColors(design, board, colors.enemy, colors.friend);
  var all = _.union(colors.friend, colors.enemy);
  _.each(board.moves, function(move) {
      if (move.actions.length < 1) return;
      var pos = move.actions[0][0][0];
      var piece = board.getPiece(pos);
      if (piece === null) return;
      if (_.indexOf(colors.friend, piece.player) < 0) {
          move.failed = true;
          return;
      }
      pos = move.actions[0][1][0];
      var target = board.getPiece(pos);
      if ((target !== null) && (_.indexOf(colors.enemy, target.player) < 0)) {
          move.failed = true;
          return;
      }
      _.each(all, function(c) {
          if (_.indexOf(colors.enemy, c) == 0) return;
          if (design.inZone(c, 1, pos)) {
              if ((board.getPiece(pos) === null) || (_.indexOf(colors.friend, c) == 0)) move.failed = true;
          }
      });
      if (v === null) {
          move.setValue(0, 0);
          return;
      }
      if (v == 0) {
          move.setValue(0, piece.player);
          if (piece.player == 1) {
              move.setValue(1, 2);
              move.setValue(2, 1);
          } else {
              move.setValue(1, 1);
              move.setValue(2, 2);
          }
          return;
      }
  });
  CheckInvariants(board);
}

})();
<commit_msg>Sovereign Chess (fix)<commit_after>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "sovereign-chess-restriction") {
      checkVersion(design, name, value);
  }
}

var getColors = function(design, board, val) {
  if (val === null) return {
      friend: [1],
      enemy:  []
  };
  if (val == 0) return {
      friend: [1, 2],
      enemy:  []
  };
  var ix = board.player;
  var f = board.getValue(ix);
  if (f === null) {
      f = ix;
  }
  ix = (ix == 1) ? 2 : 1;
  var e = board.getValue(ix);
  if (e === null) {
      e = ix;
  }
  return {
      friend: [f],
      enemy:  [e]
  };
}

Dagaz.Model.expandColors = function(design, board, colors, restricted) {
  for (var ix = 0; ix < colors.length; ix++) {
       _.each(design.allPositions(), function(pos) {
           var piece = board.getPiece(pos);
           if (piece === null) return;
           if (piece.player != colors[ix]) return;
           for (var player = 1; player <= 12 ; player++) {
                if ((_.indexOf(colors, player) < 0) && design.inZone(player, 1, pos) && (_.indexOf(restricted, player) < 0)) {
                    colors.push(player);
                }
           }
       });
  }
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  var v = board.getValue(0);
  var colors = getColors(design, board, v);
  Dagaz.Model.expandColors(design, board, colors.friend, colors.enemy);
  Dagaz.Model.expandColors(design, board, colors.enemy, colors.friend);
  var all = _.union(colors.friend, colors.enemy);
  _.each(board.moves, function(move) {
      if (move.actions.length < 1) return;
      var pos = move.actions[0][0][0];
      var piece = board.getPiece(pos);
      if (piece === null) return;
      if (_.indexOf(colors.friend, piece.player) < 0) {
          move.failed = true;
          return;
      }
      pos = move.actions[0][1][0];
      var target = board.getPiece(pos);
      if ((target !== null) && (_.indexOf(colors.enemy, target.player) < 0)) {
          move.failed = true;
          return;
      }
      _.each(all, function(c) {
          if (_.indexOf(colors.enemy, c) == 0) return;
          if (design.inZone(c, 1, pos)) {
              if (design.inZone(c, 1, move.actions[0][0][0])) return;
              if ((board.getPiece(pos) === null) || (_.indexOf(colors.friend, c) == 0)) move.failed = true;
          }
      });
      if (v === null) {
          move.setValue(0, 0);
          return;
      }
      if (v == 0) {
          move.setValue(0, piece.player);
          if (piece.player == 1) {
              move.setValue(1, 2);
              move.setValue(2, 1);
          } else {
              move.setValue(1, 1);
              move.setValue(2, 2);
          }
          return;
      }
  });
  CheckInvariants(board);
}

})();
<|endoftext|>


<commit_before>/**
 * Legend module.
 *
 * @return singleton instance of the legend class (extends Widget).
 */
define([
  'underscore',
  'handlebars',
  'map/views/Widget',
  'map/presenters/LegendPresenter',
  'text!map/templates/legend/legend.handlebars',
  'text!map/templates/legend/loss.handlebars',
  'text!map/templates/legend/imazon.handlebars',
  'text!map/templates/legend/fires.handlebars',
  'text!map/templates/legend/forest2000.handlebars',
  'text!map/templates/legend/pantropical.handlebars',
  'text!map/templates/legend/idnPrimary.handlebars',
  'text!map/templates/legend/intact2013.handlebars',
  'text!map/templates/legend/grump.handlebars',
  'text!map/templates/legend/stories.handlebars',
  'text!map/templates/legend/terra_i.handlebars',
  'text!map/templates/legend/concesiones_forestales.handlebars',
  'text!map/templates/legend/concesiones_forestalesType.handlebars',
  'text!map/templates/legend/hondurasForest.handlebars',
  'text!map/templates/legend/colombiaForestChange.handlebars'
], function(_, Handlebars, Widget, Presenter, tpl, lossTpl, imazonTpl, firesTpl,
    forest2000Tpl, pantropicalTpl, idnPrimaryTpl, intact2013Tpl, grumpTpl, storiesTpl, terra_iTpl, concesionesTpl, concesionesTypeTpl, hondurasForestTPL,colombiaForestChangeTPL) {

  'use strict';

  var LegendView = Widget.extend({

    className: 'widget widget-legend',

    template: Handlebars.compile(tpl),

    /**
     * Optional layers detail templates.
     */
    detailsTemplates: {
      loss: Handlebars.compile(lossTpl),
      imazon: Handlebars.compile(imazonTpl),
      fires: Handlebars.compile(firesTpl),
      forest2000: Handlebars.compile(forest2000Tpl),
      pantropical: Handlebars.compile(pantropicalTpl),
      idn_primary: Handlebars.compile(idnPrimaryTpl),
      ifl_2013_deg: Handlebars.compile(intact2013Tpl),
      grump2000: Handlebars.compile(grumpTpl),
      user_stories:  Handlebars.compile(storiesTpl),
      terraicanvas: Handlebars.compile(terra_iTpl),
      concesiones_forestales: Handlebars.compile(concesionesTpl),
      concesiones_forestalesNS: Handlebars.compile(concesionesTypeTpl),
      WMSLayer: Handlebars.compile(hondurasForestTPL),
      colombia_forest_change: Handlebars.compile(colombiaForestChangeTPL)
    },

    options: {
      hidden: true
    },

    events: function(){
      return _.extend({}, LegendView.__super__.events, {
        'click .widget-closed': '_toggleBoxClosed',
        'click .layer-sublayer': '_toggleLayer'
      });
    },

    initialize: function() {
      _.bindAll(this, 'update');
      this.presenter = new Presenter(this);
      LegendView.__super__.initialize.apply(this);
    },

    /**
     * Update legend widget by calling widget._update.
     *
     * @param  {array}  categories layers ordered by category
     * @param  {object} options    legend options
     */
    _renderLegend: function(categories, options) {
      var layers = _.flatten(categories);
      var layersLength = layers.length;

      // Append details template to layer.
      _.each(layers, function(layer) {
        if (this.detailsTemplates[layer.slug]) {
          layer.detailsTpl = this.detailsTemplates[layer.slug]({
            threshold: options.threshold || 30,
            layerTitle: layer.title
          });
        }
        // if (layer.slug === 'loss') layer.source = 'loss';
      }, this);

      // Search for layer 'nothing'
      _.each(categories, function(category) {
        for (var i = 0; i< category.length; i++) {
          if(category[i]['slug'] === 'nothing'){
            category[i]['source'] = null;
          } else {
            category[i]['source'] = category[i]['slug'];
          }
        }
      }, this);

      var html = this.template({
        categories: categories,
        layersLength: layersLength
      });

      this._update(html);
      this.presenter.initExperiment('source');
    },

    /**
     * Toggle selected sublayers on the legend widget.
     *
     * @param  {object} layers The layers object
     */
    toggleSelected: function(layers) {
      _.each(this.$el.find('.layer-sublayer'), function(div) {
        var $div = $(div);
        var $toggle = $div.find('.onoffswitch');
        var layer = layers[$div.data('sublayer')];

        if (layer) {
          $toggle.addClass('checked');
          $toggle.css('background', layer.category_color);
        } else {
          $toggle.removeClass('checked').css('background', '');
        }
      }, this);
    },

    /**
     * Set widget from layers object.
     *
     * @param  {array} layers
     */
    update: function(categories, options) {
      if (categories.length === 0) {
        this.model.set('hidden', true);
      } else {
        this.model.set({'hidden': false, 'boxClosed': false});
        this._renderLegend(categories, options);
      }
    },

    /**
     * Handles a toggle layer change UI event by dispatching
     * to LegendPresenter.
     *
     * @param  {event} event Click event
     */
    _toggleLayer: function(event) {
      var layerSlug = $(event.currentTarget).data('sublayer');
      this.presenter.toggleLayer(layerSlug);
    }

  });

  return LegendView;
});
<commit_msg>Hook tigers legend to map<commit_after>/**
 * Legend module.
 *
 * @return singleton instance of the legend class (extends Widget).
 */
define([
  'underscore',
  'handlebars',
  'map/views/Widget',
  'map/presenters/LegendPresenter',
  'text!map/templates/legend/legend.handlebars',
  'text!map/templates/legend/loss.handlebars',
  'text!map/templates/legend/imazon.handlebars',
  'text!map/templates/legend/fires.handlebars',
  'text!map/templates/legend/forest2000.handlebars',
  'text!map/templates/legend/pantropical.handlebars',
  'text!map/templates/legend/idnPrimary.handlebars',
  'text!map/templates/legend/intact2013.handlebars',
  'text!map/templates/legend/grump.handlebars',
  'text!map/templates/legend/stories.handlebars',
  'text!map/templates/legend/terra_i.handlebars',
  'text!map/templates/legend/concesiones_forestales.handlebars',
  'text!map/templates/legend/concesiones_forestalesType.handlebars',
  'text!map/templates/legend/hondurasForest.handlebars',
  'text!map/templates/legend/colombiaForestChange.handlebars',
  'text!map/templates/legend/tigers.handlebars'
], function(_, Handlebars, Widget, Presenter, tpl, lossTpl, imazonTpl, firesTpl,
    forest2000Tpl, pantropicalTpl, idnPrimaryTpl, intact2013Tpl, grumpTpl, storiesTpl, terra_iTpl, concesionesTpl, concesionesTypeTpl, hondurasForestTPL,colombiaForestChangeTPL, tigersTPL) {

  'use strict';

  var LegendView = Widget.extend({

    className: 'widget widget-legend',

    template: Handlebars.compile(tpl),

    /**
     * Optional layers detail templates.
     */
    detailsTemplates: {
      loss: Handlebars.compile(lossTpl),
      imazon: Handlebars.compile(imazonTpl),
      fires: Handlebars.compile(firesTpl),
      forest2000: Handlebars.compile(forest2000Tpl),
      pantropical: Handlebars.compile(pantropicalTpl),
      idn_primary: Handlebars.compile(idnPrimaryTpl),
      ifl_2013_deg: Handlebars.compile(intact2013Tpl),
      grump2000: Handlebars.compile(grumpTpl),
      user_stories:  Handlebars.compile(storiesTpl),
      terraicanvas: Handlebars.compile(terra_iTpl),
      concesiones_forestales: Handlebars.compile(concesionesTpl),
      concesiones_forestalesNS: Handlebars.compile(concesionesTypeTpl),
      WMSLayer: Handlebars.compile(hondurasForestTPL),
      colombia_forest_change: Handlebars.compile(colombiaForestChangeTPL),
      tigers: Handlebars.compile(tigersTPL)
    },

    options: {
      hidden: true
    },

    events: function(){
      return _.extend({}, LegendView.__super__.events, {
        'click .widget-closed': '_toggleBoxClosed',
        'click .layer-sublayer': '_toggleLayer'
      });
    },

    initialize: function() {
      _.bindAll(this, 'update');
      this.presenter = new Presenter(this);
      LegendView.__super__.initialize.apply(this);
    },

    /**
     * Update legend widget by calling widget._update.
     *
     * @param  {array}  categories layers ordered by category
     * @param  {object} options    legend options
     */
    _renderLegend: function(categories, options) {
      var layers = _.flatten(categories);
      var layersLength = layers.length;

      // Append details template to layer.
      _.each(layers, function(layer) {
        if (this.detailsTemplates[layer.slug]) {
          layer.detailsTpl = this.detailsTemplates[layer.slug]({
            threshold: options.threshold || 30,
            layerTitle: layer.title
          });
        }
        // if (layer.slug === 'loss') layer.source = 'loss';
      }, this);

      // Search for layer 'nothing'
      _.each(categories, function(category) {
        for (var i = 0; i< category.length; i++) {
          if(category[i]['slug'] === 'nothing'){
            category[i]['source'] = null;
          } else {
            category[i]['source'] = category[i]['slug'];
          }
        }
      }, this);

      var html = this.template({
        categories: categories,
        layersLength: layersLength
      });

      this._update(html);
      this.presenter.initExperiment('source');
    },

    /**
     * Toggle selected sublayers on the legend widget.
     *
     * @param  {object} layers The layers object
     */
    toggleSelected: function(layers) {
      _.each(this.$el.find('.layer-sublayer'), function(div) {
        var $div = $(div);
        var $toggle = $div.find('.onoffswitch');
        var layer = layers[$div.data('sublayer')];

        if (layer) {
          $toggle.addClass('checked');
          $toggle.css('background', layer.category_color);
        } else {
          $toggle.removeClass('checked').css('background', '');
        }
      }, this);
    },

    /**
     * Set widget from layers object.
     *
     * @param  {array} layers
     */
    update: function(categories, options) {
      if (categories.length === 0) {
        this.model.set('hidden', true);
      } else {
        this.model.set({'hidden': false, 'boxClosed': false});
        this._renderLegend(categories, options);
      }
    },

    /**
     * Handles a toggle layer change UI event by dispatching
     * to LegendPresenter.
     *
     * @param  {event} event Click event
     */
    _toggleLayer: function(event) {
      var layerSlug = $(event.currentTarget).data('sublayer');
      this.presenter.toggleLayer(layerSlug);
    }

  });

  return LegendView;
});
<|endoftext|>


<commit_before>// This JS file is for the map and list view creations on the homepage of the
// Maps4All site for the user. This example requires the Places library. Include
// the libraries=places parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var oms;
var markers = [];
var infowindow;
var focusZoom = 17;
var locationMarker;

// Click listener for a marker.
function markerListener(marker, event) {
  $("#map").show();
  $("#resource-info").hide();

  // Show marker info bubble
  var markerInfoWindowTemplate = $("#marker-info-window-template").html();
  var compiledMarkerInfoWindowTemplate =
    Handlebars.compile(markerInfoWindowTemplate);
  var context = {
    name: marker.title,
    address: marker.address,
    avg_rating: marker.avg_rating,
  };
  var markerInfo = compiledMarkerInfoWindowTemplate(context);

  if (infowindow) {
    infowindow.close();
  }
  infowindow = new google.maps.InfoWindow({
    content: markerInfo,
    maxWidth: 300,
  });
  infowindow.open(map, marker);

  // Marker "more information" link to detailed resource information view
  $(".more-info").click(function() {
    displayDetailedResourceView(marker);
  });
}

// Generate the detailed resource page view after clicking "more information"
// on a marker
function displayDetailedResourceView(marker) {
  // get descriptor information as associations
  $.get('get-associations/' + marker.resourceID).done(function(associations) {
    $("#map").hide();
    $("#resource-info").empty();
    $("#resource-info").show();
    var associationObject = JSON.parse(associations);
    var descriptors = [];
    for (var key in associationObject) {
      var descriptor = {
        key: key,
        value: associationObject[key],
      };
      descriptors.push(descriptor);
    }
    // Detailed resource information template generation
    var resourceTemplate = $("#resource-template").html();
    var compiledResourceTemplate = Handlebars.compile(resourceTemplate);
    var context = {
      name: marker.title,
      address: marker.address,
      suggestionUrl: 'suggestion/' + marker.resourceID,
      descriptors: descriptors,
      avg_rating: marker.avg_rating,
    };
    var resourceInfo = compiledResourceTemplate(context);
    $("#resource-info").html(resourceInfo);

    // Set handlers and populate DOM elements from resource template
    // Can only reference elements in template after compilation
    $('#back-button').click(function() {
      $("#map").show();
      $("#resource-info").hide();
      resizeMapListGrid();
    });

    $('.ui.rating')
    .rating({
      initialRating: 0,
      maxRating: 5,
      onRate: function(value) {
        if (value !== 0){
          $('#submit-rating').removeClass('disabled').addClass('active');}
      }
    });

    $('#submit-rating').click(function(e) {
    e.preventDefault();
    var rating = $('#rating-input').rating('get rating');
    var review = $('#review').val();
    var id = marker.resourceID;
    submitReview(rating,review,id);
    });

    // Map for single resource on detailed resource info page
    var singleResourceMap = new google.maps.Map(
      document.getElementById('single-resource-map'),
      {
        center: marker.getPosition(),
        zoom: focusZoom,
      }
    );
    var singleMarker = new google.maps.Marker({
      position: marker.getPosition(),
      map: singleResourceMap,
    });
  });
}

var submitReview = function(rating, review, id){
  var ratingReview = {
  'rating': rating,
  'review': review,
  'id': id,
};
$.ajax({
   url: '/rating-post',
   data: JSON.stringify(ratingReview),
   contentType: 'application/json',
   dataType: 'json',
   method: 'POST'
});
$(".userRating").hide();
$(".successMessage").show();
}

/*
 * Initializes the map, the corresponding list of resources and search
 * functionality on the resources
 */
function initMap() {
  // hide resource-info
  $("#resource-info").empty();
  $("#resource-info").hide();

  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 39.949, lng: -75.181}, // TODO(#52): Do not hardcode this.
    zoom: focusZoom,
  });

  oms = new OverlappingMarkerSpiderfier(map, {keepSpiderfied: true, nearbyDistance: 10});

  // Add click listener to marker for displaying infoWindow
  oms.addListener('click', markerListener);

  infowindow = new google.maps.InfoWindow();
  initLocationSearch(map);
  initResourceSearch();

  $.get('/get-resources').done(function(resourcesString) {
    var resources = JSON.parse(resourcesString);
    populateMarkers(resources);
  });

  google.maps.event.addListenerOnce(map, 'idle', function() {
    populateListDiv();
  });
}

/*
 * Initialize searching on the map by location input.
 * When entering a new location, re-center and zoom the map onto that location
 * and create a custom location marker.
 */
function initLocationSearch(map) {
  var input = document.getElementById('pac-input');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Autocomplete's returned place contains no geometry");
      return;
    }

    var address = '';
    if (place.address_components) {
      address = [
        ((place.address_components[0] &&
          place.address_components[0].short_name) || ''),
        ((place.address_components[1] &&
          place.address_components[1].short_name) || ''),
        ((place.address_components[2] &&
          place.address_components[2].short_name) || '')
      ].join(' ');
    }

    if (!locationMarker) {
      locationMarker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          scale: 8,
          strokeColor: 'grey',
          fillColor: 'black',
          fillOpacity: 1,
        },
      });
    } else {
      locationMarker.setPosition(place.geometry.location);
    }

    // Marker info window for searched location
    var searchedLocationInfoWindowTemplate =
      $("#searched-location-info-window-template").html();
    var compiledLocInfoWindowTemplate =
      Handlebars.compile(searchedLocationInfoWindowTemplate);
    var context = {
      name: place.name,
      address: address,
    };
    var locationMarkerInfo = compiledLocInfoWindowTemplate(context);

    infowindow.setContent(locationMarkerInfo);
    infowindow.open(map, locationMarker);
  });

  // Delete location marker when deleting location query
  $('#pac-input').keyup(function() {
    if ($(this).val() === "") {
      locationMarker.setMap(null);
      locationMarker = null;
    }
  });
}

/*
 * Initialize searching on the map by resource name input
 */
function initResourceSearch() {
  // Click 'Search' on resource name input
  $('#search-user-resources').click(function() {
    var query = '?' + 'name=' + $('#resources-input').val();
    var requiredOptions = [];
    $("#search-resources-req-options :selected").each(function() {
      requiredOptions.push($(this).val());
    });
    for (var i = 0; i < requiredOptions.length; i++) {
      query += '&reqoption=' + requiredOptions[i];
    }
    var endpoint = '/search-resources'+query;
    resourceSearchRequest(endpoint);
  });

  // Remove query from resource name input displays
  // all resources again
  $('#resources-input').keyup(function() {
    if ($(this).val().length === 0) {
      resourceSearchRequest('/get-resources');
    }
  });
}

function resourceSearchRequest(endpoint) {
  $.get(endpoint).done(function(resourcesString) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
    markers = [];
    var resources = JSON.parse(resourcesString);
    if (resources.length != 0) {
      populateMarkers(resources);
    }
    populateListDiv();
  });
}

/*
 * Create markers for each resource and add them to the map
 * Expand the map to show all resources
 */
function populateMarkers(resources) {
  for (var i = 0; i < resources.length; i++) {
    createMarker(resources[i]);
  }

  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
    oms.addMarker(markers[i]);
    bounds.extend(markers[i].getPosition());
  }

  map.fitBounds(bounds);
  map.setCenter(bounds.getCenter());
}

/*
 * Create a marker for each resource and handle clicking on a marker.
 * Handle clicking on more information for a resource
 */
function createMarker(resource) {
  var markerToAdd = new google.maps.Marker({
    map: map
  });
  latLng = new google.maps.LatLng(resource.latitude, resource.longitude);
  markerToAdd.setPosition(latLng);
  markerToAdd.setVisible(true);
  markerToAdd.title = resource.name;
  markerToAdd.json_data = {
    csrf_token: $('meta[name="csrf-token"]').prop('content'),
    data: resource.name
  };
  markerToAdd.avg_rating = resource.avg_rating;
  markerToAdd.resourceID = resource.id;
  markerToAdd.address = resource.address;

  markers.push(markerToAdd);
}

/*
 * Show a corresponding list of resources adjacent to the map
 */
function populateListDiv() {
  var markersToShow = markers;
  $("#list").empty();

  var listResources = [];
  $.each(markersToShow, function(i, markerToShow) {
    var listResource = {
      name: markerToShow.title,
      address: markerToShow.address,
      avg_rating: markerToShow.avg_rating,
    };
    listResources.push(listResource);
  });

  var listTemplate = $("#listview-template").html();
  var compiledListTemplate = Handlebars.compile(listTemplate);
  var context = {
    resource: listResources,
  };
  var listView = compiledListTemplate(context);
  $("#list").html(listView);

  // Can only add handlers to elements in template after compilation
  $(".list-resource").each(function(i, element) {
    element.addEventListener('click', function() {
      markerListener(markersToShow[i], 'click');
    });
  });
}

// Resize map/list area - set height to fit screen
function resizeMapListGrid() {
  var navHeight = $('.ui.navigation.grid').height();
  // TODO: remove hack of subtracting 40
  $('#map-list-grid').height($('body').height() - navHeight - 40);

  var center = map.getCenter();
  // Need to call resize event on map or creates dead grey area on map
  google.maps.event.trigger(map, "resize");
  map.setCenter(center);
}
<commit_msg>fixed indentaiton within submitRating function)<commit_after>// This JS file is for the map and list view creations on the homepage of the
// Maps4All site for the user. This example requires the Places library. Include
// the libraries=places parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var oms;
var markers = [];
var infowindow;
var focusZoom = 17;
var locationMarker;

// Click listener for a marker.
function markerListener(marker, event) {
  $("#map").show();
  $("#resource-info").hide();

  // Show marker info bubble
  var markerInfoWindowTemplate = $("#marker-info-window-template").html();
  var compiledMarkerInfoWindowTemplate =
    Handlebars.compile(markerInfoWindowTemplate);
  var context = {
    name: marker.title,
    address: marker.address,
    avg_rating: marker.avg_rating,
  };
  var markerInfo = compiledMarkerInfoWindowTemplate(context);

  if (infowindow) {
    infowindow.close();
  }
  infowindow = new google.maps.InfoWindow({
    content: markerInfo,
    maxWidth: 300,
  });
  infowindow.open(map, marker);

  // Marker "more information" link to detailed resource information view
  $(".more-info").click(function() {
    displayDetailedResourceView(marker);
  });
}

// Generate the detailed resource page view after clicking "more information"
// on a marker
function displayDetailedResourceView(marker) {
  // get descriptor information as associations
  $.get('get-associations/' + marker.resourceID).done(function(associations) {
    $("#map").hide();
    $("#resource-info").empty();
    $("#resource-info").show();
    var associationObject = JSON.parse(associations);
    var descriptors = [];
    for (var key in associationObject) {
      var descriptor = {
        key: key,
        value: associationObject[key],
      };
      descriptors.push(descriptor);
    }
    // Detailed resource information template generation
    var resourceTemplate = $("#resource-template").html();
    var compiledResourceTemplate = Handlebars.compile(resourceTemplate);
    var context = {
      name: marker.title,
      address: marker.address,
      suggestionUrl: 'suggestion/' + marker.resourceID,
      descriptors: descriptors,
      avg_rating: marker.avg_rating,
    };
    var resourceInfo = compiledResourceTemplate(context);
    $("#resource-info").html(resourceInfo);

    // Set handlers and populate DOM elements from resource template
    // Can only reference elements in template after compilation
    $('#back-button').click(function() {
      $("#map").show();
      $("#resource-info").hide();
      resizeMapListGrid();
    });

    $('.ui.rating')
    .rating({
      initialRating: 0,
      maxRating: 5,
      onRate: function(value) {
        if (value !== 0){
          $('#submit-rating').removeClass('disabled').addClass('active');}
      }
    });

    $('#submit-rating').click(function(e) {
      e.preventDefault();
      var rating = $('#rating-input').rating('get rating');
      var review = $('#review').val();
      var id = marker.resourceID;
      submitReview(rating,review,id);
    });

    // Map for single resource on detailed resource info page
    var singleResourceMap = new google.maps.Map(
      document.getElementById('single-resource-map'),
      {
        center: marker.getPosition(),
        zoom: focusZoom,
      }
    );
    var singleMarker = new google.maps.Marker({
      position: marker.getPosition(),
      map: singleResourceMap,
    });
  });
}

function submitReview(rating, review, id){
  var ratingReview = {
  'rating': rating,
  'review': review,
  'id': id,
  };
  $.ajax({
     url: '/rating-post',
     data: JSON.stringify(ratingReview),
     contentType: 'application/json',
     dataType: 'json',
     method: 'POST'
  });
  $(".userRating").hide();
  $(".successMessage").show();
}

/*
 * Initializes the map, the corresponding list of resources and search
 * functionality on the resources
 */
function initMap() {
  // hide resource-info
  $("#resource-info").empty();
  $("#resource-info").hide();

  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 39.949, lng: -75.181}, // TODO(#52): Do not hardcode this.
    zoom: focusZoom,
  });

  oms = new OverlappingMarkerSpiderfier(map, {keepSpiderfied: true, nearbyDistance: 10});

  // Add click listener to marker for displaying infoWindow
  oms.addListener('click', markerListener);

  infowindow = new google.maps.InfoWindow();
  initLocationSearch(map);
  initResourceSearch();

  $.get('/get-resources').done(function(resourcesString) {
    var resources = JSON.parse(resourcesString);
    populateMarkers(resources);
  });

  google.maps.event.addListenerOnce(map, 'idle', function() {
    populateListDiv();
  });
}

/*
 * Initialize searching on the map by location input.
 * When entering a new location, re-center and zoom the map onto that location
 * and create a custom location marker.
 */
function initLocationSearch(map) {
  var input = document.getElementById('pac-input');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      window.alert("Autocomplete's returned place contains no geometry");
      return;
    }

    var address = '';
    if (place.address_components) {
      address = [
        ((place.address_components[0] &&
          place.address_components[0].short_name) || ''),
        ((place.address_components[1] &&
          place.address_components[1].short_name) || ''),
        ((place.address_components[2] &&
          place.address_components[2].short_name) || '')
      ].join(' ');
    }

    if (!locationMarker) {
      locationMarker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          scale: 8,
          strokeColor: 'grey',
          fillColor: 'black',
          fillOpacity: 1,
        },
      });
    } else {
      locationMarker.setPosition(place.geometry.location);
    }

    // Marker info window for searched location
    var searchedLocationInfoWindowTemplate =
      $("#searched-location-info-window-template").html();
    var compiledLocInfoWindowTemplate =
      Handlebars.compile(searchedLocationInfoWindowTemplate);
    var context = {
      name: place.name,
      address: address,
    };
    var locationMarkerInfo = compiledLocInfoWindowTemplate(context);

    infowindow.setContent(locationMarkerInfo);
    infowindow.open(map, locationMarker);
  });

  // Delete location marker when deleting location query
  $('#pac-input').keyup(function() {
    if ($(this).val() === "") {
      locationMarker.setMap(null);
      locationMarker = null;
    }
  });
}

/*
 * Initialize searching on the map by resource name input
 */
function initResourceSearch() {
  // Click 'Search' on resource name input
  $('#search-user-resources').click(function() {
    var query = '?' + 'name=' + $('#resources-input').val();
    var requiredOptions = [];
    $("#search-resources-req-options :selected").each(function() {
      requiredOptions.push($(this).val());
    });
    for (var i = 0; i < requiredOptions.length; i++) {
      query += '&reqoption=' + requiredOptions[i];
    }
    var endpoint = '/search-resources'+query;
    resourceSearchRequest(endpoint);
  });

  // Remove query from resource name input displays
  // all resources again
  $('#resources-input').keyup(function() {
    if ($(this).val().length === 0) {
      resourceSearchRequest('/get-resources');
    }
  });
}

function resourceSearchRequest(endpoint) {
  $.get(endpoint).done(function(resourcesString) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
    markers = [];
    var resources = JSON.parse(resourcesString);
    if (resources.length != 0) {
      populateMarkers(resources);
    }
    populateListDiv();
  });
}

/*
 * Create markers for each resource and add them to the map
 * Expand the map to show all resources
 */
function populateMarkers(resources) {
  for (var i = 0; i < resources.length; i++) {
    createMarker(resources[i]);
  }

  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
    oms.addMarker(markers[i]);
    bounds.extend(markers[i].getPosition());
  }

  map.fitBounds(bounds);
  map.setCenter(bounds.getCenter());
}

/*
 * Create a marker for each resource and handle clicking on a marker.
 * Handle clicking on more information for a resource
 */
function createMarker(resource) {
  var markerToAdd = new google.maps.Marker({
    map: map
  });
  latLng = new google.maps.LatLng(resource.latitude, resource.longitude);
  markerToAdd.setPosition(latLng);
  markerToAdd.setVisible(true);
  markerToAdd.title = resource.name;
  markerToAdd.json_data = {
    csrf_token: $('meta[name="csrf-token"]').prop('content'),
    data: resource.name
  };
  markerToAdd.avg_rating = resource.avg_rating;
  markerToAdd.resourceID = resource.id;
  markerToAdd.address = resource.address;

  markers.push(markerToAdd);
}

/*
 * Show a corresponding list of resources adjacent to the map
 */
function populateListDiv() {
  var markersToShow = markers;
  $("#list").empty();

  var listResources = [];
  $.each(markersToShow, function(i, markerToShow) {
    var listResource = {
      name: markerToShow.title,
      address: markerToShow.address,
      avg_rating: markerToShow.avg_rating,
    };
    listResources.push(listResource);
  });

  var listTemplate = $("#listview-template").html();
  var compiledListTemplate = Handlebars.compile(listTemplate);
  var context = {
    resource: listResources,
  };
  var listView = compiledListTemplate(context);
  $("#list").html(listView);

  // Can only add handlers to elements in template after compilation
  $(".list-resource").each(function(i, element) {
    element.addEventListener('click', function() {
      markerListener(markersToShow[i], 'click');
    });
  });
}

// Resize map/list area - set height to fit screen
function resizeMapListGrid() {
  var navHeight = $('.ui.navigation.grid').height();
  // TODO: remove hack of subtracting 40
  $('#map-list-grid').height($('body').height() - navHeight - 40);

  var center = map.getCenter();
  // Need to call resize event on map or creates dead grey area on map
  google.maps.event.trigger(map, "resize");
  map.setCenter(center);
}
<|endoftext|>


<commit_before>ngPopup.factory("ngPopupBuilder", function($q, $http){
    var ngPopupBuilder = {
        layoutInit: function(option){
            var templateHtml = (option.template) ? option.template : '';
            var templateUrlHtml = '';
            var html = null;
            console.log(option)
            if(option.templateUrl) {
                var xmlHttpRequest = new XMLHttpRequest();
                xmlHttpRequest.onreadystatechange = function () {
                    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                        templateUrlHtml = xmlHttpRequest.responseText;
                    }
                }
                xmlHttpRequest.open("GET", option.templateUrl, false);
                xmlHttpRequest.send(null);
            }
            html = '
' +
            '
' +
            '

' + '

' + '

' + '

' +
            '
' +
            '
' +
            '

' + '

' + '

' + '

' +
            '
' +
            '
' +
                ''+option.title+'' +
            '
' +
            '' +
            '' +
            '' +
            '' +
            '
' +
            '
' +
            '
' +
            templateHtml +
            templateUrlHtml +
            '
' +
            '
';

            return html;

        },
        getDefaultMethods: function(options,element,scope){
            var $element = element[0];
            var fun = {
                open: function(newPosition){
                    if(newPosition != null){
                        $element.style.top = newPosition.top + "px";
                        $element.style.left = newPosition.left + "px";
                    }
                    $element.style.display = 'block';
                },
                close: function(){
                    $element.style.display = 'none';
                },
                maximize: function(){
                    $element.getElementsByClassName('content')[0].style.display = 'block';
                    $element.style.top = window.screenTop ? window.screenTop : window.screenY +10 + "px";
                    $element.style.left = window.screenLeft ? window.screenLeft : window.screenX +10 + "px";
                    $element.style.width = window.innerWidth - 30+ "px";
                    $element.style.height = window.innerHeight - 30 + "px";
                    //this.updateParentScopeOptions(options,$element);
                    options.position.top =  $element.offsetTop;
                    options.position.left = $element.offsetLeft;
                    options.width = $element.offsetWidth;
                    options.height = $element.offsetHeight;
                },
                minimize: function(){
                    $element.getElementsByClassName('content')[0].style.display = 'none';
                    $element.style.height = $element.getElementsByClassName('titleBar')[0].style.height;
                    $element.style.width = '200px';
                    options.position.top =  $element.offsetTop;
                    options.position.left = $element.offsetLeft;
                    options.width = $element.offsetWidth;
                    options.height = $element.offsetHeight;
                },
                togglePin: function(event){
                    if($option.pinned != true){
                        $element.style.position = 'fixed';
                        angular.element(event.target).removeClass('glyphicon-resize-small');
                        angular.element(event.target).addClass('glyphicon-resize-full');
                        $option.pinned = true;
                    }
                    else{
                        $element.style.position = 'absolute';
                        angular.element(event.target).removeClass('glyphicon-resize-full');
                        angular.element(event.target).addClass('glyphicon-resize-small');
                        $option.pinned = false;
                    }

                },
                isOpened: function(){
                    return ($element.style.display != 'none') ? true : false;
                },
                isMaximized: function(){

                },
                isMinimized: function(){
                    return ($element.getElementsByClassName('content')[0].style.display != 'none') ? false : true;
                }
            };

            return fun;
        },
        getDefaultOptions: function(){
            var defaultOption = {
                modelName : "",
                width : 100,
                height : 100,
                template: "123",
                templateUrl : "",
                resizable : true,
                draggable : true,
                position : {
                    top : 100,
                    left : 100
                },
                title : "",
                modal : false,
                pinned : false,
                onOpen : function(){},
                onClose  : function(){},
                onDragStart : function(){},
                onDragEnd : function(){},
                onResize : function(){}

            };

            return defaultOption;
        },
        callParentScopeApply: function(scope){
            if(!scope.$$phase){
                scope.$apply()
            }
        },
        updateParentScopeOptions: function(options,element){
            options.position.top =  element.offsetTop;
            options.position.left = element.offsetLeft;
            options.width = element.offsetWidth;
            options.height = element.offsetHeight;
        }
    };

    return ngPopupBuilder;
});<commit_msg>add setTitle(newTitle) in ngPopup methods<commit_after>ngPopup.factory("ngPopupBuilder", function($q, $http){
    var ngPopupBuilder = {
        layoutInit: function(option){
            var templateHtml = (option.template) ? option.template : '';
            var templateUrlHtml = '';
            var html = null;
            console.log(option)
            if(option.templateUrl) {
                var xmlHttpRequest = new XMLHttpRequest();
                xmlHttpRequest.onreadystatechange = function () {
                    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                        templateUrlHtml = xmlHttpRequest.responseText;
                    }
                }
                xmlHttpRequest.open("GET", option.templateUrl, false);
                xmlHttpRequest.send(null);
            }
            html = '
' +
            '
' +
            '

' + '

' + '

' + '

' +
            '
' +
            '
' +
            '

' + '

' + '

' + '

' +
            '
' +
            '
' +
                ''+option.title+'' +
            '
' +
            '' +
            '' +
            '' +
            '' +
            '
' +
            '
' +
            '
' +
            templateHtml +
            templateUrlHtml +
            '
' +
            '
';

            return html;

        },
        getDefaultMethods: function(options,element,scope){
            var $element = element[0];
            var fun = {
                open: function(newPosition){
                    if(newPosition != null){
                        $element.style.top = newPosition.top + "px";
                        $element.style.left = newPosition.left + "px";
                    }
                    $element.style.display = 'block';
                },
                close: function(){
                    $element.style.display = 'none';
                },
                maximize: function(){
                    $element.getElementsByClassName('content')[0].style.display = 'block';
                    $element.style.top = window.screenTop ? window.screenTop : window.screenY +10 + "px";
                    $element.style.left = window.screenLeft ? window.screenLeft : window.screenX +10 + "px";
                    $element.style.width = window.innerWidth - 30+ "px";
                    $element.style.height = window.innerHeight - 30 + "px";
                    //this.updateParentScopeOptions(options,$element);
                    options.position.top =  $element.offsetTop;
                    options.position.left = $element.offsetLeft;
                    options.width = $element.offsetWidth;
                    options.height = $element.offsetHeight;
                },
                minimize: function(){
                    $element.getElementsByClassName('content')[0].style.display = 'none';
                    $element.style.height = $element.getElementsByClassName('titleBar')[0].style.height;
                    $element.style.width = '200px';
                    options.position.top =  $element.offsetTop;
                    options.position.left = $element.offsetLeft;
                    options.width = $element.offsetWidth;
                    options.height = $element.offsetHeight;
                },
                togglePin: function(event){
                    if($option.pinned != true){
                        $element.style.position = 'fixed';
                        angular.element(event.target).removeClass('glyphicon-resize-small');
                        angular.element(event.target).addClass('glyphicon-resize-full');
                        $option.pinned = true;
                    }
                    else{
                        $element.style.position = 'absolute';
                        angular.element(event.target).removeClass('glyphicon-resize-full');
                        angular.element(event.target).addClass('glyphicon-resize-small');
                        $option.pinned = false;
                    }

                },
                setTitle: function(newTitle){
                    $element.getElementsByClassName('title')[0].innerHTML = newTitle;
                },
                isOpened: function(){
                    return ($element.style.display != 'none') ? true : false;
                },
                isMaximized: function(){

                },
                isMinimized: function(){
                    return ($element.getElementsByClassName('content')[0].style.display != 'none') ? false : true;
                }
            };

            return fun;
        },
        getDefaultOptions: function(){
            var defaultOption = {
                modelName : "",
                width : 100,
                height : 100,
                template: "123",
                templateUrl : "",
                resizable : true,
                draggable : true,
                position : {
                    top : 100,
                    left : 100
                },
                title : "",
                modal : false,
                pinned : false,
                onOpen : function(){},
                onClose  : function(){},
                onDragStart : function(){},
                onDragEnd : function(){},
                onResize : function(){}

            };

            return defaultOption;
        },
        callParentScopeApply: function(scope){
            if(!scope.$$phase){
                scope.$apply()
            }
        },
        updateParentScopeOptions: function(options,element){
            options.position.top =  element.offsetTop;
            options.position.left = element.offsetLeft;
            options.width = element.offsetWidth;
            options.height = element.offsetHeight;
        }
    };

    return ngPopupBuilder;
});<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//
// BrowserOptions class
// Encapsulated handling of browser options page.
//
function BrowserOptions() {
  OptionsPage.call(this, 'browser', templateData.browserPage, 'browserPage');
}

cr.addSingletonGetter(BrowserOptions);

BrowserOptions.prototype = {
  // Inherit BrowserOptions from OptionsPage.
  __proto__: OptionsPage.prototype,

  /**
   * Initialize BrowserOptions page.
   */
  initializePage: function() {
    // Call base class implementation to start preference initialization.
    OptionsPage.prototype.initializePage.call(this);

    // Wire up buttons.
    $('startupAddButton').onclick = function(event) {
      // TODO(stuartmorgan): Spawn add sub-dialog.
    };
    $('startupRemoveButton').onclick = function(event) {
      // TODO(stuartmorgan): Remove selected element(s).
    };
    $('startupUseCurrentButton').onclick = function(event) {
      // TODO(stuartmorgan): Add all open tabs (except this one).
    };
    $('defaultSearchManageEnginesButton').onclick = function(event) {
      // TODO(stuartmorgan): Spawn search engine management sub-dialog.
    };
    $('defaultBrowserUseAsDefaultButton').onclick = function(event) {
      chrome.send('becomeDefaultBrowser');
    };
  },

  /**
   * Update the Default Browsers section based on the current state.
   * @param {String} statusString Description of the current default state.
   * @param {Boolean} isDefault Whether or not the browser is currently default.
   */
  updateDefaultBrowserState_: function(statusString, isDefault) {
    var label = $('defaultBrowserState');
    label.textContent = statusString;
    if (isDefault) {
      label.classList.add('current');
    } else {
      label.classList.remove('current');
    }

    $('defaultBrowserUseAsDefaultButton').disabled = isDefault;
  },

  /**
   * Clears the search engine popup.
   * @private
   */
  clearSearchEngines_: function() {
    $('defaultSearchEngine').textContent = '';
  },

  /**
   * Updates the search engine popup with the given entries.
   * @param {Array} engines List of available search engines.
   * @param {Integer} defaultValue The value of the current default engine.
   */
  updateSearchEngines_: function(engines, defaultValue) {
    this.clearSearchEngines_();
    engineSelect = $('defaultSearchEngine');
    engineCount = engines.length
    var defaultIndex = -1;
    for (var i = 0; i < engineCount; i++) {
      var engine = engines[i]
      var option = new Option(engine['name'], engine['index']);
      if (defaultValue == option.value)
        defaultIndex = i;
      engineSelect.appendChild(option);
    }
    if (defaultIndex >= 0)
      engineSelect.selectedIndex = defaultIndex;
  },

  /**
   * Set the default search engine based on the popup selection.
   */
  setDefaultBrowser: function() {
    var engineSelect = $('defaultSearchEngine');
    var selectedIndex = engineSelect.selectedIndex;
    if (selectedIndex >= 0) {
      var selection = engineSelect.options[selectedIndex];
      chrome.send('setDefaultSearchEngine', [String(selection.value)]);
    }
  },
};

BrowserOptions.updateDefaultBrowserState = function(statusString, isDefault) {
  BrowserOptions.getInstance().updateDefaultBrowserState_(statusString,
                                                          isDefault);
}

BrowserOptions.updateSearchEngines = function(engines, defaultValue) {
  BrowserOptions.getInstance().updateSearchEngines_(engines, defaultValue);
}
<commit_msg>Strip & accelerator markers from buttons on the Basics DOMUI pref page<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//
// BrowserOptions class
// Encapsulated handling of browser options page.
//
function BrowserOptions() {
  OptionsPage.call(this, 'browser', templateData.browserPage, 'browserPage');
}

cr.addSingletonGetter(BrowserOptions);

BrowserOptions.prototype = {
  // Inherit BrowserOptions from OptionsPage.
  __proto__: OptionsPage.prototype,

  /**
   * Initialize BrowserOptions page.
   */
  initializePage: function() {
    // Call base class implementation to start preference initialization.
    OptionsPage.prototype.initializePage.call(this);

    // Wire up buttons.
    $('startupAddButton').onclick = function(event) {
      // TODO(stuartmorgan): Spawn add sub-dialog.
    };
    $('startupRemoveButton').onclick = function(event) {
      // TODO(stuartmorgan): Remove selected element(s).
    };
    $('startupUseCurrentButton').onclick = function(event) {
      // TODO(stuartmorgan): Add all open tabs (except this one).
    };
    $('defaultSearchManageEnginesButton').onclick = function(event) {
      // TODO(stuartmorgan): Spawn search engine management sub-dialog.
    };
    $('defaultBrowserUseAsDefaultButton').onclick = function(event) {
      chrome.send('becomeDefaultBrowser');
    };

    // Remove Windows-style accelerators from button labels.
    // TODO(stuartmorgan): Remove this once the strings are updated.
    $('startupAddButton').textContent =
        localStrings.getStringWithoutAccelerator('startupAddButton');
    $('startupRemoveButton').textContent =
        localStrings.getStringWithoutAccelerator('startupRemoveButton');
  },

  /**
   * Update the Default Browsers section based on the current state.
   * @param {String} statusString Description of the current default state.
   * @param {Boolean} isDefault Whether or not the browser is currently default.
   */
  updateDefaultBrowserState_: function(statusString, isDefault) {
    var label = $('defaultBrowserState');
    label.textContent = statusString;
    if (isDefault) {
      label.classList.add('current');
    } else {
      label.classList.remove('current');
    }

    $('defaultBrowserUseAsDefaultButton').disabled = isDefault;
  },

  /**
   * Clears the search engine popup.
   * @private
   */
  clearSearchEngines_: function() {
    $('defaultSearchEngine').textContent = '';
  },

  /**
   * Updates the search engine popup with the given entries.
   * @param {Array} engines List of available search engines.
   * @param {Integer} defaultValue The value of the current default engine.
   */
  updateSearchEngines_: function(engines, defaultValue) {
    this.clearSearchEngines_();
    engineSelect = $('defaultSearchEngine');
    engineCount = engines.length
    var defaultIndex = -1;
    for (var i = 0; i < engineCount; i++) {
      var engine = engines[i]
      var option = new Option(engine['name'], engine['index']);
      if (defaultValue == option.value)
        defaultIndex = i;
      engineSelect.appendChild(option);
    }
    if (defaultIndex >= 0)
      engineSelect.selectedIndex = defaultIndex;
  },

  /**
   * Set the default search engine based on the popup selection.
   */
  setDefaultBrowser: function() {
    var engineSelect = $('defaultSearchEngine');
    var selectedIndex = engineSelect.selectedIndex;
    if (selectedIndex >= 0) {
      var selection = engineSelect.options[selectedIndex];
      chrome.send('setDefaultSearchEngine', [String(selection.value)]);
    }
  },
};

BrowserOptions.updateDefaultBrowserState = function(statusString, isDefault) {
  BrowserOptions.getInstance().updateDefaultBrowserState_(statusString,
                                                          isDefault);
}

BrowserOptions.updateSearchEngines = function(engines, defaultValue) {
  BrowserOptions.getInstance().updateSearchEngines_(engines, defaultValue);
}
<|endoftext|>