<commit_before>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  history: [],
  picks: [],
  players: [],
  settings: {
    app: {
      domes: ['ARI', 'ATL', 'DAL', 'DET', 'HOU', 'IND', 'MIN', 'NOS'],
      draftOrderTypes: {
        'random': 'ran',
        'sequential': 'seq',
        'serpentine': 'ser'
      },
      positions: [
        { key: 'QB', name: 'QB', category: 'Offense', order: 1 },
        { key: 'RB', name: 'RB', category: 'Offense', order: 2 },
        { key: 'WR', name: 'WR', category: 'Offense', order: 3 },
        { key: 'TE', name: 'TE', category: 'Offense', order: 4 },
        { key: 'DE', name: 'Defensive End', category: 'Defense', order: 5 },
        { key: 'DT', name: 'Defensive Tackle', category: 'Defense', order: 6 },
        { key: 'LB', name: 'Linebacker', category: 'Defense', order: 7 },
        { key: 'CB', name: 'Cornerback', category: 'Defense', order: 8 },
        { key: 'S', name: 'Safety', category: 'Defense', order: 9 },
        { key: 'Off', name: 'Offense', category: 'Team', order: 10 },
        { key: 'Def', name: 'Defense/Special Teams', category: 'Team', order: 11 },
        { key: 'TMQB', name: 'Team QB', category: 'Team', order: 12 },
        { key: 'TMRB', name: 'Team RB', category: 'Team', order: 13 },
        { key: 'TMWR', name: 'Team WR', category: 'Team', order: 14 },
        { key: 'TMTE', name: 'Team TE', category: 'Team', order: 15 },
        { key: 'TMDL', name: 'Team Defensive Line', category: 'Team', order: 16 },
        { key: 'TMLB', name: 'Team Linebackers', category: 'Team', order: 17 },
        { key: 'TMDB', name: 'Team Defensive Backs', category: 'Team', order: 18 },
        { key: 'TMPK', name: 'Team Place Kicker', category: 'Team', order: 19 },
        { key: 'TMPN', name: 'Team Punter', category: 'Team', order: 20 },
        { key: 'ST', name: 'Special Teams', category: 'Other', order: 21 },
        { key: 'PK', name: 'Kicker', category: 'Other', order: 22 },
        { key: 'PN', name: 'Punter', category: 'Other', order: 23 },
        { key: 'Coach', name: 'Coach', category: 'Other', order: 24 },
        { key: 'XX', name: 'Unknown', order: 25 }
      ]
    },
    /*
      Family settings
    */
    league: {
      draftOrderType: 'ser',
      keepers: false,
      positions: [
        { key: 'QB', min: 2, max: 4 },
        { key: 'RB', min: 2, max: 6 },
        { key: 'WR', min: 2, max: 6 },
        { key: 'TE', min: 1, max: 6 },
        { key: 'PK', min: 1, max: 3 },
        { key: 'Def', min: 1, max: 3 }
      ],
      rosterSize: 18,
      secondsPerPick: 60,
      teams: [
        { name: 'Team Dad', owner: 'Don Koser', draftOrder: 1 },
        { name: 'Team Mom', owner: 'Sue Koser', draftOrder: 2 },
        { name: 'From Wentz It Came', owner: 'Brian Koser', draftOrder: 3, isUser: true },
        { name: 'Team Zach', owner: 'Zach Koser', draftOrder: 4 },
        { name: 'Team Matt', owner: 'Matt Koser', draftOrder: 5 },
        { name: 'Team Amanda', owner: 'Amanda Koser', draftOrder: 6 },
        { name: 'Pensacola Pandas', owner: 'Josh Hutt', draftOrder: 7 },
        { name: 'Team Megan', owner: 'Megan Hutt', draftOrder: 8 }
      ]
    },
    team: {
      idealSize: [
        { positionKey: 'QB', count: 3 },
        { positionKey: 'RB', count: 5 },
        { positionKey: 'WR', count: 6 },
        { positionKey: 'TE', count: 2 },
        { positionKey: 'PK', count: 1 },
        { positionKey: 'Def', count: 1 }
      ],
      rankings: [],
      tiers: [
        { positionKey: 'QB', sizes: [3, 7, 3, 6, 6, 7] },
        { positionKey: 'RB', sizes: [] },
        { positionKey: 'WR', sizes: [] },
        { positionKey: 'TE', sizes: [1] },
        { positionKey: 'PK', sizes: [] },
        { positionKey: 'Def', sizes: [] }
      ]
    }
    /*
      CTS settings
    */
    // league: {
    //   draftOrderType: 'ser',
    //   keepers: true,
    //   positions: [
    //     { key: 'QB', min: 1, max: 6 },
    //     { key: 'RB', min: 1, max: 6 },
    //     { key: 'WR', min: 1, max: 6 },
    //     { key: 'TE', min: 1, max: 6 },
    //     { key: 'PK', min: 1, max: 5 },
    //     { key: 'Def', min: 1, max: 5 }
    //   ]
    //   rosterSize: 11,
    //   secondsPerPick: 60,
    //   teams: [
    //     { name: 'Mark’s Team', owner: 'Mark Garrett', draftOrder: 1, keeper: '10273' },
    //     { name: 'Team Evan', owner: 'Evan Bernard', draftOrder: 2, keeper: '9988' },
    //     { name: 'From Wentz It Came', owner: 'Brian Koser', draftOrder: 3, keeper: '7836', isUser: true },
    //     { name: 'Sack Dak Quarterback', owner: 'Kristy King', draftOrder: 4, keeper: '10271' },
    //     { name: 'London Sillinannies', owner: 'Zach Brown', draftOrder: 5, keeper: '11679' },
    //     { name: 'Alderaan Explosions', owner: 'Brandon Ellison', draftOrder: 6, keeper: '10695' },
    //     { name: 'Christian’s Team', owner: 'Christian Boyer', draftOrder: 7, keeper: '12171' },
    //     { name: 'Don’t Stop Talibing', owner: 'James Hostick', draftOrder: 8, keeper: '12150' }
    //   ]
    // },
    // team: {
    //   idealSize: [
    //     { positionKey: 'QB', count: 3 },
    //     { positionKey: 'RB', count: 2 },
    //     { positionKey: 'WR', count: 2 },
    //     { positionKey: 'TE', count: 1 },
    //     { positionKey: 'PK', count: 1 },
    //     { positionKey: 'Def', count: 1 }
    //   ],
    //   rankings: [],
    //   tiers: [
    //     { positionKey: 'QB', sizes: [3, 7, 3, 6, 6, 7] },
    //     { positionKey: 'RB', sizes: [] },
    //     { positionKey: 'WR', sizes: [] },
    //     { positionKey: 'TE', sizes: [1] },
    //     { positionKey: 'PK', sizes: [] },
    //     { positionKey: 'Def', sizes: [] }
    //   ]
    // }

    /*
      Crossroads settings
    */
    // league: {
    //   draftOrderType: 'ser',
    //   positions: [
    //     { key: 'QB', min: 1, max: 4 },
    //     { key: 'RB', min: 1, max: 8 },
    //     { key: 'WR', min: 2, max: 8 },
    //     { key: 'TE', min: 1, max: 3 },
    //     { key: 'PK', min: 1, max: 3 },
    //     { key: 'Def', min: 1, max: 3 },
    //     { key: 'Coach', min: 1, max: 10 }
    //   ],
    //   rosterSize: 17,
    //   secondsPerPick: 60,
    //   teams: [
    //     { name: 'The Commish', owner: 'Aaron Smith', draftOrder: 12 },
    //     { name: '’Aints -', owner: 'Matt McLean' draftOrder: 11 },
    //     { name: 'Play It Again Sam', owner: 'Brian Koser', draftOrder: 10, isUser: true },
    //     { name: 'O. J.', owner: 'Tuck Chastain', draftOrder: 9 },
    //     { name: 'Buck stops here', owner: 'Terry Buckner', draftOrder: 8 },
    //     { name: 'Small Arms Dealer', owner: 'Scott Hopkins', draftOrder: 7 },
    //     { name: 'Fluoride Bandits', owner: 'Shane Herrington', draftOrder: 6 },
    //     { name: 'Brown Mikes DeadBeat Bums', owner: 'Brown Mike',  draftOrder: 5 },
    //     { name: 'Alabama Yard rats', owner: 'Philip Quinney', draftOrder: 4 },
    //     { name: 'Cam Burglar', owner: 'Justin Tolbert', draftOrder: 3 },
    //     { name: 'Amen Corner', owner: 'Ben Harris', draftOrder: 2 },
    //     { name: 'Crossroads Zealots', owner: 'Joe Chastain', draftOrder: 1 }
    //   ]
    // },
    // team: {
    //   idealSize: [
    //     { positionKey: 'QB', count: 2 },
    //     { positionKey: 'RB', count: 4 },
    //     { positionKey: 'WR', count: 5 },
    //     { positionKey: 'TE', count: 2 },
    //     { positionKey: 'PK', count: 1 },
    //     { positionKey: 'Def', count: 2 },
    //     { positionKey: 'Coach', count: 1 }
    //   ]
    // }
  }
}

const mutations = {
  ADDPICK (state, pick) {
    state.picks.push(pick)
  },
  ADDSTATEENTRY (state, entry) {
    state.history.push(entry)
  },
  SETPLAYERS (state, players) {
    state.players = players
  },
  SETTEAMRANKINGS (state, rankings) {
    state.settings.team.rankings = rankings
  },
  UNDOLASTPICK (state) {
    state.picks.pop()
  },
  UNDOSTATEENTRY (state) {
    state.history.pop()
  },
  UPDATEKEEPERS (state, keeperPicks) {
    state.picks = keeperPicks
  }
}

export default new Vuex.Store({
  state,
  mutations
})
<commit_msg>Set Koser family draft order<commit_after>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  history: [],
  picks: [],
  players: [],
  settings: {
    app: {
      domes: ['ARI', 'ATL', 'DAL', 'DET', 'HOU', 'IND', 'MIN', 'NOS'],
      draftOrderTypes: {
        'random': 'ran',
        'sequential': 'seq',
        'serpentine': 'ser'
      },
      positions: [
        { key: 'QB', name: 'QB', category: 'Offense', order: 1 },
        { key: 'RB', name: 'RB', category: 'Offense', order: 2 },
        { key: 'WR', name: 'WR', category: 'Offense', order: 3 },
        { key: 'TE', name: 'TE', category: 'Offense', order: 4 },
        { key: 'DE', name: 'Defensive End', category: 'Defense', order: 5 },
        { key: 'DT', name: 'Defensive Tackle', category: 'Defense', order: 6 },
        { key: 'LB', name: 'Linebacker', category: 'Defense', order: 7 },
        { key: 'CB', name: 'Cornerback', category: 'Defense', order: 8 },
        { key: 'S', name: 'Safety', category: 'Defense', order: 9 },
        { key: 'Off', name: 'Offense', category: 'Team', order: 10 },
        { key: 'Def', name: 'Defense/Special Teams', category: 'Team', order: 11 },
        { key: 'TMQB', name: 'Team QB', category: 'Team', order: 12 },
        { key: 'TMRB', name: 'Team RB', category: 'Team', order: 13 },
        { key: 'TMWR', name: 'Team WR', category: 'Team', order: 14 },
        { key: 'TMTE', name: 'Team TE', category: 'Team', order: 15 },
        { key: 'TMDL', name: 'Team Defensive Line', category: 'Team', order: 16 },
        { key: 'TMLB', name: 'Team Linebackers', category: 'Team', order: 17 },
        { key: 'TMDB', name: 'Team Defensive Backs', category: 'Team', order: 18 },
        { key: 'TMPK', name: 'Team Place Kicker', category: 'Team', order: 19 },
        { key: 'TMPN', name: 'Team Punter', category: 'Team', order: 20 },
        { key: 'ST', name: 'Special Teams', category: 'Other', order: 21 },
        { key: 'PK', name: 'Kicker', category: 'Other', order: 22 },
        { key: 'PN', name: 'Punter', category: 'Other', order: 23 },
        { key: 'Coach', name: 'Coach', category: 'Other', order: 24 },
        { key: 'XX', name: 'Unknown', order: 25 }
      ]
    },
    /*
      Family settings
    */
    league: {
      draftOrderType: 'ser',
      keepers: false,
      positions: [
        { key: 'QB', min: 2, max: 4 },
        { key: 'RB', min: 2, max: 6 },
        { key: 'WR', min: 2, max: 6 },
        { key: 'TE', min: 1, max: 6 },
        { key: 'PK', min: 1, max: 3 },
        { key: 'Def', min: 1, max: 3 }
      ],
      rosterSize: 18,
      secondsPerPick: 60,
      teams: [
        { name: 'Team Matt', owner: 'Matt Koser', draftOrder: 1 },
        { name: 'Team Megan', owner: 'Megan Hutt', draftOrder: 2 },
        { name: 'Team Amanda', owner: 'Amanda Koser', draftOrder: 3 },
        { name: 'Team DadKos', owner: 'Don Koser', draftOrder: 4 },
        { name: 'From Wentz It Came', owner: 'Brian Koser', draftOrder: 5, isUser: true },
        { name: 'Mom’s Marauders', owner: 'Sue Koser', draftOrder: 6 },
        { name: 'Sith Knights', owner: 'Zach Koser', draftOrder: 7 },
        { name: 'Pensacola Pandas', owner: 'Josh Hutt', draftOrder: 8 }
      ]
    },
    team: {
      idealSize: [
        { positionKey: 'QB', count: 3 },
        { positionKey: 'RB', count: 5 },
        { positionKey: 'WR', count: 6 },
        { positionKey: 'TE', count: 2 },
        { positionKey: 'PK', count: 1 },
        { positionKey: 'Def', count: 1 }
      ],
      rankings: [],
      tiers: [
        { positionKey: 'QB', sizes: [3, 7, 3, 6, 6, 7] },
        { positionKey: 'RB', sizes: [] },
        { positionKey: 'WR', sizes: [] },
        { positionKey: 'TE', sizes: [1] },
        { positionKey: 'PK', sizes: [] },
        { positionKey: 'Def', sizes: [] }
      ]
    }
    /*
      CTS settings
    */
    // league: {
    //   draftOrderType: 'ser',
    //   keepers: true,
    //   positions: [
    //     { key: 'QB', min: 1, max: 6 },
    //     { key: 'RB', min: 1, max: 6 },
    //     { key: 'WR', min: 1, max: 6 },
    //     { key: 'TE', min: 1, max: 6 },
    //     { key: 'PK', min: 1, max: 5 },
    //     { key: 'Def', min: 1, max: 5 }
    //   ]
    //   rosterSize: 11,
    //   secondsPerPick: 60,
    //   teams: [
    //     { name: 'Mark’s Team', owner: 'Mark Garrett', draftOrder: 1, keeper: '10273' },
    //     { name: 'Team Evan', owner: 'Evan Bernard', draftOrder: 2, keeper: '9988' },
    //     { name: 'From Wentz It Came', owner: 'Brian Koser', draftOrder: 3, keeper: '7836', isUser: true },
    //     { name: 'Sack Dak Quarterback', owner: 'Kristy King', draftOrder: 4, keeper: '10271' },
    //     { name: 'London Sillinannies', owner: 'Zach Brown', draftOrder: 5, keeper: '11679' },
    //     { name: 'Alderaan Explosions', owner: 'Brandon Ellison', draftOrder: 6, keeper: '10695' },
    //     { name: 'Christian’s Team', owner: 'Christian Boyer', draftOrder: 7, keeper: '12171' },
    //     { name: 'Don’t Stop Talibing', owner: 'James Hostick', draftOrder: 8, keeper: '12150' }
    //   ]
    // },
    // team: {
    //   idealSize: [
    //     { positionKey: 'QB', count: 3 },
    //     { positionKey: 'RB', count: 2 },
    //     { positionKey: 'WR', count: 2 },
    //     { positionKey: 'TE', count: 1 },
    //     { positionKey: 'PK', count: 1 },
    //     { positionKey: 'Def', count: 1 }
    //   ],
    //   rankings: [],
    //   tiers: [
    //     { positionKey: 'QB', sizes: [3, 7, 3, 6, 6, 7] },
    //     { positionKey: 'RB', sizes: [] },
    //     { positionKey: 'WR', sizes: [] },
    //     { positionKey: 'TE', sizes: [1] },
    //     { positionKey: 'PK', sizes: [] },
    //     { positionKey: 'Def', sizes: [] }
    //   ]
    // }

    /*
      Crossroads settings
    */
    // league: {
    //   draftOrderType: 'ser',
    //   positions: [
    //     { key: 'QB', min: 1, max: 4 },
    //     { key: 'RB', min: 1, max: 8 },
    //     { key: 'WR', min: 2, max: 8 },
    //     { key: 'TE', min: 1, max: 3 },
    //     { key: 'PK', min: 1, max: 3 },
    //     { key: 'Def', min: 1, max: 3 },
    //     { key: 'Coach', min: 1, max: 10 }
    //   ],
    //   rosterSize: 17,
    //   secondsPerPick: 60,
    //   teams: [
    //     { name: 'The Commish', owner: 'Aaron Smith', draftOrder: 12 },
    //     { name: '’Aints -', owner: 'Matt McLean' draftOrder: 11 },
    //     { name: 'Play It Again Sam', owner: 'Brian Koser', draftOrder: 10, isUser: true },
    //     { name: 'O. J.', owner: 'Tuck Chastain', draftOrder: 9 },
    //     { name: 'Buck stops here', owner: 'Terry Buckner', draftOrder: 8 },
    //     { name: 'Small Arms Dealer', owner: 'Scott Hopkins', draftOrder: 7 },
    //     { name: 'Fluoride Bandits', owner: 'Shane Herrington', draftOrder: 6 },
    //     { name: 'Brown Mikes DeadBeat Bums', owner: 'Brown Mike',  draftOrder: 5 },
    //     { name: 'Alabama Yard rats', owner: 'Philip Quinney', draftOrder: 4 },
    //     { name: 'Cam Burglar', owner: 'Justin Tolbert', draftOrder: 3 },
    //     { name: 'Amen Corner', owner: 'Ben Harris', draftOrder: 2 },
    //     { name: 'Crossroads Zealots', owner: 'Joe Chastain', draftOrder: 1 }
    //   ]
    // },
    // team: {
    //   idealSize: [
    //     { positionKey: 'QB', count: 2 },
    //     { positionKey: 'RB', count: 4 },
    //     { positionKey: 'WR', count: 5 },
    //     { positionKey: 'TE', count: 2 },
    //     { positionKey: 'PK', count: 1 },
    //     { positionKey: 'Def', count: 2 },
    //     { positionKey: 'Coach', count: 1 }
    //   ]
    // }
  }
}

const mutations = {
  ADDPICK (state, pick) {
    state.picks.push(pick)
  },
  ADDSTATEENTRY (state, entry) {
    state.history.push(entry)
  },
  SETPLAYERS (state, players) {
    state.players = players
  },
  SETTEAMRANKINGS (state, rankings) {
    state.settings.team.rankings = rankings
  },
  UNDOLASTPICK (state) {
    state.picks.pop()
  },
  UNDOSTATEENTRY (state) {
    state.history.pop()
  },
  UPDATEKEEPERS (state, keeperPicks) {
    state.picks = keeperPicks
  }
}

export default new Vuex.Store({
  state,
  mutations
})
<|endoftext|>


<commit_before>// This code (and its parent process in changes.js) is a Node.JS listener
//	listening to CouchDB's _changes feed, and is derived from
//	https://github.com/mikeal/node.couch.js and
//	http://dominicbarnes.us/node-couchdb-api/api/database/changes.html
// It monitors when requests are submitted to:
//	(when configuring a directory's settings) get a url in general
//	(when a directory is already configured) download all cong data for a directory
// TODO: Could we use backbone-couch.js here instead of cradle, in order to use our
//	Backbone model here?

var buffer = '',
	http = require('http'),
	config = require('./rcl/config'),
	db = config.db,
	log = require('./rcl/lib').log;
	//$ = require('jquery');
//var model = require('model.js').model
	//stdin = process.openStdin();
if (config.debug)
	var longjohn = require('./rcl/node_modules/longjohn')

//stdin.setEncoding('utf8');

// Declare utility functions
function get_url(doc, from_url, to_html, status_flag){
    http.get(doc[from_url], function(res){
        var pageData = ''
        res.on('data', function(chunk){
            pageData += chunk
        })
        res.on('end', function(){
            // TODO: Check to see if we got a 404 response
            // Write the contents of the html variable back to the database
            doc[to_html] = pageData
            doc[status_flag] = 'gotten'
            // TODO: Use Backbone here instead of cradle
            db.save(doc._id, doc._rev, doc, function(err, res){
                // TODO: Do anything more that needs to be done here
            });
        })
    });
}
function get_url_set(doc, from_urls, to_html, status_flag){
    for (var i=0; i<doc[from_urls].length; i++){
        doc[status_flag] = 'getting'
        http.get(doc[from_urls][i], function(res){
            var pageData = ''
            res.on('data', function(chunk){
                pageData += chunk
            })
            res.on('end', function(){
                // TODO: Check to see if we got a 404 response
                // Write the contents of the html variable back to the database
                if (!doc[to_html] || doc[to_html] == ''){
                    doc[to_html] = new Array() // declare as array
                }
                var temp_items = doc[to_html]
                var num_items = temp_items.push(pageData)
                doc[to_html] = temp_items
                // TODO: Start here
                if (num_items==doc[from_urls].length){
                    // We've gotten all the items' html!
                    doc[status_flag] = 'gotten'
                }
                // TODO: Use Backbone here instead of cradle
                db.save(doc._id, doc._rev, doc, function(err, res){
                    // TODO: Do anything more that needs to be done here
                });
            })
        });
    }
}

// Handle all changes
process.on('message', function(doc){

	// Watch for requests to get the contents of a URL for a church directory
	// TODO: Check to see if the URL is valid
	if (doc.collection == 'directory' && doc.get_url_html=='requested' && doc.url){
		// E.g., when a user enters "opc.org/locator.html" into the church directory configuration page,
		// 	then go get the contents of that URL.
        get_url(doc, 'url', 'url_html', 'get_url_html')
	}
	// Watch for requests to get the contents of a state page URL
    if (doc.collection == 'directory' && doc.get_state_url_html=='requested' && doc.state_url){
            get_url(doc, 'state_page_values', 'state_url_html', 'get_state_url_html')
    }
});
<commit_msg>Disabled debugging to ignore longjohn require error for now<commit_after>// This code (and its parent process in changes.js) is a Node.JS listener
//	listening to CouchDB's _changes feed, and is derived from
//	https://github.com/mikeal/node.couch.js and
//	http://dominicbarnes.us/node-couchdb-api/api/database/changes.html
// It monitors when requests are submitted to:
//	(when configuring a directory's settings) get a url in general
//	(when a directory is already configured) download all cong data for a directory
// TODO: Could we use backbone-couch.js here instead of cradle, in order to use our
//	Backbone model here?

var buffer = '',
	http = require('http'),
	config = require('./rcl/config'),
	db = config.db,
	log = require('./rcl/lib').log;
	//$ = require('jquery');
//var model = require('model.js').model
	//stdin = process.openStdin();
if (config.debug)
	var longjohn = require('longjohn/')

//stdin.setEncoding('utf8');

// Declare utility functions
function get_url(doc, from_url, to_html, status_flag){
    http.get(doc[from_url], function(res){
        var pageData = ''
        res.on('data', function(chunk){
            pageData += chunk
        })
        res.on('end', function(){
            // TODO: Check to see if we got a 404 response
            // Write the contents of the html variable back to the database
            doc[to_html] = pageData
            doc[status_flag] = 'gotten'
            // TODO: Use Backbone here instead of cradle
            db.save(doc._id, doc._rev, doc, function(err, res){
                // TODO: Do anything more that needs to be done here
            });
        })
    });
}
function get_url_set(doc, from_urls, to_html, status_flag){
    for (var i=0; i<doc[from_urls].length; i++){
        doc[status_flag] = 'getting'
        http.get(doc[from_urls][i], function(res){
            var pageData = ''
            res.on('data', function(chunk){
                pageData += chunk
            })
            res.on('end', function(){
                // TODO: Check to see if we got a 404 response
                // Write the contents of the html variable back to the database
                if (!doc[to_html] || doc[to_html] == ''){
                    doc[to_html] = new Array() // declare as array
                }
                var temp_items = doc[to_html]
                var num_items = temp_items.push(pageData)
                doc[to_html] = temp_items
                // TODO: Start here
                if (num_items==doc[from_urls].length){
                    // We've gotten all the items' html!
                    doc[status_flag] = 'gotten'
                }
                // TODO: Use Backbone here instead of cradle
                db.save(doc._id, doc._rev, doc, function(err, res){
                    // TODO: Do anything more that needs to be done here
                });
            })
        });
    }
}

// Handle all changes
process.on('message', function(doc){

	// Watch for requests to get the contents of a URL for a church directory
	// TODO: Check to see if the URL is valid
	if (doc.collection == 'directory' && doc.get_url_html=='requested' && doc.url){
		// E.g., when a user enters "opc.org/locator.html" into the church directory configuration page,
		// 	then go get the contents of that URL.
        get_url(doc, 'url', 'url_html', 'get_url_html')
	}
	// Watch for requests to get the contents of a state page URL
    if (doc.collection == 'directory' && doc.get_state_url_html=='requested' && doc.state_url){
            get_url(doc, 'state_page_values', 'state_url_html', 'get_state_url_html')
    }
});
<|endoftext|>


<commit_before>GAME.setConsts({
});

GAME.Bullet = (function() {

    function newBullet() {
        return {
            x : -1,
            y : -1,
            xvel : 0,
            yvel : 0,

            angle : 0,

            path : []
        }
    }

    function step(bullet) {
        bullet.x += xvel;
        bullet.y += yvel;
    }

    function detectCollisions(bullet) {
        for (ent : GAME.entities) {
            if (GAME.Entity.dist(bullet, ent) < 1) {
                if (ent.isPlayer) {
                    GAME.end();
                } else { // bullet hit an enemy
                    GAME.yay();
                    GAME.score++;
                }
            }
        }

        // look at 9 surrounding tiles
        for (wall : walls) {
            if (collision) {
                theta = calculateThetaOut();
                // undoStep(); // TODO: is this necessary?
                bullet.path.push([bullet.x, bullet.y]);
            }
        }
    }

    return {
        newBullet : newBullet,
        step : step
    }
})();<commit_msg>Add good collision checking with bullet-walls<commit_after>GAME.setConsts({
});

GAME.Bullet = (function() {

    function newBullet() {
        return {
            x : -1,
            y : -1,
            xvel : 0,
            yvel : 0,

            angle : 0,

            path : []
        }
    }

    function step(bullet) {
        bullet.x += xvel;
        bullet.y += yvel;
    }

    function detectCollisions(bullet) {
        for (ent : GAME.entities) {
            if (GAME.Entity.dist(bullet, ent) < 1) {
                if (ent.isPlayer) {
                    GAME.end();
                } else { // bullet hit an enemy
                    GAME.yay();
                    GAME.score++;
                }
            }
        }

        // check collision with surrounding tiles
        rx = Math.round(bullet.x)
        ry = Math.round(bullet.y)
        for (var i = rx - 1.5; i < 3; i++) {
            for (var j = ry - 1.5; j < 3; j++) {
                tilecoors = {x: i, y: j}
                if (GAME.current_level.tilemap[i][j] == WALL_TILE && dist(bullet, tilecoors) < 1) {
                    theta = calculateThetaOut();
                    // change to new angle, reverse some velocity
                    // undoStep(); // TODO: is this necessary?
                    bullet.path.push([bullet.x, bullet.y]);
                }
            }
        }
    }

    return {
        newBullet : newBullet,
        step : step
    }
})();<|endoftext|>


<commit_before>var userid;

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
    }

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }
 }

 function getAllTeachers() {
     var teachers = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    var studentLists = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
        });
    });
    return studentLists;
}

 function addGroup($courseid) {
     alert("Groep toevoegen  voor vak " + $courseid);

 }

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

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

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
        var courseid = $('#projectHeader').attr("data-value");

        addGroup($courseid);

        $('addGroupForm').hide();

    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
}
<commit_msg>methode aangroep wijzigen linkt leggen tussen course - teacher - studentlist<commit_after>var userid;

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
    }

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }
 }

 function getAllTeachers() {
     var teachers = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    var studentLists = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
        });
    });
    return studentLists;
}

 function addGroup($courseid) {
     alert("Groep toevoegen  voor vak " + $courseid);

 }

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

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

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
        alert($('#projectHeader').attr("data-value"));

        addGroup($courseid);

        $('addGroupForm').hide();

    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
}
<|endoftext|>


<commit_before>// Normalise window.URL
window.URL || (window.URL = window.webkitURL || window.msURL || window.oURL);

// Normalise navigator.getUserMedia
navigator.getUserMedia || (navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
//
// toString for the older implementation (found by https://github.com/agektmr)
var options = {video: true, toString: function(){ return "video"; }};
navigator.getUserMedia(options, successCallback, errorCallback);

// using the normalised window.URL
function successCallback(stream) {
    video = document.querySelector("#videoplay");
    video.src = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(stream) : stream;
}

function drawFrame() {
    var canvas = document.querySelector('canvas'),
        context = canvas.getContext('2d');

    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    setTimeout(drawFrame, 50);
}

ccv.detect_objects({canvas : (ccv.pre(canvas)), cascade: cascade, interval: 2, min_neighbors: 1});

// highlight
context.fillRect(face.x, face.y, face.width, face.height);

// mask
context.drawImage(mask, face.x, face.y, face.width, face.height);<commit_msg>JS Updated<commit_after>CamKit = function()
{
    this.selector = '';

    this.video = true;
    this.audio = true;

    this.width = 0;
    this.height = 0;

    this.init = function() {
        var error = function(){
            console.log('Your browser does not support getUserMedia function. Please update it.');
        }

        // If the navigator supports the method
        //alert(!navigator.webkitGetUserMedia);
        if(!((navigator.getUserMedia) || (navigator.webkitGetUserMedia) || (navigator.mozGetUserMedia))){
            error();
            return false;
        }

        // Attribute missing
        if(this.selector == '') {
            console.log('Query selector is empty. Use CamKit.selector to select a DOM element.')
            return false;
        }

        var selector = this.selector;
        var width = this.width;
        var heigth = this.height;

        var attr = {video: this.video, audio: this.audio}

        if(navigator.getUserMedia){
            navigator.getUserMedia(attr, function(midia_local) {
                video = document.querySelector(this.selector);
                video.src = window.webkitURL.createObjectURL(midia_local);
                video.width = width;
                video.height = height;
            }, error());
        } else if(navigator.webkitGetUserMedia) {
            navigator.webkitGetUserMedia(attr, function(midia_local) {
                video = document.querySelector(selector);
                video.src = window.webkitURL.createObjectURL(midia_local);
                video.width = width;
                video.height = height;
            }, error());
        } else if(navigator.mozGetUserMedia) {
            navigator.mozGetUserMedia(attr, function(midia_local) {
                video = document.querySelector(this.selector);
                video.src = window.webkitURL.createObjectURL(midia_local);
                video.width = width;
                video.height = height;
            }, error());
        }

        return true;
    }

}<|endoftext|>


<commit_before>"use strict";

/*
 * Simple RestFace server
 *
 * Dynamically loads & runs front & back-end handlers, and dispatches between
 * them.
 */

var fs = require('fs');
//var prfun = require('prfun');
var Verbs = require('./Verbs');
var http = require('http');
var url = require('url');
var RouteSwitch = require('routeswitch');
var Busboy = require('busboy');

    // TODO: use bunyan or the Parsoid logger backend!
var log = function (level) {
    var msg = JSON.stringify(Array.prototype.slice.call(arguments), null, 2);
    if (/^error/.test(level)) {
        console.error(msg);
    } else {
        console.log(msg);
    }
};
var app = {};

// Optimized URL parsing
var qs = require('querystring');
// Should make it into 0.12, see https://github.com/joyent/node/pull/7878
var SIMPLE_PATH = /^(\/(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/;
function parseURL (uri) {
    // Fast path for simple path uris
    var fastMatch = SIMPLE_PATH.exec(uri);
    if (fastMatch) {
        return {
            protocol: null,
            slashes: null,
            auth: null,
            host: null,
            port: null,
            hostname: null,
            hash: null,
            search: fastMatch[2] || '',
            pathname: fastMatch[1],
            path: fastMatch[1],
            query: fastMatch[2] && qs.parse(fastMatch[2]) || {},
            href: uri
        };
    } else {
        return url.parse(uri, true);
    }
}

// Parse a POST request into request.body with BusBoy
// Drops file uploads on the floor without creating temporary files
//
// @param {request} HTTP request
// @returns {Promise<>}
function parsePOST(req) {
    if (req.method === 'PUT') {
        return new Promise(function(resolve) {
            var chunks = [];
            req.on('data', function(chunk) {
                chunks.push(chunk);
            });

            req.on('end', function() {
                req.body = Buffer.concat(chunks);
                resolve();
            });
        });
    } else if (req.method !== 'POST') {
        return Promise.resolve();
    } else {
        var headers = req.headers;
        if (!headers['content-type']) {
            headers = {
                'content-type': 'application/binary'
            };
        }

        return new Promise(function(resolve) {
            // Parse POST data
            var bboy = new Busboy({
                headers: headers,
                // Increase the form field size limit from the 1M default.
                limits: { fieldSize: 15 * 1024 * 1024 }
            });
            req.body = req.body || {};
            bboy.on('field', function (field, val) {
                req.body[field] = val;
            });
            bboy.on('finish', function () {
                resolve();
            });
            req.pipe(bboy);
        });
    }
}

// Handle a single request
function handleRequest (req, resp) {

    // Start off by parsing any POST data with BusBoy
    return parsePOST(req)

    // Then process the request
    .then(function() {
        // Create the virtual HTTP service
        var verbs = new Verbs(null, {}, app.frontendRouter, app.backendRouter);

        // Create a new, clean request object
        var urlData = parseURL(req.url);
        var newReq = {
            uri: urlData.pathname,
            query: urlData.query,
            method: req.method,
            headers: req.headers,
            body: req.body
        };
        return verbs.request(newReq);
    })

    // And finally handle the response
    .then(function(response) {
        //console.log('resp', response);
        var body = response.body;
        if (body) {
            // Convert to a buffer
            if (typeof body === 'object') {
                body = new Buffer(JSON.stringify(body));
            } else if (body.constructor !== Buffer) {
                body = new Buffer(body);
            }
            if (!response.headers) {
                response.headers = {};
            }
            response.headers.connection = 'close';
            response.headers['content-length'] = body.length;
            resp.writeHead(response.status || 500, '', response.headers);
            resp.end(body);
        } else {
            resp.writeHead(response.status || 500, '', response.headers);
            resp.end();
        }

    })
    .catch (function(e) {
        log('error/request', e, e.stack);
        // XXX: proper error reporting
        resp.writeHead(500, "Internal error");
        resp.end(e);
    });
}

// Main app setup
function main() {
    // Load handlers & set up routers
    return Promise.all([
            RouteSwitch.fromHandlers('./handlers/frontend', log),
            RouteSwitch.fromHandlers('./handlers/backend', log)
            ])
    .then(function(routers) {
        app.frontendRouter = routers[0];
        app.backendRouter = routers[1];
        var server = http.createServer(handleRequest);
        server.listen(8888);
        log('notice', 'listening on port 8888');
    })
    .catch(function(e) {
        log('error', e, e.stack);
    });
}

if (module.parent === null) {
    main();
} else {
    module.exports = main;
}
<commit_msg>Don't JSON.stringify buffers<commit_after>"use strict";

/*
 * Simple RestFace server
 *
 * Dynamically loads & runs front & back-end handlers, and dispatches between
 * them.
 */

var fs = require('fs');
//var prfun = require('prfun');
var Verbs = require('./Verbs');
var http = require('http');
var url = require('url');
var RouteSwitch = require('routeswitch');
var Busboy = require('busboy');

    // TODO: use bunyan or the Parsoid logger backend!
var log = function (level) {
    var msg = JSON.stringify(Array.prototype.slice.call(arguments), null, 2);
    if (/^error/.test(level)) {
        console.error(msg);
    } else {
        console.log(msg);
    }
};
var app = {};

// Optimized URL parsing
var qs = require('querystring');
// Should make it into 0.12, see https://github.com/joyent/node/pull/7878
var SIMPLE_PATH = /^(\/(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/;
function parseURL (uri) {
    // Fast path for simple path uris
    var fastMatch = SIMPLE_PATH.exec(uri);
    if (fastMatch) {
        return {
            protocol: null,
            slashes: null,
            auth: null,
            host: null,
            port: null,
            hostname: null,
            hash: null,
            search: fastMatch[2] || '',
            pathname: fastMatch[1],
            path: fastMatch[1],
            query: fastMatch[2] && qs.parse(fastMatch[2]) || {},
            href: uri
        };
    } else {
        return url.parse(uri, true);
    }
}

// Parse a POST request into request.body with BusBoy
// Drops file uploads on the floor without creating temporary files
//
// @param {request} HTTP request
// @returns {Promise<>}
function parsePOST(req) {
    if (req.method === 'PUT') {
        return new Promise(function(resolve) {
            var chunks = [];
            req.on('data', function(chunk) {
                chunks.push(chunk);
            });

            req.on('end', function() {
                req.body = Buffer.concat(chunks);
                resolve();
            });
        });
    } else if (req.method !== 'POST') {
        return Promise.resolve();
    } else {
        var headers = req.headers;
        if (!headers['content-type']) {
            headers = {
                'content-type': 'application/binary'
            };
        }

        return new Promise(function(resolve) {
            // Parse POST data
            var bboy = new Busboy({
                headers: headers,
                // Increase the form field size limit from the 1M default.
                limits: { fieldSize: 15 * 1024 * 1024 }
            });
            req.body = req.body || {};
            bboy.on('field', function (field, val) {
                req.body[field] = val;
            });
            bboy.on('finish', function () {
                resolve();
            });
            req.pipe(bboy);
        });
    }
}

// Handle a single request
function handleRequest (req, resp) {

    // Start off by parsing any POST data with BusBoy
    return parsePOST(req)

    // Then process the request
    .then(function() {
        // Create the virtual HTTP service
        var verbs = new Verbs(null, {}, app.frontendRouter, app.backendRouter);

        // Create a new, clean request object
        var urlData = parseURL(req.url);
        var newReq = {
            uri: urlData.pathname,
            query: urlData.query,
            method: req.method,
            headers: req.headers,
            body: req.body
        };
        return verbs.request(newReq);
    })

    // And finally handle the response
    .then(function(response) {
        //console.log('resp', response);
        var body = response.body;
        if (body) {
            // Convert to a buffer
            if (!Buffer.isBuffer(body)) {
                if (typeof body === 'object') {
                    body = new Buffer(JSON.stringify(body));
                } else  {
                    body = new Buffer(body);
                }
            }
            if (!response.headers) {
                response.headers = {};
            }
            response.headers.connection = 'close';
            response.headers['content-length'] = body.length;
            resp.writeHead(response.status || 500, '', response.headers);
            resp.end(body);
        } else {
            resp.writeHead(response.status || 500, '', response.headers);
            resp.end();
        }

    })
    .catch (function(e) {
        log('error/request', e, e.stack);
        // XXX: proper error reporting
        resp.writeHead(500, "Internal error");
        resp.end(e);
    });
}

// Main app setup
function main() {
    // Load handlers & set up routers
    return Promise.all([
            RouteSwitch.fromHandlers('./handlers/frontend', log),
            RouteSwitch.fromHandlers('./handlers/backend', log)
            ])
    .then(function(routers) {
        app.frontendRouter = routers[0];
        app.backendRouter = routers[1];
        var server = http.createServer(handleRequest);
        server.listen(8888);
        log('notice', 'listening on port 8888');
    })
    .catch(function(e) {
        log('error', e, e.stack);
    });
}

if (module.parent === null) {
    main();
} else {
    module.exports = main;
}
<|endoftext|>


<commit_before>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log(studid);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

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

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<commit_msg>inactief zetten van link<commit_after>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(studid, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log("studid: " + id);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

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

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>'use strict';

function canvas_draw(){
    if(core_menu_open){
        return;
    }

    canvas_buffer.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );

    draw_logic();

    canvas_canvas.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );
    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    canvas_draw();
    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
}

// Required args: vertices
// Optional args: properties, style, type, x, y
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_style,
        'type': 'lineTo',
        'x': 0,
        'y': 0,
      },
    });

    canvas_buffer.save();
    canvas_buffer.translate(
      args['x'],
      args['y']
    );

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'],
          args['vertices'][vertex]['y'],
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    for(var property in args['properties']){
        canvas_buffer[property] = core_handle_defaults({
          'default': canvas_buffer,
          'var': args['properties'][property],
        });
    }

    canvas_buffer[args['style']]();

    canvas_buffer.restore();
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['stops']){
        gradient.addColorStop(
          args['stops'][step]['offset'] || 0,
          args['stops'][step]['color'] || '#000'
        );
    }
    return gradient;
}

function canvas_init(){
    var properties = '';
    if(!canvas_oncontextmenu){
        properties = ' oncontextmenu="return false" ';
    }

    document.body.appendChild(core_html({
      'properties': {
        'id': 'wrap',
        'innerHTML': '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>',
      },
    }));

    canvas_buffer = document.getElementById('buffer').getContext('2d');
    canvas_canvas = document.getElementById('canvas').getContext('2d');

    canvas_resize();
    canvas_setmode();
}

function canvas_logicloop(){
    if(core_menu_open){
        return;
    }

    logic();
}

function canvas_resize(){
    canvas_height = window.innerHeight;
    document.getElementById('buffer').height = canvas_height;
    document.getElementById('canvas').height = canvas_height;
    canvas_y = canvas_height / 2;

    canvas_width = window.innerWidth;
    document.getElementById('buffer').width = canvas_width;
    document.getElementById('canvas').width = canvas_width;
    canvas_x = canvas_width / 2;

    canvas_buffer.font = canvas_fonts['medium'];

    core_call({
      'todo': 'resize_logic',
    });
}

// Optional args: mode, newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'mode': 0,
        'newgame': false,
      },
    });

    core_storage_save();

    window.cancelAnimationFrame(canvas_animationFrame);
    window.clearInterval(canvas_interval);

    canvas_resize();

    core_mode = args['mode'];

    core_call({
      'args': core_mode,
      'todo': 'load_data',
    });

    if(args['newgame']){
        core_escape();
    }

    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        canvas_interval = window.setInterval(
          canvas_logicloop,
          core_storage_data['frame-ms']
        );
    }
}

var canvas_animationFrame = 0;
var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_height = 0;
var canvas_interval = 0;
var canvas_oncontextmenu = true;
var canvas_style = 'fill';
var canvas_width = 0;
var canvas_x = 0;
var canvas_y = 0;

window.onresize = canvas_resize;
<commit_msg>made canvas_draw_path() translate optional<commit_after>'use strict';

function canvas_draw(){
    if(core_menu_open){
        return;
    }

    canvas_buffer.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );

    draw_logic();

    canvas_canvas.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );
    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    canvas_draw();
    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
}

// Required args: vertices
// Optional args: properties, style, type, x, y
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_style,
        'translate': false,
        'type': 'lineTo',
        'x': 0,
        'y': 0,
      },
    });

    if(args['translate']){
        canvas_buffer.save();
        canvas_buffer.translate(
          args['x'],
          args['y']
        );
    }

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'],
          args['vertices'][vertex]['y'],
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    for(var property in args['properties']){
        canvas_buffer[property] = core_handle_defaults({
          'default': canvas_buffer,
          'var': args['properties'][property],
        });
    }

    canvas_buffer[args['style']]();

    if(args['translate']){
        canvas_buffer.restore();
    }
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['stops']){
        gradient.addColorStop(
          args['stops'][step]['offset'] || 0,
          args['stops'][step]['color'] || '#000'
        );
    }
    return gradient;
}

function canvas_init(){
    var properties = '';
    if(!canvas_oncontextmenu){
        properties = ' oncontextmenu="return false" ';
    }

    document.body.appendChild(core_html({
      'properties': {
        'id': 'wrap',
        'innerHTML': '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>',
      },
    }));

    canvas_buffer = document.getElementById('buffer').getContext('2d');
    canvas_canvas = document.getElementById('canvas').getContext('2d');

    canvas_resize();
    canvas_setmode();
}

function canvas_logicloop(){
    if(core_menu_open){
        return;
    }

    logic();
}

function canvas_resize(){
    canvas_height = window.innerHeight;
    document.getElementById('buffer').height = canvas_height;
    document.getElementById('canvas').height = canvas_height;
    canvas_y = canvas_height / 2;

    canvas_width = window.innerWidth;
    document.getElementById('buffer').width = canvas_width;
    document.getElementById('canvas').width = canvas_width;
    canvas_x = canvas_width / 2;

    canvas_buffer.font = canvas_fonts['medium'];

    core_call({
      'todo': 'resize_logic',
    });
}

// Optional args: mode, newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'mode': 0,
        'newgame': false,
      },
    });

    core_storage_save();

    window.cancelAnimationFrame(canvas_animationFrame);
    window.clearInterval(canvas_interval);

    canvas_resize();

    core_mode = args['mode'];

    core_call({
      'args': core_mode,
      'todo': 'load_data',
    });

    if(args['newgame']){
        core_escape();
    }

    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        canvas_interval = window.setInterval(
          canvas_logicloop,
          core_storage_data['frame-ms']
        );
    }
}

var canvas_animationFrame = 0;
var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_height = 0;
var canvas_interval = 0;
var canvas_oncontextmenu = true;
var canvas_style = 'fill';
var canvas_width = 0;
var canvas_x = 0;
var canvas_y = 0;

window.onresize = canvas_resize;
<|endoftext|>


<commit_before>var MjsController = function(mjs, notification, item, auth, $rootScope, $scope,
                             $state, $stateParams, $http, apiClient) {
	var self = this;
	this.notification = notification;
	this.mjs = mjs;
	this.auth = auth;
	this.item = item;
	this.selected_branch = 0;
	this.mjs_items = [];
	this.$scope = $scope;
	this.branch_edit_status = {
            1: false,
            2: false,
            3: false,
            4: false,
    };
    this.in_rename_mode = false;
	this.rmdialog_status = false;
	this.in_edit_mode = false;

	Object.defineProperty(this, 'signedin', {
		get: function() {
			return auth.is_signedin();
		}
	});

  if ($stateParams.user_id) {
    // another user's story - story.html
    $http.get(apiClient.urls.story+'/'+$stateParams.user_id)
         .then(function(res) {
           var items_ids = []
           self.user = res.data;
           res.data.story_items.forEach(function(i) {
             items_ids.push(i.id)
           });
           self.load(items_ids);
         });
  }
  else {
    // logged in user story - mjs.html
    if(!auth.user) {
      $rootScope.$on('loggedin', function(event, user) {
        var items_ids = [];
        self.user = user;
        user.story_items.forEach(function (i) {
          items_ids.push(i.id)
        })
        self.load(items_ids);
        self.public_url = $state.href('story',{user_id: user.hash},{absolute: true});
      });
    } else {
      var items_ids = mjs.get_items_ids();
      self.user = auth.user;
      self.public_url = $state.href('story',{user_id: self.user.hash},{absolute: true});
      if (items_ids.length > 0) {
        self.load(items_ids);
      }
    }
  };

	$rootScope.$on('item-removed', function(events, item_slug) {
		var mjs_items = [];
		for (var i in self.mjs_items) {
			if(self.mjs_items[i].Slug.En != item_slug) {
				mjs_items.push(self.mjs_items[i]);
			}
		}
		self.mjs_items = mjs_items;
	});
};

MjsController.prototype = {
	init: function() {
		var self = this;
		self.load(this.mjs.get_items_ids());
	},

	load: function(items_ids) {
		var self = this;

		this.mjs_items = [];
		this.notification.loading(true);

		this.item.get_items(items_ids).then(function (items) {
        var counters = [0,0,0,0]
        items.forEach(function (item_data) {
          var item_string = self.item.get_key(item_data);
          self.user.story_items.every(function(item) {
              if (item_string == item.id) {
                  item_data.in_branch = item.in_branch.slice();
                  return false;
              }
              return true;
          });
          item_data.in_branch.forEach(function(in_branch, i) {
            if (in_branch)
              counters[i] += 1;
          });
        });
				self.mjs_items = items;
        self.items_counters = counters;

		}).finally(function() { self.notification.loading(false); });
	},

	stopPropagation: function($event) {
		$event.stopPropagation();
	},

	rename_branch: function(branch_num, new_name) {
		this.mjs.rename_branch(branch_num, new_name);
	},

	rename_user: function(new_name) {
		this.mjs.rename_user(new_name);
	},

	toggle_branch_edit: function(branch_num)  {
		if (this.branch_edit_status[branch_num]) {
			this.branch_edit_status[branch_num] = false;
			this.in_edit_mode = false;
		}
		else {
			for(var branch in this.branch_edit_status) {
				if (this.branch_edit_status[branch] && branch != branch_num) {
					this.branch_edit_status[branch] = false;
					break;
				}
			}
			this.branch_edit_status[branch_num] = true;
			this.in_edit_mode = true;
		}
	},

	navigate_to_branch: function(branch_num) {
		this.selected_branch = branch_num;
	},

	toggle_branch_rmdialog: function()  {
		this.rmdialog_status = !(this.rmdialog_status);

	},
};

angular.module('main').controller('MjsController', ['mjs', 'notification',
								  'item', 'auth', '$rootScope', '$scope', '$state',
                  '$stateParams', '$http', 'apiClient',
                  MjsController]);
<commit_msg>missing story link at public story page - #167<commit_after>var MjsController = function(mjs, notification, item, auth, $rootScope, $scope,
                             $state, $stateParams, $http, apiClient) {
	var self = this;
	this.notification = notification;
	this.mjs = mjs;
	this.auth = auth;
	this.item = item;
	this.selected_branch = 0;
	this.mjs_items = [];
	this.$scope = $scope;
	this.branch_edit_status = {
            1: false,
            2: false,
            3: false,
            4: false,
    };
    this.in_rename_mode = false;
	this.rmdialog_status = false;
	this.in_edit_mode = false;

	Object.defineProperty(this, 'signedin', {
		get: function() {
			return auth.is_signedin();
		}
	});

  if ($stateParams.user_id) {
    // another user's story - story.html
	self.public_url = $state.href('story',{user_id: $stateParams.user_id},
								  {absolute: true});
    $http.get(apiClient.urls.story+'/'+$stateParams.user_id)
         .then(function(res) {
           var items_ids = []
           self.user = res.data;
           res.data.story_items.forEach(function(i) {
             items_ids.push(i.id)
           });
           self.load(items_ids);
         });
  }
  else {
    // logged in user story - mjs.html
    if(!auth.user) {
      $rootScope.$on('loggedin', function(event, user) {
        var items_ids = [];
        self.user = user;
        user.story_items.forEach(function (i) {
          items_ids.push(i.id)
        })
        self.load(items_ids);
        self.public_url = $state.href('story',{user_id: user.hash},{absolute: true});
      });
    } else {
      var items_ids = mjs.get_items_ids();
      self.user = auth.user;
      self.public_url = $state.href('story',{user_id: self.user.hash},{absolute: true});
      if (items_ids.length > 0) {
        self.load(items_ids);
      }
    }
  };

	$rootScope.$on('item-removed', function(events, item_slug) {
		var mjs_items = [];
		for (var i in self.mjs_items) {
			if(self.mjs_items[i].Slug.En != item_slug) {
				mjs_items.push(self.mjs_items[i]);
			}
		}
		self.mjs_items = mjs_items;
	});
};

MjsController.prototype = {
	init: function() {
		var self = this;
		self.load(this.mjs.get_items_ids());
	},

	load: function(items_ids) {
		var self = this;

		this.mjs_items = [];
		this.notification.loading(true);

		this.item.get_items(items_ids).then(function (items) {
        var counters = [0,0,0,0]
        items.forEach(function (item_data) {
          var item_string = self.item.get_key(item_data);
          self.user.story_items.every(function(item) {
              if (item_string == item.id) {
                  item_data.in_branch = item.in_branch.slice();
                  return false;
              }
              return true;
          });
          item_data.in_branch.forEach(function(in_branch, i) {
            if (in_branch)
              counters[i] += 1;
          });
        });
				self.mjs_items = items;
        self.items_counters = counters;

		}).finally(function() { self.notification.loading(false); });
	},

	stopPropagation: function($event) {
		$event.stopPropagation();
	},

	rename_branch: function(branch_num, new_name) {
		this.mjs.rename_branch(branch_num, new_name);
	},

	rename_user: function(new_name) {
		this.mjs.rename_user(new_name);
	},

	toggle_branch_edit: function(branch_num)  {
		if (this.branch_edit_status[branch_num]) {
			this.branch_edit_status[branch_num] = false;
			this.in_edit_mode = false;
		}
		else {
			for(var branch in this.branch_edit_status) {
				if (this.branch_edit_status[branch] && branch != branch_num) {
					this.branch_edit_status[branch] = false;
					break;
				}
			}
			this.branch_edit_status[branch_num] = true;
			this.in_edit_mode = true;
		}
	},

	navigate_to_branch: function(branch_num) {
		this.selected_branch = branch_num;
	},

	toggle_branch_rmdialog: function()  {
		this.rmdialog_status = !(this.rmdialog_status);

	},
};

angular.module('main').controller('MjsController', ['mjs', 'notification',
								  'item', 'auth', '$rootScope', '$scope', '$state',
                  '$stateParams', '$http', 'apiClient',
                  MjsController]);
<|endoftext|>


<commit_before>
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Candidatura');
    data.addColumn('number', 'Porcentaje de votos');
    for ( var c in resultados ) {
        data.addRow([c, parseFloat(resultados[c]['Total'])]);
    }

    // Set chart options
    var options = {'title':'Resultados elecciones rectorado',
                   'width':'95%',
                   'is3D' : true,
                   'fontSize' : 36,
                   'height':400,
                   'legend': {'position':'bottom'}};

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('total'));
    chart.draw(data, options);

    // Create the data table.
    var sectores = new google.visualization.DataTable();
    sectores.addColumn('string', 'Sector - %');
    var columnas = new Object;
    for ( var c in resultados ) {
	sectores.addColumn('number', '% '+c);
	for ( var s in resultados[c]['Sector'] ) {
	    columnas[resultados[c]['Sector'][s]["Sector"]] = [];
        }
    }
    console.log( columnas );
    for ( var c in resultados ) {
        for ( var s in resultados[c]['Sector'] ) {
	    columnas[resultados[c]['Sector'][s]["Sector"]].push(parseFloat(resultados[c]['Sector'][s]['Resultado']));
	}
    }

    for (var c in columnas ) {
	console.log("Columna " + c);
	sectores.addRow([c,columnas[c][0],columnas[c][1]]);
    }

    // Set chart options
    options = {'title':'Resultados elecciones rectorado - Sectores',
               'width':'95%',
               'fontSize' : 24,
               'height':500,
               'legend': {'position':'bottom'} };

    // Instantiate and draw our chart, passing in some options.
    var chart_sectores = new google.visualization.BarChart(document.getElementById('sectores'));
    chart_sectores.draw(sectores, options);
}
<commit_msg>Con resize<commit_after>
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Candidatura');
    data.addColumn('number', 'Porcentaje de votos');
    for ( var c in resultados ) {
        data.addRow([c, parseFloat(resultados[c]['Total'])]);
    }

    // Set chart options
    var options = {'title':'Resultados elecciones rectorado',
                   'width':'95%',
                   'is3D' : true,
                   'fontSize' : 36,
                   'height':400,
                   'legend': {'position':'bottom'}};

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('total'));
    chart.draw(data, options);

    // Create the data table.
    var sectores = new google.visualization.DataTable();
    sectores.addColumn('string', 'Sector - %');
    var columnas = new Object;
    for ( var c in resultados ) {
	sectores.addColumn('number', '% '+c);
	for ( var s in resultados[c]['Sector'] ) {
	    columnas[resultados[c]['Sector'][s]["Sector"]] = [];
        }
    }
    console.log( columnas );
    for ( var c in resultados ) {
        for ( var s in resultados[c]['Sector'] ) {
	    columnas[resultados[c]['Sector'][s]["Sector"]].push(parseFloat(resultados[c]['Sector'][s]['Resultado']));
	}
    }

    for (var c in columnas ) {
	console.log("Columna " + c);
	sectores.addRow([c,columnas[c][0],columnas[c][1]]);
    }

    // Set chart options
    options = {'title':'Resultados elecciones rectorado - Sectores',
               'width':'95%',
               'fontSize' : 24,
               'height':500,
               'legend': {'position':'bottom'} };

    // Instantiate and draw our chart, passing in some options.
    var chart_sectores = new google.visualization.BarChart(document.getElementById('sectores'));
    chart_sectores.draw(sectores, options);
}

window.onload = drawChart();
window.onresize = drawChart;
<|endoftext|>


<commit_before>var fbPerson = new Firebase('https://trivia-crossroads.firebaseio.com/Person');
var profileList = [];
var dayDrop = document.getElementById('day');
var specialtyDrop = document.getElementById('specialty');
var locationDrop = document.getElementById('locations');
var toggle = document.getElementById('toggle');

function generateTable(dataArray){
  var table = document.getElementById('profileDisplay');
  var tbody = document.createElement('tbody');
  for(var i = 0; i < dataArray.length; i++){
    var tr = document.createElement('tr');

    for(var j in dataArray[i]){
      var td = document.createElement('td');
      td.textContent = dataArray[i][j];
      tr.appendChild(td);
    }
  tbody.appendChild(tr);
  }
  table.appendChild(tbody);
  table.removeChild(tbody.previousSibling);
}

function sortDay(e){
  var pickedDay = dayDrop.options[dayDrop.selectedIndex].text;
  if (pickedDay == "--"){
    sortArray = profileList;
  } else {
    sortArray = profileList.filter(function av(v){return v.day === pickedDay;});
  }
  generateTable(sortArray);
}

function sortSpecialty(e){
  var pickedSpecialty = specialtyDrop.options[specialtyDrop.selectedIndex].text;
  if (pickedSpecialty === 'Sorcery, Phrenology, and Chiromancy') {
    pickedSpecialty = 'Sorcery';
  }
  if (pickedSpecialty == "--"){
    sortArray = profileList;
  } else {
    sortArray = profileList.filter(function av(v){return v.specialty === pickedSpecialty;});
  }
  generateTable(sortArray);
}

function sortLocation(e){
  var pickedLocation = locationDrop.options[locationDrop.selectedIndex].text;
  if (pickedLocation == "--"){
    sortArray = profileList;
  } else {
    sortArray = profileList.filter(function av(v){return v.location === pickedLocation;});
  }
  generateTable(sortArray);
}

function storagePull(){
  fbPerson.once("value", function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      profileList.push(JSON.parse(childSnapshot.val()));
    });
    generateTable(profileList);
    var sortArray = [];
    dayDrop.addEventListener('change', sortDay);
    specialtyDrop.addEventListener('change', sortSpecialty);
    locationDrop.addEventListener('change', sortLocation);
  });
}

function togglePeople (event){
  if (event.target.id == 'dayButton') {
   dayDrop.removeAttribute('class', 'hidden');
    specialtyDrop.setAttribute('class', 'hidden');
    locationDrop.setAttribute('class', 'hidden');
  } else if (event.target.id == 'specialtyButton') {
  specialtyDrop.removeAttribute('class', 'hidden');
    dayDrop.setAttribute('class', 'hidden');
    locationDrop.setAttribute('class', 'hidden');
  } else if (event.target.id == 'locationButton') {
  locationDrop.removeAttribute('class', 'hidden');
    dayDrop.setAttribute('class', 'hidden');
    specialtyDrop.setAttribute('class', 'hidden');
  }

}

storagePull();
toggle.addEventListener('click', togglePeople);

<commit_msg>moved all the functions into an object<commit_after>var fbPerson = new Firebase('https://trivia-crossroads.firebaseio.com/Person');
var profileList = [];
var dayDrop = document.getElementById('day');
var specialtyDrop = document.getElementById('specialty');
var locationDrop = document.getElementById('locations');
var toggle = document.getElementById('toggle');

var peopleTable = {
   generateTable: function(dataArray){
    var table = document.getElementById('profileDisplay');
    var tbody = document.createElement('tbody');
    for(var i = 0; i < dataArray.length; i++){
      var tr = document.createElement('tr');

      for(var j in dataArray[i]){
        var td = document.createElement('td');
        td.textContent = dataArray[i][j];
        tr.appendChild(td);
      }
    tbody.appendChild(tr);
    }
    table.appendChild(tbody);
    table.removeChild(tbody.previousSibling);
  },

   sortDay: function(e){
    var pickedDay = dayDrop.options[dayDrop.selectedIndex].text;
    if (pickedDay == "--"){
      sortArray = profileList;
    } else {
      sortArray = profileList.filter(function av(v){return v.day === pickedDay;});
    }
    peopleTable.generateTable(sortArray);
  },

   sortSpecialty: function(e){
    var pickedSpecialty = specialtyDrop.options[specialtyDrop.selectedIndex].text;
    if (pickedSpecialty === 'Sorcery, Phrenology, and Chiromancy') {
      pickedSpecialty = 'Sorcery';
    }
    if (pickedSpecialty == "--"){
      sortArray = profileList;
    } else {
      sortArray = profileList.filter(function av(v){return v.specialty === pickedSpecialty;});
    }
    peopleTable.generateTable(sortArray);
  },

   sortLocation: function(e){
    var pickedLocation = locationDrop.options[locationDrop.selectedIndex].text;
    if (pickedLocation == "--"){
      sortArray = profileList;
    } else {
      sortArray = profileList.filter(function av(v){return v.location === pickedLocation;});
    }
    peopleTable.generateTable(sortArray);
  },

   storagePull: function(){
    fbPerson.once("value", function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        profileList.push(JSON.parse(childSnapshot.val()));
      });
      peopleTable.generateTable(profileList);
      var sortArray = [];
      dayDrop.addEventListener('change', peopleTable.sortDay);
      specialtyDrop.addEventListener('change', peopleTable.sortSpecialty);
      locationDrop.addEventListener('change', peopleTable.sortLocation);
    });
  },

   togglePeople: function(event){
    if (event.target.id == 'dayButton') {
     dayDrop.removeAttribute('class', 'hidden');
      specialtyDrop.setAttribute('class', 'hidden');
      locationDrop.setAttribute('class', 'hidden');
    } else if (event.target.id == 'specialtyButton') {
    specialtyDrop.removeAttribute('class', 'hidden');
      dayDrop.setAttribute('class', 'hidden');
      locationDrop.setAttribute('class', 'hidden');
    } else if (event.target.id == 'locationButton') {
    locationDrop.removeAttribute('class', 'hidden');
      dayDrop.setAttribute('class', 'hidden');
      specialtyDrop.setAttribute('class', 'hidden');
    }

  }
}

peopleTable.storagePull();
toggle.addEventListener('click', peopleTable.togglePeople);

<|endoftext|>