<commit_before>import { Report, Position, Task, Location } from "models"
import faker from "faker"
import _isEmpty from "lodash/isEmpty"
import _isEqual from "lodash/isEqual"
import _uniqWith from "lodash/uniqWith"
import { runGQL, populate } from "../simutils"

async function getRandomPerson(user, variables) {
  const positionsQuery = Object.assign({}, variables, {
    pageNum: 0,
    pageSize: 1
  })
  const totalCount = (await runGQL(user, {
    query: `
        query ($positionsQuery: PositionSearchQueryInput) {
          positionList(query: $positionsQuery) {
            totalCount
          }
        }
      `,
    variables: {
      positionsQuery
    }
  })).data.positionList.totalCount
  let positions = null
  if (totalCount > 0) {
    positionsQuery.pageNum = faker.random.number({ max: totalCount - 1 })
    positions = (await runGQL(user, {
      query: `
          query ($positionsQuery: PositionSearchQueryInput) {
            positionList(query: $positionsQuery) {
              list {
                uuid
                type
                person {
                  uuid
                  name
                  role
                }
              }
            }
          }
        `,
      variables: {
        positionsQuery
      }
    })).data.positionList.list
  }
  return _isEmpty(positions) ? null : positions[0].person
}

export const randomAdvisor = async function(user) {
  return getRandomPerson(user, {
    status: Position.STATUS.ACTIVE,
    isFilled: true,
    type: [Position.TYPE.ADVISOR]
  })
}

export const randomPrincipal = async function(user) {
  return getRandomPerson(user, {
    status: Position.STATUS.ACTIVE,
    isFilled: true,
    type: [Position.TYPE.PRINCIPAL]
  })
}

async function populateReport(report, user, args) {
  const emptyArray = () => {
    return []
  }

  /* eslint-disable no-unused-vars */
  const emptyObject = () => {
    return {}
  }
  /* eslint-enable no-unused-vars */

  async function activeLocation() {
    const totalCount = (await runGQL(user, {
      query: `
        query ($locationQuery: LocationSearchQueryInput) {
          locationList(query: $locationQuery) {
            totalCount
          }
        }
      `,
      variables: {
        locationQuery: {
          pageNum: 0,
          pageSize: 1,
          status: Location.STATUS.ACTIVE
        }
      }
    })).data.locationList.totalCount
    let activeLocations = null
    if (totalCount > 0) {
      const random = faker.random.number({ max: totalCount - 1 })
      activeLocations = (await runGQL(user, {
        query: `
          query ($locationQuery: LocationSearchQueryInput) {
            locationList(query: $locationQuery) {
              list {
                uuid
              }
            }
          }
        `,
        variables: {
          locationQuery: {
            pageNum: random,
            pageSize: 1,
            status: Location.STATUS.ACTIVE
          }
        }
      })).data.locationList.list
    }
    return _isEmpty(activeLocations) ? null : activeLocations[0]
  }

  async function activeTask() {
    const totalCount = (await runGQL(user, {
      query: `
        query ($taskQuery: TaskSearchQueryInput) {
          taskList(query: $taskQuery) {
            totalCount
          }
        }
      `,
      variables: {
        taskQuery: {
          pageNum: 0,
          pageSize: 1,
          status: Task.STATUS.ACTIVE
        }
      }
    })).data.taskList.totalCount
    let activeTasks = null
    if (totalCount > 0) {
      const random = faker.random.number({ max: totalCount - 1 })
      activeTasks = (await runGQL(user, {
        query: `
          query ($taskQuery: TaskSearchQueryInput) {
            taskList(query: $taskQuery) {
              list {
                uuid
              }
            }
          }
        `,
        variables: {
          taskQuery: {
            pageNum: random,
            pageSize: 1,
            status: Task.STATUS.ACTIVE
          }
        }
      })).data.taskList.list
    }
    return _isEmpty(activeTasks) ? null : activeTasks[0]
  }

  const location = await activeLocation()
  async function getAttendees() {
    const attendees = []
    const nbOfAdvisors = faker.random.number({ min: 1, max: 5 })
    for (let i = 0; i < nbOfAdvisors; i++) {
      const advisor = await randomAdvisor(user)
      if (advisor) {
        advisor.primary = i === 0
        attendees.push(advisor)
      }
    }

    const nbOfPrincipals = faker.random.number({ min: 1, max: 5 })
    for (let i = 0; i < nbOfPrincipals; i++) {
      const principal = await randomPrincipal(user)
      if (principal) {
        principal.primary = i === 0
        attendees.push(principal)
      }
    }

    return [..._uniqWith(attendees, _isEqual)]
  }
  const attendees = await getAttendees()
  async function getTasks() {
    const reportTasks = []
    const nbOfTasks = faker.random.number({ min: 1, max: 3 })

    for (let i = 0; i < nbOfTasks; i++) {
      reportTasks.push(await activeTask())
    }

    return [..._uniqWith(reportTasks, _isEqual)]
  }
  const tasks = await getTasks()
  const template = {
    intent: () => faker.lorem.paragraph(),
    engagementDate: () => faker.date.recent().toISOString(),
    duration: () => faker.random.number({ min: 1, max: 480 }),
    cancelledReason: () =>
      faker.random.arrayElement([
        "CANCELLED_BY_ADVISOR",
        "CANCELLED_BY_PRINCIPAL",
        "CANCELLED_DUE_TO_TRANSPORTATION",
        "CANCELLED_DUE_TO_FORCE_PROTECTION",
        "CANCELLED_DUE_TO_ROUTES",
        "CANCELLED_DUE_TO_THREAT"
      ]),
    atmosphere: () =>
      faker.random.arrayElement(["POSITIVE", "NEUTRAL", "NEGATIVE"]),
    atmosphereDetails: () => faker.lorem.sentence(),
    location,
    attendees,
    tasks,
    reportText: () => faker.lorem.paragraphs(),
    nextSteps: () => faker.lorem.sentence(),
    keyOutcomes: () => faker.lorem.sentence(),
    tags: emptyArray,
    reportSensitiveInformation: () => null,
    authorizationGroups: emptyArray,
    state: (args && args.state) || Report.STATE.DRAFT
  }

  populate(report, template)
    .intent.always()
    .engagementDate.always()
    .duration.often()
    .cancelledReason.often()
    .atmosphere.always()
    .atmosphereDetails.always()
    .location.always()
    .attendees.always()
    .tasks.always()
    .reportText.always()
    .nextSteps.always()
    .keyOutcomes.always()
    .tags.rarely()
    .reportSensitiveInformation.and()
    .authorizationGroups.rarely()
    .state.always()

  return report
}

const createReport = async function(user, args) {
  const report = new Report()
  if (await populateReport(report, user, args)) {
    console.debug(`Creating report ${report.intent.green}`)
    const { reportTags, cancelled, ...reportStripped } = report // TODO: we need to do this more generically

    return (await runGQL(user, {
      query:
        "mutation($report: ReportInput!) { createReport(report: $report) { uuid } }",
      variables: { report: reportStripped }
    })).data.createReport
  }
}

const updateDraftReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          list {
            uuid
            intent
            engagementDate
            duration
            keyOutcomes
            nextSteps
            cancelledReason
            atmosphere
            atmosphereDetails
            attendees {
              uuid
              primary
            }
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = !_isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  if (await populateReport(report, user)) {
    return (await runGQL(user, {
      query:
        "mutation($report: ReportInput!) { updateReport(report: $report) { uuid } }",
      variables: { report: report }
    })).data.updateReport
  }
}

const submitDraftReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          list {
            uuid
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = _isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  return (await runGQL(user, {
    query: "mutation($uuid: String!) { submitReport(uuid: $uuid) { uuid } }",
    variables: { uuid: report.uuid }
  })).data.submitReport
}

const approveReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          pendingApprovalOf: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          pendingApprovalOf: "${user.person.uuid}"
        }) {
          list {
            uuid
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = _isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  return (await runGQL(user, {
    query: "mutation ($uuid: String!) { approveReport(uuid: $uuid) { uuid } }",
    variables: { uuid: report.uuid }
  })).data.approveReport
}

export { createReport, updateDraftReport, submitDraftReport, approveReport }
<commit_msg>NCI-Agency/anet#379: Fix issue with report generation<commit_after>import { Report, Position, Task, Location } from "models"
import faker from "faker"
import _isEmpty from "lodash/isEmpty"
import _isEqual from "lodash/isEqual"
import _uniqWith from "lodash/uniqWith"
import { runGQL, populate } from "../simutils"

async function getRandomPerson(user, variables) {
  const positionsQuery = Object.assign({}, variables, {
    pageNum: 0,
    pageSize: 1
  })
  const totalCount = (await runGQL(user, {
    query: `
        query ($positionsQuery: PositionSearchQueryInput) {
          positionList(query: $positionsQuery) {
            totalCount
          }
        }
      `,
    variables: {
      positionsQuery
    }
  })).data.positionList.totalCount
  let positions = null
  if (totalCount > 0) {
    positionsQuery.pageNum = faker.random.number({ max: totalCount - 1 })
    positions = (await runGQL(user, {
      query: `
          query ($positionsQuery: PositionSearchQueryInput) {
            positionList(query: $positionsQuery) {
              list {
                uuid
                type
                person {
                  uuid
                  name
                  role
                }
              }
            }
          }
        `,
      variables: {
        positionsQuery
      }
    })).data.positionList.list
  }
  return _isEmpty(positions) ? null : positions[0].person
}

export const randomAdvisor = async function(user) {
  return getRandomPerson(user, {
    status: Position.STATUS.ACTIVE,
    isFilled: true,
    type: [Position.TYPE.ADVISOR]
  })
}

export const randomPrincipal = async function(user) {
  return getRandomPerson(user, {
    status: Position.STATUS.ACTIVE,
    isFilled: true,
    type: [Position.TYPE.PRINCIPAL]
  })
}

async function populateReport(report, user, args) {
  const emptyArray = () => {
    return []
  }

  /* eslint-disable no-unused-vars */
  const emptyObject = () => {
    return {}
  }
  /* eslint-enable no-unused-vars */

  async function activeLocation() {
    const totalCount = (await runGQL(user, {
      query: `
        query ($locationQuery: LocationSearchQueryInput) {
          locationList(query: $locationQuery) {
            totalCount
          }
        }
      `,
      variables: {
        locationQuery: {
          pageNum: 0,
          pageSize: 1,
          status: Location.STATUS.ACTIVE
        }
      }
    })).data.locationList.totalCount
    let activeLocations = null
    if (totalCount > 0) {
      const random = faker.random.number({ max: totalCount - 1 })
      activeLocations = (await runGQL(user, {
        query: `
          query ($locationQuery: LocationSearchQueryInput) {
            locationList(query: $locationQuery) {
              list {
                uuid
              }
            }
          }
        `,
        variables: {
          locationQuery: {
            pageNum: random,
            pageSize: 1,
            status: Location.STATUS.ACTIVE
          }
        }
      })).data.locationList.list
    }
    return _isEmpty(activeLocations) ? null : activeLocations[0]
  }

  async function activeTask() {
    const totalCount = (await runGQL(user, {
      query: `
        query ($taskQuery: TaskSearchQueryInput) {
          taskList(query: $taskQuery) {
            totalCount
          }
        }
      `,
      variables: {
        taskQuery: {
          pageNum: 0,
          pageSize: 1,
          status: Task.STATUS.ACTIVE
        }
      }
    })).data.taskList.totalCount
    let activeTasks = null
    if (totalCount > 0) {
      const random = faker.random.number({ max: totalCount - 1 })
      activeTasks = (await runGQL(user, {
        query: `
          query ($taskQuery: TaskSearchQueryInput) {
            taskList(query: $taskQuery) {
              list {
                uuid
              }
            }
          }
        `,
        variables: {
          taskQuery: {
            pageNum: random,
            pageSize: 1,
            status: Task.STATUS.ACTIVE
          }
        }
      })).data.taskList.list
    }
    return _isEmpty(activeTasks) ? null : activeTasks[0]
  }

  const location = await activeLocation()
  async function getAttendees() {
    const attendees = []
    const nbOfAdvisors = faker.random.number({ min: 1, max: 5 })
    for (let i = 0; i < nbOfAdvisors; i++) {
      const advisor = await randomAdvisor(user)
      if (advisor) {
        advisor.primary = i === 0
        attendees.push(advisor)
      }
    }

    const nbOfPrincipals = faker.random.number({ min: 1, max: 5 })
    for (let i = 0; i < nbOfPrincipals; i++) {
      const principal = await randomPrincipal(user)
      if (principal) {
        principal.primary = i === 0
        attendees.push(principal)
      }
    }

    return [..._uniqWith(attendees, _isEqual)]
  }
  const attendees = await getAttendees()
  async function getTasks() {
    const reportTasks = []
    const nbOfTasks = faker.random.number({ min: 1, max: 3 })

    for (let i = 0; i < nbOfTasks; i++) {
      reportTasks.push(await activeTask())
    }

    return [..._uniqWith(reportTasks, _isEqual)]
  }
  const tasks = await getTasks()
  const template = {
    intent: () => faker.lorem.paragraph(),
    engagementDate: () => faker.date.recent().toISOString(),
    duration: () => faker.random.number({ min: 1, max: 480 }),
    cancelledReason: () =>
      faker.random.arrayElement([
        "CANCELLED_BY_ADVISOR",
        "CANCELLED_BY_PRINCIPAL",
        "CANCELLED_DUE_TO_TRANSPORTATION",
        "CANCELLED_DUE_TO_FORCE_PROTECTION",
        "CANCELLED_DUE_TO_ROUTES",
        "CANCELLED_DUE_TO_THREAT"
      ]),
    atmosphere: () =>
      faker.random.arrayElement(["POSITIVE", "NEUTRAL", "NEGATIVE"]),
    atmosphereDetails: () => faker.lorem.sentence(),
    location,
    attendees,
    tasks,
    reportText: () => faker.lorem.paragraphs(),
    nextSteps: () => faker.lorem.sentence(),
    keyOutcomes: () => faker.lorem.sentence(),
    tags: emptyArray,
    reportSensitiveInformation: () => null,
    authorizationGroups: emptyArray,
    state: (args && args.state) || Report.STATE.DRAFT
  }

  populate(report, template)
    .intent.always()
    .engagementDate.always()
    .duration.often()
    .cancelledReason.often()
    .atmosphere.always()
    .atmosphereDetails.always()
    .location.always()
    .attendees.always()
    .tasks.always()
    .reportText.always()
    .nextSteps.always()
    .keyOutcomes.always()
    .tags.rarely()
    .reportSensitiveInformation.and()
    .authorizationGroups.rarely()
    .state.always()

  return report
}

const createReport = async function(user, grow, args) {
  const report = new Report()
  if (await populateReport(report, user, args)) {
    console.debug(`Creating report ${report.intent.green}`)
    const { reportTags, cancelled, ...reportStripped } = report // TODO: we need to do this more generically

    return (await runGQL(user, {
      query:
        "mutation($report: ReportInput!) { createReport(report: $report) { uuid } }",
      variables: { report: reportStripped }
    })).data.createReport
  }
}

const updateDraftReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          list {
            uuid
            intent
            engagementDate
            duration
            keyOutcomes
            nextSteps
            cancelledReason
            atmosphere
            atmosphereDetails
            attendees {
              uuid
              primary
            }
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = !_isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  if (await populateReport(report, user)) {
    return (await runGQL(user, {
      query:
        "mutation($report: ReportInput!) { updateReport(report: $report) { uuid } }",
      variables: { report: report }
    })).data.updateReport
  }
}

const submitDraftReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          state: ${Report.STATE.DRAFT},
          authorUuid: "${user.person.uuid}"
        }) {
          list {
            uuid
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = _isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  return (await runGQL(user, {
    query: "mutation($uuid: String!) { submitReport(uuid: $uuid) { uuid } }",
    variables: { uuid: report.uuid }
  })).data.submitReport
}

const approveReport = async function(user) {
  const totalCount = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: 0,
          pageSize: 1,
          pendingApprovalOf: "${user.person.uuid}"
        }) {
          totalCount
        }
      }
    `,
    variables: {}
  })).data.reportList.totalCount
  if (totalCount === 0) {
    return null
  }
  const random = faker.random.number({ max: totalCount - 1 })
  const reports = (await runGQL(user, {
    query: `
      query {
        reportList(query: {
          pageNum: ${random},
          pageSize: 1,
          pendingApprovalOf: "${user.person.uuid}"
        }) {
          list {
            uuid
          }
        }
      }
    `,
    variables: {}
  })).data.reportList.list
  const report = _isEmpty(reports) && reports[0]
  if (!report) {
    return null
  }

  return (await runGQL(user, {
    query: "mutation ($uuid: String!) { approveReport(uuid: $uuid) { uuid } }",
    variables: { uuid: report.uuid }
  })).data.approveReport
}

export { createReport, updateDraftReport, submitDraftReport, approveReport }
<|endoftext|>


<commit_before>Template.unsubscribe.created = function(){
  var hash = Session.get('userEmailHash');
  Meteor.call('unsubscribeUser', hash, function(error, result){
    if(result){
      Session.set('unsubscribedMessage', 'You have been unsubscribed from all notifications.');
    }else{
      Session.set('unsubscribedMessage', 'User not found.');
    }
  });
}

Template.unsubscribe.helpers({
  unsubscribed : function(){
    return Session.get('unsubscribedMessage');
  }
});<commit_msg>tracking unsubscribes<commit_after>Template.unsubscribe.created = function(){
  var hash = Session.get('userEmailHash');
  Meteor.call('unsubscribeUser', hash, function(error, result){
    if(result){
      Session.set('unsubscribedMessage', 'You have been unsubscribed from all notifications.');
    }else{
      Session.set('unsubscribedMessage', 'User not found.');
    }
  });
  trackEvent('notificationsUnsubcribe', {hash: hash});
}

Template.unsubscribe.helpers({
  unsubscribed : function(){
    return Session.get('unsubscribedMessage');
  }
});<|endoftext|>


<commit_before>(function() {
    'use strict';

    function Boot() {
    }

    Boot.prototype.preload = function() {

        // Load animations before game start
        game.load.json('preload-loading-icon',
            'assets/img/preload/loading-icon.json');

        game.load.json('preload-game-name',
            'assets/img/preload/game-name.json');

        // configure game
        if (game.device.desktop) {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            game.scale.pageAlignHorizontally = true;
            game.scale.pageAlignVertically = true;
        } else {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            // game.scale.minWidth = 480;
            // game.scale.minHeight = 260;
            // game.scale.maxWidth = 640;
            // game.scale.maxHeight = 480;
            // game.scale.forceOrientation(true);
            // game.scale.pageAlignHorizontally = true;
            // game.scale.refresh(true);
        }
    };

    Boot.prototype.create = function() {
        game.state.start('ladingScreen');
    }

    window['CountryLife'] = window['CountryLife'] || {};
    window['CountryLife'].Boot = Boot;
}());
<commit_msg>Update Boot.js<commit_after>(function() {
    'use strict';

    function Boot() {
    }

    Boot.prototype.preload = function() {

        // Load animations before game start
        game.load.json('preload-loading-icon',
            'assets/img/preload/loading-icon.json');

        game.load.json('preload-game-name',
            'assets/img/preload/game-name.json');

        // configure game
        if (game.device.desktop) {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            game.scale.pageAlignHorizontally = true;
            game.scale.pageAlignVertically = true;
        } else {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            game.scale.minWidth = 480;
            game.scale.minHeight = 260;
            game.scale.maxWidth = 640;
            game.scale.maxHeight = 480;
            game.scale.forceOrientation(true);
            game.scale.pageAlignHorizontally = true;
            game.scale.refresh(true);
        }
    };

    Boot.prototype.create = function() {
        game.state.start('ladingScreen');
    }

    window['CountryLife'] = window['CountryLife'] || {};
    window['CountryLife'].Boot = Boot;
}());
<|endoftext|>


<commit_before>'use strict';

class Balance {
    constructor(request, response){
        this.request = request;
        this.response = response;
        this.currentUser = request.user;
    }

    transfer() {
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const cpf = this.request.params.cpf;
        const value = this.request.params.value;
        const sbalance = this.currentUser.get("balance") || 0;

        if(cpf === undefined || value === undefined || value > sbalance){
            this.response.error({message: "Parametros invalidos..."});
            return;
        }

        let query = new Parse.Query(Parse.User);
        query.equalTo("username", cpf);
        query.first().then((user) => {
            user.set("balance", user.get('balance')+parseFloat(value));
            return user.save(null, {useMasterKey:true});
        }).then((user) => {
            return this.currentUser.fetch();
        }).then((user) => {
            user.set("balance", user.get('balance')-parseFloat(value));
            return user.save(null, {useMasterKey:true});
        }).then((user) => {
            this.response.success(user);
        }, (error) => {
            this.response.error(error);
        })
    }

    pay() {
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const cpf = this.request.params.cpf;
        const purchase = this.request.params.purchase;
        const sbalance = this.currentUser.get("balance") || 0;

        if (cpf === undefined || purchase === undefined) {
            this.response.error({message: "Parâmetros inválidos!"});
            return;
        }

        const value = sbalance - purchase;
        if(value < 0){
            this.response.error({message: "Não há saldo suficiente!"});
            return;
        }

        let query = new Parse.Query(Parse.User);
        query.equalTo("username", cpf);

        try {
            query.first()
                .then((user) => {
                    return this.currentUser.fetch();
                })
                .then((user) => {
                    user.set("balance", value);
                    return user.save();
                })
                .then((user) => {
                    this.response.success(user);
                }, (error) => {
                    this.response.error(error);
                })
        } catch (Error) {
            this.response.error({message: "Não foi possível realizar operação!"});
            return;
        }
    }

    getClientData(){
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const data = this.request.params.identification;
        if(data === undefined){
            this.response.error({message: "Parametros invalidos..."});
            return;
        }

        let query;
        if(data.length === 11){
            query = new Parse.Query(Parse.User);
            query.equalTo('username', data);
        } else if(data.length === 7){
            query = new Parse.Query("Vehicle");
            query.equalTo("plate", data);
        } else {
            this.response.error({message: "Parametro deve ser um CPF ou uma placa..."});
            return;
        }

        query.first().then((obj) => {
            if(!obj)
                this.response.success({});

            const result = obj.get('owner') || obj;
            this.response.success(result);
        }, (error) => {
            this.response.error(error);
        });
    }
}

Parse.Cloud.define('transferBalance', (req, res) => {
    new Balance(req, res).transfer();
});

Parse.Cloud.define('pay', (req, res) => {
    new Balance(req, res).pay();
});

Parse.Cloud.define('getClientData', (req, res) => {
    new Balance(req, res).getClientData();
});<commit_msg>correçãO<commit_after>'use strict';

class Balance {
    constructor(request, response){
        this.request = request;
        this.response = response;
        this.currentUser = request.user;
    }

    transfer() {
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const cpf = this.request.params.cpf;
        const value = this.request.params.value;
        const sbalance = this.currentUser.get("balance") || 0;

        if(cpf === undefined || value === undefined || value > sbalance){
            this.response.error({message: "Parametros invalidos..."});
            return;
        }

        let query = new Parse.Query(Parse.User);
        query.equalTo("username", cpf);
        query.first().then((user) => {
            user.set("balance", user.get('balance')+parseFloat(value));
            return user.save(null, {useMasterKey:true});
        }).then((user) => {
            return this.currentUser.fetch();
        }).then((user) => {
            user.set("balance", user.get('balance')-parseFloat(value));
            return user.save(null, {useMasterKey:true});
        }).then((user) => {
            this.response.success(user);
        }, (error) => {
            this.response.error(error);
        })
    }

    pay() {
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const cpf = this.request.params.cpf;
        const purchase = this.request.params.purchase;
        const sbalance = this.currentUser.get("balance") || 0;

        if (cpf === undefined || purchase === undefined) {
            this.response.error({message: "Parâmetros inválidos!"});
            return;
        }

        const value = sbalance - purchase;
        if(value < 0){
            this.response.error({message: "Não há saldo suficiente!"});
            return;
        }

        let query = new Parse.Query(Parse.User);
        query.equalTo("username", cpf);

        try {
            query.first()
                .then((user) => {
                    return this.currentUser.fetch();
                })
                .then((user) => {
                    user.set("balance", value);
                    return user.save();
                })
                .then((user) => {
                    this.response.success(user);
                }, (error) => {
                    this.response.error(error);
                })
        } catch (Error) {
            this.response.error({message: "Não foi possível realizar operação!"});
            return;
        }
    }

    getClientData(){
        if(!this.currentUser){
            this.response.error({message: "Tem que estar logado..."});
            return;
        }

        const data = this.request.params.identification;
        if(data === undefined){
            this.response.error({message: "Parametros invalidos..."});
            return;
        }

        let query;
        if(data.length === 11){
            query = new Parse.Query(Parse.User);
            query.equalTo('username', data);
        } else if(data.length === 7){
            query = new Parse.Query("Vehicle");
            query.equalTo("plate", data);
        } else {
            this.response.error({message: "Parametro deve ser um CPF ou uma placa..."});
            return;
        }

        query.first().then((obj) => {
            if(!obj)
                this.response.error("Usuário não encontrado...");

            const result = obj.get('owner') || obj;
            this.response.success(result);
        }, (error) => {
            this.response.error(error);
        });
    }
}

Parse.Cloud.define('transferBalance', (req, res) => {
    new Balance(req, res).transfer();
});

Parse.Cloud.define('pay', (req, res) => {
    new Balance(req, res).pay();
});

Parse.Cloud.define('getClientData', (req, res) => {
    new Balance(req, res).getClientData();
});<|endoftext|>


<commit_before>describe("Turn view", function () {
    var turnsView;

    beforeEach(function () {
        var turns = new App.Collections.Turns();
        turns.reset([
            {
                turn: 2,
                startDate: '22 sep',
                endDate: '23 sep',
                rosters: [
                    {
                        team: 'Fredrikshof A',
                        location: 'Birka',
                        opponent: 'Stockholm IFK',
                        date: 'lördag den 22 september 2012, 10:00',
                        declined: {
                            count: 2,
                            names: 'Kjell Jansson, Christer Liedholm'
                        }
                    },
                    {
                        team: 'Fredrikshof F',
                        location: 'Bowl-O-Rama',
                        opponent: 'AIK F',
                        date: 'lördag den 22 september 2012, 11:40',
                        declined: {
                            count: 1,
                            names: 'Daniel Lidström'
                        }
                    },
                    {
                        team: 'Fredrikshof B',
                        location: 'Bowl-O-Rama',
                        opponent: 'Hellas B',
                        date: 'söndag den 23 september 2012, 10:00',
                        declined: null
                    }
                ]
            }
        ]);
        this.turnsView = new App.Views.Turns({ model: turns });
    });

    it("lists all matches", function () {
        expect(this.turnsView.$(".row-fluid", ".span4").length).toEqual(3);
    });
});<commit_msg>Minor<commit_after>describe("Turn view", function () {
    var turns_view;

    beforeEach(function () {
        var turns = new App.Collections.Turns();
        turns.reset([
            {
                turn: 2,
                startDate: '22 sep',
                endDate: '23 sep',
                rosters: [
                    {
                        team: 'Fredrikshof A',
                        location: 'Birka',
                        opponent: 'Stockholm IFK',
                        date: 'lördag den 22 september 2012, 10:00',
                        declined: {
                            count: 2,
                            names: 'Kjell Jansson, Christer Liedholm'
                        }
                    },
                    {
                        team: 'Fredrikshof F',
                        location: 'Bowl-O-Rama',
                        opponent: 'AIK F',
                        date: 'lördag den 22 september 2012, 11:40',
                        declined: {
                            count: 1,
                            names: 'Daniel Lidström'
                        }
                    },
                    {
                        team: 'Fredrikshof B',
                        location: 'Bowl-O-Rama',
                        opponent: 'Hellas B',
                        date: 'söndag den 23 september 2012, 10:00',
                        declined: null
                    }
                ]
            }
        ]);
        this.turns_view = new App.Views.Turns({ model: turns });
    });

    it("lists all matches", function () {
        expect(this.turnsView.$(".row-fluid", ".span4").length).toEqual(3);
    });
});<|endoftext|>


<commit_before>function scrollBack(timechangeratio) {
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	var timespan = until - from;
	var timechange = timespan * timechangeratio;
	if (timechange < 60) {
		if (parseInt(new Date().getTime().toString().substr(-3)) % 75 < 17) {
			timechange = 60;
		}
		else {
			timechange = 0;
		}
	}
	var newfrom = from - timechange;
	var newuntil = until - timechange;
	if (newfrom < mindatetime) {
		newfrom = mindatetime;
		newuntil = newfrom + timespan;
	}
	if (newuntil > maxdatetime) {
		newuntil = maxdatetime;
		newfrom = newuntil - timespan;
	}
	$("from").value = unix2datestr(newfrom);
	$("until").value = unix2datestr(newuntil);
	updateEvents();
}

function scrollForward(timechangeratio) {
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	var timespan = (until - from);
	var timechange = Math.round(timespan * timechangeratio);
	if (timechange < 60) {
		if (parseInt(new Date().getTime().toString().substr(-3)) % 75 < 17) {
			timechange = 60;
		}
		else {
			timechange = 0;
		}
	}
	var newfrom = from + timechange;
	var newuntil = until + timechange;
	if (newfrom < mindatetime) {
		newfrom = mindatetime;
		newuntil = newfrom + timespan;
	}
	if (newuntil > maxdatetime) {
		newuntil = maxdatetime;
		newfrom = newuntil - timespan;
	}
	$("from").value = unix2datestr(newfrom);
	$("until").value = unix2datestr(newuntil);
	updateEvents();
}

function updateViewDropdown() {
	views = JSON.parse(GET('api.php?getViews'));
	var sv = $("selectView");
	sv.options.length = 0;
	sv.options.add(new Option("Select a view", -1));
	for (var viewi in views) {
		var view = views[viewi];
		sv.options.add(new Option(view.name + " (" + view.filter + ")", view.rowid));
	}
}

function filterEvents() {
	var starttime = new Date().getTime();
	filteredEvents = [];
	var filter = $("filter").value;
	if (filter.length == 0) {
		filteredEvents = events;
		return;
	}
	for (var eventi in events) {
		var event = events[eventi];
		if ($("advfilter").checked) {
			var filters = filter.split("|");
			for (var filters2 in filters) {
				filters3 = filters[filters2];
				var ok = true;
				var filters3 = filters3.split("&");
				for (var filters4 in filters3) {
					filters4 = filters3[filters4].split(":");
					var field = filters4[0];
					var filter = filters4[1];
					switch (field) {
						case 'dtls':
							field = event.details;
							break;
						case 'sum':
							field = event.summary;
							break;
						case 'dev':
							field = event.device;
							break;
						case 'src':
							field = event.source;
							break;
						default:
							return [];
					}
					if (!new RegExp(filter).test(field)) {
						console.log(filter + " did not match " + field);
						ok = false;
						break;
					}
				}
				if (!ok) {
					continue;
				}
				else {
					filteredEvents.push(event);
					break;
				}
			}
		}
		else {
			// No advanced filters
			if ($("regexfilter").checked) {
				re = new RegExp(filter);
				if (re.test(event.summary)
						|| re.test(event.details)
						|| re.test(event.source)
						|| re.test(event.device)) {
					filteredEvents.push(event);
				}
			}
			else {
				if (event.summary.indexOf(filter) != -1
						|| event.details.indexOf(filter) != -1
						|| event.source.indexOf(filter) != -1
						|| event.device.indexOf(filter) != -1) {
					filteredEvents.push(event);
				}
			}
		}
		if (starttime + maxtime < new Date().getTime()) {
			console.log("Error 1895: I won't be working overtime.");
			return;
		}
	}
	if (displayRenderingTime) {
		console.log("Filtering time: " + (new Date().getTime() - starttime) + "ms");
	}
}

function updateEvents() {
	var starttime = new Date().getTime();
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	if (from == false || until == false) {
		console.log("Invalid date.");
		return;
	}
	var timespan = until - from;

	$("timeline").innerHTML = '';

	var previousEventPosPerc = 0;
	var previousEventTop = 0;
	for (var eventi in filteredEvents) {
		var event = filteredEvents[eventi];
		if (event.datetime < from || event.datetime > until) {
			continue;
		}
		var posPerc = (event.datetime - from) / timespan * 100;
		var left = Math.round(posPerc) + "%";
		var top = 0;
		if (previousEventPosPerc / posPerc > 0.9) {
			if (previousEventTop > 600) {
				previousEventTop = 0;
			}
			top = previousEventTop + 95;
		}

		var col = (eventi % 2) * 8 + 247;
		var evtDiv = newDiv($("timeline"));
		var cur = (event.details.length > 0 ? "pointer" : "auto");
		evtDiv.style = obj2style(
			{ width: "150px"
			, position: "absolute"
			, left: left
			, "background-color": "rgb(" + col + "," + col + "," + col + ")"
			, border: "1px solid grey"
			, "border-left": "2px solid black"
			, "border-bottom": "2px solid black"
			, "word-wrap": "break-word"
			, top: top + "px"
			, cursor: cur
		});
		evtDiv.onmouseover = function(ev) {
			ev.target.style.zIndex = 9999;
		};
		evtDiv.onmouseout  = function(ev) {
			ev.target.style.zIndex = 0;
		};
		var summary = (event.summary.length > 0 ? event.summary + "
" : "");
		evtDiv.innerHTML = "" + event.printableDatetime + "
"
			+ "@" + event.device + ":
"
			+ summary
			+ "Source: " + event.source + "";
		evtDiv.pleasedontkillme = {details: event.details};
		evtDiv.onclick = function(ev) {
			alert(ev.target.pleasedontkillme.details);
		};

		if (top == 0) {
			previousEventPosPerc = posPerc;
		}
		previousEventTop = top;

		if (starttime + maxtime < new Date().getTime()) {
			console.log("Error 6571: I won't be working overtime.");
			return;
		}
	}

	if (displayRenderingTime) {
		console.log("Event render time: " + (new Date().getTime() - starttime) + "ms");
	}
	starttime = new Date().getTime();

	if (window.lastTimespan != timespan) {
		// Render timeline block background
		var altcol = "235, 250, 235";
		col = altcol;
		var html = '';
		var daywidth = (3600 * 24) / (until - from) * 100;
		var hourwidth = 3600 / (until - from) * 100;
		for (var i = from; i < until - 3600 * 24; i += 3600 * 24) {
			html += "

";
			if (col == altcol) {
				col = "255, 255, 255";
			}
			else {
				col = altcol;
			}
		}
		html += "
";
		if (hourwidth > 0.5) {
			for (var i = from; i < until - 3600; i += 3600) {
				html += "

";
				if (col == altcol) {
					col = "255, 255, 255";
				}
				else {
					col = altcol;
				}
			}
		}
		$("timelinebg").innerHTML = html;
	}

	window.lastTimespan = timespan;

	if (displayRenderingTime) {
		console.log("Block bg rendering: " + (new Date().getTime() - starttime) + "ms");
	}
}

<commit_msg>No pointer cursor when there are no details<commit_after>function scrollBack(timechangeratio) {
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	var timespan = until - from;
	var timechange = timespan * timechangeratio;
	if (timechange < 60) {
		if (parseInt(new Date().getTime().toString().substr(-3)) % 75 < 17) {
			timechange = 60;
		}
		else {
			timechange = 0;
		}
	}
	var newfrom = from - timechange;
	var newuntil = until - timechange;
	if (newfrom < mindatetime) {
		newfrom = mindatetime;
		newuntil = newfrom + timespan;
	}
	if (newuntil > maxdatetime) {
		newuntil = maxdatetime;
		newfrom = newuntil - timespan;
	}
	$("from").value = unix2datestr(newfrom);
	$("until").value = unix2datestr(newuntil);
	updateEvents();
}

function scrollForward(timechangeratio) {
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	var timespan = (until - from);
	var timechange = Math.round(timespan * timechangeratio);
	if (timechange < 60) {
		if (parseInt(new Date().getTime().toString().substr(-3)) % 75 < 17) {
			timechange = 60;
		}
		else {
			timechange = 0;
		}
	}
	var newfrom = from + timechange;
	var newuntil = until + timechange;
	if (newfrom < mindatetime) {
		newfrom = mindatetime;
		newuntil = newfrom + timespan;
	}
	if (newuntil > maxdatetime) {
		newuntil = maxdatetime;
		newfrom = newuntil - timespan;
	}
	$("from").value = unix2datestr(newfrom);
	$("until").value = unix2datestr(newuntil);
	updateEvents();
}

function updateViewDropdown() {
	views = JSON.parse(GET('api.php?getViews'));
	var sv = $("selectView");
	sv.options.length = 0;
	sv.options.add(new Option("Select a view", -1));
	for (var viewi in views) {
		var view = views[viewi];
		sv.options.add(new Option(view.name + " (" + view.filter + ")", view.rowid));
	}
}

function filterEvents() {
	var starttime = new Date().getTime();
	filteredEvents = [];
	var filter = $("filter").value;
	if (filter.length == 0) {
		filteredEvents = events;
		return;
	}
	for (var eventi in events) {
		var event = events[eventi];
		if ($("advfilter").checked) {
			var filters = filter.split("|");
			for (var filters2 in filters) {
				filters3 = filters[filters2];
				var ok = true;
				var filters3 = filters3.split("&");
				for (var filters4 in filters3) {
					filters4 = filters3[filters4].split(":");
					var field = filters4[0];
					var filter = filters4[1];
					switch (field) {
						case 'dtls':
							field = event.details;
							break;
						case 'sum':
							field = event.summary;
							break;
						case 'dev':
							field = event.device;
							break;
						case 'src':
							field = event.source;
							break;
						default:
							return [];
					}
					if (!new RegExp(filter).test(field)) {
						console.log(filter + " did not match " + field);
						ok = false;
						break;
					}
				}
				if (!ok) {
					continue;
				}
				else {
					filteredEvents.push(event);
					break;
				}
			}
		}
		else {
			// No advanced filters
			if ($("regexfilter").checked) {
				re = new RegExp(filter);
				if (re.test(event.summary)
						|| re.test(event.details)
						|| re.test(event.source)
						|| re.test(event.device)) {
					filteredEvents.push(event);
				}
			}
			else {
				if (event.summary.indexOf(filter) != -1
						|| event.details.indexOf(filter) != -1
						|| event.source.indexOf(filter) != -1
						|| event.device.indexOf(filter) != -1) {
					filteredEvents.push(event);
				}
			}
		}
		if (starttime + maxtime < new Date().getTime()) {
			console.log("Error 1895: I won't be working overtime.");
			return;
		}
	}
	if (displayRenderingTime) {
		console.log("Filtering time: " + (new Date().getTime() - starttime) + "ms");
	}
}

function updateEvents() {
	var starttime = new Date().getTime();
	var from = datestr2unix($("from").value);
	var until = datestr2unix($("until").value);
	if (from == false || until == false) {
		console.log("Invalid date.");
		return;
	}
	var timespan = until - from;

	$("timeline").innerHTML = '';

	var previousEventPosPerc = 0;
	var previousEventTop = 0;
	for (var eventi in filteredEvents) {
		var event = filteredEvents[eventi];
		if (event.datetime < from || event.datetime > until) {
			continue;
		}
		var posPerc = (event.datetime - from) / timespan * 100;
		var left = Math.round(posPerc) + "%";
		var top = 0;
		if (previousEventPosPerc / posPerc > 0.9) {
			if (previousEventTop > 600) {
				previousEventTop = 0;
			}
			top = previousEventTop + 95;
		}

		var col = (eventi % 2) * 8 + 247;
		var evtDiv = newDiv($("timeline"));
		var cur = (event.details.length > 0 && event.details != "\n" ? "pointer" : "auto");
		evtDiv.style = obj2style(
			{ width: "150px"
			, position: "absolute"
			, left: left
			, "background-color": "rgb(" + col + "," + col + "," + col + ")"
			, border: "1px solid grey"
			, "border-left": "2px solid black"
			, "border-bottom": "2px solid black"
			, "word-wrap": "break-word"
			, top: top + "px"
			, cursor: cur
		});
		evtDiv.onmouseover = function(ev) {
			ev.target.style.zIndex = 9999;
		};
		evtDiv.onmouseout  = function(ev) {
			ev.target.style.zIndex = 0;
		};
		var summary = (event.summary.length > 0 ? event.summary + "
" : "");
		evtDiv.innerHTML = "" + event.printableDatetime + "
"
			+ "@" + event.device + ":
"
			+ summary
			+ "Source: " + event.source + "";
		evtDiv.pleasedontkillme = {details: event.details};
		evtDiv.onclick = function(ev) {
			alert(ev.target.pleasedontkillme.details);
		};

		if (top == 0) {
			previousEventPosPerc = posPerc;
		}
		previousEventTop = top;

		if (starttime + maxtime < new Date().getTime()) {
			console.log("Error 6571: I won't be working overtime.");
			return;
		}
	}

	if (displayRenderingTime) {
		console.log("Event render time: " + (new Date().getTime() - starttime) + "ms");
	}
	starttime = new Date().getTime();

	if (window.lastTimespan != timespan) {
		// Render timeline block background
		var altcol = "235, 250, 235";
		col = altcol;
		var html = '';
		var daywidth = (3600 * 24) / (until - from) * 100;
		var hourwidth = 3600 / (until - from) * 100;
		for (var i = from; i < until - 3600 * 24; i += 3600 * 24) {
			html += "

";
			if (col == altcol) {
				col = "255, 255, 255";
			}
			else {
				col = altcol;
			}
		}
		html += "
";
		if (hourwidth > 0.5) {
			for (var i = from; i < until - 3600; i += 3600) {
				html += "

";
				if (col == altcol) {
					col = "255, 255, 255";
				}
				else {
					col = altcol;
				}
			}
		}
		$("timelinebg").innerHTML = html;
	}

	window.lastTimespan = timespan;

	if (displayRenderingTime) {
		console.log("Block bg rendering: " + (new Date().getTime() - starttime) + "ms");
	}
}

<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

function selectionCount()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.selectionCount(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.selectionCount(MusicListModel.SelectByID);
    }
}

function clearSelected()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        multiSelectModel.clearSelected(MusicListModel.SelectByIndex);
        break;
    default:
        multiSelectModel.clearSelected(MusicListModel.SelectByID);
    }
}

function getSelectedURIs()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.getSelectedURIs(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.getSelectedURIs(MusicListModel.SelectByID);
    }
}

function getSelectedIDs()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.getSelectedIDs(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.getSelectedIDs(MusicListModel.SelectByID);
    }
}

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue() {
    playqueueModel.addItems(getSelectedIDs());
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue() {
    if(playqueueModel.playindex == targetIndex)
    {
        audio.stop();
        resourceManager.userwantsplayback = false;
    }
    playqueueModel.removeIndex(targetIndex);
    updateNowNextPlaying();
}

function removeFromPlaylist(list) {
    list.removeIndex(targetIndex);
    clearSelected();
}

function removeMultipleFromPlayqueue() {
    var playid = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.ID);
    var ids = getSelectedIDs();
    var i;
    for (i in ids) {
        if(ids[i] == playid)
        {
            audio.stop();
            resourceManager.userwantsplayback = false;
            break;
        }
    }
    playqueueModel.removeSelected();
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function removeMultipleFromPlaylist(list) {
    list.removeSelected();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    var idx = playqueueModel.count;
    addToPlayqueue(item);
    playqueueModel.playindex = idx;
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay()
{
    var ids = getSelectedIDs();
    var idx = playqueueModel.count;
    playqueueModel.addItems(ids);
    playqueueModel.playindex = idx;
    playNewSong();
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(val) {
    var ids = getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function audioplay()
{
    resourceManager.userwantsplayback = true;
    dbusControl.updateNowNextTracks();
    dbusControl.playbackState = 1;
    playqueueModel.playstatus = MusicListModel.Playing;
    toolbar.playing = true;
}

function pause()
{
    audio.pause();
    resourceManager.userwantsplayback = false;
    dbusControl.playbackState = 2;
    playqueueModel.playstatus = MusicListModel.Paused;
    toolbar.playing = false;
}

function stop()
{
    audio.stop();
    resourceManager.userwantsplayback = false;
    dbusControl.updateNowNextTracks();
    dbusControl.playbackState = 3;
    playqueueModel.playstatus = MusicListModel.Stopped;
    toolbar.playing = false;
}

function play()
{
    if (audio.paused ) {
        audioplay();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueModel.playindex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueModel.playindex == -1)
        playqueueModel.playindex = 0;

    toolbar.trackName = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.Title);
    if(playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.Artist)[0]) {
        toolbar.artistName = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.Artist)[0];
    } else {
        toolbar.artistName = ""
    }

    audio.source = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.URI);
    audioplay();
    editorModel.setViewed(playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.ID));
    return true;
}

function playNextSong() {
    if (playqueueModel.playindex < (playqueueView.count -1))
    {
        playqueueModel.playindex++;
    }
    else
    {
        if (loop){
            playqueueModel.playindex = 0;
        }else{
            stop();
            return;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (playqueueModel.playindex == 0)
    {
        if (loop) {
            playqueueModel.playindex = playqueueView.count - 1;
        }else {
            stop();
            return;
        }
    }
    else
    {
        playqueueModel.playindex--;
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else  if (playqueueModel.playindex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueModel.playindex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueModel.playindex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatAlbumLength(length)
{
    var hours = parseInt(length/3600);
    var mins = parseInt( (length%3600)/60 );
    var time = "";
    if( hours == 0 && mins == 0 )
    {//only show seconds
        var secs = parseInt( length%3600 );
        time = (secs==1) ? qsTr("1 second") : qsTr("%1 seconds").arg(secs);
    }
    else
    {
        if( hours == 0 )
        {//only show minutes
            time = (mins==1) ? qsTr("1 minute") : qsTr("%1 minutes").arg(mins);
        }
        else
        {
            if( mins == 0 )
            {//only show hours
                time = ((hours == 1) ? qsTr("1 hour") : qsTr("%1 hours").arg(hours));
            }
            else
            {//show hours and minutes
                time = ((hours == 1) ? qsTr("1 hour") : qsTr("%1 hours").arg(hours)) + ((mins == 1) ? qsTr(" 1 minute") : qsTr(" %1 minutes").arg(mins));
            }
        }
    }
    return time
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        labelArtist = item.mtitle;
        window.addPage(artistDetailViewContent);
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        labelAlbum = item.mtitle;
        currentAlbum = item;
        window.addPage(albumDetailViewContent);
        break;
    case 5:
        // type is playlist
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        window.addPage(playlistDetailViewContent);
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
}
<commit_msg>fixed issue of song not playing if there's not artist data<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

function selectionCount()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.selectionCount(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.selectionCount(MusicListModel.SelectByID);
    }
}

function clearSelected()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        multiSelectModel.clearSelected(MusicListModel.SelectByIndex);
        break;
    default:
        multiSelectModel.clearSelected(MusicListModel.SelectByID);
    }
}

function getSelectedURIs()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.getSelectedURIs(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.getSelectedURIs(MusicListModel.SelectByID);
    }
}

function getSelectedIDs()
{
    switch(multiSelectModel.type) {
    case MusicListModel.NowPlaying:
    case MusicListModel.MusicPlaylist:
        return multiSelectModel.getSelectedIDs(MusicListModel.SelectByIndex);
    default:
        return multiSelectModel.getSelectedIDs(MusicListModel.SelectByID);
    }
}

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue() {
    playqueueModel.addItems(getSelectedIDs());
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue() {
    if(playqueueModel.playindex == targetIndex)
    {
        audio.stop();
        resourceManager.userwantsplayback = false;
    }
    playqueueModel.removeIndex(targetIndex);
    updateNowNextPlaying();
}

function removeFromPlaylist(list) {
    list.removeIndex(targetIndex);
    clearSelected();
}

function removeMultipleFromPlayqueue() {
    var playid = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.ID);
    var ids = getSelectedIDs();
    var i;
    for (i in ids) {
        if(ids[i] == playid)
        {
            audio.stop();
            resourceManager.userwantsplayback = false;
            break;
        }
    }
    playqueueModel.removeSelected();
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function removeMultipleFromPlaylist(list) {
    list.removeSelected();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    var idx = playqueueModel.count;
    addToPlayqueue(item);
    playqueueModel.playindex = idx;
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay()
{
    var ids = getSelectedIDs();
    var idx = playqueueModel.count;
    playqueueModel.addItems(ids);
    playqueueModel.playindex = idx;
    playNewSong();
    updateNowNextPlaying();
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(val) {
    var ids = getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    clearSelected();
    shareObj.clearItems();
    multiSelectMode = false;
}

function audioplay()
{
    resourceManager.userwantsplayback = true;
    dbusControl.updateNowNextTracks();
    dbusControl.playbackState = 1;
    playqueueModel.playstatus = MusicListModel.Playing;
    toolbar.playing = true;
}

function pause()
{
    audio.pause();
    resourceManager.userwantsplayback = false;
    dbusControl.playbackState = 2;
    playqueueModel.playstatus = MusicListModel.Paused;
    toolbar.playing = false;
}

function stop()
{
    audio.stop();
    resourceManager.userwantsplayback = false;
    dbusControl.updateNowNextTracks();
    dbusControl.playbackState = 3;
    playqueueModel.playstatus = MusicListModel.Stopped;
    toolbar.playing = false;
}

function play()
{
    if (audio.paused ) {
        audioplay();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueModel.playindex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueModel.playindex == -1)
        playqueueModel.playindex = 0;

    toolbar.trackName = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.Title);
    try {
        toolbar.artistName = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.Artist)[0];
    }
    catch(err) {
        toolbar.artistName = "";
    }

    audio.source = playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.URI);
    audioplay();
    editorModel.setViewed(playqueueModel.datafromIndex(playqueueModel.playindex, MediaItem.ID));
    return true;
}

function playNextSong() {
    if (playqueueModel.playindex < (playqueueView.count -1))
    {
        playqueueModel.playindex++;
    }
    else
    {
        if (loop){
            playqueueModel.playindex = 0;
        }else{
            stop();
            return;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (playqueueModel.playindex == 0)
    {
        if (loop) {
            playqueueModel.playindex = playqueueView.count - 1;
        }else {
            stop();
            return;
        }
    }
    else
    {
        playqueueModel.playindex--;
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else  if (playqueueModel.playindex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueModel.playindex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueModel.playindex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatAlbumLength(length)
{
    var hours = parseInt(length/3600);
    var mins = parseInt( (length%3600)/60 );
    var time = "";
    if( hours == 0 && mins == 0 )
    {//only show seconds
        var secs = parseInt( length%3600 );
        time = (secs==1) ? qsTr("1 second") : qsTr("%1 seconds").arg(secs);
    }
    else
    {
        if( hours == 0 )
        {//only show minutes
            time = (mins==1) ? qsTr("1 minute") : qsTr("%1 minutes").arg(mins);
        }
        else
        {
            if( mins == 0 )
            {//only show hours
                time = ((hours == 1) ? qsTr("1 hour") : qsTr("%1 hours").arg(hours));
            }
            else
            {//show hours and minutes
                time = ((hours == 1) ? qsTr("1 hour") : qsTr("%1 hours").arg(hours)) + ((mins == 1) ? qsTr(" 1 minute") : qsTr(" %1 minutes").arg(mins));
            }
        }
    }
    return time
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        labelArtist = item.mtitle;
        window.addPage(artistDetailViewContent);
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        labelAlbum = item.mtitle;
        currentAlbum = item;
        window.addPage(albumDetailViewContent);
        break;
    case 5:
        // type is playlist
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        window.addPage(playlistDetailViewContent);
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
}
<|endoftext|>


<commit_before>function adjustTop(){
  var headerHeight = jQuery('.navbar-fixed-top').height();
  jQuery('.columns').css('padding-top', headerHeight + 'px');
}

$(function () {

  adjustTop();

  // open sidebar item if child item is active
  var currentLocation = $(location).attr('href');
  console.log(currentLocation);
  var currentSlug = currentLocation.substring(currentLocation.indexOf('/docs'), currentLocation.length);
  console.log(currentSlug);
  var navItem = $('.Nav .Nav li');
  for(var $i = 0; $i < navItem.length; $i++){
    console.log($(navItem[$i]).children('a').attr('href'));
    if($(navItem[$i]).children('a').attr('href') === currentSlug) {
      $(navItem[$i]).addClass('Nav__item--active');
      $(navItem[$i]).parents('.parent-list').addClass('Nav__item--open');
    }
  }

  $(window).on('resize', function(){
    adjustTop();
  });

  $('.Nav li').has('.Nav').addClass('parent-list');

  $('.Nav .has-children > a').click(function (e) {
    e.preventDefault();
    var $this = $(this);
    var parent = $this.parent();
    var subNavCollapse = $('#sub-nav-collapse');

    if (subNavCollapse.hasClass('nav-expanded')) return;

    parent.siblings().find('ul').slideUp();
    $this.next().slideToggle();
    parent.parent().find('.Nav__item-open').not(parent).removeClass('Nav__item-open');
    if (parent.hasClass('Nav__item-open')) parent.removeClass('Nav__item-open')
    else parent.addClass('Nav__item-open');
  });

  // Bootstrap Table Class
  $('table').addClass('table');

  // Responsive menu spinner
  $('#menu-spinner-button').click(function () {
    $('#sub-nav-collapse').slideToggle();
  });

  // Catch browser resize
  $(window).resize(function () {
    // Remove transition inline style on large screens
    if ($(window).width() >= 768)
      $('#sub-nav-collapse').removeAttr('style');
  });
});

//Fix GitHub Ribbon overlapping Scrollbar
var t = $('#github-ribbon');
var a = $('article');
if (t[0] && a[0] && a[0].scrollHeight > $('.right-column').height()) t[0].style.right = '16px';

//Toggle Code Block Visibility
function toggleCodeBlocks() {
  var t = localStorage.getItem("toggleCodeStats")
  t = (t + 1) % 3;
  localStorage.setItem("toggleCodeStats", t);
  var a = $('.content-page article');
  var c = a.children().filter('pre');
  var d = $('.right-column');
  if (d.hasClass('float-view')) {
    d.removeClass('float-view');
    $('#toggleCodeBlockBtn')[0].innerHTML = "Hide Code Blocks";
  } else {
    if (c.hasClass('hidden')) {
      d.addClass('float-view');
      c.removeClass('hidden');
      $('#toggleCodeBlockBtn')[0].innerHTML = "Show Code Blocks Inline";
    } else {
      c.addClass('hidden');
      $('#toggleCodeBlockBtn')[0].innerHTML = "Show Code Blocks";
    }
  }
}

if (localStorage.getItem("toggleCodeStats") >= 0) {
  var t = localStorage.getItem("toggleCodeStats");
  if (t == 1) {
    toggleCodeBlocks();
    localStorage.setItem("toggleCodeStats", 1);
  }
  if (t == 2) {
    toggleCodeBlocks();
    toggleCodeBlocks();
    localStorage.setItem("toggleCodeStats", 2);
  }
} else {
  localStorage.setItem("toggleCodeStats", 0);
}

$('.expand-all-nav').click(function(e) {
  toggleAllExpand(e);
});

function toggleAllExpand(e) {
  var navList = $('.sub-nav-collapse');
  var toggledClass = 'nav-expanded';

  e.preventDefault();
  if (!navList.hasClass(toggledClass)) {
    navList.addClass(toggledClass);
    e.target.innerHTML = 'Collapse All';
  }
  else {
    navList.removeClass(toggledClass);
    e.target.innerHTML = 'Expand All';
  }
}

$('.gif-toggle').click(function(e) {
  toggleGifs(e, false);
});

toggleGifs(null, true);

function toggleGifs(e, onLoad) {
  var toggleButton = $('.gif-toggle');
  var cookieName = "gifCookie";
  var gifCookie = isCookieSet(cookieName);
  var body = $('body');

  if (e) e.preventDefault();
  if (onLoad == true) {
    if (gifCookie == true) {
      body.addClass('hide-gifs');
      toggleButton.html('Gif ON');
    }
  }
  else {
    if (gifCookie == false) {
      body.addClass('hide-gifs');
      toggleButton.html('Gif ON');
      setCookie(cookieName);
    }
    else {
      body.removeClass('hide-gifs');
      toggleButton.html('Gif OFF');
      removeCookie(cookieName);
    }
  }
}

function setCookie(name) {
  document.cookie = name + "=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;";
}

function removeCookie(name) {
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;";
}

function isCookieSet(name) {
  var re = new RegExp('[; ]'+name+'=([^\\s;]*)');
  var sMatch = (' '+document.cookie).match(re);

  if (name && sMatch) return true;
  return false;
}

$('.logout').click(function() {
  clearAuthCookie($(this).data('cookie'));
});

function clearAuthCookie(names) {
  for (var key in names) {
     document.cookie = names[key] + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  }
  document.location.reload(true);
}

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
     this.setAttribute('target', '_blank');
   }
});

// Add data attribute from TH

var headers = document.getElementsByTagName('th');
var rows = document.getElementsByTagName('tr');

function stripTags(str) {
  return str.replace(/(<([^>]+)>)/ig,"").trim();
}

Array.prototype.forEach.call(rows, function(row) {
  var cells = row.getElementsByTagName('td');
  for (var i = 0; i < cells.length; i++) {
    cells[i].setAttribute('data-name', stripTags(headers[i].innerHTML));
  }
});<commit_msg>Continue trying to fix js nav bug on deployed site<commit_after>function adjustTop(){
  var headerHeight = jQuery('.navbar-fixed-top').height();
  jQuery('.columns').css('padding-top', headerHeight + 'px');
}

$(function () {

  adjustTop();

  // open sidebar item if child item is active
  var currentLocation = $(location).attr('href');
  var currentSlug = currentLocation.substring(currentLocation.indexOf('/docs'), currentLocation.length);
  console.log(currentSlug);
  var navItem = $('.Nav .Nav li');
  for(var $i = 0; $i < navItem.length; $i++){
    var navLink = $(navItem[$i]).children('a').attr('href');
    var navSlug = navLink.substring(navLink.indexOf('/docs'), navLink.length);
    console.log(navSlug);
    if(navSlug === currentSlug) {
      $(navItem[$i]).addClass('Nav__item--active');
      $(navItem[$i]).parents('.parent-list').addClass('Nav__item--open');
    }
  }

  $(window).on('resize', function(){
    adjustTop();
  });

  $('.Nav li').has('.Nav').addClass('parent-list');

  $('.Nav .has-children > a').click(function (e) {
    e.preventDefault();
    var $this = $(this);
    var parent = $this.parent();
    var subNavCollapse = $('#sub-nav-collapse');

    if (subNavCollapse.hasClass('nav-expanded')) return;

    parent.siblings().find('ul').slideUp();
    $this.next().slideToggle();
    parent.parent().find('.Nav__item-open').not(parent).removeClass('Nav__item-open');
    if (parent.hasClass('Nav__item-open')) parent.removeClass('Nav__item-open')
    else parent.addClass('Nav__item-open');
  });

  // Bootstrap Table Class
  $('table').addClass('table');

  // Responsive menu spinner
  $('#menu-spinner-button').click(function () {
    $('#sub-nav-collapse').slideToggle();
  });

  // Catch browser resize
  $(window).resize(function () {
    // Remove transition inline style on large screens
    if ($(window).width() >= 768)
      $('#sub-nav-collapse').removeAttr('style');
  });
});

//Fix GitHub Ribbon overlapping Scrollbar
var t = $('#github-ribbon');
var a = $('article');
if (t[0] && a[0] && a[0].scrollHeight > $('.right-column').height()) t[0].style.right = '16px';

//Toggle Code Block Visibility
function toggleCodeBlocks() {
  var t = localStorage.getItem("toggleCodeStats")
  t = (t + 1) % 3;
  localStorage.setItem("toggleCodeStats", t);
  var a = $('.content-page article');
  var c = a.children().filter('pre');
  var d = $('.right-column');
  if (d.hasClass('float-view')) {
    d.removeClass('float-view');
    $('#toggleCodeBlockBtn')[0].innerHTML = "Hide Code Blocks";
  } else {
    if (c.hasClass('hidden')) {
      d.addClass('float-view');
      c.removeClass('hidden');
      $('#toggleCodeBlockBtn')[0].innerHTML = "Show Code Blocks Inline";
    } else {
      c.addClass('hidden');
      $('#toggleCodeBlockBtn')[0].innerHTML = "Show Code Blocks";
    }
  }
}

if (localStorage.getItem("toggleCodeStats") >= 0) {
  var t = localStorage.getItem("toggleCodeStats");
  if (t == 1) {
    toggleCodeBlocks();
    localStorage.setItem("toggleCodeStats", 1);
  }
  if (t == 2) {
    toggleCodeBlocks();
    toggleCodeBlocks();
    localStorage.setItem("toggleCodeStats", 2);
  }
} else {
  localStorage.setItem("toggleCodeStats", 0);
}

$('.expand-all-nav').click(function(e) {
  toggleAllExpand(e);
});

function toggleAllExpand(e) {
  var navList = $('.sub-nav-collapse');
  var toggledClass = 'nav-expanded';

  e.preventDefault();
  if (!navList.hasClass(toggledClass)) {
    navList.addClass(toggledClass);
    e.target.innerHTML = 'Collapse All';
  }
  else {
    navList.removeClass(toggledClass);
    e.target.innerHTML = 'Expand All';
  }
}

$('.gif-toggle').click(function(e) {
  toggleGifs(e, false);
});

toggleGifs(null, true);

function toggleGifs(e, onLoad) {
  var toggleButton = $('.gif-toggle');
  var cookieName = "gifCookie";
  var gifCookie = isCookieSet(cookieName);
  var body = $('body');

  if (e) e.preventDefault();
  if (onLoad == true) {
    if (gifCookie == true) {
      body.addClass('hide-gifs');
      toggleButton.html('Gif ON');
    }
  }
  else {
    if (gifCookie == false) {
      body.addClass('hide-gifs');
      toggleButton.html('Gif ON');
      setCookie(cookieName);
    }
    else {
      body.removeClass('hide-gifs');
      toggleButton.html('Gif OFF');
      removeCookie(cookieName);
    }
  }
}

function setCookie(name) {
  document.cookie = name + "=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;";
}

function removeCookie(name) {
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;";
}

function isCookieSet(name) {
  var re = new RegExp('[; ]'+name+'=([^\\s;]*)');
  var sMatch = (' '+document.cookie).match(re);

  if (name && sMatch) return true;
  return false;
}

$('.logout').click(function() {
  clearAuthCookie($(this).data('cookie'));
});

function clearAuthCookie(names) {
  for (var key in names) {
     document.cookie = names[key] + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  }
  document.location.reload(true);
}

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
     this.setAttribute('target', '_blank');
   }
});

// Add data attribute from TH

var headers = document.getElementsByTagName('th');
var rows = document.getElementsByTagName('tr');

function stripTags(str) {
  return str.replace(/(<([^>]+)>)/ig,"").trim();
}

Array.prototype.forEach.call(rows, function(row) {
  var cells = row.getElementsByTagName('td');
  for (var i = 0; i < cells.length; i++) {
    cells[i].setAttribute('data-name', stripTags(headers[i].innerHTML));
  }
});<|endoftext|>


<commit_before>(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            param: 'defaultValue'
        }, options || {});

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
                init();
            });
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function() {
                // toggleClass all of a sudden stopped working???
                if( ($this).hasClass("selected") )  $(this).removeClass("selected");
                if( !($this).hasClass("selected") )  $(this).addClass("selected");
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
                $(this).removeClass("hover");
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);<commit_msg>debugging issue with sample site<commit_after>(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            param: 'defaultValue'
        }, options || {});

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
                init();
            });
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function() {
                // toggleClass all of a sudden stopped working???
                if( $(this).hasClass("selected") )  $(this).removeClass("selected");
                if( !$(this).hasClass("selected") )  $(this).addClass("selected");
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
                $(this).removeClass("hover");
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);<|endoftext|>


<commit_before>/**
* aggCtrl
* @desc this controller is attached to each aggregation displayed
*/
Curiosity.controller('aggCtrl', function($scope, $modal, aggFactory, template){
	$scope.aggTypeSelected = false;
	$scope.data = aggFactory.info;
	$scope.tplData = template.info;

	/**
	* @desc function call by ng-init, called to load aggregation specifique data, and load template in $templateCache
	* @param string name : the name of the aggregation attached to the controller
	*/
	$scope.init = function (name) {
		$scope.curAgg = {};
		$scope.curAgg.validate = false;
		if (typeof(name) === "undefined") {
			$scope.curAgg = aggFactory.newEmptyAggregation(false);
		}
		else {
			$scope.curAgg = aggFactory.getAggregation(name);
			initTemplate($scope.curAgg);
		}
	}

	/**
	* @desc remove an aggregation from a container, used for nestedAgg
	* @param array container target array
	* @param int idx row's index to remove
	*/
	$scope.removeAgg = function (container, idx) {
		container.splice(idx, 1);
	}

	/**
	* @desc remove an aggregation from the aggregation list of aggFactory
	* @param object agg : the aggregation to remove
	* @param int id : the aggregation id
	*/
	$scope.removeMainAgg = function (agg, id) {
		aggFactory.removeMainAgg(agg, id);
	}

	/**
	* @desc change an aggregation type (terms, range ...)
	* @param object agg the aggregation to change type
	* @idx int idx the index of the new aggregation type in aggList
	*/
	$scope.changeAggType = function (agg,idx) {
		if (typeof (idx) != "undefined" && idx != null && idx >= 0) {
			agg.type = $scope.data.aggList[idx].type;
			agg.displayTemplate = $scope.data.aggList[idx].template;
			agg.resultTemplate = $scope.data.aggList[idx].resultTemplate;
			agg.aggTypeSelected = true;
		}
	}

	/**
	* @desc modifie the validate attr of an aggregation
	* @param object agg the agg to modify
	*/
	$scope.validateAgg = function (agg) {
		agg.validate = !agg.validate;
	}

	/**
	* @desc add a nested aggregation to an aggregation
	* @param object agg the agg to modify
	*/
	$scope.addNestedAgg = function (agg) {
		aggFactory.addNestedAgg(agg)
	}

	/**
	* @desc ask template service to add a template to the $templateCache whenever the template id different from default
	* @param string the template name
	*/
	$scope.loadTpl = function (tpl) {
		if (typeof(tpl) !== "undefined" && tpl != "default") {
			template.addTemplateToCacheFromName("aggregationsTemplates", tpl);
		}
	}

	/**
	* @desc add an interval to a range aggregation
	* @param object agg target aggregation
	*/
	$scope.addInterval = function (agg) {
		if (typeof (agg.intervals) === "undefined") {
			agg.intervals = [];
		}
		agg.intervals.push({});
	}
	/**
 	* @desc remove an interval to a range aggregation
 	* @param object agg target aggregation
 	* @param int index index to remove
 	*/
	$scope.removeInterval =  function(agg, index) {
		if (typeof (agg.intervals) !== "undefined") {
			agg.intervals.splice(index, 1);
		}
	}

	/**
	* @desc open a modal which contains the fields list. When closed change aggregation field attr value
	* @params 'sm' | 'lg' size modal size
	*/
	$scope.openModalFields = function (size, curAgg) {
		var modalInstance = $modal.open({
			templateUrl: 'template/modal/fieldsModal.html',
			controller: mappingModalCtrl,
			resolve: {
				item: function () {
					return curAgg;
				}}
			});
		modalInstance.result.then(function (value) {
			value.item.field = value.value;
		}, function () {
		})
	};

	/**
	* @desc load aggregation and nested aggregation template in $templateCache
	* @param object agg target aggregation
	*/
	function initTemplate(agg) {
		$scope.loadTpl(agg.tpl);
		if (typeof(agg.nested) !== "undefined") {
		for (sub_agg in agg.nested)
			initTemplate(sub_agg);
		}
	}
});<commit_msg>Fix regression in agg nested association<commit_after>/**
* aggCtrl
* @desc this controller is attached to each aggregation displayed
*/
Curiosity.controller('aggCtrl', function($scope, $modal, aggFactory, template){
	$scope.aggTypeSelected = false;
	$scope.data = aggFactory.info;
	$scope.tplData = template.info;

	/**
	* @desc function call by ng-init, called to load aggregation specifique data, and load template in $templateCache
	* @param string name : the name of the aggregation attached to the controller
	*/
	$scope.init = function (name) {
		$scope.curAgg = {};
		$scope.curAgg.validate = false;
		if (typeof(name) === "undefined") {
			$scope.curAgg = aggFactory.newEmptyAggregation(false);
		}
		else {
			$scope.curAgg = aggFactory.getAggregation(name);
			initTemplate($scope.curAgg);
		}
	}

	/**
	* @desc remove an aggregation from a container, used for nestedAgg
	* @param array container target array
	* @param int idx row's index to remove
	*/
	$scope.removeAgg = function (container, idx) {
		container.splice(idx, 1);
	}

	/**
	* @desc remove an aggregation from the aggregation list of aggFactory
	* @param object agg : the aggregation to remove
	* @param int id : the aggregation id
	*/
	$scope.removeMainAgg = function (agg, id) {
		aggFactory.removeMainAgg(agg, id);
	}

	/**
	* @desc change an aggregation type (terms, range ...)
	* @param object agg the aggregation to change type
	* @idx int idx the index of the new aggregation type in aggList
	*/
	$scope.changeAggType = function (agg,idx) {
		if (typeof (idx) != "undefined" && idx != null && idx >= 0) {
			agg.type = $scope.data.aggList[idx].type;
			agg.displayTemplate = $scope.data.aggList[idx].template;
			agg.resultTemplate = $scope.data.aggList[idx].resultTemplate;
			agg.aggTypeSelected = true;
		}
	}

	/**
	* @desc modifie the validate attr of an aggregation
	* @param object agg the agg to modify
	*/
	$scope.validateAgg = function (agg) {
		agg.validate = !agg.validate;
	}

	/**
	* @desc add a nested aggregation to an aggregation
	* @param object agg the agg to modify
	*/
	$scope.addNestedAgg = function (agg) {
		aggFactory.addNestedAgg(agg)
	}

	/**
	* @desc ask template service to add a template to the $templateCache whenever the template id different from default
	* @param string the template name
	*/
	$scope.loadTpl = function (tpl) {
		if (typeof(tpl) !== "undefined" && tpl != "default") {
			template.addTemplateToCacheFromName("aggregationsTemplates", tpl);
		}
	}

	/**
	* @desc add an interval to a range aggregation
	* @param object agg target aggregation
	*/
	$scope.addInterval = function (agg) {
		if (typeof (agg.intervals) === "undefined") {
			agg.intervals = [];
		}
		agg.intervals.push({});
	}
	/**
 	* @desc remove an interval to a range aggregation
 	* @param object agg target aggregation
 	* @param int index index to remove
 	*/
	$scope.removeInterval =  function(agg, index) {
		if (typeof (agg.intervals) !== "undefined") {
			agg.intervals.splice(index, 1);
		}
	}

	/**
	* @desc open a modal which contains the fields list. When closed change aggregation field attr value
	* @params 'sm' | 'lg' size modal size
	*/
	$scope.openModalFields = function (size, curAgg) {
		var modalInstance = $modal.open({
			templateUrl: 'template/modal/fieldsModal.html',
			controller: mappingModalCtrl,
			resolve: {
				item: function () {
					return curAgg;
				}}
			});
		modalInstance.result.then(function (value) {
			value.item.field = value.value;
		}, function () {
		})
	};

	/**
	* @desc load aggregation and nested aggregation template in $templateCache
	* @param object agg target aggregation
	*/
	function initTemplate(agg) {
		$scope.loadTpl(agg.tpl);
		if (typeof(agg.nested) !== "undefined") {
			for (sub_agg in agg.nested) {
				initTemplate(agg.nested[sub_agg]);
			}
		}
	}
});<|endoftext|>