<commit_before>'use strict';

/**
 * @ngdoc function
 * @name MatchCalendarApp.controller:PostGeneratorGameType
 * @description
 * # PostGeneratorGameType
 * Service of the MatchCalendarApp
 */
angular.module('MatchCalendarApp')
    .factory('PostGeneratorGameType', ['PostGeneratorGameTypeField', function (PostGeneratorGameTypeField) {

        /**
         * Create a new game type
         *
         * @param {Object} options
         * @param {String} options.name - the name of the game mode
         * @param {String} options.description - a short description of the game mode
         * @param {PostGeneratorGameTypeField[]} [options.fields] - list of fields needed for the gamemode
         * @param {Function} [options.formatter] - optional formatter to override the default
         * @constructor
         */
        var GameType = function(options) {
            this.name = options.name;
            this.description = options.description || 'No description set';
            this.fields = options.fields || [];
            this.format = options.formatter || function() { return 'ERROR CREATING GAME TYPE'; };
        };

        // generic formatter to use with size based game types
        var genericSizeFormatter = function(fieldAnswers) {
            return this.name + ' To' + fieldAnswers.size;
        };

        GameType.types = {};

        GameType.types.FFA = new GameType({
            name: 'FFA',
            description: 'Every man for himself.',
            fields: [],
            format: function() {
                return 'FFA';
            }
        });

        GameType.types.CHOSEN = new GameType({
            name: 'Chosen',
            description: 'Players form their teams before the match.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.RANDOM = new GameType({
            name: 'Random',
            description: 'Players are assigned random teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.PICKED = new GameType({
            name: 'Picked',
            description: 'Players take turns joining a team.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.MYSTERY = new GameType({
            name: 'Mystery',
            description: 'Players are assigned unknown teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.CAPTAINS = new GameType({
            name: 'Captains',
            description: 'Selected team leaders pick their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of captains',
                    defaultValue: 4,
                    type: 'number',
                    name: 'captains'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Selection Method',
                    defaultValue: '',
                    name: 'selection'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.captains + ' Captains ' + fieldAnswers.selection;
            }
        });

        GameType.types.AUCTION = new GameType({
            name: 'Auction',
            description: 'Selected team leaders buy their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of buyers',
                    defaultValue: 4,
                    type: 'number',
                    name: 'buyers'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Currency',
                    defaultValue: 'diamonds',
                    type: 'text',
                    name: 'currency'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.buyers + ' buyers Auction (' + fieldAnswers.currency;
            }
        });

        GameType.types.ALLIANCES = new GameType({
            name: 'Alliance',
            description: 'Players can form informal teams on their own.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Max amount of players for an alliance',
                    defaultValue: 8,
                    type: 'number',
                    name: 'max'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Can alliances win?',
                    defaultValue: true,
                    type: 'boolean',
                    name: 'canWin'
                })
            ],
            format: function(fieldAnswers) {
                return 'Alliances up to ' + fieldAnswers.max + '. Alliances can' + (fieldAnswers.canWin ? '' : 'not') + ' win';
            }
        });

        return GameType;
    }]);
<commit_msg>feat(PostGeneratorGameType): add custom type<commit_after>'use strict';

/**
 * @ngdoc function
 * @name MatchCalendarApp.controller:PostGeneratorGameType
 * @description
 * # PostGeneratorGameType
 * Service of the MatchCalendarApp
 */
angular.module('MatchCalendarApp')
    .factory('PostGeneratorGameType', ['PostGeneratorGameTypeField', function (PostGeneratorGameTypeField) {

        /**
         * Create a new game type
         *
         * @param {Object} options
         * @param {String} options.name - the name of the game mode
         * @param {String} options.description - a short description of the game mode
         * @param {PostGeneratorGameTypeField[]} [options.fields] - list of fields needed for the gamemode
         * @param {Function} [options.formatter] - optional formatter to override the default
         * @constructor
         */
        var GameType = function(options) {
            this.name = options.name;
            this.description = options.description || 'No description set';
            this.fields = options.fields || [];
            this.format = options.formatter || function() { return 'ERROR CREATING GAME TYPE'; };
        };

        // generic formatter to use with size based game types
        var genericSizeFormatter = function(fieldAnswers) {
            return this.name + ' To' + fieldAnswers.size;
        };

        GameType.types = {};

        GameType.types.FFA = new GameType({
            name: 'FFA',
            description: 'Every man for himself.',
            fields: [],
            format: function() {
                return 'FFA';
            }
        });

        GameType.types.CHOSEN = new GameType({
            name: 'Chosen',
            description: 'Players form their teams before the match.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.RANDOM = new GameType({
            name: 'Random',
            description: 'Players are assigned random teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.PICKED = new GameType({
            name: 'Picked',
            description: 'Players take turns joining a team.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.MYSTERY = new GameType({
            name: 'Mystery',
            description: 'Players are assigned unknown teammates.',
            fields: [PostGeneratorGameTypeField.TEAM_SIZE],
            format: genericSizeFormatter
        });

        GameType.types.CAPTAINS = new GameType({
            name: 'Captains',
            description: 'Selected team leaders pick their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of captains',
                    defaultValue: 4,
                    type: 'number',
                    name: 'captains'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Selection Method',
                    defaultValue: '',
                    name: 'selection'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.captains + ' Captains ' + fieldAnswers.selection;
            }
        });

        GameType.types.AUCTION = new GameType({
            name: 'Auction',
            description: 'Selected team leaders buy their teammates.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Number of buyers',
                    defaultValue: 4,
                    type: 'number',
                    name: 'buyers'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Currency',
                    defaultValue: 'diamonds',
                    type: 'text',
                    name: 'currency'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.buyers + ' buyers Auction (' + fieldAnswers.currency;
            }
        });

        GameType.types.ALLIANCES = new GameType({
            name: 'Alliance',
            description: 'Players can form informal teams on their own.',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'Max amount of players for an alliance',
                    defaultValue: 8,
                    type: 'number',
                    name: 'max'
                }),
                new PostGeneratorGameTypeField({
                    question: 'Can alliances win?',
                    defaultValue: true,
                    type: 'boolean',
                    name: 'canWin'
                })
            ],
            format: function(fieldAnswers) {
                return 'Alliances up to ' + fieldAnswers.max + '. Alliances can' + (fieldAnswers.canWin ? '' : 'not') + ' win';
            }
        });

        GameType.types.CUSTOM = new GameType({
            name: 'Custom',
            description: 'Custom team types',
            fields: [
                new PostGeneratorGameTypeField({
                    question: 'What to show in post title',
                    defaultValue: 'Custom',
                    type: 'text',
                    name: 'custom'
                })
            ],
            format: function(fieldAnswers) {
                return fieldAnswers.custom;
            }
        });

        return GameType;
    }]);
<|endoftext|>


<commit_before>// @flow
import { api, type Claims } from 'neon-js'
import { map, reduce } from 'lodash'

import {
  showErrorNotification,
  showSuccessNotification,
  showInfoNotification
} from './notifications'
import {
  getNetwork,
  getWIF,
  getAddress,
  getSigningFunction,
  getPublicKey,
  getIsHardwareLogin,
  getNEO
} from '../core/deprecated'
import { toBigNumber, toNumber } from '../core/math'
import { ASSETS } from '../core/constants'
import { FIVE_MINUTES_MS } from '../core/time'
import poll from '../util/poll'

const POLL_ATTEMPTS = 50
const POLL_FREQUENCY = 5000

const fetchClaims = async ({ net, address }) => {
  const response = await api.loadBalance(api.getClaimsFrom, { net, address })
  const { claims } = response.claims
  return map(claims, 'claim')
}

const calculateClaimableAmount = (claims: Claims) => {
  return reduce(claims, (sum, claim) => claim.plus(sum), 0).toString()
}

const getClaimableAmount = async ({ net, address }) => {
  const claims = await fetchClaims({ net, address })
  return calculateClaimableAmount(claims)
}

const updateClaimableAmount = async ({ net, address, publicKey, privateKey, signingFunction, balance }) => {
  const { response } = await api.sendAsset({
    net,
    address,
    publicKey,
    privateKey,
    signingFunction,
    intents: api.makeIntent({ [ASSETS.NEO]: toNumber(balance) }, address)
  })

  if (!response.result || !response.txid) {
    throw new Error('Transaction failed!')
  }

  return response.result.response
}

const pollForUpdatedClaimableAmount = async ({ net, address, claimableAmount }) => {
  return poll(async () => {
    const updatedClaimableAmount = await getClaimableAmount({ net, address })

    if (toBigNumber(updatedClaimableAmount).eq(claimableAmount)) {
      throw new Error('Waiting for updated claims')
    }

    return updatedClaimableAmount
  }, { attempts: POLL_ATTEMPTS, frequency: POLL_FREQUENCY })
}

const getUpdatedClaimableAmount = async ({ net, address, balance, publicKey, privateKey, signingFunction }) => {
  const claimableAmount = await getClaimableAmount({ net, address })

  if (toBigNumber(balance).eq(0)) {
    return claimableAmount
  } else {
    await updateClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
    return pollForUpdatedClaimableAmount({ net, address, claimableAmount })
  }
}

export const doGasClaim = () => async (dispatch: DispatchType, getState: GetStateType) => {
  const state = getState()
  const address = getAddress(state)
  const net = getNetwork(state)
  const balance = getNEO(state)
  const publicKey = getPublicKey(state)
  const privateKey = getWIF(state)
  const signingFunction = getSigningFunction(state)
  const isHardwareClaim = getIsHardwareLogin(state)

  dispatch(disableClaim(true))

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 1 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Calculating claimable GAS...' }))
  }

  // step 1: update available claims
  try {
    await getUpdatedClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Calculating claimable GAS failed.' }))
    return
  }

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 2 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Claiming GAS...' }))
  }

  // step 2: send claim request
  try {
    const { response } = await api.claimGas({ net, address, publicKey, privateKey, signingFunction })

    if (!response.result) {
      throw new Error('Claiming GAS failed')
    }
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Claiming GAS failed.' }))
    return
  }

  dispatch(showSuccessNotification({
    message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
  }))
  setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
}

// Constants
export const DISABLE_CLAIM = 'DISABLE_CLAIM'

// Actions
export function disableClaim (disableClaimButton: boolean) {
  return {
    type: DISABLE_CLAIM,
    payload: { disableClaimButton }
  }
}

// State Getters
export const getDisableClaimButton = (state: Object) => state.claim.disableClaimButton

const initialState = {
  disableClaimButton: false
}

export default (state: Object = initialState, action: ReduxAction) => {
  switch (action.type) {
    case DISABLE_CLAIM:
      const { disableClaimButton } = action.payload
      return {
        ...state,
        disableClaimButton
      }
    default:
      return state
  }
}
<commit_msg>patch<commit_after>// @flow
import { api, type Claims } from 'neon-js'
import { map, reduce } from 'lodash'

import {
  showErrorNotification,
  showSuccessNotification,
  showInfoNotification
} from './notifications'
import {
  getNetwork,
  getWIF,
  getAddress,
  getSigningFunction,
  getPublicKey,
  getIsHardwareLogin,
  getNEO
} from '../core/deprecated'
import { toBigNumber, toNumber } from '../core/math'
import { ASSETS } from '../core/constants'
import { FIVE_MINUTES_MS } from '../core/time'
import poll from '../util/poll'

const POLL_ATTEMPTS = 50
const POLL_FREQUENCY = 5000

const fetchClaims = async ({ net, address }) => {
  api.setApiSwitch(1)
  const response = await api.loadBalance(api.getClaimsFrom, { net, address })
  api.setApiSwitch(0)
  const { claims } = response.claims
  return map(claims, 'claim')
}

const calculateClaimableAmount = (claims: Claims) => {
  return reduce(claims, (sum, claim) => claim.plus(sum), 0).toString()
}

const getClaimableAmount = async ({ net, address }) => {
  const claims = await fetchClaims({ net, address })
  return calculateClaimableAmount(claims)
}

const updateClaimableAmount = async ({ net, address, publicKey, privateKey, signingFunction, balance }) => {
  const { response } = await api.sendAsset({
    net,
    address,
    publicKey,
    privateKey,
    signingFunction,
    intents: api.makeIntent({ [ASSETS.NEO]: toNumber(balance) }, address)
  })

  if (!response.result || !response.txid) {
    throw new Error('Transaction failed!')
  }

  return response.result.response
}

const pollForUpdatedClaimableAmount = async ({ net, address, claimableAmount }) => {
  return poll(async () => {
    const updatedClaimableAmount = await getClaimableAmount({ net, address })

    if (toBigNumber(updatedClaimableAmount).eq(claimableAmount)) {
      throw new Error('Waiting for updated claims')
    }

    return updatedClaimableAmount
  }, { attempts: POLL_ATTEMPTS, frequency: POLL_FREQUENCY })
}

const getUpdatedClaimableAmount = async ({ net, address, balance, publicKey, privateKey, signingFunction }) => {
  const claimableAmount = await getClaimableAmount({ net, address })

  if (toBigNumber(balance).eq(0)) {
    return claimableAmount
  } else {
    await updateClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
    return pollForUpdatedClaimableAmount({ net, address, claimableAmount })
  }
}

export const doGasClaim = () => async (dispatch: DispatchType, getState: GetStateType) => {
  const state = getState()
  const address = getAddress(state)
  const net = getNetwork(state)
  const balance = getNEO(state)
  const publicKey = getPublicKey(state)
  const privateKey = getWIF(state)
  const signingFunction = getSigningFunction(state)
  const isHardwareClaim = getIsHardwareLogin(state)

  dispatch(disableClaim(true))

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 1 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Calculating claimable GAS...' }))
  }

  // step 1: update available claims
  try {
    await getUpdatedClaimableAmount({ net, address, balance, publicKey, privateKey, signingFunction })
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Calculating claimable GAS failed.' }))
    return
  }

  if (isHardwareClaim) {
    dispatch(showInfoNotification({ message: 'Please sign transaction 2 of 2 on hardware device.' }))
  } else {
    dispatch(showInfoNotification({ message: 'Claiming GAS...' }))
  }

  // step 2: send claim request
  try {
    api.setApiSwitch(1)
    const { response } = await api.claimGas({ net, address, publicKey, privateKey, signingFunction })
    api.setApiSwitch(0)

    if (!response.result) {
      throw new Error('Claiming GAS failed')
    }
  } catch (err) {
    dispatch(disableClaim(false))
    dispatch(showErrorNotification({ message: 'Claiming GAS failed.' }))
    return
  }

  dispatch(showSuccessNotification({
    message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
  }))
  setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
}

// Constants
export const DISABLE_CLAIM = 'DISABLE_CLAIM'

// Actions
export function disableClaim (disableClaimButton: boolean) {
  return {
    type: DISABLE_CLAIM,
    payload: { disableClaimButton }
  }
}

// State Getters
export const getDisableClaimButton = (state: Object) => state.claim.disableClaimButton

const initialState = {
  disableClaimButton: false
}

export default (state: Object = initialState, action: ReduxAction) => {
  switch (action.type) {
    case DISABLE_CLAIM:
      const { disableClaimButton } = action.payload
      return {
        ...state,
        disableClaimButton
      }
    default:
      return state
  }
}
<|endoftext|>


<commit_before>/**
 * @fileOverview
 * grunt commands for grunt-cli that will make your life better!
 *
 * @author Pieces029
 */
module.exports = function (grunt) {
    'use strict';

    grunt.initConfig({
        watch: {
            livereload: {
                files: ['src/index.html'],
                tasks: 'htmllint',
                options: {
                    livereload: true
                }
            }
        },
        connect: {
            server: {
                options: {
                    port: 8888,
                    base: 'src',
                    keepalive: true,
                    hostname: '127.0.0.1',
                    livereload: true
                }
            }
        },
        concurrent: {
            target: {
                tasks: ['connect', 'watch', 'open:connect'],
                options: {
                    logConcurrentOutput: true
                }
            }
        },
        open: {
            connect: {
                path: 'http://127.0.0.1:8888',
                app: 'google-chrome'
            },
            file: {
                path: 'src/index.html',
                app: 'google-chrome'
            },
            release: {
                path: 'http://pieces029.github.io/Dagger-Presentation',
                app: 'google-chrome'
            }
        },
        htmllint: {
            all: ["src/index.html"]
        },
        imagemin: {
            dynamic: {
                files: [
                    {
                        expand: true,
                        cwd: 'src/',
                        src: ['**/*.{png,jpg,gif}'],
                        dest: 'src/'
                    }
                ]
            }
        },
        clean: {
            build: [
                "dist/css",
                "dist/fonts",
                "dist/images",
                "dist/lib",
                "dist/index.html"
            ]
        },
        copy: {
            release: {
                expand: true,
                cwd: 'src/',
                src: '**',
                dest: 'dist/',
                options: {
                    process: function (content, srcpath) {
                        return content.replace(
                            "{ src: 'lib/reveal.js/plugin/remotes/remotes.js', async: true, condition: function () { return !!document.body.classList; }}",
                            ""
                        );
                    }
                }
            }
        },
        githubPages: {
            target: {
                options: {
                    // The default commit message for the gh-pages branch
                    commitMessage: 'pushing updates'
                },
                // The folder where your gh-pages repo is
                src: 'dist'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-github-pages');
    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-html');

    // Default task
    grunt.registerTask('default', ['help']);

    grunt.registerTask('help', 'Prints out the specific details of each command', function () {
        console.log("Available Commands");
        console.log("  watch:\tAuto pushes updates to the browser on save");
        console.log("  connect:\tStart a local server for testing on port 8888");
        console.log("  dev:\tRuns all dev commands, if your are developing you want this");
        console.log("  open:connect\tOpens Google Chrome to the index page on port 8888");
        console.log("  open:file\tOpens the html file in chrome");
        console.log("  open:release\tOpens the page in github pages");
        console.log("  imagemin\tOptimize your images for the web");
    });

    grunt.registerTask('dev', 'Runs all dev commands, if your are developing you want this', 'concurrent:target');

    grunt.registerTask('release', 'Creates the release build and publishes it to github pages',
        [
            'clean:build',
            'imagemin',
            'copy:release',
            'deploy'
        ]
    );

    grunt.registerTask('deploy', ['githubPages:target']);
};
<commit_msg>fixed - updated to remove remotes on gh-pages<commit_after>/**
 * @fileOverview
 * grunt commands for grunt-cli that will make your life better!
 *
 * @author Pieces029
 */
module.exports = function (grunt) {
    'use strict';

    grunt.initConfig({
        watch: {
            livereload: {
                files: ['src/index.html'],
                tasks: 'htmllint',
                options: {
                    livereload: true
                }
            }
        },
        connect: {
            server: {
                options: {
                    port: 8888,
                    base: 'src',
                    keepalive: true,
                    hostname: '127.0.0.1',
                    livereload: true
                }
            }
        },
        concurrent: {
            target: {
                tasks: ['connect', 'watch', 'open:connect'],
                options: {
                    logConcurrentOutput: true
                }
            }
        },
        open: {
            connect: {
                path: 'http://127.0.0.1:8888',
                app: 'google-chrome'
            },
            file: {
                path: 'src/index.html',
                app: 'google-chrome'
            },
            release: {
                path: 'http://pieces029.github.io/Dagger-Presentation',
                app: 'google-chrome'
            }
        },
        htmllint: {
            all: ["src/index.html"]
        },
        imagemin: {
            dynamic: {
                files: [
                    {
                        expand: true,
                        cwd: 'src/',
                        src: ['**/*.{png,jpg,gif}'],
                        dest: 'src/'
                    }
                ]
            }
        },
        clean: {
            build: [
                "dist/css",
                "dist/fonts",
                "dist/images",
                "dist/lib",
                "dist/index.html"
            ]
        },
        copy: {
            release: {
                expand: true,
                cwd: 'src/',
                src: '**',
                dest: 'dist/'
            },
            releaseReplace: { // Done this way instead of with regular copy is it screws up the image files that are being copied over
                src: 'dist/index.html',
                dest: 'dist/index.html',
                options: {
                    process: function (content, srcpath) {
                        return content.replace(
                            "{ src: 'lib/reveal.js/plugin/remotes/remotes.js', async: true, condition: function () { return !!document.body.classList; }}",
                            ""
                        );
                    }
                }
            }
        },
        githubPages: {
            target: {
                options: {
                    // The default commit message for the gh-pages branch
                    commitMessage: 'pushing updates'
                },
                // The folder where your gh-pages repo is
                src: 'dist'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-github-pages');
    grunt.loadNpmTasks('grunt-concurrent');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-html');

    // Default task
    grunt.registerTask('default', ['help']);

    grunt.registerTask('help', 'Prints out the specific details of each command', function () {
        console.log("Available Commands");
        console.log("  watch:\tAuto pushes updates to the browser on save");
        console.log("  connect:\tStart a local server for testing on port 8888");
        console.log("  dev:\tRuns all dev commands, if your are developing you want this");
        console.log("  open:connect\tOpens Google Chrome to the index page on port 8888");
        console.log("  open:file\tOpens the html file in chrome");
        console.log("  open:release\tOpens the page in github pages");
        console.log("  imagemin\tOptimize your images for the web");
    });

    grunt.registerTask('dev', 'Runs all dev commands, if your are developing you want this', 'concurrent:target');

    grunt.registerTask('release', 'Creates the release build and publishes it to github pages',
        [
            'clean:build',
            'imagemin',
            'copy:release',
            'copy:releaseReplace',
            'deploy'
        ]
    );

    grunt.registerTask('deploy', ['githubPages:target']);
};
<|endoftext|>


<commit_before>define(['backbone', 'jquery'], function (Backbone, $) {
    return Backbone.Model.extend({
        read: function (callback, scope) {
            this._doRequest({
                type: "GET",
                data: {
                    'format': 'json'
                },
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
            }, callback, scope, 'read');
        },

        save: function (callback, scope) {
            this._doRequest({
                type: "POST",
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
                data: JSON.stringify(this.toJSON())
            }, callback, scope, 'save');
        },

        delete: function (callback, scope) {
            this._doRequest({
                type: "DELETE",
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
                data: JSON.stringify(this.toJSON())
            }, callback, scope, 'delete');
        },

        _doRequest: function (config, callback, scope, eventname) {
            var self = this;
            if (! scope){
                scope = self;
            }
            $.ajax($.extend({
                complete: function (request, status) {
                    if (typeof callback === 'function') {
                        callback.call(scope, request, status, self);
                    }
                    if (status === 'success' &&  request.responseJSON) {
                        self.set(request.responseJSON);
                        self.trigger(eventname, self);
                    }
                }
            }, config));
        }
    });
});
<commit_msg>adding documentation, re #453<commit_after>define(['backbone', 'jquery'], function (Backbone, $) {
    return Backbone.Model.extend({
        /**
         * A backbone model to manage RESTful requests on a per model basis
         * @constructor
         * @name AbstractModel
        */

        /**
         * Issues a request for a model instance from the server using the id of the model in the url
         * @memberof AbstractModel.prototype
         * @param  {function} callback - the function to call when the request returns
         * @param  {object} scope - (optional) the scope used for the callback
        */
        read: function (callback, scope) {
            this._doRequest({
                type: "GET",
                data: {
                    'format': 'json'
                },
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
            }, callback, scope, 'read');
        },

        /**
         * Posts a model back to the server using the id of the model in the url
         * @memberof AbstractModel.prototype
         * @param  {function} callback - the function to call when the request returns
         * @param  {object} scope - (optional) the scope used for the callback
        */
        save: function (callback, scope) {
            this._doRequest({
                type: "POST",
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
                data: JSON.stringify(this.toJSON())
            }, callback, scope, 'save');
        },

        /**
         * Sends a delete request to the server using the id of the model in the url
         * @memberof AbstractModel.prototype
         * @param  {function} callback - the function to call when the request returns
         * @param  {object} scope - (optional) the scope used for the callback
        */
        delete: function (callback, scope) {
            this._doRequest({
                type: "DELETE",
                url: this.url.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', this.get('id')),
                data: JSON.stringify(this.toJSON())
            }, callback, scope, 'delete');
        },

        /**
         * _doRequest - a wrapper around a simple ajax call
         * @memberof AbstractModel.prototype
         * @param  {object} config - a config object to pass to the ajax request
         * @param  {function} callback - function to call when the request returns
         * @param  {object} scope - (optional) the scope used for the callback
         * @param  {string} eventname - (optional) the event to trigger upon successfull return of the request
         */
        _doRequest: function (config, callback, scope, eventname) {
            var self = this;
            if (! scope){
                scope = self;
            }
            $.ajax($.extend({
                complete: function (request, status) {
                    if (typeof callback === 'function') {
                        callback.call(scope, request, status, self);
                    }
                    if (status === 'success' &&  request.responseJSON) {
                        self.set(request.responseJSON);
                        self.trigger(eventname, self);
                    }
                }
            }, config));
        }
    });
});
<|endoftext|>


<commit_before>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
var config = require('../config/config');

module.exports = {
    pdf: function(Ficha) {
        // Parsear area de desarrollo
        var areaYObjetivoPorSeccion = config.areaYObjetivoPorSeccion(Ficha.seccion, Ficha.areadedesarrollo);
        var areadedesarrollo = areaYObjetivoPorSeccion.area;
        var objetivo = areaYObjetivoPorSeccion.objetivo;
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 100,height: 100}, { text: ''+Ficha.nombreactividad+'', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ { text: 'NOMBRE DE LA ACTIVIDAD', style: 'morrarro' }, { text: 'SECCIÓN', style: 'morrarro' }, { text: ''+objectivo.toUpperCase()+'', style: 'morrarro' }, { text: 'PARTICIPANTES', style: 'morrarro' } ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'OBJETIVOS EDUCATIVOS', style: 'morrarro' }],
                            [ ''+Ficha.objetivo+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'DESCRIPCIÓN DE LA ACTIVIDAD', style: 'morrarro' }],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'RECOMENDACIONES', style: 'morrarro' }],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'MATERIALES', style: 'morrarro' }],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ { text: 'TIEMPOS', style: 'morrarro' }, { text: 'AUTOR', style: 'morrarro' }, { text: 'FECHA', style: 'morrarro' }],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ],
                    color: 'purple'
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                morrarro:{
                    color: 'purple'
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<commit_msg>Update fichaReme.js<commit_after>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
var config = require('../config/config');

module.exports = {
    pdf: function(Ficha) {
        // Parsear area de desarrollo
        var areaYObjetivoPorSeccion = config.areaYObjetivoPorSeccion(Ficha.seccion, Ficha.areadedesarrollo);
        var areadedesarrollo = areaYObjetivoPorSeccion.area;
        var nombrearea = areaYObjetivoPorSeccion.nombrearea;
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 100,height: 100}, { text: ''+Ficha.nombreactividad+'', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ { text: 'NOMBRE DE LA ACTIVIDAD', style: 'morrarro' }, { text: 'SECCIÓN', style: 'morrarro' }, { text: ''+nombrearea.toUpperCase()+'', style: 'morrarro' }, { text: 'PARTICIPANTES', style: 'morrarro' } ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'OBJETIVOS EDUCATIVOS', style: 'morrarro' }],
                            [ ''+Ficha.objetivo+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'DESCRIPCIÓN DE LA ACTIVIDAD', style: 'morrarro' }],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'RECOMENDACIONES', style: 'morrarro' }],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ { text: 'MATERIALES', style: 'morrarro' }],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ { text: 'TIEMPOS', style: 'morrarro' }, { text: 'AUTOR', style: 'morrarro' }, { text: 'FECHA', style: 'morrarro' }],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ],
                    color: 'purple'
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                morrarro:{
                    color: 'purple'
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<|endoftext|>


<commit_before>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
module.exports = {
    pdf: function(Ficha) {
        // Parsear area de desarrollo
        var areadedesarrollo = "";
        var area = "";
        switch (Ficha.seccion) {
            case 'manada':
                area = "Presa";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Bagheera (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Kaa (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Baloo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Rikki-Tikki-Tavi (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Kotick (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Francisco de Asís (Espiritualidad)";
                        break;
                };
                break;
            case 'tropa':
                area = "Territorio";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Pez (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Tortuga (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'comunidad':
                area = "Desafío";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Delfín (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Caballo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'clan':
                area = "Área de Desarrollo";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Corporalidad";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Creatividad";
                        break;
                    case "caracter":
                        areadedesarrollo = "Carácter";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Afectividad";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Sociabilidad";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Espiritualidad";
                        break;
                };
                break;
        };
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 100,height: 100}, { text: ''+Ficha.nombreactividad+'', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', ''+area.toUpperCase()+'', 'PARTICIPANTES' ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'DESCRIPCIÓN DE LA ACTIVIDAD'],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'RECOMENDACIONES'],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'MATERIALES'],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ 'TIEMPOS', 'AUTOR', 'FECHA'],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ]
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<commit_msg>Update fichaReme.js<commit_after>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
module.exports = {
    pdf: function(Ficha) {
        // Parsear area de desarrollo
        var areadedesarrollo = "";
        var area = "";
        switch (Ficha.seccion) {
            case 'manada':
                area = "Presa";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Bagheera (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Kaa (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Baloo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Rikki-Tikki-Tavi (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Kotick (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Francisco de Asís (Espiritualidad)";
                        break;
                };
                break;
            case 'tropa':
                area = "Territorio";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Pez (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Tortuga (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'comunidad':
                area = "Desafío";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Delfín (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Caballo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'clan':
                area = "Área de Desarrollo";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Corporalidad";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Creatividad";
                        break;
                    case "caracter":
                        areadedesarrollo = "Carácter";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Afectividad";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Sociabilidad";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Espiritualidad";
                        break;
                };
                break;
        };
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                {
                    layout: 'noBorders',
                    table: {
                        headerRows: 0,
                        widths: [ '*', '*'],

                        body: [
                            [ { image: path.join(__dirname, '/../../public/img/logo.png'), width: 100,height: 100}, { text: ''+Ficha.nombreactividad+'', style: 'header'}]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', ''+area.toUpperCase()+'', 'PARTICIPANTES' ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'DESCRIPCIÓN DE LA ACTIVIDAD'],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'RECOMENDACIONES'],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'MATERIALES'],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ 'TIEMPOS', 'AUTOR', 'FECHA'],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ],
                    color: 'purple'
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                morrarro:{
                    color: 'purple'
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<|endoftext|>


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

	var PageController = ['$scope', 'auth', 'api', 'gameBoardTitles', 'boardSearchOptions', 'boardProcessor', '$rootScope', '$timeout', '$stateParams', '$state', function($scope, auth, api, gameBoardTitles, boardSearchOptions, boardProcessor, $rootScope, $timeout, $stateParams, $state) {

		$rootScope.pageTitle = "My Boards";

		var updateBoards = function(limit) {
			$scope.setLoading(true);
			api.userGameBoards($scope.selectedFilterOption.value, $scope.selectedSortOption.value, 0, limit).$promise.then(function(boards) {
				$scope.boards = boards;
				boardProcessor.augmentBoards(boards.results, $scope.user._id);
				$scope.filterOptions = boardProcessor.filterOptions;
				$scope.setLoading(false);
			})
		};

		$scope.isTeacher = $scope.user != null && ($scope.user.role == 'TEACHER' || $scope.user.role == 'ADMIN' || $scope.user.role == 'CONTENT_EDITOR' || $scope.user.role == 'EVENT_MANAGER');
		$scope.boardSearchOptions = boardSearchOptions;
		$scope.propertyName = 'lastVisited';
		$scope.reverse = true;
		$scope.sortIcon = {sortable: '⇕', ascending: '⇑', descending: '⇓'};

		$scope.loadMore = function() {
			if (mergeInProgress) return;
			mergeInProgress = true;
			$scope.setLoading(true);
			api.userGameBoards($scope.selectedFilterOption.value, $scope.selectedSortOption.value, $scope.boards.results.length).$promise.then(function(newBoards){
				// Merge new boards into results
				boardProcessor.augmentBoards(newBoards.results, $scope.user._id);
				$.merge($scope.boards.results, newBoards.results);
				$scope.setLoading(false);
				mergeInProgress = false;
			});
		};

		$scope.deleteBoard = function(board){
			lookupAssignedGroups(board).$promise.then(function(groupsAssigned) {
				if (groupsAssigned != null && groupsAssigned.length != 0) {
					if ($scope.user.role == "ADMIN" || $scope.user.role == "EVENT_MANAGER") {
						alert("Warning: You currently have groups assigned to this board. If you delete this your groups will still be assigned but you won't be able to unassign them or see the board in your Assigned Boards or My boards page.");
					} else {
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Not Allowed", "You have groups assigned to this board. To delete this board, you must unassign all groups.");
						return;
					}
				}

				var boardTitle = board.title ? board.title : $scope.generateGameBoardTitle(board);
				// Warn user before deleting
				var confirmation = confirm("You are about to delete " + boardTitle + " board?");
				if (confirmation) {
					// TODO: This needs to be reviewed
					// Currently reloading boards after delete
					$scope.setLoading(true);
					api.deleteGameBoard(board.id).$promise.then(function(){
						updateBoards($scope.boards.results.length);
						$scope.setLoading(false);
						$scope.showToast($scope.toastTypes.Success, "Board Deleted", "You have successfully deleted the board: " + boardTitle);
					}).catch(function(e){
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Failed", "With error message: (" + e.status + ") " + e.data.errorMessage != undefined ? e.data.errorMessage : "");
					});
				}
			})
		}

		$scope.sortBy = function(propertyName) {
			$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
			$scope.propertyName = propertyName;
		};

		$scope.$watchGroup(["selectedNoBoardsOption", "selectedFilterOption"], function(newVal, oldVal) {
			if (newVal !== oldVal) {
				updateBoards($scope.selectedNoBoardsOption.value);
			}
		});

		$scope.$watch("selectedSortOption", function(newVal, oldVal) {
			if (newVal !== oldVal) {
				updateBoards($scope.boards.results.length);
			}
		});

		$scope.$watch("selectedViewOption", function(newVal, oldVal) {
			if (newVal !== oldVal) {
				var allBoardsLoaded = $scope.selectedFilterOption == boardSearchOptions.filter.values.all && $scope.selectedNoBoardsOption == boardSearchOptions.noBoards.values.all;
				$state.go('boards', {view: $scope.selectedViewOption.value}, {notify: !allBoardsLoaded}); // only request boards if all boards are not already loaded
				setDefaultBoardSearchOptions($scope.selectedViewOption.defaultFieldName, allBoardsLoaded);
				window.scrollTo(0, 0);
			}
		});

		var setDefaultBoardSearchOptions = function(viewDefaultField, allBoardsLoaded) {
			if (['cardDefault', 'tableDefault'].indexOf(viewDefaultField) >= 0) {
				// API parameters
				for (boardSearchParameter in $scope.boardSearchOptions) {
					var boardSearchOption = boardSearchOptions[boardSearchParameter];
					var selectedOptionVariableName = 'selected' + boardSearchParameter.charAt(0).toUpperCase() + boardSearchParameter.slice(1) + 'Option';
					var defaultValueKey = boardSearchOption[viewDefaultField];
					// if all boards are loaded ignore default assignment for selectedNoBoardsOption
					if (!(allBoardsLoaded && selectedOptionVariableName == 'selectedNoBoardsOption')) {
						$scope[selectedOptionVariableName] = boardSearchOption.values[defaultValueKey];
					}
				}
				// Front-end filters
				$scope.exactMatch = {
					completion: undefined,
					createdBy: undefined
				};
				$scope.partialMatch = {
					title: undefined,
					subjects: undefined,
					levels: undefined
				};
			}
		};

		var lookupAssignedGroups = function(board) {
			var groups = api.assignments.getAssignedGroups({gameId: board.id});
			return groups;
		};

		// main
		var mergeInProgress = false;
		var suggestedViewValueForScreenSize = Foundation.utils.is_medium_up() ? boardSearchOptions.view.values.table : boardSearchOptions.view.values.card;
		var queryParamDefinedViewValue = $stateParams.view && boardSearchOptions.view.values[$stateParams.view];
		var initialViewValue = queryParamDefinedViewValue || suggestedViewValueForScreenSize;

		setDefaultBoardSearchOptions(initialViewValue.defaultFieldName, false);
		updateBoards($scope.selectedNoBoardsOption.value);
	}];

	return {
		PageController: PageController
	};
})
<commit_msg>Reorder code for minor improvement to readability<commit_after>/**
 * Copyright 2014 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([], function() {

	var PageController = ['$scope', 'auth', 'api', 'gameBoardTitles', 'boardSearchOptions', 'boardProcessor', '$rootScope', '$timeout', '$stateParams', '$state', function($scope, auth, api, gameBoardTitles, boardSearchOptions, boardProcessor, $rootScope, $timeout, $stateParams, $state) {

		$rootScope.pageTitle = "My Boards";

		var updateBoards = function(limit) {
			$scope.setLoading(true);
			api.userGameBoards($scope.selectedFilterOption.value, $scope.selectedSortOption.value, 0, limit).$promise.then(function(boards) {
				$scope.boards = boards;
				boardProcessor.augmentBoards(boards.results, $scope.user._id);
				$scope.filterOptions = boardProcessor.filterOptions;
				$scope.setLoading(false);
			})
		};

		$scope.isTeacher = $scope.user != null && ($scope.user.role == 'TEACHER' || $scope.user.role == 'ADMIN' || $scope.user.role == 'CONTENT_EDITOR' || $scope.user.role == 'EVENT_MANAGER');
		$scope.boardSearchOptions = boardSearchOptions;
		$scope.propertyName = 'lastVisited';
		$scope.reverse = true;
		$scope.sortIcon = {sortable: '⇕', ascending: '⇑', descending: '⇓'};

		$scope.loadMore = function() {
			if (mergeInProgress) return;
			mergeInProgress = true;
			$scope.setLoading(true);
			api.userGameBoards($scope.selectedFilterOption.value, $scope.selectedSortOption.value, $scope.boards.results.length).$promise.then(function(newBoards){
				// Merge new boards into results
				boardProcessor.augmentBoards(newBoards.results, $scope.user._id);
				$.merge($scope.boards.results, newBoards.results);
				$scope.setLoading(false);
				mergeInProgress = false;
			});
		};

		$scope.deleteBoard = function(board){
			lookupAssignedGroups(board).$promise.then(function(groupsAssigned) {
				if (groupsAssigned != null && groupsAssigned.length != 0) {
					if ($scope.user.role == "ADMIN" || $scope.user.role == "EVENT_MANAGER") {
						alert("Warning: You currently have groups assigned to this board. If you delete this your groups will still be assigned but you won't be able to unassign them or see the board in your Assigned Boards or My boards page.");
					} else {
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Not Allowed", "You have groups assigned to this board. To delete this board, you must unassign all groups.");
						return;
					}
				}

				var boardTitle = board.title ? board.title : $scope.generateGameBoardTitle(board);
				// Warn user before deleting
				var confirmation = confirm("You are about to delete " + boardTitle + " board?");
				if (confirmation) {
					// TODO: This needs to be reviewed
					// Currently reloading boards after delete
					$scope.setLoading(true);
					api.deleteGameBoard(board.id).$promise.then(function(){
						updateBoards($scope.boards.results.length);
						$scope.setLoading(false);
						$scope.showToast($scope.toastTypes.Success, "Board Deleted", "You have successfully deleted the board: " + boardTitle);
					}).catch(function(e){
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Failed", "With error message: (" + e.status + ") " + e.data.errorMessage != undefined ? e.data.errorMessage : "");
					});
				}
			})
		}

		$scope.sortBy = function(propertyName) {
			$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
			$scope.propertyName = propertyName;
		};

		$scope.$watchGroup(["selectedNoBoardsOption", "selectedFilterOption"], function(newVal, oldVal) {
			if (newVal !== oldVal) {
				updateBoards($scope.selectedNoBoardsOption.value);
			}
		});

		$scope.$watch("selectedSortOption", function(newVal, oldVal) {
			if (newVal !== oldVal) {
				updateBoards($scope.boards.results.length);
			}
		});

		$scope.$watch("selectedViewOption", function(newVal, oldVal) {
			if (newVal !== oldVal) {
				var allBoardsLoaded = $scope.selectedFilterOption == boardSearchOptions.filter.values.all && $scope.selectedNoBoardsOption == boardSearchOptions.noBoards.values.all;
				$state.go('boards', {view: $scope.selectedViewOption.value}, {notify: !allBoardsLoaded}); // only request boards if all boards are not already loaded
				setDefaultBoardSearchOptions($scope.selectedViewOption.defaultFieldName, allBoardsLoaded);
				window.scrollTo(0, 0);
			}
		});

		var setDefaultBoardSearchOptions = function(viewDefaultField, allBoardsLoaded) {
			if (['cardDefault', 'tableDefault'].indexOf(viewDefaultField) >= 0) {
				// API parameters
				for (boardSearchParameter in $scope.boardSearchOptions) {
					var boardSearchOption = boardSearchOptions[boardSearchParameter];
					var selectedOptionVariableName = 'selected' + boardSearchParameter.charAt(0).toUpperCase() + boardSearchParameter.slice(1) + 'Option';
					var defaultValueKey = boardSearchOption[viewDefaultField];
					// if all boards are loaded ignore default assignment for selectedNoBoardsOption
					if (!(allBoardsLoaded && selectedOptionVariableName == 'selectedNoBoardsOption')) {
						$scope[selectedOptionVariableName] = boardSearchOption.values[defaultValueKey];
					}
				}
				// Front-end filters
				$scope.exactMatch = {
					completion: undefined,
					createdBy: undefined
				};
				$scope.partialMatch = {
					title: undefined,
					subjects: undefined,
					levels: undefined
				};
			}
		};

		var lookupAssignedGroups = function(board) {
			var groups = api.assignments.getAssignedGroups({gameId: board.id});
			return groups;
		};

		// main
		var mergeInProgress = false;
		var queryParamDefinedViewValue = $stateParams.view && boardSearchOptions.view.values[$stateParams.view];
		var suggestedViewValueForScreenSize = Foundation.utils.is_medium_up() ? boardSearchOptions.view.values.table : boardSearchOptions.view.values.card;
		var initialViewValue = queryParamDefinedViewValue || suggestedViewValueForScreenSize;

		setDefaultBoardSearchOptions(initialViewValue.defaultFieldName, false);
		updateBoards($scope.selectedNoBoardsOption.value);
	}];

	return {
		PageController: PageController
	};
})
<|endoftext|>


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

	var PageController = ['$scope', 'auth', 'api', 'gameBoardTitles', '$rootScope', '$timeout', function($scope, auth, api, gameBoardTitles, $rootScope, $timeout) {

		$rootScope.pageTitle = "My Boards";

		$scope.generateGameBoardTitle = gameBoardTitles.generate;

		$scope.filterOptions = [
			{label: "All Boards", val: null},
			{label: "Not Started", val: "not_attempted"},
			{label: "In Progress", val: "in_progress"},
			{label: "Completed", val: "completed"}
		];

		$scope.sortOptions = [
			{label: "Date Created", val: "created"},
			{label: "Date Visited", val: "visited"}
		];

		$scope.filterOption = $scope.filterOptions[0];
		$scope.sortOption = $scope.sortOptions[1];

		var updateBoards = function(limit) {
			$scope.setLoading(true);
			api.userGameBoards($scope.filterOption.val, $scope.sortOption.val, 0, limit).$promise.then(function(boards) {
				$scope.boards = boards;
				$scope.setLoading(false);
			})
		};

		// update boards when filters have been selected
		$scope.$watch("filterOption", function(newVal, oldVal) {
			// TODO: For some reason these watch functions are being fired for no reason
			if (newVal === oldVal) {
				return;
			}
			updateBoards();
		});

		$scope.$watch("sortOption", function(newVal, oldVal) {
			if (newVal === oldVal) {
				return;
			}
			updateBoards();
		});

		updateBoards();

		var mergeInProgress = false;
		$scope.loadMore = function() {
			if (mergeInProgress) return;
			mergeInProgress = true;
			$scope.setLoading(true);
			api.userGameBoards($scope.filterOption.val, $scope.sortOption.val, $scope.boards.results.length).$promise.then(function(newBoards){
				// Merge new boards into results
				$.merge($scope.boards.results, newBoards.results);
				$scope.setLoading(false);
				mergeInProgress = false;
			});
		};

		$scope.deleteBoard = function(board){
			lookupAssignedGroups(board).$promise.then(function(groupsAssigned) {
				if (groupsAssigned != null && groupsAssigned.length != 0){
					alert("Warning: You currently have groups assigned to this board. If you delete this your groups will still be assigned but you won't be able to see the board in your Assigned Boards or My boards page.")
				}

				var boardTitle = board.title ? board.title : $scope.generateGameBoardTitle(board);
				// Warn user before deleting
				var confirmation = confirm("You are about to delete "+ boardTitle + " board?");
				if (confirmation){
	       			// TODO: This needs to be reviewed
	       			// Currently reloading boards after delete
					$scope.setLoading(true);
	       			api.deleteGameBoard(board.id).$promise.then(function(){
				        updateBoards($scope.boards.results.length);
				        $scope.setLoading(false);
				        $scope.showToast($scope.toastTypes.Success, "Board Deleted", "You have successfully deleted the board: " + boardTitle);
	       			}).catch(function(e){
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Failed", "With error message: (" + e.status + ") "+ e.status + ") "+ e.data.errorMessage != undefined ? e.data.errorMessage : "");
	       			});
				}
			})
		}

		// duplicate code - I know its bad but this whole file is duplicated so one more function isn't going to destroy the world - just until we refactor this file...
		var lookupAssignedGroups = function(board) {
			var groups = api.assignments.getAssignedGroups({gameId: board.id});
			return groups;
		}

		$scope.calculateBoardLevels = function(board) {
			// TODO: this logic is duplicated in the assignments controller. We should refactor.
			levels = [];
			for(var i = 0; i < board.questions.length; i++) {
				if (levels.indexOf(board.questions[i].level) == -1 && board.questions[i].level != 0) {
					levels.push(board.questions[i].level);
				}
			}

			levels.sort(function (a, b) {
   				return a > b ? 1 : a < b ? -1 : 0;
			});

			return levels;
		};

		$scope.calculateBoardSubjects = function(board) {
			subjects = [];
			for(i = 0; i < board.questions.length; i++) {
				var q = board.questions[i];

				if (q.tags && q.tags.indexOf("maths") > -1 && subjects.indexOf("maths") == -1)
					subjects.push("maths");
				else if (q.tags && q.tags.indexOf("physics") > -1 && subjects.indexOf("physics") == -1)
					subjects.push("physics");
			}

			return subjects;
		}
	}];

	return {
		PageController: PageController
	};
})<commit_msg>Fix repeated text in MyBoardsController error popup.<commit_after>/**
 * Copyright 2014 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([], function() {

	var PageController = ['$scope', 'auth', 'api', 'gameBoardTitles', '$rootScope', '$timeout', function($scope, auth, api, gameBoardTitles, $rootScope, $timeout) {

		$rootScope.pageTitle = "My Boards";

		$scope.generateGameBoardTitle = gameBoardTitles.generate;

		$scope.filterOptions = [
			{label: "All Boards", val: null},
			{label: "Not Started", val: "not_attempted"},
			{label: "In Progress", val: "in_progress"},
			{label: "Completed", val: "completed"}
		];

		$scope.sortOptions = [
			{label: "Date Created", val: "created"},
			{label: "Date Visited", val: "visited"}
		];

		$scope.filterOption = $scope.filterOptions[0];
		$scope.sortOption = $scope.sortOptions[1];

		var updateBoards = function(limit) {
			$scope.setLoading(true);
			api.userGameBoards($scope.filterOption.val, $scope.sortOption.val, 0, limit).$promise.then(function(boards) {
				$scope.boards = boards;
				$scope.setLoading(false);
			})
		};

		// update boards when filters have been selected
		$scope.$watch("filterOption", function(newVal, oldVal) {
			// TODO: For some reason these watch functions are being fired for no reason
			if (newVal === oldVal) {
				return;
			}
			updateBoards();
		});

		$scope.$watch("sortOption", function(newVal, oldVal) {
			if (newVal === oldVal) {
				return;
			}
			updateBoards();
		});

		updateBoards();

		var mergeInProgress = false;
		$scope.loadMore = function() {
			if (mergeInProgress) return;
			mergeInProgress = true;
			$scope.setLoading(true);
			api.userGameBoards($scope.filterOption.val, $scope.sortOption.val, $scope.boards.results.length).$promise.then(function(newBoards){
				// Merge new boards into results
				$.merge($scope.boards.results, newBoards.results);
				$scope.setLoading(false);
				mergeInProgress = false;
			});
		};

		$scope.deleteBoard = function(board){
			lookupAssignedGroups(board).$promise.then(function(groupsAssigned) {
				if (groupsAssigned != null && groupsAssigned.length != 0){
					alert("Warning: You currently have groups assigned to this board. If you delete this your groups will still be assigned but you won't be able to see the board in your Assigned Boards or My boards page.")
				}

				var boardTitle = board.title ? board.title : $scope.generateGameBoardTitle(board);
				// Warn user before deleting
				var confirmation = confirm("You are about to delete "+ boardTitle + " board?");
				if (confirmation){
	       			// TODO: This needs to be reviewed
	       			// Currently reloading boards after delete
					$scope.setLoading(true);
	       			api.deleteGameBoard(board.id).$promise.then(function(){
				        updateBoards($scope.boards.results.length);
				        $scope.setLoading(false);
				        $scope.showToast($scope.toastTypes.Success, "Board Deleted", "You have successfully deleted the board: " + boardTitle);
	       			}).catch(function(e){
						$scope.showToast($scope.toastTypes.Failure, "Board Deletion Failed", "With error message: (" + e.status + ") " + e.data.errorMessage != undefined ? e.data.errorMessage : "");
	       			});
				}
			})
		}

		// duplicate code - I know its bad but this whole file is duplicated so one more function isn't going to destroy the world - just until we refactor this file...
		var lookupAssignedGroups = function(board) {
			var groups = api.assignments.getAssignedGroups({gameId: board.id});
			return groups;
		}

		$scope.calculateBoardLevels = function(board) {
			// TODO: this logic is duplicated in the assignments controller. We should refactor.
			levels = [];
			for(var i = 0; i < board.questions.length; i++) {
				if (levels.indexOf(board.questions[i].level) == -1 && board.questions[i].level != 0) {
					levels.push(board.questions[i].level);
				}
			}

			levels.sort(function (a, b) {
   				return a > b ? 1 : a < b ? -1 : 0;
			});

			return levels;
		};

		$scope.calculateBoardSubjects = function(board) {
			subjects = [];
			for(i = 0; i < board.questions.length; i++) {
				var q = board.questions[i];

				if (q.tags && q.tags.indexOf("maths") > -1 && subjects.indexOf("maths") == -1)
					subjects.push("maths");
				else if (q.tags && q.tags.indexOf("physics") > -1 && subjects.indexOf("physics") == -1)
					subjects.push("physics");
			}

			return subjects;
		}
	}];

	return {
		PageController: PageController
	};
})<|endoftext|>


<commit_before>'use strict';
angular.module('arethusa.core').directive('pluginSetting', [
  'userPreferences',
  function (userPreferences) {
    return {
      restrict: 'A',
      scope: true,
      link: function(scope, element, attrs) {
        scope.change = function() {
          var model = scope.setting.model;
          var value = scope.plugin[model];
          var change = scope.plugin[scope.setting.change];
          userPreferences.set(scope.plugin.name, model, value);
          if (change) change();
        };
      },
      templateUrl: 'templates/arethusa.core/plugin_setting.html'
    };
  }
]);

<commit_msg>pluginSetting: Fix calling of change function<commit_after>'use strict';
angular.module('arethusa.core').directive('pluginSetting', [
  'userPreferences',
  function (userPreferences) {
    return {
      restrict: 'A',
      scope: true,
      link: function(scope, element, attrs) {
        scope.change = function() {
          var model = scope.setting.model;
          var value = scope.plugin[model];
          var change = scope.setting.change;
          userPreferences.set(scope.plugin.name, model, value);
          if (angular.isFunction(change)) change();
        };
      },
      templateUrl: 'templates/arethusa.core/plugin_setting.html'
    };
  }
]);

<|endoftext|>


<commit_before>"use strict";

angular.module('arethusa.core').directive('tokenSelector', [
  'state', '_', 'StateChangeWatcher', 'Highlighter', 'translator',
  function(state, _, StateChangeWatcher, Highlighter, translator) {
    return {
      restrict: 'A',
      scope: {
        tokens: "=tokenSelector"
      },
      link: function(scope, element, attrs) {
        var hasNoTokensSelected = true;
        var hasAllTokensSelected = false;
        var style = scope.style || { "background-color": "rgb(255, 216, 216)" }; // a very light red

        scope.countOfSelectedTokens = function() {
          return state.hasClickSelections();
        };

        scope.$watch('countOfSelectedTokens()', function(newValue, oldValue) {
          hasNoTokensSelected = newValue === 0;
          hasAllTokensSelected = newValue === state.totalTokens;

          updateSelectors();
        });

        var callbacks = {
          newMatch: function(token) {
            if (unusedHighlighter.isActive) state.addStyle(token.id, style);
          },
          lostMatch: function(token) {
            if (unusedHighlighter.isActive) highlighter.removeStyle(token.id);
          },
          changedCount: function(newCount) {
            unusedSelector.count = newCount;
            translator("selector.unused", setLabel(unusedSelector));
          }
        };
        var unusedWatcher = new StateChangeWatcher('head.id', callbacks);

        var highlighter = new Highlighter(unusedWatcher, style);

        var selectAll = function() {
          state.multiSelect(Object.keys(scope.tokens));
        };

        var selectUnused = function() {
          highlighter.unapplyHighlighting();
          state.multiSelect(Object.keys(unusedWatcher.matchingTokens));
        };

        function switchHighlighting() {
          if (unusedHighlighter.isActive) {
            highlighter.unapplyHighlighting();
          } else {
            highlighter.applyHighlighting();
          }
          unusedHighlighter.isActive = !unusedHighlighter.isActive;
        }

        function setLabel(obj) {
          return function(translationFn) {
              obj.label = translationFn(obj);
          };
        }

        var noneSelector = {
          action: function() {
            state.deselectAll();
            highlighter.applyHighlighting();
          },
          isActive: true
        };
        translator("selector.none", setLabel(noneSelector));

        var allSelector = {
          action: selectAll,
          isActive: false
        };
        translator("selector.all", setLabel(allSelector));

        var unusedSelector = {
          action: selectUnused,
          isActive: false,
          count: 0
        };
        translator("selector.unused", setLabel(unusedSelector));

        var unusedHighlighter = {
          action: switchHighlighting,
          styleClasses: 'unused-highlighter',
          isActive: false
        };
        translator("selector.highlightUnused", setLabel(unusedHighlighter));

        scope.selectors = [
          noneSelector,
          allSelector,
          unusedSelector,
          unusedHighlighter
        ];

        var areAllSelected = function(tokens) {
          return _.all(Object.keys(tokens), function(tokenId) {
            return state.isClicked(tokenId);
          });
        };

        var updateSelectors = function() {
          noneSelector.isActive = hasNoTokensSelected;
          allSelector.isActive = hasAllTokensSelected;

          unusedSelector.isActive = !hasNoTokensSelected &&
            scope.countOfSelectedTokens() === unusedWatcher.count &&
            areAllSelected(unusedWatcher.matchingTokens);
        };

        unusedWatcher.initCount();
      },
      templateUrl: 'templates/arethusa.core/token_selector.html'
    };
  }
]);

<commit_msg>Disable all selector for performance reasons<commit_after>"use strict";

angular.module('arethusa.core').directive('tokenSelector', [
  'state', '_', 'StateChangeWatcher', 'Highlighter', 'translator',
  function(state, _, StateChangeWatcher, Highlighter, translator) {
    return {
      restrict: 'A',
      scope: {
        tokens: "=tokenSelector"
      },
      link: function(scope, element, attrs) {
        var hasNoTokensSelected = true;
        var hasAllTokensSelected = false;
        var style = scope.style || { "background-color": "rgb(255, 216, 216)" }; // a very light red

        scope.countOfSelectedTokens = function() {
          return state.hasClickSelections();
        };

        scope.$watch('countOfSelectedTokens()', function(newValue, oldValue) {
          hasNoTokensSelected = newValue === 0;
          hasAllTokensSelected = newValue === state.totalTokens;

          updateSelectors();
        });

        var callbacks = {
          newMatch: function(token) {
            if (unusedHighlighter.isActive) state.addStyle(token.id, style);
          },
          lostMatch: function(token) {
            if (unusedHighlighter.isActive) highlighter.removeStyle(token.id);
          },
          changedCount: function(newCount) {
            unusedSelector.count = newCount;
            translator("selector.unused", setLabel(unusedSelector));
          }
        };
        var unusedWatcher = new StateChangeWatcher('head.id', callbacks);

        var highlighter = new Highlighter(unusedWatcher, style);

        var selectAll = function() {
          state.multiSelect(Object.keys(scope.tokens));
        };

        var selectUnused = function() {
          highlighter.unapplyHighlighting();
          state.multiSelect(Object.keys(unusedWatcher.matchingTokens));
        };

        function switchHighlighting() {
          if (unusedHighlighter.isActive) {
            highlighter.unapplyHighlighting();
          } else {
            highlighter.applyHighlighting();
          }
          unusedHighlighter.isActive = !unusedHighlighter.isActive;
        }

        function setLabel(obj) {
          return function(translationFn) {
              obj.label = translationFn(obj);
          };
        }

        var noneSelector = {
          action: function() {
            state.deselectAll();
            highlighter.applyHighlighting();
          },
          isActive: true
        };
        translator("selector.none", setLabel(noneSelector));

        var allSelector = {
          action: selectAll,
          isActive: false
        };
        translator("selector.all", setLabel(allSelector));

        var unusedSelector = {
          action: selectUnused,
          isActive: false,
          count: 0
        };
        translator("selector.unused", setLabel(unusedSelector));

        var unusedHighlighter = {
          action: switchHighlighting,
          styleClasses: 'unused-highlighter',
          isActive: false
        };
        translator("selector.highlightUnused", setLabel(unusedHighlighter));

        scope.selectors = [
          noneSelector,
          // allSelector, // not used right now for performance reasons
          unusedSelector,
          unusedHighlighter
        ];

        var areAllSelected = function(tokens) {
          return _.all(Object.keys(tokens), function(tokenId) {
            return state.isClicked(tokenId);
          });
        };

        var updateSelectors = function() {
          noneSelector.isActive = hasNoTokensSelected;
          allSelector.isActive = hasAllTokensSelected;

          unusedSelector.isActive = !hasNoTokensSelected &&
            scope.countOfSelectedTokens() === unusedWatcher.count &&
            areAllSelected(unusedWatcher.matchingTokens);
        };

        unusedWatcher.initCount();
      },
      templateUrl: 'templates/arethusa.core/token_selector.html'
    };
  }
]);

<|endoftext|>