<commit_before>'use strict';
var Alexa = require('alexa-sdk');

var APP_ID = "amzn1.ask.skill.bd898084-7a07-4fde-ba4b-74b6cdad08b4";
var SKILL_NAME = 'Prime Numbers';

exports.handler = function (event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

const MAX_N = 10000; // one million
const MAX_PRIME = 104729; // one millionth prime number
const SQRT_MAX_PRIME = 324; // sqrt(one millionth prime number) + 1

var nthPrime = function (n) {
    var m = 0, mark = [];

    mark[1] = true;

    for (var k = 0; k <= SQRT_MAX_PRIME; k = m) {
        for (m = k + 1; m < MAX_PRIME; m++) {
            if (!mark[m]) break;
        }
        for (var i = m * 2; i < MAX_PRIME; i += m) {
            mark[i] = true;
        }
    }

    for (var k = 0, i = 1; i < MAX_PRIME; i++) {
        if (!mark[i]) {
            if (n-- <= 1) {
                return i;
                break;
            }
        }
    }

    return 0; // some kind of error occurred
};

var isPrime = function (number) {
    if (number < 2) return false;
    if (number % 2 == 0) return (number == 2);
    var root = Math.sqrt(number);
    for (var i = 3; i <= root; i += 2) {
        if (number % i == 0) return false;
    }
    return true;
};

var addNth = function (number) {
    var onesPlace = number % 10;
    if (onesPlace == 1) return number + 'st';
    if (onesPlace == 2) return number + 'nd';
    if (onesPlace == 3) return number + 'rd';
    return number + 'th';
};

const ITH_TO_NUM = {
    "first": 1,
    "second": 2,
    "third": 3,
    "fourth": 4,
    "fifth": 5,
    "sixth": 6,
    "seventh": 7,
    "eighth": 8,
    "ninth": 9,
    "tenth": 10,
    "eleventh": 11,
    "twelfth": 12,
    "thirteenth": 13,
    "fourteenth": 14,
    "fifteenth": 15,
    "sixteenth": 16,
    "seventeenth": 17,
    "eighteenth": 18,
    "nineteenth": 19,
    "ith": 0,
    "1st": 1,
    "2nd": 2,
    "3rd": 3,
    "4th": 4,
    "5th": 5,
    "6th": 6,
    "7th": 7,
    "8th": 8,
    "9th": 9,
    "10th": 10,
    "11th": 11,
    "12th": 12,
    "13th": 13,
    "14th": 14,
    "15th": 15,
    "16th": 16,
    "17th": 17,
    "18th": 18,
    "19th": 19,
    "0th": 0
};

var calcNumber = function(slot1, slot2) {
    var n1, n2;
    if (slot2 == null || slot2.value == null) {
        n2 = 0;
    } else {
        try {
            n2 = ITH_TO_NUM[slot2.value];
        } catch (e) {
            n2 = 0;
        }
    }
    try {
        n1 = parseInt(slot1.value);
        if (isNaN(n1)) n1 = 0;
    } catch (e) {
        n1 = 0;
    }
    return n1 + n2;
}

var handlers = {
    'LaunchRequest': function () {
        this.emit('AMAZON.HelpIntent');
    },
    'NthPrimeIntent': function (n) {
        var slots = this.event.request.intent.slots;
        var n = calcNumber(slots.Number_One, slots.Number_Two);
        // this.emit(':tell', '(((' + JSON.stringify(slots) + ', ' + n + ')))');

        if (n == null || n < 1) {
            this.emit('UnrecognizedError');
        } else if (n > MAX_N) {
            this.emit('TooBigError');
        } else {
            this.emit(':tell', 'The ' + addNth(n) + ' prime number is '
                + nthPrime(n) + '.');
        }
    },
    'IsPrimeIntent': function () {
        var n = this.event.request.intent.slots.Number;
        if (n == null || n.value == null) {
            this.emit('UnrecognizedError');
            return;
        }
        var nInt = parseInt(n.value);
        if (isNaN(nInt) || n.value < 1) {
            this.emit('UnrecognizedError');
        } else if (n.value > MAX_PRIME) {
            this.emit('TooBigError');
        } else {
            var prime = isPrime(nInt);
            this.emit(':tell', nInt + ' is ' + (prime ? '' : 'not ')
                + 'a prime number');
        }
        // this.emit(':tell', 'Gabe you\'re not crazy. This is working. :)');
    },
    'UnrecognizedError': function() {
        this.emit(':tell', "I'm sorry, I didn't understand the number you gave.",
            SKILL_NAME, "I've encountered an error understanding that number.");
        this.emit('AMAZON.StopIntent');
    },
    'TooBigError': function() {
        this.emit(':tell', "I'm sorry, I can't work with numbers that big.",
            SKILL_NAME, "Try smaller numbers.");
        this.emit('AMAZON.StopIntent');
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = "You can ask me for the enth prime number, you can "
            + "ask me whether a number is prime, or, you can say exit... What can I "
            + "help you with?";
        var reprompt = "What can I help you with?";
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = "You can ask how many people are in space, you can ask me to list the people in space, or, you can say exit... What can I help you with?";
        var reprompt = "What can I help you with?";
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', 'Goodbye');
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', 'Goodbye');
    }
};
<commit_msg>Fixed bug causing NaN to display occasionally<commit_after>'use strict';
var Alexa = require('alexa-sdk');

var APP_ID = "amzn1.ask.skill.bd898084-7a07-4fde-ba4b-74b6cdad08b4";
var SKILL_NAME = 'Prime Numbers';

exports.handler = function (event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    alexa.registerHandlers(handlers);
    alexa.execute();
};

const MAX_N = 10000; // one million
const MAX_PRIME = 104729; // one millionth prime number
const SQRT_MAX_PRIME = 324; // sqrt(one millionth prime number) + 1

var nthPrime = function (n) {
    var m = 0, mark = [];

    mark[1] = true;

    for (var k = 0; k <= SQRT_MAX_PRIME; k = m) {
        for (m = k + 1; m < MAX_PRIME; m++) {
            if (!mark[m]) break;
        }
        for (var i = m * 2; i < MAX_PRIME; i += m) {
            mark[i] = true;
        }
    }

    for (var k = 0, i = 1; i < MAX_PRIME; i++) {
        if (!mark[i]) {
            if (n-- <= 1) {
                return i;
                break;
            }
        }
    }

    return 0; // some kind of error occurred
};

var isPrime = function (number) {
    if (number < 2) return false;
    if (number % 2 == 0) return (number == 2);
    var root = Math.sqrt(number);
    for (var i = 3; i <= root; i += 2) {
        if (number % i == 0) return false;
    }
    return true;
};

var addNth = function (number) {
    var onesPlace = number % 10;
    if (onesPlace == 1) return number + 'st';
    if (onesPlace == 2) return number + 'nd';
    if (onesPlace == 3) return number + 'rd';
    return number + 'th';
};

const ITH_TO_NUM = {
    "first": 1,
    "second": 2,
    "third": 3,
    "fourth": 4,
    "fifth": 5,
    "sixth": 6,
    "seventh": 7,
    "eighth": 8,
    "ninth": 9,
    "tenth": 10,
    "eleventh": 11,
    "twelfth": 12,
    "thirteenth": 13,
    "fourteenth": 14,
    "fifteenth": 15,
    "sixteenth": 16,
    "seventeenth": 17,
    "eighteenth": 18,
    "nineteenth": 19
};

var calcNumber = function(slot1, slot2) {
    var n1, n2;
    if (slot2 == null || slot2.value == null) {
        n2 = 0;
    } else {
        n2 = parseInt(slot2.value);
        if (isNaN(n2)) {
            try {
                n2 = ITH_TO_NUM[slot2.value];
            } catch (e) {
                n2 = 0;
            }
        }
    }
    try {
        n1 = parseInt(slot1.value);
        if (isNaN(n1)) n1 = 0;
    } catch (e) {
        n1 = 0;
    }
    return n1 + n2;
}

var handlers = {
    'LaunchRequest': function () {
        this.emit('AMAZON.HelpIntent');
    },
    'NthPrimeIntent': function (n) {
        var slots = this.event.request.intent.slots;
        var n = calcNumber(slots.Number_One, slots.Number_Two);
        // this.emit(':tell', '(((' + JSON.stringify(slots) + ', ' + n + ')))');

        if (n == null || n < 1) {
            this.emit('UnrecognizedError');
        } else if (n > MAX_N) {
            this.emit('TooBigError');
        } else {
            this.emit(':tell', 'The ' + addNth(n) + ' prime number is '
                + nthPrime(n) + '.');
        }
    },
    'IsPrimeIntent': function () {
        var n = this.event.request.intent.slots.Number;
        if (n == null || n.value == null) {
            this.emit('UnrecognizedError');
            return;
        }
        var nInt = parseInt(n.value);
        if (isNaN(nInt) || n.value < 1) {
            this.emit('UnrecognizedError');
        } else if (n.value > MAX_PRIME) {
            this.emit('TooBigError');
        } else {
            var prime = isPrime(nInt);
            this.emit(':tell', nInt + ' is ' + (prime ? '' : 'not ')
                + 'a prime number');
        }
        // this.emit(':tell', 'Gabe you\'re not crazy. This is working. :)');
    },
    'UnrecognizedError': function() {
        this.emit(':tell', "I'm sorry, I didn't understand the number you gave.",
            SKILL_NAME, "I've encountered an error understanding that number.");
        this.emit('AMAZON.StopIntent');
    },
    'TooBigError': function() {
        this.emit(':tell', "I'm sorry, I can't work with numbers that big.",
            SKILL_NAME, "Try smaller numbers.");
        this.emit('AMAZON.StopIntent');
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = "You can ask me for the enth prime number, you can "
            + "ask me whether a number is prime, or, you can say exit... What can I "
            + "help you with?";
        var reprompt = "What can I help you with?";
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = "You can ask how many people are in space, you can ask me to list the people in space, or, you can say exit... What can I help you with?";
        var reprompt = "What can I help you with?";
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', 'Goodbye');
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', 'Goodbye');
    }
};
<|endoftext|>


<commit_before>// chat-server build for martijncasteel.com using some irc basics but not fully
// implementing the standard. Also borrowed some ideas from ircd.js

var net = require('net'),
    carrier = require('carrier'),

    User = require('./user').User,
    Users = require('./user').Users,

    Channel = require('./channel').Channel,
    Channels = require('./channel').Channels,

    Commands = require('./commands'),

    irc = require('./protocol');

function Connection(stream) {
  this.stream = stream;
  this.object = null;

  this.__defineGetter__('id', function() {
    return this.object ? this.object.id : 'Unregistered';
  });
}

function Server(){
  this.users = new Users(this);
  this.channels = new Channels(this);
  this.commands = new Commands(this);

  this.config = {
    hostname: 'macbook.local',
    network: 'Martijn Casteel IRC network',
    email: 'irc@martijncasteel.com',

    motd: 'hellow to my server!',

    version: '0.2.1',
    comments: null
  };

  this.created = Date.now();
}

Server.init = function(){
  var server = new Server();

  // TODO configuration

  server.start();

  process.on('SIGHUP', function() {
    console.log('Reloading config...');

  });

  process.on('SIGTERM', function() {
    console.log('Exiting...');
    server.close();
  });
}

Server.prototype = {
  version: '0.0.1',

  get host() { return ':' + this.config.hostname; },

  start: function() {
    var server = this;
    this.server = net.createServer(handle);

    this.server.listen({
      host: 'localhost',
      port: 3000,
    });

    console.log('listening on localhost:3000');

    function handle(stream) {
      try {

        var message = carrier.carry(stream),
            client = new Connection(stream);

        client.object = new User(server, client);
        console.log(client.object.address + ' joined');

        message.on('line', function(line) {
          server.data(client, line);
        });

        stream.on('end', function() { server.end(client); });
        stream.on('error', function() { });

      } catch (exception) {
        console.error(exception);
      }
    }
  },

  data: function(client, line) {
    var message = this.parse(line);

    if (client.object.registered === false) {
        if (['PASS', 'USER', 'NICK'].indexOf(message.command) === -1) {
          client.object.send(this.host, irc.errors.not_registered, ':You have not registered');
          return;
        }
    }

    if (!this.commands[message.command]) {
      client.object.send(this.host, irc.errors.unknown_command, message.command, ':Unknown command');
      return;
    }

    // execute command using the parsed message
    this.commands[message.command].apply(this.commands, [client.object].concat(message.args));
  },

  parse: function(data) {
    var parts = data.trim().split(/ :/),
        args = parts[0].split(' ');

    parts = [parts.shift(), parts.join(' :')];

    if (parts.length > 0) {
      args.push(parts[1]);
    }

    if (data.match(/^:/)) {
      args[1] = args.splice(0, 1, args[1]);
      args[1] = (args[1] + '').replace(/^:/, '');
    }

    return {
      command: args[0].toUpperCase(),
      args: args.slice(1)
    };
  },

  end: function(client) {
    var user = client.object;

    if (user) {
      console.log(user.address + ' left');

      if (user.stream && user.stream.end) {
        user.stream.end();
      }

      this.users.remove(user);
      user = null;
    }
  },

  normalize: function(name) {
    return name &&
           name.toLowerCase()
           .replace(/{/g, '[')
           .replace(/}/g, ']')
           .replace(/\|/g, '\\')
           .trim();
  }
}

exports.Server = Server;
<commit_msg>Continue without proxy<commit_after>// chat-server build for martijncasteel.com using some irc basics but not fully
// implementing the standard. Also borrowed some ideas from ircd.js

var net = require('net'),
    carrier = require('carrier'),

    User = require('./user').User,
    Users = require('./user').Users,

    Channel = require('./channel').Channel,
    Channels = require('./channel').Channels,

    Commands = require('./commands'),

    irc = require('./protocol');

function Connection(stream) {
  this.stream = stream;
  this.object = null;

  this.__defineGetter__('id', function() {
    return this.object ? this.object.id : 'Unregistered';
  });
}

function Server(){
  this.users = new Users(this);
  this.channels = new Channels(this);
  this.commands = new Commands(this);

  this.config = {
    hostname: 'martijncasteel.com',
    network: 'Martijn Casteel IRC network',
    email: 'irc@martijncasteel.com',

    motd: 'hellow to my server!',

    version: '0.2.1',
    comments: null
  };

  this.created = Date.now();
}

Server.init = function(){
  var server = new Server();

  // TODO configuration

  server.start();

  process.on('SIGHUP', function() {
    console.log('Reloading config...');

  });

  process.on('SIGTERM', function() {
    console.log('Exiting...');
    server.close();
  });
}

Server.prototype = {
  version: '0.0.1',

  get host() { return ':' + this.config.hostname; },

  start: function() {
    var server = this;
    this.server = net.createServer(handle);

    this.server.listen({
      host: 'martijncasteel.nl',
      port: 6667,
    });

    console.log('listening on martijncasteel.nl:6667');

    function handle(stream) {
      try {

        var message = carrier.carry(stream),
            client = new Connection(stream);

        client.object = new User(server, client);
        console.log(client.object.address + ' joined');

        message.on('line', function(line) {
          server.data(client, line);
        });

        stream.on('end', function() { server.end(client); });
        stream.on('error', function() { });

      } catch (exception) {
        console.error(exception);
      }
    }
  },

  data: function(client, line) {
    var message = this.parse(line);

    if (client.object.registered === false) {
        if (['PASS', 'USER', 'NICK'].indexOf(message.command) === -1) {
          client.object.send(this.host, irc.errors.not_registered, ':You have not registered');
          return;
        }
    }

    if (!this.commands[message.command]) {
      client.object.send(this.host, irc.errors.unknown_command, message.command, ':Unknown command');
      return;
    }

    // execute command using the parsed message
    this.commands[message.command].apply(this.commands, [client.object].concat(message.args));
  },

  parse: function(data) {
    var parts = data.trim().split(/ :/),
        args = parts[0].split(' ');

    parts = [parts.shift(), parts.join(' :')];

    if (parts.length > 0) {
      args.push(parts[1]);
    }

    if (data.match(/^:/)) {
      args[1] = args.splice(0, 1, args[1]);
      args[1] = (args[1] + '').replace(/^:/, '');
    }

    return {
      command: args[0].toUpperCase(),
      args: args.slice(1)
    };
  },

  end: function(client) {
    var user = client.object;

    if (user) {
      console.log(user.address + ' left');

      if (user.stream && user.stream.end) {
        user.stream.end();
      }

      this.users.remove(user);
      user = null;
    }
  },

  normalize: function(name) {
    return name &&
           name.toLowerCase()
           .replace(/{/g, '[')
           .replace(/}/g, ']')
           .replace(/\|/g, '\\')
           .trim();
  }
}

exports.Server = Server;
<|endoftext|>


<commit_before>var async = require("async");

var tracks = require("./tracks.js"),
    lastfm = require("./lastfm.js"),
    spotify = require("./spotify.js");

module.exports = function(data, callback) {
    data = tracks(data);

    var artists = data.filter(function(card) {
        return card.type === "artist";
    });

    async.map(artists, function(artist, callback) {
        spotify("search", {
            type: "artist",
            q: artist.name
        }, function(search) {
            if(typeof search.artists.items[0] === "object") {
                spotify("artists/" + search.artists.items[0].id + "/top-tracks", {
                    country: "GB",
                    limit: artist.trackNum
                }, function(tracks) {
                    var arr = [];

                    tracks.tracks.forEach(function(track) {
                        arr.push(track.uri);
                    });

                    callback(null, arr);
                });
            } else {
                callback({});
            }
        });
    }, function(err, data) {
        var uris = [];

        data.forEach(function(tracks) {
            tracks.forEach(function(track) {
                uris.push(track);
            });
        });

        callback(uris);
    });

};
<commit_msg>fixed limiting ability<commit_after>var async = require("async");

var tracks = require("./tracks.js"),
    lastfm = require("./lastfm.js"),
    spotify = require("./spotify.js");

module.exports = function(data, callback) {
    data = tracks(data);

    var artists = data.filter(function(card) {
        return card.type === "artist";
    });

    async.map(artists, function(artist, callback) {
        spotify("search", {
            type: "artist",
            q: artist.name
        }, function(search) {
            if(typeof search.artists.items[0] === "object") {
                spotify("artists/" + search.artists.items[0].id + "/top-tracks", {
                    country: "GB",
                    limit: 10
                }, function(tracks) {
                    var arr = [];

                    for(var i = 0; i < artist.trackNum; i++) {
                        arr.push(tracks.tracks[i].uri);
                    }

                    callback(null, arr);
                });
            } else {
                callback({});
            }
        });
    }, function(err, data) {
        var uris = [];

        data.forEach(function(tracks) {
            tracks.forEach(function(track) {
                uris.push(track);
            });
        });

        callback(uris);
    });

};
<|endoftext|>


<commit_before>export default function assertString(input) {
  const isString = (typeof input === 'string' || input instanceof String);

  if (!isString) {
    let invalidType;
    if (input === null) {
      invalidType = 'null';
    } else {
      invalidType = typeof input;
      if (invalidType === 'object' && input.constructor) {
        invalidType = input.constructor.name;
      } else {
        invalidType = `a ${invalidType}`;
      }
    }
    let message = 'This library (validator.js) validates strings only, ';
    message += `Instead it received ${invalidType}.`;
    throw new TypeError(message);
  }
}
<commit_msg>Update assertString.js<commit_after>export default function assertString(input) {
  const isString = (typeof input === 'string' || input instanceof String);

  if (!isString) {
    let invalidType;
    if (input === null) {
      invalidType = 'null';
    } else {
      invalidType = typeof input;
      if (invalidType === 'object' && input.constructor) {
        invalidType = input.constructor.name;
      } else {
        invalidType = `a ${invalidType}`;
      }
    }
    let message = 'This library (validator.js) validates strings only, ';
    message += `instead it received ${invalidType}.`;
    throw new TypeError(message);
  }
}
<|endoftext|>


<commit_before>// generated with http://jsonschema.net
// todo: look at using typson to generate this from a ts definition file: https://github.com/lbovet/typson
schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "https://github.com/britishlibrary/UniversalViewer",
    "type": "object",
    "properties": {
        "options": {
            "id": "options",
            "type": "object",
            "options": {
                "collapsed": true
            },
            "properties": {
                "theme": {
                    "id": "theme",
                    "type": "string"
                },
                "leftPanelEnabled": {
                    "id": "leftPanelEnabled",
                    "type": "boolean"
                },
                "rightPanelEnabled": {
                    "id": "rightPanelEnabled",
                    "type": "boolean"
                },
                "overrideFullScreen": {
                    "id": "overrideFullScreen",
                    "type": "boolean"
                },
                "pagingEnabled": {
                    "id": "pagingEnabled",
                    "type": "boolean"
                },
                "sectionMappings": {
                    "id": "sectionMappings",
                    "type": "object",
                    "properties": {
                        "CoverFrontOutside": {
                            "id": "CoverFrontOutside",
                            "type": "string"
                        },
                        "CoverBackOutside": {
                            "id": "CoverBackOutside",
                            "type": "string"
                        },
                        "TitlePage": {
                            "id": "TitlePage",
                            "type": "string"
                        },
                        "TableOfContents": {
                            "id": "TableOfContents",
                            "type": "string"
                        },
                        "PartOfWork": {
                            "id": "PartOfWork",
                            "type": "string"
                        }
                    }
                }
            }
        },
        "modules": {
            "id": "modules",
            "type": "object",
            "options": {
                "collapsed": true
            },
            "properties": {
                "genericDialogue": {
                    "id": "genericDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "emptyValue": {
                                    "id": "emptyValue",
                                    "type": "string"
                                },
                                "pageNotFound": {
                                    "id": "pageNotFound",
                                    "type": "string"
                                },
                                "ok": {
                                    "id": "ok",
                                    "type": "string"
                                },
                                "refresh": {
                                    "id": "refresh",
                                    "type": "string"
                                },
                                "invalidNumber": {
                                    "id": "invalidNumber",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "helpDialogue": {
                    "id": "helpDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "text": {
                                    "id": "text",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "settingsDialogue": {
                    "id": "settingsDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "pagingEnabled": {
                                    "id": "pagingEnabled",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "embedDialogue": {
                    "id": "embedDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "embedTemplate": {
                                    "id": "embedTemplate",
                                    "type": "string"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "instructions": {
                                    "id": "instructions",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "pagingHeaderPanel": {
                    "id": "pagingHeaderPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "help": {
                                    "id": "help",
                                    "type": "string"
                                },
                                "image": {
                                    "id": "image",
                                    "type": "string"
                                },
                                "page": {
                                    "id": "page",
                                    "type": "string",
                                    "required": true
                                },
                                "first": {
                                    "id": "first",
                                    "type": "string"
                                },
                                "previous": {
                                    "id": "previous",
                                    "type": "string"
                                },
                                "next": {
                                    "id": "next",
                                    "type": "string"
                                },
                                "last": {
                                    "id": "last",
                                    "type": "string"
                                },
                                "go": {
                                    "id": "go",
                                    "type": "string"
                                },
                                "of": {
                                    "id": "of",
                                    "type": "string"
                                },
                                "emptyValue": {
                                    "id": "emptyValue",
                                    "type": "string"
                                },
                                "close": {
                                    "id": "close",
                                    "type": "string"
                                }
                            },
                            "required": ["page"]
                        }
                    }
                },
                "treeViewLeftPanel": {
                    "id": "treeViewLeftPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "thumbsLoadRange": {
                                    "id": "thumbsLoadRange",
                                    "type": "integer"
                                },
                                "thumbsImageFadeInDuration": {
                                    "id": "thumbsImageFadeInDuration",
                                    "type": "integer"
                                },
                                "panelCollapsedWidth": {
                                    "id": "panelCollapsedWidth",
                                    "type": "integer"
                                },
                                "panelExpandedWidth": {
                                    "id": "panelExpandedWidth",
                                    "type": "integer"
                                },
                                "panelOpen": {
                                    "id": "panelOpen",
                                    "type": "boolean"
                                },
                                "panelAnimationDuration": {
                                    "id": "panelAnimationDuration",
                                    "type": "integer"
                                },
                                "oneColThumbWidth": {
                                    "id": "oneColThumbWidth",
                                    "type": "integer"
                                },
                                "oneColThumbHeight": {
                                    "id": "oneColThumbHeight",
                                    "type": "integer"
                                },
                                "twoColThumbWidth": {
                                    "id": "twoColThumbWidth",
                                    "type": "integer"
                                },
                                "twoColThumbHeight": {
                                    "id": "twoColThumbHeight",
                                    "type": "integer"
                                },
                                "galleryThumbWidth": {
                                    "id": "galleryThumbWidth",
                                    "type": "integer"
                                },
                                "galleryThumbHeight": {
                                    "id": "galleryThumbHeight",
                                    "type": "integer"
                                },
                                "thumbsExtraHeight": {
                                    "id": "thumbsExtraHeight",
                                    "type": "integer"
                                },
                                "elideCount": {
                                    "id": "ellideCount",
                                    "type": "integer"
                                }

                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "index": {
                                    "id": "index",
                                    "type": "string"
                                },
                                "thumbnails": {
                                    "id": "thumbnails",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "seadragonCenterPanel": {
                    "id": "seadragonCenterPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "pageGap": {
                                    "id": "pageGap",
                                    "type": "number"
                                },
                                "defaultZoomLevel": {
                                    "id": "defaultZoomLevel",
                                    "type": "integer"
                                },
                                "controlsFadeAfterInactive": {
                                    "id": "controlsFadeAfterInactive",
                                    "type": "integer"
                                },
                                "controlsFadeDelay": {
                                    "id": "controlsFadeDelay",
                                    "type": "integer"
                                },
                                "controlsFadeLength": {
                                    "id": "controlsFadeLength",
                                    "type": "integer"
                                },
                                "navigatorPosition": {
                                    "id": "navigatorPosition",
                                    "type": "string",
                                    "enum": ["BOTTOM_RIGHT", "BOTTOM_LEFT", "TOP_LEFT", "TOP_RIGHT"]
                                },
                                "trimAttributionCount": {
                                    "id": "trimAttributionCount",
                                    "type": "integer"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "previous": {
                                    "id": "previous",
                                    "type": "string"
                                },
                                "next": {
                                    "id": "next",
                                    "type": "string"
                                },
                                "zoomIn": {
                                    "id": "zoomIn",
                                    "type": "string"
                                },
                                "zoomOut": {
                                    "id": "zoomOut",
                                    "type": "string"
                                },
                                "imageUnavailable": {
                                    "id": "imageUnavailable",
                                    "type": "string"
                                },
                                "acknowledgements": {
                                    "id": "acknowledgements",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "moreInfoRightPanel": {
                    "id": "moreInfoRightPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "panelCollapsedWidth": {
                                    "id": "panelCollapsedWidth",
                                    "type": "integer"
                                },
                                "panelExpandedWidth": {
                                    "id": "panelExpandedWidth",
                                    "type": "integer"
                                },
                                "panelAnimationDuration": {
                                    "id": "panelAnimationDuration",
                                    "type": "integer"
                                },
                                "panelOpen": {
                                    "id": "panelOpen",
                                    "type": "boolean"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "holdingText": {
                                    "id": "holdingText",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "footerPanel": {
                    "id": "footerPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "embedEnabled": {
                                    "id": "embedEnabled",
                                    "type": "boolean"
                                },
                                "minimiseButtons": {
                                    "id": "minimiseButtons",
                                    "type": "boolean"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "fullScreen": {
                                    "id": "fullScreen",
                                    "type": "string"
                                },
                                "exitFullScreen": {
                                    "id": "exitFullScreen",
                                    "type": "string"
                                },
                                "embed": {
                                    "id": "embed",
                                    "type": "string"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

$(function(){

    var testBuild = getQuerystringParameter("build");
    var isLocalhost = document.location.href.indexOf('localhost') != -1;
    var editor;

    if (testBuild){
        $("body").append('<script type="text/javascript" id="embedUV" src="/build/uv-1.0.20/js/embed.js"><\/script>');
    } else {
        if (isLocalhost){
            $("body").append('<script type="text/javascript" id="embedUV" src="/src/js/embed.js"><\/script>');
        } else {
            // built version

            // remove '/examples' from paths
            $('.uv').updateAttr('data-config', '/examples/', '/');

            if ($('.uv').attr('data-uri')){
                $('.uv').updateAttr('data-uri', '/examples/', '/');
            }

            $('#config option').each(function() {
                $(this).updateAttr('value', '/examples/', '/');
            });

            $('#manifest option').each(function() {
                $(this).updateAttr('value', '/examples/', '/');
            });

            $("body").append('<script type="text/javascript" id="embedUV" src="/build/uv-1.0.20/js/embed.js"><\/script>');
        }
    }

    setTimeout(function(){
        if ($('#manifest option').length || $('#manifest optgroup').length){
            setSelectedManifest();
        }

        if ($('#config option').length || $('#config optgroup').length){
            setSelectedConfig();
        }

        createEditor();

        loadViewer();
    }, 2000);

    function loadViewer() {
        initPlayers($('.uv'));
    }

    function isIE8(){
        return (browserDetect.browser === "Explorer" && browserDetect.version === 8);
    }

    function createEditor() {

        if (isIE8() || typeof(JSONEditor) === "undefined") {
            $("#edit-config").hide();
            return;
        }

        editor = new JSONEditor(document.getElementById('editor'),{
            form_name_root: "",
            theme: 'foundation5',
            iconlib: 'fontawesome4',
            schema: schema,
            disable_edit_json: false,
            disable_properties: true,
            required_by_default: true
        });

        editor.on('change',function() {
            // Get an array of errors from the validator
            var errors = editor.validate();

            // Not valid
            if(errors.length) {
                console.log(errors);
            }
        });
    }

    $('#manifest').on('change', function(){
        buildQuerystring();
    });

    $('#config').on('change', function(){
        buildQuerystring();
    });

    function buildQuerystring() {
        var config = $('#config option:selected').val();
        var manifest = $('#manifest option:selected').val();

        // clear hash params
        document.location.hash = "";

        var qs = document.location.search.replace('?', '');
        qs = updateURIKeyValuePair(qs, "config", config);
        qs = updateURIKeyValuePair(qs, "manifest", manifest);

        // reload
        window.location.search = qs;
    }

    function setSelectedManifest(){

        var manifest = getQuerystringParameter("manifest");

        if (manifest) {
            $("#manifest").val(manifest);
        } else {
            manifest = $('#manifest option')[0].value;
        }

        $('.uv').attr('data-uri', manifest);
    }

    function setSelectedConfig(){

        var config = getQuerystringParameter("config");

        if (config) {
            $("#config").val(config);
        } else {
            config = $('#config option')[0].value;
        }

        $('.uv').attr('data-config', config);
    }

    $('#editBtn').on('click', function(e) {
        e.preventDefault();

        $('#editPnl').toggleClass('show', 'hide');
        $('#saveBtn').toggleClass('show', 'hide');
        $(this).toggleText('Edit', 'Close');

        if ($('#editPnl').hasClass('show')){

            // first get the default extension config
            // todo: figure out how to make this work for more than just seadragon extension
            $.getJSON('/build/uv-1.0.20/js/coreplayer-seadragon-extension-config.js', function(baseConfig){
                var configUrl = $('#config option:selected').val();

                $.getJSON(configUrl, function(config){
                    $.extend(true, baseConfig, config);
                    editor.setValue(baseConfig);
                });
            });
        }
    });

    $('#saveBtn').on('click', function(e) {
        e.preventDefault();

        var errors = editor.validate();

        if(errors.length) {
            console.log(errors);
            return;
        }

        // save contents of #json to session storage, set data-config attribute to 'sessionstorage' and reload viewer
        sessionStorage.setItem("uv-config", JSON.stringify(editor.getValue()));

        $('.uv').attr('data-config', 'sessionstorage');

        loadViewer();
    });

    // test overrideFullScreen option
    $(document).bind("onToggleFullScreen", function (event, isFullScreen) {
        console.log('full screen: ' + isFullScreen);
    });

    // test currentViewUri event
    $(document).bind("onCurrentViewUri", function (event, obj) {
        console.log(obj);
    });

    $(document).bind("onLoad", function (event, obj) {

    });
});<commit_msg>added settings<commit_after>// generated with http://jsonschema.net
// todo: look at using typson to generate this from a ts definition file: https://github.com/lbovet/typson
schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "https://github.com/britishlibrary/UniversalViewer",
    "type": "object",
    "properties": {
        "options": {
            "id": "options",
            "type": "object",
            "options": {
                "collapsed": true
            },
            "properties": {
                "theme": {
                    "id": "theme",
                    "type": "string"
                },
                "leftPanelEnabled": {
                    "id": "leftPanelEnabled",
                    "type": "boolean"
                },
                "rightPanelEnabled": {
                    "id": "rightPanelEnabled",
                    "type": "boolean"
                },
                "overrideFullScreen": {
                    "id": "overrideFullScreen",
                    "type": "boolean"
                },
                "pagingEnabled": {
                    "id": "pagingEnabled",
                    "type": "boolean"
                },
                "sectionMappings": {
                    "id": "sectionMappings",
                    "type": "object",
                    "properties": {
                        "CoverFrontOutside": {
                            "id": "CoverFrontOutside",
                            "type": "string"
                        },
                        "CoverBackOutside": {
                            "id": "CoverBackOutside",
                            "type": "string"
                        },
                        "TitlePage": {
                            "id": "TitlePage",
                            "type": "string"
                        },
                        "TableOfContents": {
                            "id": "TableOfContents",
                            "type": "string"
                        },
                        "PartOfWork": {
                            "id": "PartOfWork",
                            "type": "string"
                        }
                    }
                }
            }
        },
        "modules": {
            "id": "modules",
            "type": "object",
            "options": {
                "collapsed": true
            },
            "properties": {
                "genericDialogue": {
                    "id": "genericDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "emptyValue": {
                                    "id": "emptyValue",
                                    "type": "string"
                                },
                                "pageNotFound": {
                                    "id": "pageNotFound",
                                    "type": "string"
                                },
                                "ok": {
                                    "id": "ok",
                                    "type": "string"
                                },
                                "refresh": {
                                    "id": "refresh",
                                    "type": "string"
                                },
                                "invalidNumber": {
                                    "id": "invalidNumber",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "helpDialogue": {
                    "id": "helpDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "text": {
                                    "id": "text",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "settingsDialogue": {
                    "id": "settingsDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "pagingEnabled": {
                                    "id": "pagingEnabled",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "embedDialogue": {
                    "id": "embedDialogue",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "embedTemplate": {
                                    "id": "embedTemplate",
                                    "type": "string"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "title": {
                                    "id": "title",
                                    "type": "string"
                                },
                                "instructions": {
                                    "id": "instructions",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "pagingHeaderPanel": {
                    "id": "pagingHeaderPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "help": {
                                    "id": "help",
                                    "type": "string"
                                },
                                "image": {
                                    "id": "image",
                                    "type": "string"
                                },
                                "page": {
                                    "id": "page",
                                    "type": "string",
                                    "required": true
                                },
                                "first": {
                                    "id": "first",
                                    "type": "string"
                                },
                                "previous": {
                                    "id": "previous",
                                    "type": "string"
                                },
                                "next": {
                                    "id": "next",
                                    "type": "string"
                                },
                                "last": {
                                    "id": "last",
                                    "type": "string"
                                },
                                "go": {
                                    "id": "go",
                                    "type": "string"
                                },
                                "of": {
                                    "id": "of",
                                    "type": "string"
                                },
                                "emptyValue": {
                                    "id": "emptyValue",
                                    "type": "string"
                                },
                                "close": {
                                    "id": "close",
                                    "type": "string"
                                },
                                "settings": {
                                    "id": "settings",
                                    "type": "string"
                                }
                            },
                            "required": ["page"]
                        }
                    }
                },
                "treeViewLeftPanel": {
                    "id": "treeViewLeftPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "thumbsLoadRange": {
                                    "id": "thumbsLoadRange",
                                    "type": "integer"
                                },
                                "thumbsImageFadeInDuration": {
                                    "id": "thumbsImageFadeInDuration",
                                    "type": "integer"
                                },
                                "panelCollapsedWidth": {
                                    "id": "panelCollapsedWidth",
                                    "type": "integer"
                                },
                                "panelExpandedWidth": {
                                    "id": "panelExpandedWidth",
                                    "type": "integer"
                                },
                                "panelOpen": {
                                    "id": "panelOpen",
                                    "type": "boolean"
                                },
                                "panelAnimationDuration": {
                                    "id": "panelAnimationDuration",
                                    "type": "integer"
                                },
                                "oneColThumbWidth": {
                                    "id": "oneColThumbWidth",
                                    "type": "integer"
                                },
                                "oneColThumbHeight": {
                                    "id": "oneColThumbHeight",
                                    "type": "integer"
                                },
                                "twoColThumbWidth": {
                                    "id": "twoColThumbWidth",
                                    "type": "integer"
                                },
                                "twoColThumbHeight": {
                                    "id": "twoColThumbHeight",
                                    "type": "integer"
                                },
                                "galleryThumbWidth": {
                                    "id": "galleryThumbWidth",
                                    "type": "integer"
                                },
                                "galleryThumbHeight": {
                                    "id": "galleryThumbHeight",
                                    "type": "integer"
                                },
                                "thumbsExtraHeight": {
                                    "id": "thumbsExtraHeight",
                                    "type": "integer"
                                },
                                "elideCount": {
                                    "id": "ellideCount",
                                    "type": "integer"
                                }

                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "index": {
                                    "id": "index",
                                    "type": "string"
                                },
                                "thumbnails": {
                                    "id": "thumbnails",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "seadragonCenterPanel": {
                    "id": "seadragonCenterPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "pageGap": {
                                    "id": "pageGap",
                                    "type": "number"
                                },
                                "defaultZoomLevel": {
                                    "id": "defaultZoomLevel",
                                    "type": "integer"
                                },
                                "controlsFadeAfterInactive": {
                                    "id": "controlsFadeAfterInactive",
                                    "type": "integer"
                                },
                                "controlsFadeDelay": {
                                    "id": "controlsFadeDelay",
                                    "type": "integer"
                                },
                                "controlsFadeLength": {
                                    "id": "controlsFadeLength",
                                    "type": "integer"
                                },
                                "navigatorPosition": {
                                    "id": "navigatorPosition",
                                    "type": "string",
                                    "enum": ["BOTTOM_RIGHT", "BOTTOM_LEFT", "TOP_LEFT", "TOP_RIGHT"]
                                },
                                "trimAttributionCount": {
                                    "id": "trimAttributionCount",
                                    "type": "integer"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "previous": {
                                    "id": "previous",
                                    "type": "string"
                                },
                                "next": {
                                    "id": "next",
                                    "type": "string"
                                },
                                "zoomIn": {
                                    "id": "zoomIn",
                                    "type": "string"
                                },
                                "zoomOut": {
                                    "id": "zoomOut",
                                    "type": "string"
                                },
                                "imageUnavailable": {
                                    "id": "imageUnavailable",
                                    "type": "string"
                                },
                                "acknowledgements": {
                                    "id": "acknowledgements",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "moreInfoRightPanel": {
                    "id": "moreInfoRightPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "panelCollapsedWidth": {
                                    "id": "panelCollapsedWidth",
                                    "type": "integer"
                                },
                                "panelExpandedWidth": {
                                    "id": "panelExpandedWidth",
                                    "type": "integer"
                                },
                                "panelAnimationDuration": {
                                    "id": "panelAnimationDuration",
                                    "type": "integer"
                                },
                                "panelOpen": {
                                    "id": "panelOpen",
                                    "type": "boolean"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "holdingText": {
                                    "id": "holdingText",
                                    "type": "string"
                                }
                            }
                        }
                    }
                },
                "footerPanel": {
                    "id": "footerPanel",
                    "type": "object",
                    "options": {
                        "collapsed": true
                    },
                    "properties": {
                        "options": {
                            "id": "options",
                            "type": "object",
                            "properties": {
                                "embedEnabled": {
                                    "id": "embedEnabled",
                                    "type": "boolean"
                                },
                                "minimiseButtons": {
                                    "id": "minimiseButtons",
                                    "type": "boolean"
                                }
                            }
                        },
                        "content": {
                            "id": "content",
                            "type": "object",
                            "properties": {
                                "fullScreen": {
                                    "id": "fullScreen",
                                    "type": "string"
                                },
                                "exitFullScreen": {
                                    "id": "exitFullScreen",
                                    "type": "string"
                                },
                                "embed": {
                                    "id": "embed",
                                    "type": "string"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

$(function(){

    var testBuild = getQuerystringParameter("build");
    var isLocalhost = document.location.href.indexOf('localhost') != -1;
    var editor;

    if (testBuild){
        $("body").append('<script type="text/javascript" id="embedUV" src="/build/uv-1.0.20/js/embed.js"><\/script>');
    } else {
        if (isLocalhost){
            $("body").append('<script type="text/javascript" id="embedUV" src="/src/js/embed.js"><\/script>');
        } else {
            // built version

            // remove '/examples' from paths
            $('.uv').updateAttr('data-config', '/examples/', '/');

            if ($('.uv').attr('data-uri')){
                $('.uv').updateAttr('data-uri', '/examples/', '/');
            }

            $('#config option').each(function() {
                $(this).updateAttr('value', '/examples/', '/');
            });

            $('#manifest option').each(function() {
                $(this).updateAttr('value', '/examples/', '/');
            });

            $("body").append('<script type="text/javascript" id="embedUV" src="/build/uv-1.0.20/js/embed.js"><\/script>');
        }
    }

    setTimeout(function(){
        if ($('#manifest option').length || $('#manifest optgroup').length){
            setSelectedManifest();
        }

        if ($('#config option').length || $('#config optgroup').length){
            setSelectedConfig();
        }

        createEditor();

        loadViewer();
    }, 2000);

    function loadViewer() {
        initPlayers($('.uv'));
    }

    function isIE8(){
        return (browserDetect.browser === "Explorer" && browserDetect.version === 8);
    }

    function createEditor() {

        if (isIE8() || typeof(JSONEditor) === "undefined") {
            $("#edit-config").hide();
            return;
        }

        editor = new JSONEditor(document.getElementById('editor'),{
            form_name_root: "",
            theme: 'foundation5',
            iconlib: 'fontawesome4',
            schema: schema,
            disable_edit_json: false,
            disable_properties: true,
            required_by_default: true
        });

        editor.on('change',function() {
            // Get an array of errors from the validator
            var errors = editor.validate();

            // Not valid
            if(errors.length) {
                console.log(errors);
            }
        });
    }

    $('#manifest').on('change', function(){
        buildQuerystring();
    });

    $('#config').on('change', function(){
        buildQuerystring();
    });

    function buildQuerystring() {
        var config = $('#config option:selected').val();
        var manifest = $('#manifest option:selected').val();

        // clear hash params
        document.location.hash = "";

        var qs = document.location.search.replace('?', '');
        qs = updateURIKeyValuePair(qs, "config", config);
        qs = updateURIKeyValuePair(qs, "manifest", manifest);

        // reload
        window.location.search = qs;
    }

    function setSelectedManifest(){

        var manifest = getQuerystringParameter("manifest");

        if (manifest) {
            $("#manifest").val(manifest);
        } else {
            manifest = $('#manifest option')[0].value;
        }

        $('.uv').attr('data-uri', manifest);
    }

    function setSelectedConfig(){

        var config = getQuerystringParameter("config");

        if (config) {
            $("#config").val(config);
        } else {
            config = $('#config option')[0].value;
        }

        $('.uv').attr('data-config', config);
    }

    $('#editBtn').on('click', function(e) {
        e.preventDefault();

        $('#editPnl').toggleClass('show', 'hide');
        $('#saveBtn').toggleClass('show', 'hide');
        $(this).toggleText('Edit', 'Close');

        if ($('#editPnl').hasClass('show')){

            // first get the default extension config
            // todo: figure out how to make this work for more than just seadragon extension
            $.getJSON('/build/uv-1.0.20/js/coreplayer-seadragon-extension-config.js', function(baseConfig){
                var configUrl = $('#config option:selected').val();

                $.getJSON(configUrl, function(config){
                    $.extend(true, baseConfig, config);
                    editor.setValue(baseConfig);
                });
            });
        }
    });

    $('#saveBtn').on('click', function(e) {
        e.preventDefault();

        var errors = editor.validate();

        if(errors.length) {
            console.log(errors);
            return;
        }

        // save contents of #json to session storage, set data-config attribute to 'sessionstorage' and reload viewer
        sessionStorage.setItem("uv-config", JSON.stringify(editor.getValue()));

        $('.uv').attr('data-config', 'sessionstorage');

        loadViewer();
    });

    // test overrideFullScreen option
    $(document).bind("onToggleFullScreen", function (event, isFullScreen) {
        console.log('full screen: ' + isFullScreen);
    });

    // test currentViewUri event
    $(document).bind("onCurrentViewUri", function (event, obj) {
        console.log(obj);
    });

    $(document).bind("onLoad", function (event, obj) {

    });
});<|endoftext|>


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

    define(
        [
            'lodash',
            'jquery'
        ],
        function (_, $) {
            return function (baseUrl, ajaxOptions, noCache, logErrors) {
                var queryString;

                queryString = function (parameters) {
                    return _.map(parameters, function (value, key) {
                        return '(' + key + ':' + value + ')';
                    })
                    .join(' AND ');
                };

                return function (parameters, callback) {
                    $.ajax(_.merge({}, ajaxOptions, {
                        url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : '') + '&limit=500',
                        success: function (result) {
                            if (!result.ok) {
                                return callback(new Error('Invalid response received from server'));
                            }
                            delete result.ok;
                            callback(undefined, _.values(result));
                        },
                        error: function (jqXHR, textStatus, err) {
                            if (logErrors && console && typeof console.error === 'function') {
                                console.error(err);
                            }
                            callback(err);
                        }
                    }));
                };
            };
        }
    );
}());
<commit_msg>Remove temporary artificial results limit.<commit_after>(function () {
    'use strict';

    define(
        [
            'lodash',
            'jquery'
        ],
        function (_, $) {
            return function (baseUrl, ajaxOptions, noCache, logErrors) {
                var queryString;

                queryString = function (parameters) {
                    return _.map(parameters, function (value, key) {
                        return '(' + key + ':' + value + ')';
                    })
                    .join(' AND ');
                };

                return function (parameters, callback) {
                    $.ajax(_.merge({}, ajaxOptions, {
                        url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''),
                        success: function (result) {
                            if (!result.ok) {
                                return callback(new Error('Invalid response received from server'));
                            }
                            delete result.ok;
                            callback(undefined, _.values(result));
                        },
                        error: function (jqXHR, textStatus, err) {
                            if (logErrors && console && typeof console.error === 'function') {
                                console.error(err);
                            }
                            callback(err);
                        }
                    }));
                };
            };
        }
    );
}());
<|endoftext|>


<commit_before>/**
 * At least we all get to write some Javascript, eh?
 *
 * JD woz 'ere 2k15
 *
 * Based entirely off http://www.webcodo.net/comments-system-using-php-ajax/
 */
var commentsThingy = function EmptyCommentsThingy() {
	console.error("Failed to build the native Comments function.");
};

var deleteComment = function emptyDeleteComment() {
	console.error("Failed to build the native Delete Comments function.");
};

(function () {
	var commentRoot, containerDiv, containerId, newCommentCount, writeBox;
	newCommentCount = 250;
	writeBox = [
		'
',
		'
',
		'Write a comment ...',
		'
',
		'
',
		'

',
		'<textarea id="newCommentBody"></textarea>',
		'
You have ', newCommentCount, ' characters left.
',
		'
Post comment
',
		'
Cancel
',
		'
',
		'
'
	].join('');

	function createComment(data) {
		containerDiv.innerHTML += [
			'
',
			'',
			'
', '
',
			'
',
			data.author.name,
			'
',
			'', data.created, '',
			((data.permissions.delete) ? 'Delete  ' : ''),
			'
',
			'
', data.comment, '
',
			'
',
			'
'
		].join('');
	}

	function initWriteBox() {
		containerDiv.innerHTML += writeBox;

		setTimeout(function () {
			document.querySelector('#commentWriteBox .new-com-bt').onclick = function OnNewCommentButtonClick() {
				document.querySelector('#commentWriteBox .new-com-bt').style.display = 'none';
				document.querySelector('#commentWriteBox .new-com-cnt').style.display = 'block';
				document.getElementById('newCommentBody').focus();
			};

			document.getElementById('newCommentBody').onkeyup = function OnNewCommentBodyKeyUp() {
				var commentLength, opacity;
				commentLength = document.getElementById('newCommentBody').value.length;

				if (commentLength > 0) {
					if (commentLength > newCommentCount) {
						opacity = 0.6;
						document.getElementById('commentError').innerText = 'Please enter a shorter comment.';
						document.getElementById('newCommentCount').innerText = "-" + (commentLength - newCommentCount);
					}
					else {
						opacity = 1;
						document.getElementById('commentError').innerText = '';
						document.getElementById('newCommentCount').innerText = '' + (newCommentCount - commentLength);
					}
				}
				else {
					opacity = 0.6;
					document.getElementById('newCommentCount').innerText = '' + newCommentCount;
				}

				document.querySelector('#commentWriteBox .bt-add-com').style.opacity = opacity;
			};

			document.querySelector('#commentWriteBox .bt-cancel-com').onclick = function OnNewCommentCancelClick() {
				document.getElementById('newCommentBody').value = '';
				document.getElementById('newCommentCount').innerText = '' + newCommentCount;
				document.getElementById('commentError').innerText = '';
				document.querySelector('#' + containerId + ' .new-com-cnt').style.display = 'none';
				document.querySelector('#' + containerId + ' .new-com-bt').style.display = 'block';
			};

			document.querySelector('#commentWriteBox .bt-add-com').onclick = function OnNewCommentSubmit() {
				var commentBody, writeBoxElem;

				commentBody = document.getElementById('newCommentBody').value;
				if ((commentBody.length == 0) || (commentBody.length > newCommentCount)) {
					return;
				}

				writeBoxElem = document.getElementById('commentWriteBox');
				writeBoxElem.innerHTML = '
Sending...
';
				API.POST(
					"/comment", {root: commentRoot, comment: commentBody},
					function onCommentCreate(data) {
						writeBoxElem.parentNode.removeChild(writeBoxElem);
						createComment(data.body);
						initWriteBox();
					},
					function onCommentCreateError(data) {
						console.error("onCommentCreateError", data);
					}
				);
			};
		}, 200);
	}

	deleteComment = function deleteComment(id) {
		console.log(id);
	}

	commentsThingy = function CommentsThingy(commentBodyId, root) {
		containerId = commentBodyId;
		containerDiv = document.getElementById(commentBodyId);
		commentRoot = root;
		API.GET(
			"/comment/thread", {root: root},
			function onCommentGet(data) {
				if (data.body && data.body.length) {
					for (var i = 0; i < data.body.length; i++) {
						createComment(data.body[i]);
					}
				}
				initWriteBox();
			},
			function onCommentGetError(data) {
				console.error("onCommentGetError", data);
			}
		);
	};
})();<commit_msg>Comment deleting now works, w00t.<commit_after>/**
 * At least we all get to write some Javascript, eh?
 *
 * JD woz 'ere 2k15
 *
 * Based entirely off http://www.webcodo.net/comments-system-using-php-ajax/
 */
var commentsThingy = function EmptyCommentsThingy() {
	console.error("Failed to build the native Comments function.");
};

var deleteComment = function emptyDeleteComment() {
	console.error("Failed to build the native Delete Comments function.");
};

(function () {
	var commentRoot, containerDiv, containerId, newCommentCount, writeBox;
	newCommentCount = 250;
	writeBox = [
		'
',
		'
',
		'Write a comment ...',
		'
',
		'
',
		'

',
		'<textarea id="newCommentBody"></textarea>',
		'
You have ', newCommentCount, ' characters left.
',
		'
Post comment
',
		'
Cancel
',
		'
',
		'
'
	].join('');

	function createComment(data) {
		containerDiv.innerHTML += [
			'
',
			'',
			'
', '
',
			'
',
			data.author.name,
			'
',
			'', data.created, '',
			((data.permissions.delete) ? 'Delete  ' : ''),
			'
',
			'
', data.comment, '
',
			'
',
			'
'
		].join('');
	}

	function initWriteBox() {
		containerDiv.innerHTML += writeBox;

		setTimeout(function () {
			document.querySelector('#commentWriteBox .new-com-bt').onclick = function OnNewCommentButtonClick() {
				document.querySelector('#commentWriteBox .new-com-bt').style.display = 'none';
				document.querySelector('#commentWriteBox .new-com-cnt').style.display = 'block';
				document.getElementById('newCommentBody').focus();
			};

			document.getElementById('newCommentBody').onkeyup = function OnNewCommentBodyKeyUp() {
				var commentLength, opacity;
				commentLength = document.getElementById('newCommentBody').value.length;

				if (commentLength > 0) {
					if (commentLength > newCommentCount) {
						opacity = 0.6;
						document.getElementById('commentError').innerText = 'Please enter a shorter comment.';
						document.getElementById('newCommentCount').innerText = "-" + (commentLength - newCommentCount);
					}
					else {
						opacity = 1;
						document.getElementById('commentError').innerText = '';
						document.getElementById('newCommentCount').innerText = '' + (newCommentCount - commentLength);
					}
				}
				else {
					opacity = 0.6;
					document.getElementById('newCommentCount').innerText = '' + newCommentCount;
				}

				document.querySelector('#commentWriteBox .bt-add-com').style.opacity = opacity;
			};

			document.querySelector('#commentWriteBox .bt-cancel-com').onclick = function OnNewCommentCancelClick() {
				document.getElementById('newCommentBody').value = '';
				document.getElementById('newCommentCount').innerText = '' + newCommentCount;
				document.getElementById('commentError').innerText = '';
				document.querySelector('#' + containerId + ' .new-com-cnt').style.display = 'none';
				document.querySelector('#' + containerId + ' .new-com-bt').style.display = 'block';
			};

			document.querySelector('#commentWriteBox .bt-add-com').onclick = function OnNewCommentSubmit() {
				var commentBody, writeBoxElem;

				commentBody = document.getElementById('newCommentBody').value;
				if ((commentBody.length == 0) || (commentBody.length > newCommentCount)) {
					return;
				}

				writeBoxElem = document.getElementById('commentWriteBox');
				writeBoxElem.innerHTML = '
Sending...
';
				API.POST(
					"/comment", {root: commentRoot, comment: commentBody},
					function onCommentCreate(data) {
						writeBoxElem.parentNode.removeChild(writeBoxElem);
						createComment(data.body);
						initWriteBox();
					},
					function onCommentCreateError(data) {
						console.error("onCommentCreateError", data);
					}
				);
			};
		}, 200);
	}

	deleteComment = function deleteComment(id) {
		API.DELETE("/comment/" + id, {},
			function Success(){
				var element = document.getElementById("comment_" + id);
				element.parentNode.removeChild(element);

			},
			function Error(){
				console.error("Failed to delete comment with ID " + id);
			}
		);
	}

	commentsThingy = function CommentsThingy(commentBodyId, root) {
		containerId = commentBodyId;
		containerDiv = document.getElementById(commentBodyId);
		commentRoot = root;
		API.GET(
			"/comment/thread", {root: root},
			function onCommentGet(data) {
				if (data.body && data.body.length) {
					for (var i = 0; i < data.body.length; i++) {
						createComment(data.body[i]);
					}
				}
				initWriteBox();
			},
			function onCommentGetError(data) {
				console.error("onCommentGetError", data);
			}
		);
	};
})();<|endoftext|>


<commit_before>
  //-------------------------------------------------------------------------------------------- !private methods
  function _S4(){
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }

  function _guid(){
    return (_S4()+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+_S4()+_S4());
  }

  function _indexPop(key) {
      localStorage.removeItem(key);
      k = key;
       var index = this._indexGet();
       var position = index.indexOf(key);
       if(position != -1){
      index = index.filter(function(val) {return val != key.toString()});
         }
         this._indexSet(index);
  }

   function _indexGet() {
       var index = this._storeGet('index');
       return index ? index : [];
     }

    function _indexAdd(key){
      var index = this._indexGet();
    index.push(key);
      this._indexSet(index);
    }

    function _indexSet(index) {
      localStorage.setItem('index', JSON.stringify(index));
    }

    function _getAll() {
      var r = [];
      var keys = this._indexGet();
      for (var i = 0 ; i < keys.length ; i++){
        var rv = this._storeGet(keys[i]);
        if (rv != undefined) r.push(rv);
      }
      return r
    }

    function _storeGet(key){
      try{
        return JSON.parse(localStorage.getItem(key));
      } catch(e){
        alert('ohhh my gosh! you tried to get and parse an invalid record! check your json.');
        return false
      }
    }

    function _storeSet(key,value){
      localStorage.setItem(key, JSON.stringify(value));
      this._indexAdd(key);
    }

  //-------------------------------------------------------------------------------------------- end of methods!

  //-------------------------------------------------------------------------------------------- !backbone views

  //-------------------------------------------------------------------------------------------- !backbone collection

  var List = Backbone.Collection.extend({
    model: Item
  });

  index = _indexGet();

  //-------------------------------------------------------------------------------------------- end of collection!

  //-------------------------------------------------------------------------------------------- !ItemView

  var ItemView = Backbone.View.extend({
    tagName: 'li',
    events: {
      'click span.delete': 'remove',
      'click span.edit': 'edit',
      'keypress input#modify': 'modItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'unrender', 'remove');
      this.model.bind('remove', this.unrender);
    },
    render: function(){
      $(this.el).html(''+this.model.get('title')+'[X][EDIT]');
      return this;
    },
    unrender: function(){
      $(this.el).remove();
    },
    remove: function(){
      var id = this.model.get('id_todo');
      _indexPop(id);
      this.model.destroy();
    },
    edit: function(){
      if(typeof(modify)!='object'){
        var value = JSON.parse(localStorage.getItem(this.model.get('id_todo')))['title'];
        $(this.el).html("<input id='modify'></input>");
        $('#modify').val(value);
        $("#modify").focus();
      }
    },
    modItem: function(){
      if (event.keyCode == 13 && modify.value!=''){
        var val = modify.value;
        var id = this.model.get('id_todo');
        var item = new Item();
        var title = modify.value;
        var column = title.match(regColumn)? title.match(regColumn).pop().substring(1) : '';
        var color = title.match(regColor)? title.match(regColor).pop().substring(1) : '';
        item.set({
          id_todo: id,
          title: val,
          column: column,
          color: color
        });
        _indexPop(id);
        item.save();
        $(this.el).html(''+val+'[X][EDIT]');
      }
    }

  });

  //-------------------------------------------------------------------------------------------- end of ItemView!

  //-------------------------------------------------------------------------------------------- !ListView
  var ListView = Backbone.View.extend({
    el: $('body'),
    events: {
      'keypress input#add': 'addItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'addItem', 'appendItem');
      this.collection = new List();
      this.collection.bind('add', this.appendItem);
      this.render();
    },

    count: function(){
      this.collection.add(_getAll())
    },

    render: function(){
      //$(this.el).append("<input id='add'></input>");
      $("#kanban").append("

");
      _(this.collection.models).each(function(item){
        appendItem(item);
      }, this);
      this.count();
    },

    addItem: function(){
      if (event.keyCode == 13 && add.value!=''){
        var item = new Item();
        var title = add.value;
        var column = title.match(regColumn)? title.match(regColumn).pop().substring(1) : '';
        var color = title.match(regColor)? title.match(regColor).pop().substring(1) : '';

        item.set({
          id_todo: _guid(),
          title: title,
          column: column,
          color: color
        });
        item.save();
        this.collection.add(item);
        add.value = '';
      }
    },

    appendItem: function(item){
      var itemView = new ItemView({
        model: item
      });
      $('ol', this.el).append(itemView.render().el);
    }
  });

  //-------------------------------------------------------------------------------------------- end of ListView!

  //-------------------------------------------------------------------------------------------- end of backbone views
<commit_msg>working on counting the columns<commit_after>
  //-------------------------------------------------------------------------------------------- !private methods
  function _S4(){
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }

  function _guid(){
    return (_S4()+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+"-"+_S4()+_S4()+_S4());
  }

  function _indexPop(key) {
      localStorage.removeItem(key);
      k = key;
       var index = this._indexGet();
       var position = index.indexOf(key);
       if(position != -1){
      index = index.filter(function(val) {return val != key.toString()});
         }
         this._indexSet(index);
  }

   function _indexGet() {
       var index = this._storeGet('index');
       return index ? index : [];
     }

    function _indexAdd(key){
      var index = this._indexGet();
    index.push(key);
      this._indexSet(index);
    }

    function _indexSet(index) {
      localStorage.setItem('index', JSON.stringify(index));
    }

    function _getAll() {
      var r = [];
      var keys = this._indexGet();
      for (var i = 0 ; i < keys.length ; i++){
        var rv = this._storeGet(keys[i]);
        if (rv != undefined) r.push(rv);
      }
      return r
    }

    function _storeGet(key){
      try{
        return JSON.parse(localStorage.getItem(key));
      } catch(e){
        alert('ohhh my gosh! you tried to get and parse an invalid record! check your json.');
        return false
      }
    }

    function _storeSet(key,value){
      localStorage.setItem(key, JSON.stringify(value));
      this._indexAdd(key);
    }

    function _countColumns(){
      var colcount = [];
      _.each(COLUMNS, function(col){
        colcount.push(_.filter(column_count, function(value){
          return value==col
        }))
      });
      //console.log(colcount);
    }
  //-------------------------------------------------------------------------------------------- end of methods!

  //-------------------------------------------------------------------------------------------- !backbone views

  //-------------------------------------------------------------------------------------------- !backbone collection

  var List = Backbone.Collection.extend({
    model: Item
  });

  index = _indexGet();
  var column_count = [];

  //-------------------------------------------------------------------------------------------- end of collection!

  //-------------------------------------------------------------------------------------------- !ItemView

  var ItemView = Backbone.View.extend({
    tagName: 'li',
    events: {
      'click span.delete': 'remove',
      'click span.edit': 'edit',
      'keypress input#modify': 'modItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'unrender', 'remove');
      this.model.bind('remove', this.unrender);
    },
    render: function(){
      $(this.el).html(''+this.model.get('title')+'[X][EDIT]');
      column_count.push(this.model.get('column'));
      return this;
    },
    unrender: function(){
      $(this.el).remove();
    },
    remove: function(){
      var id = this.model.get('id_todo');
      _indexPop(id);
      this.model.destroy();
    },
    edit: function(){
      if(typeof(modify)!='object'){
        var value = JSON.parse(localStorage.getItem(this.model.get('id_todo')))['title'];
        $(this.el).html("<input id='modify'></input>");
        $('#modify').val(value);
        $("#modify").focus();
      }
    },
    modItem: function(){
      if (event.keyCode == 13 && modify.value!=''){
        var val = modify.value;
        var id = this.model.get('id_todo');
        var item = new Item();
        var title = modify.value;
        var column = title.match(regColumn)? title.match(regColumn).pop().substring(1) : '';
        var color = title.match(regColor)? title.match(regColor).pop().substring(1) : '';
        item.set({
          id_todo: id,
          title: val,
          column: column,
          color: color
        });
        _indexPop(id);
        item.save();
        $(this.el).html(''+val+'[X][EDIT]');
      }
    }

  });

  //-------------------------------------------------------------------------------------------- end of ItemView!

  //-------------------------------------------------------------------------------------------- !ListView
  var ListView = Backbone.View.extend({
    el: $('body'),
    events: {
      'keypress input#add': 'addItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'addItem', 'appendItem');
      this.collection = new List();
      this.collection.bind('add', this.appendItem);
      this.render();
    },

    count: function(){
      this.collection.add(_getAll())
      _countColumns();
    },

    render: function(){
      //$(this.el).append("<input id='add'></input>");
      $("#kanban").append("

");
      _(this.collection.models).each(function(item){
        appendItem(item);
      }, this);
      this.count();
    },

    addItem: function(){
      if (event.keyCode == 13 && add.value!=''){
        var item = new Item();
        var title = add.value;
        var column = title.match(regColumn)? title.match(regColumn).pop().substring(1) : '';
        var color = title.match(regColor)? title.match(regColor).pop().substring(1) : '';

        item.set({
          id_todo: _guid(),
          title: title,
          column: column,
          color: color
        });
        item.save();
        this.collection.add(item);
        add.value = '';
      }
    },

    appendItem: function(item){
      var itemView = new ItemView({
        model: item
      });
      $('ol', this.el).append(itemView.render().el);
    }
  });

  //-------------------------------------------------------------------------------------------- end of ListView!

  //-------------------------------------------------------------------------------------------- end of backbone views
<|endoftext|>