<commit_before>const jsonfile = require('jsonfile')
const Discord = require('discord.js');
const cowsay_mod = require("cowsay");
const fortunes = require('fortunes');
const figlet_mod = require('figlet');
const client = new Discord.Client();
const config = require('./config.json');

var file = 'db.json'
var db = jsonfile.readFileSync(file);

function saveFile(file) {
  jsonfile.writeFile(file, db, function (err) {
    if(err) console.error(err);
  })
}
function help(msg) {
  msg.channel.sendMessage("Commands:\n\n`!info @user`: gives you the set info on a user\n`!chinfo <info>`: changes your listing\n`!rminfo`: removes your listing\n\nOther commands:\n\n`!interject`\n`!norichard`\n`!gentoo`\n`!paste`\n`!cowsay <text>`\n`!fortune`\n`!step`\n`!figlet`");
}
function info(msg) {
  let userId
  if(msg.content.substr(8,1) === '!') {
    userId = msg.content.substr(9,18);
  }
  else if(msg.content.substr(6) === '') {
    userId = msg.author.id;
  }
  else {
    userId = msg.content.substr(8,18);
  }
  if(db.info[userId]) {
    msg.channel.sendMessage('```'+db.info[userId]+'```');
  }
  else {
    msg.channel.sendMessage('No info found for <@' + userId + '>')
  }
}

function chinfo(msg) {
  if(msg.content.substr(8) === '') {
    delete db.info[msg.author.id]
    msg.channel.sendMessage('Info removed.')
  }
  else {
    db.info[msg.author.id] = msg.content.substr(8).replace(/[`]/g, '');
    msg.channel.sendMessage('Info changed to: ```'+db.info[msg.author.id]+'```');
  }
  saveFile(file);
}

function rminfo(msg) {
  delete db.info[msg.author.id]
  msg.channel.sendMessage('Info removed.')
  saveFile(file);
}

function slap(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps around a bit with a large trout');
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps '+ msg.content.substr(6) +' around a bit with a large trout');
  }
  else {
    msg.channel.sendMessage('!slap: Permission denied')
  }
}

function interject(msg) {
  const pasta = "I'd just like to interject for a moment. What you’re referring to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called “Linux”, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called “Linux” distributions are really distributions of GNU/Linux.";
  let args = msg.content.substr(11).split('/');
  if (args[1]) msg.channel.sendMessage(pasta.replace(/GNU/g, args[0]).replace(/Linux/g, args[1]));
  else msg.channel.sendMessage(pasta);
}

function norichard(msg) {
  msg.channel.sendMessage("No, Richard, it's 'Linux', not 'GNU/Linux'. The most important contributions that the FSF made to Linux were the creation of the GPL and the GCC compiler. Those are fine and inspired products. GCC is a monumental achievement and has earned you, RMS, and the Free Software Foundation countless kudos and much appreciation.\nFollowing are some reasons for you to mull over, including some already answered in your FAQ.\nOne guy, Linus Torvalds, used GCC to make his operating system (yes, Linux is an OS -- more on this later). He named it 'Linux' with a little help from his friends. Why doesn't he call it GNU/Linux? Because he wrote it, with more help from his friends, not you. You named your stuff, I named my stuff -- including the software I wrote using GCC -- and Linus named his stuff. The proper name is Linux because Linus Torvalds says so. Linus has spoken. Accept his authority. To do otherwise is to become a nag. You don't want to be known as a nag, do you?\n(An operating system) != (a distribution). Linux is an operating system. By my definition, an operating system is that software which provides and limits access to hardware resources on a computer. That definition applies whereever you see Linux in use. However, Linux is usually distributed with a collection of utilities and applications to make it easily configurable as a desktop system, a server, a development box, or a graphics workstation, or whatever the user needs. In such a configuration, we have a Linux (based) distribution. Therein lies your strongest argument for the unwieldy title 'GNU/Linux' (when said bundled software is largely from the FSF). Go bug the distribution makers on that one. Take your beef to Red Hat, Mandrake, and Slackware. At least there you have an argument. Linux alone is an operating system that can be used in various applications without any GNU software whatsoever. Embedded applications come to mind as an obvious example.");
  msg.channel.sendMessage("Next, even if we limit the GNU/Linux title to the GNU-based Linux distributions, we run into another obvious problem. XFree86 may well be more important to a particular Linux installation than the sum of all the GNU contributions. More properly, shouldn't the distribution be called XFree86/Linux? Or, at a minimum, XFree86/GNU/Linux? Of course, it would be rather arbitrary to draw the line there when many other fine contributions go unlisted. Yes, I know you've heard this one before. Get used to it. You'll keep hearing it until you can cleanly counter it.\nYou seem to like the lines-of-code metric. There are many lines of GNU code in a typical Linux distribution. You seem to suggest that (more LOC) == (more important). However, I submit to you that raw LOC numbers do not directly correlate with importance. I would suggest that clock cycles spent on code is a better metric. For example, if my system spends 90% of its time executing XFree86 code, XFree86 is probably the single most important collection of code on my system. Even if I loaded ten times as many lines of useless bloatware on my system and I never excuted that bloatware, it certainly isn't more important code than XFree86. Obviously, this metric isn't perfect either, but LOC really, really sucks. Please refrain from using it ever again in supporting any argument.\nLast, I'd like to point out that we Linux and GNU users shouldn't be fighting among ourselves over naming other people's software. But what the heck, I'm in a bad mood now. I think I'm feeling sufficiently obnoxious to make the point that GCC is so very famous and, yes, so very useful only because Linux was developed. In a show of proper respect and gratitude, shouldn't you and everyone refer to GCC as 'the Linux compiler'? Or at least, 'Linux GCC'? Seriously, where would your masterpiece be without Linux? Languishing with the HURD?");
  msg.channel.sendMessage("Be grateful for your abilities and your incredible success and your considerable fame. Continue to use that success and fame for good, not evil. Also, be especially grateful for Linux' huge contribution to that success. You, RMS, the Free Software Foundation, and GNU software have reached their current high profiles largely on the back of Linux. You have changed the world. Now, go forth and don't be a nag.\nThanks for listening.");
}

function gentoo(msg) {
  msg.channel.sendMessage("http://i.imgur.com/RLF8XyU.gif");
  msg.delete();
}
function paste(msg) {
  msg.channel.sendMessage("Please paste your log/message here: https://paste.fedoraproject.org/")
}
function cowsay(msg) {
  msg.channel.sendMessage("```\n"+ cowsay_mod.say({text: msg.content.substr(8)}) +"\n```");
}
function fortune(msg) {
  fortunes.search(function(results){
    msg.channel.sendMessage('```'+results[1]+'```');
  });
}
function step(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps');
  }
  else if(msg.content.substr(6,2) === "on" && !/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps on '+ msg.content.substr(9));
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps on '+ msg.content.substr(6));
  }
  else {
    msg.channel.sendMessage('!step: Permission denied')
  }
}
function figlet(msg) {
  msg.channel.sendMessage("```\n"+ figlet_mod.textSync(msg.content.substr(8)) +"\n```");
}
function sudo(msg) {
  if(!msg.member.roles.exists('name', 'sudoers')) {
    msg.channel.sendMessage('<@'+msg.author.id+'> is not in the sudoers file. This incident will be reported.')
    return;
  }
  if(msg.content.substr(8, 4) === 'info') {
    let userId
    let message
    if(msg.content.substr(8,1) === '!') {
      userId = msg.content.substr(16,18);
      message = msg.content.substr(36)
    }
    else {
      userId = msg.content.substr(15,18);
      message = msg.content.substr(35)
    }
    if(msg.content.substr(6, 6) === 'chinfo') {
      db.info[userId] = message;
      msg.channel.sendMessage('Info changed to: ```'+db.info[userId]+'```');
    }
    else if(msg.content.substr(6, 6) === 'rminfo') {
      delete db.info[userId];
      msg.channel.sendMessage('Info removed.');
   }
    saveFile(file);
  }
  else if(msg.content.substr(6,4) === 'slap') {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps '+ msg.content.substr(11) +' around a bit with a large trout');
  }
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  if(msg.author === client.user) return;
       if(msg.content.substr(0,  5) === '!help')          help(msg);
  else if(msg.content.substr(0,  5) === '!info')          info(msg);
  else if(msg.content.substr(0,  7) === '!chinfo')        chinfo(msg);
  else if(msg.content.substr(0,  7) === '!rminfo')        rminfo(msg);
  else if(msg.content.substr(0,  5) === '!slap')          slap(msg);
  else if(msg.content.substr(0, 10) === '!interject')     interject(msg);
  else if(msg.content.substr(0, 10) === '!norichard')     norichard(msg);
  else if(msg.content.substr(0,  7) === '!gentoo')        gentoo(msg);
  else if(msg.content.substr(0,  6) === '!paste')         paste(msg);
  else if(msg.content.substr(0,  7) === '!cowsay')        cowsay(msg);
  else if(msg.content.substr(0,  8) === '!fortune')       fortune(msg);
  else if(msg.content.substr(0,  5) === '!step')          step(msg);
  else if(msg.content.substr(0,  7) === '!figlet')        figlet(msg);
  else if(msg.content.substr(0,  5) === '!sudo')          sudo(msg);
});

client.on('guildMemberAdd', member => {
  client.channels.get('31589004683195188').sendMessage('Joined: <@' + member.id + '>')
});

client.login(config.token).then(function() {client.user.setGame("I can't remove this")});
<commit_msg>Slight refactoring 	Sprinkled some semicolon dust and removed some trailing spaces<commit_after>const jsonfile = require('jsonfile');
const Discord = require('discord.js');
const cowsay_mod = require("cowsay");
const fortunes = require('fortunes');
const figlet_mod = require('figlet');
const client = new Discord.Client();
const config = require('./config.json');

var file = 'db.json';
var db = jsonfile.readFileSync(file);

function saveFile(file) {
  jsonfile.writeFile(file, db, function (err) {
    if(err) console.error(err);
  });
}
function help(msg) {
  msg.channel.sendMessage("Commands:\n\n`!info @user`: gives you the set info on a user\n`!chinfo <info>`: changes your listing\n`!rminfo`: removes your listing\n\nOther commands:\n\n`!interject`\n`!norichard`\n`!gentoo`\n`!paste`\n`!cowsay <text>`\n`!fortune`\n`!step`\n`!figlet`");
}
function info(msg) {
  let userId;
  if(msg.content.substr(8,1) === '!') {
    userId = msg.content.substr(9,18);
  }
  else if(msg.content.substr(6) === '') {
    userId = msg.author.id;
  }
  else {
    userId = msg.content.substr(8,18);
  }
  if(db.info[userId]) {
    msg.channel.sendMessage('```'+db.info[userId]+'```');
  }
  else {
    msg.channel.sendMessage('No info found for <@' + userId + '>');
  }
}

function chinfo(msg) {
  if(msg.content.substr(8) === '') {
    delete db.info[msg.author.id];
    msg.channel.sendMessage('Info removed.');
  }
  else {
    db.info[msg.author.id] = msg.content.substr(8).replace(/[`]/g, '');
    msg.channel.sendMessage('Info changed to: ```'+db.info[msg.author.id]+'```');
  }
  saveFile(file);
}

function rminfo(msg) {
  delete db.info[msg.author.id];
  msg.channel.sendMessage('Info removed.');
  saveFile(file);
}

function slap(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps around a bit with a large trout');
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps '+ msg.content.substr(6) +' around a bit with a large trout');
  }
  else {
    msg.channel.sendMessage('!slap: Permission denied');
  }
}

function interject(msg) {
  const pasta = "I'd just like to interject for a moment. What you’re referring to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called “Linux”, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called “Linux” distributions are really distributions of GNU/Linux.";
  let args = msg.content.substr(11).split('/');
  if (args[1]) msg.channel.sendMessage(pasta.replace(/GNU/g, args[0]).replace(/Linux/g, args[1]));
  else msg.channel.sendMessage(pasta);
}

function norichard(msg) {
  msg.channel.sendMessage("No, Richard, it's 'Linux', not 'GNU/Linux'. The most important contributions that the FSF made to Linux were the creation of the GPL and the GCC compiler. Those are fine and inspired products. GCC is a monumental achievement and has earned you, RMS, and the Free Software Foundation countless kudos and much appreciation.\nFollowing are some reasons for you to mull over, including some already answered in your FAQ.\nOne guy, Linus Torvalds, used GCC to make his operating system (yes, Linux is an OS -- more on this later). He named it 'Linux' with a little help from his friends. Why doesn't he call it GNU/Linux? Because he wrote it, with more help from his friends, not you. You named your stuff, I named my stuff -- including the software I wrote using GCC -- and Linus named his stuff. The proper name is Linux because Linus Torvalds says so. Linus has spoken. Accept his authority. To do otherwise is to become a nag. You don't want to be known as a nag, do you?\n(An operating system) != (a distribution). Linux is an operating system. By my definition, an operating system is that software which provides and limits access to hardware resources on a computer. That definition applies whereever you see Linux in use. However, Linux is usually distributed with a collection of utilities and applications to make it easily configurable as a desktop system, a server, a development box, or a graphics workstation, or whatever the user needs. In such a configuration, we have a Linux (based) distribution. Therein lies your strongest argument for the unwieldy title 'GNU/Linux' (when said bundled software is largely from the FSF). Go bug the distribution makers on that one. Take your beef to Red Hat, Mandrake, and Slackware. At least there you have an argument. Linux alone is an operating system that can be used in various applications without any GNU software whatsoever. Embedded applications come to mind as an obvious example.");
  msg.channel.sendMessage("Next, even if we limit the GNU/Linux title to the GNU-based Linux distributions, we run into another obvious problem. XFree86 may well be more important to a particular Linux installation than the sum of all the GNU contributions. More properly, shouldn't the distribution be called XFree86/Linux? Or, at a minimum, XFree86/GNU/Linux? Of course, it would be rather arbitrary to draw the line there when many other fine contributions go unlisted. Yes, I know you've heard this one before. Get used to it. You'll keep hearing it until you can cleanly counter it.\nYou seem to like the lines-of-code metric. There are many lines of GNU code in a typical Linux distribution. You seem to suggest that (more LOC) == (more important). However, I submit to you that raw LOC numbers do not directly correlate with importance. I would suggest that clock cycles spent on code is a better metric. For example, if my system spends 90% of its time executing XFree86 code, XFree86 is probably the single most important collection of code on my system. Even if I loaded ten times as many lines of useless bloatware on my system and I never excuted that bloatware, it certainly isn't more important code than XFree86. Obviously, this metric isn't perfect either, but LOC really, really sucks. Please refrain from using it ever again in supporting any argument.\nLast, I'd like to point out that we Linux and GNU users shouldn't be fighting among ourselves over naming other people's software. But what the heck, I'm in a bad mood now. I think I'm feeling sufficiently obnoxious to make the point that GCC is so very famous and, yes, so very useful only because Linux was developed. In a show of proper respect and gratitude, shouldn't you and everyone refer to GCC as 'the Linux compiler'? Or at least, 'Linux GCC'? Seriously, where would your masterpiece be without Linux? Languishing with the HURD?");
  msg.channel.sendMessage("Be grateful for your abilities and your incredible success and your considerable fame. Continue to use that success and fame for good, not evil. Also, be especially grateful for Linux' huge contribution to that success. You, RMS, the Free Software Foundation, and GNU software have reached their current high profiles largely on the back of Linux. You have changed the world. Now, go forth and don't be a nag.\nThanks for listening.");
}

function gentoo(msg) {
  msg.channel.sendMessage("http://i.imgur.com/RLF8XyU.gif");
  msg.delete();
}
function paste(msg) {
  msg.channel.sendMessage("Please paste your log/message here: https://paste.fedoraproject.org/");
}
function cowsay(msg) {
  msg.channel.sendMessage("```\n"+ cowsay_mod.say({text: msg.content.substr(8)}) +"\n```");
}
function fortune(msg) {
  fortunes.search(function(results){
    msg.channel.sendMessage('```'+results[1]+'```');
  });
}
function step(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps');
  }
  else if(msg.content.substr(6,2) === "on" && !/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps on '+ msg.content.substr(9));
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.sendMessage('<@'+msg.author.id+'> steps on '+ msg.content.substr(6));
  }
  else {
    msg.channel.sendMessage('!step: Permission denied');
  }
}
function figlet(msg) {
  msg.channel.sendMessage("```\n"+ figlet_mod.textSync(msg.content.substr(8)) +"\n```");
}
function sudo(msg) {
  if(!msg.member.roles.exists('name', 'sudoers')) {
    msg.channel.sendMessage('<@'+msg.author.id+'> is not in the sudoers file. This incident will be reported.');
    return;
  }
  if(msg.content.substr(8, 4) === 'info') {
    let userId;
    let message;
    if(msg.content.substr(8,1) === '!') {
      userId = msg.content.substr(16,18);
      message = msg.content.substr(36);
    }
    else {
      userId = msg.content.substr(15,18);
      message = msg.content.substr(35);
    }
    if(msg.content.substr(6, 6) === 'chinfo') {
      db.info[userId] = message;
      msg.channel.sendMessage('Info changed to: ```'+db.info[userId]+'```');
    }
    else if(msg.content.substr(6, 6) === 'rminfo') {
      delete db.info[userId];
      msg.channel.sendMessage('Info removed.');
   }
    saveFile(file);
  }
  else if(msg.content.substr(6,4) === 'slap') {
    msg.channel.sendMessage('<@'+msg.author.id+'> slaps '+ msg.content.substr(11) +' around a bit with a large trout');
  }
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  if(msg.author === client.user) return;
       if(msg.content.substr(0,  5) === '!help')          help(msg);
  else if(msg.content.substr(0,  5) === '!info')          info(msg);
  else if(msg.content.substr(0,  7) === '!chinfo')        chinfo(msg);
  else if(msg.content.substr(0,  7) === '!rminfo')        rminfo(msg);
  else if(msg.content.substr(0,  5) === '!slap')          slap(msg);
  else if(msg.content.substr(0, 10) === '!interject')     interject(msg);
  else if(msg.content.substr(0, 10) === '!norichard')     norichard(msg);
  else if(msg.content.substr(0,  7) === '!gentoo')        gentoo(msg);
  else if(msg.content.substr(0,  6) === '!paste')         paste(msg);
  else if(msg.content.substr(0,  7) === '!cowsay')        cowsay(msg);
  else if(msg.content.substr(0,  8) === '!fortune')       fortune(msg);
  else if(msg.content.substr(0,  5) === '!step')          step(msg);
  else if(msg.content.substr(0,  7) === '!figlet')        figlet(msg);
  else if(msg.content.substr(0,  5) === '!sudo')          sudo(msg);
});

client.on('guildMemberAdd', member => {
  client.channels.get('31589004683195188').sendMessage('Joined: <@' + member.id + '>');
});

client.login(config.token).then(function() {client.user.setGame("I can't remove this");});
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global Tangram */
var picking = false;
map = (function () {
// (function () {
    // 'use strict';

    // defaults
    var map_start_location = [37.7926, -122.4003, 15]; // San Francisco
    var style_file = 'bubble-wrap.yaml';

    /*** URL parsing ***/

    // convert tile coordinates to lat-lng
    // from http://gis.stackexchange.com/questions/17278/calculate-lat-lon-bounds-for-individual-tile-generated-from-gdal2tiles
    function tile2long(x,z) { return (x/Math.pow(2,z)*360-180); }
    function tile2lat(y,z) {
        var n=Math.PI-2*Math.PI*y/Math.pow(2,z);
        return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
    }

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1).split('/');

    // location
    var defaultpos = true; // use default position

    // location is passed through url
    if (url_hash.length == 3) {
        var defaultpos = false;
        if (url_hash[1] > 180) { // parse hash as tile coordinates
            // example: http://localhost:9001/#15/5242/12663
            // add .5 to coords to center tile on screen
            map_start_location = [tile2lat(parseFloat(url_hash[2]) + .5, url_hash[0]), tile2long(parseFloat(url_hash[1]) + .5, url_hash[0]), url_hash[0]];
        }
        else { // parse hash as lat/lng coordinates
            map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
            // convert from strings
            map_start_location = map_start_location.map(Number);
        }
    }

    // enable setting language by URL argument
    // eg: '?language=en&this=no'

    var query = splitQueryParams();
    // { language: 'en', this: 'no'}

    function splitQueryParams () {
       var str = window.location.search;

       var kvArray = str.slice(1).split('&');
       // ['language=en', 'this=no']

       var obj = {};

       for (var i = 0, j=kvArray.length; i<j; i++) {
           var value = kvArray[i].split('=');
           var k = window.decodeURIComponent(value[0]);
           var v = window.decodeURIComponent(value[1]);

           obj[k] = v;
       }

       return obj;
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05, maxZoom: 20, "scrollWheelZoom": false }
    );
    map.setView(map_start_location.slice(0, 2), map_start_location[2]);

    var layer = Tangram.leafletLayer({
        scene: style_file,
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;
    var latlng = {};
    var popup = document.getElementById('popup'); // click-popup

    // setView expects format ([lat, long], zoom)
    var hash = new L.Hash(map);

    function updateKey(value) {
        keytext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.key_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    function updateValue(value) {
        valuetext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.value_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    // Feature selection
    function initFeatureSelection () {
        map.getContainer().addEventListener('mousemove', function (event) {
            picking = true;
            latlng = map.mouseEventToLatLng(event);

            var pixel = { x: event.clientX, y: event.clientY };

            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection || selection.feature == null || selection.feature.properties == null) {
                    picking = false;
                    popup.style.visibility = 'hidden';
                    return;
                }
                var properties = selection.feature.properties;

                popup.style.width = 'auto';
                popup.style.left = (pixel.x + 0) + 'px';
                popup.style.top = (pixel.y + 0) + 'px';
                popup.style.margin = '10px';
                if (properties.name) {
                    popup.innerHTML = '' + properties.name + '
';
                } else {
                    popup.innerHTML = '' + 'unnamed ' + properties.kind + '
';
                }
                popup.innerHTML += '' + 'Click to view more...' + '
';
                popup.style.visibility = 'visible';
            });
        });
    }

    function createEditLinkElement (url, type, label) {
        var el = document.createElement('div');
        var anchor = document.createElement('a');
        el.className = 'labelInner';
        anchor.href = url;
        anchor.target = '_blank';
        anchor.textContent = label;
        anchor.addEventListener('click', function (event) {
            trackOutboundLink(url, 'mapzen_carto_debug', type);
        }, false);
        el.appendChild(anchor);
        return el;
    }

    /**
    * Function that tracks a click on an outbound link in Google Analytics.
    * This function takes a valid URL string as an argument, and uses that URL string
    * as the event label. Setting the transport method to 'beacon' lets the hit be sent
    * using 'navigator.sendBeacon' in browser that support it.
    */
    function trackOutboundLink (url, post_name, editor) {
       // ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
       ga('send', 'event', 'outbound', post_name, url, {
         'transport': 'beacon',
         // If opening a link in the current window, this opens the url AFTER
         // registering the hit with Analytics. Disabled because here want the
         // link to open in a new window, so this hit can occur in the current tab.
         //'hitCallback': function(){document.location = url;}
       });
    }

    function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); }
    function lat2tile(lat,zoom)  { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }

    function mapzenTileURL() {
        // find minimum max_zoom of all sources
        var max_zoom = 21;
        for (source in scene.config.sources) {
            if (scene.config.sources.hasOwnProperty(source)) {
                if (scene.config.sources[source].max_zoom != "undefined") {
                    max_zoom = Math.min(max_zoom, scene.config.sources[source].max_zoom);
                }
            }
        }
        var zoom = max_zoom < map.getZoom() ? max_zoom : Math.floor(map.getZoom());
        var tileCoords = { x : long2tile(latlng.lng,zoom), y: lat2tile(latlng.lat,zoom), z: zoom };

        var url = 'http://vector.mapzen.com/osm/all/' + zoom + '/' + tileCoords.x  + '/' + tileCoords.y + '.topojson?api_key=vector-tiles-HqUVidw';
        return url;
    }

    /***** Render loop *****/

    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true });

    function addGUI() {
        gui.domElement.parentNode.style.zIndex = 10000;
        window.gui = gui;

        // Language selector
        var langs = {
            '(default)': false,
            'English': 'en',
            'Russian': 'ru',
            'Chinese': 'zh',
            'Japanese': 'ja',
            'Korean': 'ko',
            'Vietnamese': 'vi',
            'German': 'de',
            'French': 'fr',
            'Arabic': 'ar',
            'Spanish': 'es',
            'Italian': 'it',
            'Greek': 'el'
        };
        // use query language, else default to English
        gui.language = query.language || false;
        gui.add(gui, 'language', langs).onChange(function(value) {
            scene.config.global.ux_language = value;
            scene.updateConfig();
            //window.location.search = 'language=' + value;
        });
        gui.fallback_lang = query.language || false;
        gui.add(gui, 'fallback_lang', langs).onChange(function(value) {
            scene.config.global.ux_language_fallback = value;
            scene.updateConfig();
            //window.location.search = 'language=' + value;
        });

        // Transit selector
        var transit_overlay = {
            '(default)': false,
            'Show': true,
            'Hide': false
        };
        // use transit ux, else default to false
        gui.transit_overlay = query.transit_overlay || false;
        gui.add(gui, 'transit_overlay', transit_overlay).onChange(function(value) {
            scene.config.global.sdk_transit_overlay = (value === 'true' || value === true); // dat.gui passes a string
            scene.updateConfig();
        });

        // Building extrusion selector
        var building_3d = {
            '(default)': true,
            'Yes': true,
            'No': false
        };
        // use transit ux, else default to false
        gui.building_3d = query.building_3d || true;
        gui.add(gui, 'building_3d', building_3d).onChange(function(value) {
            scene.config.global.building_extrude = (value === 'true' || value === true); // dat.gui passes a string
            scene.updateConfig();
        });

        // Take a screenshot and save to file
        gui.save_screenshot = function () {
            return scene.screenshot().then(function(screenshot) {
                // uses FileSaver.js: https://github.com/eligrey/FileSaver.js/
                timestamp = new Date();
                month = timestamp.getMonth()+1;
                if( month < 10 ) { month = '0' + month; }
                prettydate = timestamp.getFullYear() + month + timestamp.getDate() + timestamp.getHours() + timestamp.getMinutes();
                map_location = map.getZoom() + '-' + map.getCenter().lat.toFixed(5) + '-' + map.getCenter().lng.toFixed(5);
                saveAs(screenshot.blob, 'tangram-' + map_location + '-' + prettydate + '.png');
            });
        };
        gui.add(gui, 'save_screenshot');

        // Link to edit in OSM - hold 'e' and click
        map.getContainer().addEventListener('dblclick', function (event) {
            //console.log( 'dblclick was had' );
            if( timer ) { clearTimeout( timer ); timer = null; }
            popup.style.visibility = 'hidden';
        });

        var timer;

        map.getContainer().addEventListener('click', function (event) {
            //console.log( 'click was had' );
            if( timer ) { clearTimeout( timer ); timer = null; }
            timer = setTimeout( function(){
                picking = true;
                latlng = map.mouseEventToLatLng(event);
                var pixel = { x: event.clientX, y: event.clientY };

                if( key.cmd || key.alt ) {
                    window.open( mapzenTileURL(), '_blank' );
                } else {
                    var url = 'https://www.openstreetmap.org/edit?';
                    scene.getFeatureAt(pixel).then(function(selection) {
                        if (!selection || selection.feature == null || selection.feature.properties == null) {
                            picking = false;
                            popup.style.visibility = 'hidden';
                            return;
                        }
                        //console.log(selection.feature, selection.changed);
                        // enable iD to show properties sidebar for selected feature
                        osm_type = 'node';
                        osm_zoom = '19'
                        if( selection.feature.properties.sort_key ) {
                            osm_type = 'way';
                            osm_zoom = Math.max( 17, map.getZoom() );
                        }
                        osm_id = selection.feature.properties.id;
                        if( osm_id < 0 ) {
                            osm_type = 'relation'
                            osm_id = Math.abs( osm_id );
                            osm_zoom = Math.max( 16, map.getZoom() );
                        }
                        url += osm_type + '=' + osm_id;
                        // and position the map so it's at a similar zoom to Tangram
                        if (latlng) {
                            url += '#map=' + osm_zoom + '/' + latlng.lat + '/' + latlng.lng;
                        }

                        if( key.shift ) {
                            window.open(url, '_blank');
                        } else {
                            var properties = selection.feature.properties;

                            var label = '';
                            //console.log(properties);
                            for (var x in properties) {
                                var val = properties[x]
                                label += ""+x+" : "+val+"
"
                            }

                            if (label != '') {
                                popup.style.left = (pixel.x) + 'px';
                                popup.style.top = (pixel.y) + 'px';
                                popup.style.margin = '0px';
                                popup.innerHTML = '' + label + '';
                            }

                            // JOSM editor link
                            var position = '19' + '/' + latlng.lat + '/' + latlng.lng;
                            var josmUrl = 'http://www.openstreetmap.org/edit?editor=remote#map='+position;

                            popup.appendChild(createEditLinkElement( url, 'iD', 'Edit with iD ➹') );
                            popup.appendChild(createEditLinkElement( mapzenTileURL(), 'rawTile', 'View tile data ➹') );
                            //popup.appendChild(createEditLinkElement( josmUrl, 'JOSM', 'Edit with JOSM ➹') );
                            popup.style.visibility = 'visible';
                        }
                    });
                }
                timer = null;
            }, 200 );
        });
    }

    function inIframe () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    // Add map
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            var camera = scene.config.cameras[scene.getActiveCamera()];
            // if a camera position is set in the scene file, use that
            if (defaultpos && typeof camera.position != "undefined") {
                map_start_location = [camera.position[1], camera.position[0], camera.position[2]]
            }
            map.setView([map_start_location[0], map_start_location[1]], map_start_location[2]);
        });

        // Set initial language on scene load
        layer.scene.subscribe({
            load: function (msg) {
                msg.config.global.ux_language = query.language;
            }
        });

        if (!inIframe()) {
            map.scrollWheelZoom.enable();
            addGUI();
            initFeatureSelection();
        }

        layer.addTo(map);
    });

    return map;
}());
<commit_msg>use introspection mode for debug interactivity<commit_after>/*jslint browser: true*/
/*global Tangram */
var picking = false;
map = (function () {
// (function () {
    // 'use strict';

    // defaults
    var map_start_location = [37.7926, -122.4003, 15]; // San Francisco
    var style_file = 'bubble-wrap.yaml';

    /*** URL parsing ***/

    // convert tile coordinates to lat-lng
    // from http://gis.stackexchange.com/questions/17278/calculate-lat-lon-bounds-for-individual-tile-generated-from-gdal2tiles
    function tile2long(x,z) { return (x/Math.pow(2,z)*360-180); }
    function tile2lat(y,z) {
        var n=Math.PI-2*Math.PI*y/Math.pow(2,z);
        return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
    }

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1).split('/');

    // location
    var defaultpos = true; // use default position

    // location is passed through url
    if (url_hash.length == 3) {
        var defaultpos = false;
        if (url_hash[1] > 180) { // parse hash as tile coordinates
            // example: http://localhost:9001/#15/5242/12663
            // add .5 to coords to center tile on screen
            map_start_location = [tile2lat(parseFloat(url_hash[2]) + .5, url_hash[0]), tile2long(parseFloat(url_hash[1]) + .5, url_hash[0]), url_hash[0]];
        }
        else { // parse hash as lat/lng coordinates
            map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
            // convert from strings
            map_start_location = map_start_location.map(Number);
        }
    }

    // enable setting language by URL argument
    // eg: '?language=en&this=no'

    var query = splitQueryParams();
    // { language: 'en', this: 'no'}

    function splitQueryParams () {
       var str = window.location.search;

       var kvArray = str.slice(1).split('&');
       // ['language=en', 'this=no']

       var obj = {};

       for (var i = 0, j=kvArray.length; i<j; i++) {
           var value = kvArray[i].split('=');
           var k = window.decodeURIComponent(value[0]);
           var v = window.decodeURIComponent(value[1]);

           obj[k] = v;
       }

       return obj;
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05, maxZoom: 20, "scrollWheelZoom": false }
    );
    map.setView(map_start_location.slice(0, 2), map_start_location[2]);

    var layer = Tangram.leafletLayer({
        scene: style_file,
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;
    var latlng = {};
    var popup = document.getElementById('popup'); // click-popup

    // setView expects format ([lat, long], zoom)
    var hash = new L.Hash(map);

    function updateKey(value) {
        keytext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.key_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    function updateValue(value) {
        valuetext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.value_text = value;
        }
        scene.rebuildGeometry();
        scene.requestRedraw();
    }

    // Feature selection
    function initFeatureSelection () {
        map.getContainer().addEventListener('mousemove', function (event) {
            picking = true;
            latlng = map.mouseEventToLatLng(event);

            var pixel = { x: event.clientX, y: event.clientY };

            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection || selection.feature == null || selection.feature.properties == null) {
                    picking = false;
                    popup.style.visibility = 'hidden';
                    return;
                }
                var properties = selection.feature.properties;

                popup.style.width = 'auto';
                popup.style.left = (pixel.x + 0) + 'px';
                popup.style.top = (pixel.y + 0) + 'px';
                popup.style.margin = '10px';
                if (properties.name) {
                    popup.innerHTML = '' + properties.name + '
';
                } else {
                    popup.innerHTML = '' + 'unnamed ' + properties.kind + '
';
                }
                popup.innerHTML += '' + 'Click to view more...' + '
';
                popup.style.visibility = 'visible';
            });
        });
    }

    function createEditLinkElement (url, type, label) {
        var el = document.createElement('div');
        var anchor = document.createElement('a');
        el.className = 'labelInner';
        anchor.href = url;
        anchor.target = '_blank';
        anchor.textContent = label;
        anchor.addEventListener('click', function (event) {
            trackOutboundLink(url, 'mapzen_carto_debug', type);
        }, false);
        el.appendChild(anchor);
        return el;
    }

    /**
    * Function that tracks a click on an outbound link in Google Analytics.
    * This function takes a valid URL string as an argument, and uses that URL string
    * as the event label. Setting the transport method to 'beacon' lets the hit be sent
    * using 'navigator.sendBeacon' in browser that support it.
    */
    function trackOutboundLink (url, post_name, editor) {
       // ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
       ga('send', 'event', 'outbound', post_name, url, {
         'transport': 'beacon',
         // If opening a link in the current window, this opens the url AFTER
         // registering the hit with Analytics. Disabled because here want the
         // link to open in a new window, so this hit can occur in the current tab.
         //'hitCallback': function(){document.location = url;}
       });
    }

    function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); }
    function lat2tile(lat,zoom)  { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); }

    function mapzenTileURL() {
        // find minimum max_zoom of all sources
        var max_zoom = 21;
        for (source in scene.config.sources) {
            if (scene.config.sources.hasOwnProperty(source)) {
                if (scene.config.sources[source].max_zoom != "undefined") {
                    max_zoom = Math.min(max_zoom, scene.config.sources[source].max_zoom);
                }
            }
        }
        var zoom = max_zoom < map.getZoom() ? max_zoom : Math.floor(map.getZoom());
        var tileCoords = { x : long2tile(latlng.lng,zoom), y: lat2tile(latlng.lat,zoom), z: zoom };

        var url = 'http://vector.mapzen.com/osm/all/' + zoom + '/' + tileCoords.x  + '/' + tileCoords.y + '.topojson?api_key=vector-tiles-HqUVidw';
        return url;
    }

    /***** Render loop *****/

    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true, width: 250 });

    function addGUI() {
        gui.domElement.parentNode.style.zIndex = 10000;
        window.gui = gui;

        // Language selector
        var langs = {
            '(default)': false,
            'English': 'en',
            'Russian': 'ru',
            'Chinese': 'zh',
            'Japanese': 'ja',
            'Korean': 'ko',
            'Vietnamese': 'vi',
            'German': 'de',
            'French': 'fr',
            'Arabic': 'ar',
            'Spanish': 'es',
            'Italian': 'it',
            'Greek': 'el'
        };
        // use query language, else default to English
        gui.language = query.language || false;
        gui.add(gui, 'language', langs).onChange(function(value) {
            scene.config.global.ux_language = value;
            scene.updateConfig();
            //window.location.search = 'language=' + value;
        });
        gui.fallback_lang = query.language || false;
        gui.add(gui, 'fallback_lang', langs).onChange(function(value) {
            scene.config.global.ux_language_fallback = value;
            scene.updateConfig();
            //window.location.search = 'language=' + value;
        });

        // Transit selector
        var transit_overlay = {
            '(default)': false,
            'Show': true,
            'Hide': false
        };
        // use transit ux, else default to false
        gui.transit_overlay = query.transit_overlay || false;
        gui.add(gui, 'transit_overlay', transit_overlay).onChange(function(value) {
            scene.config.global.sdk_transit_overlay = (value === 'true' || value === true); // dat.gui passes a string
            scene.updateConfig();
        });

        // Building extrusion selector
        var building_3d = {
            '(default)': true,
            'Yes': true,
            'No': false
        };
        // use transit ux, else default to false
        gui.building_3d = query.building_3d || true;
        gui.add(gui, 'building_3d', building_3d).onChange(function(value) {
            scene.config.global.building_extrude = (value === 'true' || value === true); // dat.gui passes a string
            scene.updateConfig();
        });

        // Take a screenshot and save to file
        gui.save_screenshot = function () {
            return scene.screenshot().then(function(screenshot) {
                // uses FileSaver.js: https://github.com/eligrey/FileSaver.js/
                timestamp = new Date();
                month = timestamp.getMonth()+1;
                if( month < 10 ) { month = '0' + month; }
                prettydate = timestamp.getFullYear() + month + timestamp.getDate() + timestamp.getHours() + timestamp.getMinutes();
                map_location = map.getZoom() + '-' + map.getCenter().lat.toFixed(5) + '-' + map.getCenter().lng.toFixed(5);
                saveAs(screenshot.blob, 'tangram-' + map_location + '-' + prettydate + '.png');
            });
        };
        gui.add(gui, 'save_screenshot');

        // Enable/disable interactivity for all features
        var interactive_label = 'debug_interactive';
        gui[interactive_label] = true;
        gui.add(gui, interactive_label).onChange(function(value) {
            scene.setIntrospection(value);
        });
        scene.setIntrospection(gui[interactive_label]);

        // Link to edit in OSM - hold 'e' and click
        map.getContainer().addEventListener('dblclick', function (event) {
            //console.log( 'dblclick was had' );
            if( timer ) { clearTimeout( timer ); timer = null; }
            popup.style.visibility = 'hidden';
        });

        var timer;

        map.getContainer().addEventListener('click', function (event) {
            //console.log( 'click was had' );
            if( timer ) { clearTimeout( timer ); timer = null; }
            timer = setTimeout( function(){
                picking = true;
                latlng = map.mouseEventToLatLng(event);
                var pixel = { x: event.clientX, y: event.clientY };

                if( key.cmd || key.alt ) {
                    window.open( mapzenTileURL(), '_blank' );
                } else {
                    var url = 'https://www.openstreetmap.org/edit?';
                    scene.getFeatureAt(pixel).then(function(selection) {
                        if (!selection || selection.feature == null || selection.feature.properties == null) {
                            picking = false;
                            popup.style.visibility = 'hidden';
                            return;
                        }
                        //console.log(selection.feature, selection.changed);
                        // enable iD to show properties sidebar for selected feature
                        osm_type = 'node';
                        osm_zoom = '19'
                        if( selection.feature.properties.sort_key ) {
                            osm_type = 'way';
                            osm_zoom = Math.max( 17, map.getZoom() );
                        }
                        osm_id = selection.feature.properties.id;
                        if( osm_id < 0 ) {
                            osm_type = 'relation'
                            osm_id = Math.abs( osm_id );
                            osm_zoom = Math.max( 16, map.getZoom() );
                        }
                        url += osm_type + '=' + osm_id;
                        // and position the map so it's at a similar zoom to Tangram
                        if (latlng) {
                            url += '#map=' + osm_zoom + '/' + latlng.lat + '/' + latlng.lng;
                        }

                        if( key.shift ) {
                            window.open(url, '_blank');
                        } else {
                            var properties = selection.feature.properties;

                            var label = '';
                            //console.log(properties);
                            for (var x in properties) {
                                var val = properties[x]
                                label += ""+x+" : "+val+"
"
                            }

                            if (label != '') {
                                popup.style.left = (pixel.x) + 'px';
                                popup.style.top = (pixel.y) + 'px';
                                popup.style.margin = '0px';
                                popup.innerHTML = '' + label + '';
                            }

                            // JOSM editor link
                            var position = '19' + '/' + latlng.lat + '/' + latlng.lng;
                            var josmUrl = 'http://www.openstreetmap.org/edit?editor=remote#map='+position;

                            popup.appendChild(createEditLinkElement( url, 'iD', 'Edit with iD ➹') );
                            popup.appendChild(createEditLinkElement( mapzenTileURL(), 'rawTile', 'View tile data ➹') );
                            //popup.appendChild(createEditLinkElement( josmUrl, 'JOSM', 'Edit with JOSM ➹') );
                            popup.style.visibility = 'visible';
                        }
                    });
                }
                timer = null;
            }, 200 );
        });
    }

    function inIframe () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    // Add map
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            if (!inIframe()) {
                map.scrollWheelZoom.enable();
                addGUI();
                initFeatureSelection();
            }

            var camera = scene.config.cameras[scene.getActiveCamera()];
            // if a camera position is set in the scene file, use that
            if (defaultpos && typeof camera.position != "undefined") {
                map_start_location = [camera.position[1], camera.position[0], camera.position[2]]
            }
            map.setView([map_start_location[0], map_start_location[1]], map_start_location[2]);
        });

        // Set initial language on scene load
        layer.scene.subscribe({
            load: function (msg) {
                msg.config.global.ux_language = query.language;
            }
        });

        layer.addTo(map);
    });

    return map;
}());
<|endoftext|>


<commit_before>var app = {};

// $(function() { //when DOM is ready...
	app.users = new UserCollection([

		{username:'Jennifer'},
		{username:'Jason'},
		{username:'Ty'}
]);

var LoginModel = Backbone.Model.extend({
	// // defaults : {"username" : ""},
	// replace : function(usr){
	// this.set("username", usr);
	// }
});

//LOGIN VIEW---------------------------------------------------------

var LoginView = Backbone.View.extend({
	render : function (){
		console.log("render login");
		var login = '<button id="login" type="submit">Login</button>';
		var usrBtn = '<button id="newName">Add Name</button>';
		var input = '
<input type="text" id="userField" value="Add New User Name">';
		var headline = '
To Do List
';
		var headline2 = '
Please log in.
';
		var nametag = "
name:
";
		var selector = this.userSelector();
		this.$el.html("

" + headline + headline2 + nametag + selector + login + input + usrBtn + "
");
		// this.el.append(this.$el);
	},
    userSelector: function(){
		var users = [];
		content = "";

		for (var i = 0;i < app.users.length; i++){
			users.push(app.users.models[i].attributes.username);
			content+=("<option>"+users[i]+"</option>");

      	}
		content = "<select id='selectDropdown'>"+content+"</select>";
		return content;
	},

	addNewUser: function(){
		var newUser = $("#userField").val();
		app.users.add({username: newUser});
		this.render();
	},

	events: {
		"click #login" 		: "userLogin",
		"click #newName"	: "addNewUser"
	},

	userLogin : function(){
		$("#login-area").hide();
		var selectedUser = $("#selectDropdown").val();
		var userModel = app.users.where({username: selectedUser})[0];
		 console.log(userModel);
		userView = new UserView({model: userModel});
		userView.render();
		//this.model.get(username)
		}

 });

	var UserModel = Backbone.Model.extend({
	    defaults : {"value" : ""},
	    replace : function (str) {
	      this.set("value", str);
	    }
	});

// ----------------------------------------------------------------
//USERVIEW---------------------------------------------------------
// ----------------------------------------------------------------

var UserView = Backbone.View.extend({
	render: function (){
	console.log(this.model);

	var greeting= "
 Hello, "+ this.model.get('username') +" !!
";
	var createBtn = '<button id="createTask">Create New Task</button>';
	var btn = '

<button id="logout">Logout</button>';
	var taskBtn = '

<button id="addTask" type="submit">Add Task</button>';
	var input = '
<textarea type="text" id="taskDescription" style="display: none" value="Enter Task Description"></textarea>';
	this.$el.html("
"+greeting+ createBtn + input + taskBtn +btn +"
");
	$('#app').append(this.el);

	console.log('user works!',this.el);

	},

	initialize: function(){
		this.model.on("change", this.render, this);
	},

	events: {
		"click #createTask" : "addDescription"

	},
	addDescription : function(){
        $("#taskDescription").show();

		// this.taskView.add({});
	}

});

var TaskModel = Backbone.Model.extend({
    defaults : {"value" : ""},
    replace : function (str) {
      this.set("value", str);
    }
});

var content;
var loginView;
var userView;
var taskView;
var taskCollection;
var testModel;
var taskCollectionView;

$(document).ready( function () {
	console.log("ready");

// userModel = new UserModel({title:'Make this page work!',
//                            description: 'Fix all the code!',
//                            creator: 'Jennifer'});

loginView = new LoginView({el:"#app"});
loginView.render();

userModel = new UserModel({title:'Make this page work!',
                           description: 'Fix all the code!',
                           creator: app.users});

// userView.render();

// userModel = new UserModel({creator: 'Jennifer'});
// userView = new UserView({el: "#app"})

// taskCollection = new TaskCollection();
// taskView = new TaskView({model: testModel});
// taskCollectionView = new TaskCollectionView({ collection : taskCollection});
// taskCollectionView.render();
// taskCollection.add(testModel)

// taskView.render();

// $("#app").append(userView.$el);

});

// 	 app.tasks = new TaskCollection([
// 		// test data here
// 	]);

// 	app.gui = new GUI(app.users,
// 						app.tasks,
// 						'#app');// selector of main div
// });
<commit_msg>Create new tasks button functionality<commit_after>var app = {};

// $(function() { //when DOM is ready...
	app.users = new UserCollection([

		{username:'Jennifer'},
		{username:'Jason'},
		{username:'Ty'}
]);

var LoginModel = Backbone.Model.extend({
	// // defaults : {"username" : ""},
	// replace : function(usr){
	// this.set("username", usr);
	// }
});

//LOGIN VIEW---------------------------------------------------------

var LoginView = Backbone.View.extend({
	render : function (){
		console.log("render login");
		var login = '<button id="login" type="submit">Login</button>';
		var usrBtn = '<button id="newName">Add Name</button>';
		var input = '
<input type="text" id="userField" placeholder="Add New User Name">';
		var headline = '
To Do List
';
		var headline2 = '
Please log in.
';
		var nametag = "
name:
";
		var selector = this.userSelector();
		this.$el.html("

" + headline + headline2 + nametag + selector + login + input + usrBtn + "
");
		// this.el.append(this.$el);
	},
    userSelector: function(){
		var users = [];
		content = "";

		for (var i = 0;i < app.users.length; i++){
			users.push(app.users.models[i].attributes.username);
			content+=("<option>"+users[i]+"</option>");

      	}
		content = "<select id='selectDropdown'>"+content+"</select>";
		return content;
	},

	addNewUser: function(){
		var newUser = $("#userField").val();
		app.users.add({username: newUser});
		this.render();
	},

	events: {
		"click #login" 		: "userLogin",
		"click #newName"	: "addNewUser"
	},

	userLogin : function(){
		$("#login-area").hide();
		var selectedUser = $("#selectDropdown").val();
		var userModel = app.users.where({username: selectedUser})[0];
		 console.log(userModel);
		userView = new UserView({model: userModel});
		userView.render();
		//this.model.get(username)
		}

 });

	var UserModel = Backbone.Model.extend({
	    defaults : {"value" : ""},
	    replace : function (str) {
	      this.set("value", str);
	    }
	});

// ----------------------------------------------------------------
//USERVIEW---------------------------------------------------------
// ----------------------------------------------------------------

var UserView = Backbone.View.extend({
	render: function (){
	var myTasks = [];
	console.log(this.model);

	var greeting= "
 Hello, "+ this.model.get('username') +" !!
";
	var currentTasks = "

 Here are your current tasks: "+ myTasks + "

"
	var createBtn = '<button id="createTask">Create New Task</button>';
	var logoutBtn = '

<button id="logout">Logout</button>';
	var taskBtn = '

<button id="addTask" type="submit">Add Task</button>';
	var input = '
<textarea type="text" id="taskDescription" style="display: none" value="Enter Task Description"></textarea>';
	this.$el.html("
"+greeting+ currentTasks +createBtn + input + taskBtn + logoutBtn +"
");
	$('#app').append(this.el);

	console.log('user works!',this.el);

	},

	initialize: function(){
		this.model.on("change", this.render, this);
	},

	events: {
		"click #createTask" : "addDescription",
		"click #addTask" : "taskAdder",
		"click #logout" : "logoutUser",

	},
	addDescription : function(){
        $("#taskDescription").show();
		// this.taskView.add({});
	},

	// taskAdder : function(){
 //    	enteredTasks = "<select id='selectDropdown'>"+myTasks+"</select>";
	// 	return content;
	// },

		// taskCollectionView = new TaskCollectionView({ collection : taskCollection});
      // taskView = new TaskView({model: taskModel});

    logoutUser : function(){
    	$("#userview").hide();
    	$("#login-area").show();
    }

});

var TaskModel = Backbone.Model.extend({
    defaults : {"value" : ""},
    replace : function (str) {
      this.set("value", str);
    }
});

var TaskCollection = Backbone.Collection.extend({
    model : TaskModel,
    initialize: function () {

    }
});

var TaskCollectionView = Backbone.View.extend({
    render : function () {
        var btn = '<button id="addbutton">Add Text</button>';
        var div = '

';
        this.$el.html(div + btn);
    },
    initialize : function () {
        this.listenTo(this.collection, 'add', this.addOne);
    },
    events : {
        "click #addbutton" : "addCollection"
    },

    addOne : function (txt) {
        txt.set("value","Enter something here...");
        var view = new TaskView({model : txt});
        view.render();
        this.$("#taskDescription").append(view.$el);
    }
    // addCollection : function () {
    //     this.collection.create({id : idCount});
    //     idCount = idCount+1;
    // }
});

var content;
var loginView;
var userView;
var taskView;
var taskCollection;
var taskModel;
var taskCollectionView;

$(document).ready( function () {
	console.log("ready");

loginView = new LoginView({el:"#app"});
loginView.render();

userModel = new UserModel({title:'Make this page work!',
                           description: 'Fix all the code!',
                           creator: app.users});

// userView.render();

// userModel = new UserModel({creator: 'Jennifer'});
// userView = new UserView({el: "#app"})

taskCollection = new TaskCollection();
taskCollectionView = new TaskCollectionView({ collection : taskCollection});
taskCollectionView.render();
taskCollection.add(taskModel)

// taskView.render();

// $("#app").append(userView.$el);

});

// 	 app.tasks = new TaskCollection([
// 		// test data here
// 	]);

// 	app.gui = new GUI(app.users,
// 						app.tasks,
// 						'#app');// selector of main div
// });
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global Tangram, gui */

var picking = false;
map = (function () {
// (function () {
    // 'use strict';

    var map_start_location = [40.7238, -73.9881, 14]; // NYC

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
    keytext = "kind";
    window.keytext = keytext;
    valuetext = "major_road";
    window.valuetext = valuetext;

    if (url_hash.length >= 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    if (url_hash.length == 5) {
        keytext = unescape(url_hash[3]);
        valuetext = unescape(url_hash[4]);
    }

    // Put current state on URL
    window.updateURL = function() {
        // if (picking) return;
        // console.log(window.location.hash);
        var map_latlng = map.getCenter();
        var url_options = [map.getZoom().toFixed(1), map_latlng.lat.toFixed(4), map_latlng.lng.toFixed(4), escape(keytext), escape(valuetext)];
        window.location.hash = url_options.join('/');
    }

    // function updateHash () {
    //     newhash = hash.lastHash + "/"+scene.config.layers["roads"].properties.key_text + "/"+scene.config.layers["roads"].properties.value_text;
    //     if (window.location != newhash) window.location = newhash
    // }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    // setView expects format ([lat, long], zoom)
    map.setView(map_start_location.slice(0, 3), map_start_location[2]);
    map.on('moveend', updateURL);

    // var hash = new L.Hash(map);

    function updateKey(value) {
        keytext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.key_text = value;
        }
        scene.rebuild();
        updateURL();
    }

    function updateValue(value) {
        valuetext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.value_text = value;
        }
        scene.rebuild();
        updateURL();
    }

    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true, hideable: false, width: 300 });
    function addGUI () {

        gui.domElement.parentNode.style.zIndex = 2000; // make sure GUI is on top of map
        window.gui = gui;

        gui.keyinput = keytext;
        var keyinput = gui.add(gui, 'keyinput').name("key").listen();

        gui.valueinput = valuetext;
        var valueinput = gui.add(gui, 'valueinput').name("value").listen();

        updateKey(keytext);
        updateValue(valuetext);
        keyinput.onChange(function(value) {
            updateKey(value);
        });
        valueinput.onChange(function(value) {
            updateValue(value);
        });
        //select input text when you click on it
        keyinput.domElement.id = "keyfilter";
        keyinput.domElement.onclick = function() { this.getElementsByTagName('input')[0].select(); };
        valueinput.domElement.id = "valuefilter";
        valueinput.domElement.onclick = function() { this.getElementsByTagName('input')[0].select(); };
    }

    // var scene.picking = false;
    // Feature selection
    function initFeatureSelection () {
        // Selection info shown on hover
        var selection_info = document.createElement('div');
        selection_info.setAttribute('class', 'label');
        selection_info.style.display = 'block';
        selection_info.style.zindex = 1000;

        // Show selected feature on hover
        map.getContainer().addEventListener('mousemove', function (event) {
            if (picking) return;
            var pixel = { x: event.clientX, y: event.clientY };

            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection) {
                    return;
                }
                var feature = selection.feature;
                if (feature != null) {
                    // console.log("selection map: " + JSON.stringify(feature));

                    var label = '';
                    if (feature.properties != null) {
                        // console.log(feature.properties);
                        var obj = JSON.parse(JSON.stringify(feature.properties));
                        label = "";
                        for (x in feature.properties) {
                            val = feature.properties[x];
                            label += ""+x+" : "+val+"
";
                        }
                    }

                    if (label != '') {
                        selection_info.style.left = (pixel.x + 5) + 'px';
                        selection_info.style.top = (pixel.y + 15) + 'px';
                        selection_info.innerHTML = '' + label + '';
                        map.getContainer().appendChild(selection_info);
                    }
                    else if (selection_info.parentNode != null) {
                        selection_info.parentNode.removeChild(selection_info);
                    }
                }
                else if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            });

            // Don't show labels while panning
            if (scene.panning == true) {
                if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            }
        });

        // capture popup clicks
        // scene.labelLine.addEventListener('click', function (event) {
        //     return true;
        // });

        // toggle popup picking state
        map.getContainer().addEventListener('click', function (event) {
            picking = !picking;
        });
        // toggle popup picking state
        map.getContainer().addEventListener('drag', function (event) {
            picking = false;
        });
    }

    window.setValuesFromSpan = function(span) {
        keytext = span.getAttribute("key");
        valuetext = span.getAttribute("value");
        gui.keytext=span.getAttribute("key");
        gui.keyinput=span.getAttribute("key");
        gui.valuetext=span.getAttribute("value");
        gui.valueinput=span.getAttribute("value");
        updateKey(keytext);
        updateValue(valuetext);
        // scene.rebuildGeometry();
        // scene.requestRedraw();
        updateURL();
    }

    // Add map
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            addGUI();
            var keyfilter = document.getElementById('keyfilter').getElementsByTagName('input')[0];
            if (keyfilter.value.length == 0) keyfilter.focus();
            else keyfilter.select();

            initFeatureSelection();
        });
        layer.addTo(map);
    });

    return map;

}());

<commit_msg>cleanup<commit_after>/*jslint browser: true*/
/*global Tangram, gui */

var picking = false;
map = (function () {
// (function () {
    // 'use strict';

    var map_start_location = [40.7238, -73.9881, 14]; // NYC

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
    keytext = "kind";
    window.keytext = keytext;
    valuetext = "major_road";
    window.valuetext = valuetext;

    if (url_hash.length >= 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    if (url_hash.length == 5) {
        keytext = unescape(url_hash[3]);
        valuetext = unescape(url_hash[4]);
    }

    // Put current state on URL
    window.updateURL = function() {
        var map_latlng = map.getCenter();
        var url_options = [map.getZoom().toFixed(1), map_latlng.lat.toFixed(4), map_latlng.lng.toFixed(4), escape(keytext), escape(valuetext)];
        window.location.hash = url_options.join('/');
    }

    /*** Map ***/

    var map = L.map('map',
        {"keyboardZoomOffset" : .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    // setView expects format ([lat, long], zoom)
    map.setView(map_start_location.slice(0, 3), map_start_location[2]);
    map.on('moveend', updateURL);

    function updateKey(value) {
        keytext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.key_text = value;
        }
        scene.rebuild();
        updateURL();
    }

    function updateValue(value) {
        valuetext = value;

        for (layer in scene.config.layers) {
            if (layer == "earth") continue;
            scene.config.layers[layer].properties.value_text = value;
        }
        scene.rebuild();
        updateURL();
    }

    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true, hideable: false, width: 300 });
    function addGUI () {

        gui.domElement.parentNode.style.zIndex = 2000; // make sure GUI is on top of map
        window.gui = gui;

        gui.keyinput = keytext;
        var keyinput = gui.add(gui, 'keyinput').name("key").listen();

        gui.valueinput = valuetext;
        var valueinput = gui.add(gui, 'valueinput').name("value").listen();

        updateKey(keytext);
        updateValue(valuetext);
        keyinput.onChange(function(value) {
            updateKey(value);
        });
        valueinput.onChange(function(value) {
            updateValue(value);
        });
        //select input text when you click on it
        keyinput.domElement.id = "keyfilter";
        keyinput.domElement.onclick = function() { this.getElementsByTagName('input')[0].select(); };
        valueinput.domElement.id = "valuefilter";
        valueinput.domElement.onclick = function() { this.getElementsByTagName('input')[0].select(); };
    }

    // Feature selection
    function initFeatureSelection () {
        // Selection info shown on hover
        var selection_info = document.createElement('div');
        selection_info.setAttribute('class', 'label');
        selection_info.style.display = 'block';
        selection_info.style.zindex = 1000;

        // Show selected feature on hover
        map.getContainer().addEventListener('mousemove', function (event) {
            if (picking) return;
            var pixel = { x: event.clientX, y: event.clientY };

            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection) {
                    return;
                }
                var feature = selection.feature;
                if (feature != null) {
                    // console.log("selection map: " + JSON.stringify(feature));

                    var label = '';
                    if (feature.properties != null) {
                        // console.log(feature.properties);
                        var obj = JSON.parse(JSON.stringify(feature.properties));
                        label = "";
                        for (x in feature.properties) {
                            val = feature.properties[x];
                            label += ""+x+" : "+val+"
";
                        }
                    }

                    if (label != '') {
                        selection_info.style.left = (pixel.x + 5) + 'px';
                        selection_info.style.top = (pixel.y + 15) + 'px';
                        selection_info.innerHTML = '' + label + '';
                        map.getContainer().appendChild(selection_info);
                    }
                    else if (selection_info.parentNode != null) {
                        selection_info.parentNode.removeChild(selection_info);
                    }
                }
                else if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            });

            // Don't show labels while panning
            if (scene.panning == true) {
                if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            }
        });

        // toggle popup picking state
        map.getContainer().addEventListener('click', function (event) {
            picking = !picking;
        });
        // toggle popup picking state
        map.getContainer().addEventListener('drag', function (event) {
            picking = false;
        });
    }

    window.setValuesFromSpan = function(span) {
        keytext = span.getAttribute("key");
        valuetext = span.getAttribute("value");
        gui.keytext=span.getAttribute("key");
        gui.keyinput=span.getAttribute("key");
        gui.valuetext=span.getAttribute("value");
        gui.valueinput=span.getAttribute("value");
        updateKey(keytext);
        updateValue(valuetext);
        updateURL();
    }

    // Add map
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            addGUI();
            var keyfilter = document.getElementById('keyfilter').getElementsByTagName('input')[0];
            if (keyfilter.value.length == 0) keyfilter.focus();
            else keyfilter.select();

            initFeatureSelection();
        });
        layer.addTo(map);
    });

    return map;

}());

<|endoftext|>


<commit_before>/* jshint unused:false */
(function() {
    // the baseUrl is relavant in source version and while running unit tests.
    // the`typeof` is for when this file is passed as a require argument to the build system
    // since it runs on node, it doesn't have a window object. The basePath for the build system
    // is defined in build.profile.js
    var config = {
        baseUrl: (
            typeof window !== 'undefined' &&
            window.dojoConfig &&
            window.dojoConfig.isJasmineTestRunner
        ) ? '/src' : './',
        packages: [
            'agrc',
            'app',
            'dijit',
            'dojo',
            'dojox',
            'esri',
            'ijit', {
                name: 'spin',
                location: 'spinjs',
                main: 'spin'
            }, {
                name: 'ladda',
                location: 'ladda-bootstrap',
                main: 'dist/ladda'
            }, {
                name: 'jquery',
                location: 'jquery/dist',
                main: 'jquery'
            }, {
                name: 'bootstrap',
                location: 'bootstrap',
                main: 'dist/js/bootstrap'
            }, {
                name: 'mustache',
                location: 'mustache',
                main: 'mustache'
            }
        ],
        map:{
            'app/AttributeEditor':{
                'esri/dijit/AttributeInspector':
                'app/patch/AttributeInspector'
            }
        }
    };
    require(config, [
        'jquery',

        'app/App',

        'dojo/_base/lang',
        'dojo/dom',

        'esri/config',

        'dojo/domReady!'
    ], function(
        $,

        App,

        lang,
        dom,

        esriConfig
    ) {
        // force api to use CORS on mapserv thus removing the test request on app load
        // e.g. http://mapserv.utah.gov/ArcGIS/rest/info?f=json
        esriConfig.defaults.io.corsEnabledServers.push('mapserv.utah.gov');

        // // don't initialize if this is the jasmine test runner
        if (!lang.getObject('dojoConfig.isJasmineTestRunner')) {
            var app = new App({}, dom.byId('appDiv'));
            app.startup();
        }
    });
})();<commit_msg>update packages<commit_after>((function () {
    var config = {
        baseUrl: (
            typeof window !== 'undefined' &&
            window.dojoConfig &&
            window.dojoConfig.isJasmineTestRunner
        ) ? '/src' : './',
        packages: [
            'agrc',
            'app',
            'dgauges',
            'dgrid',
            'dijit',
            'dojo',
            'dojox',
            'esri',
            'ijit',
            'layer-selector',
            'moment',
            'put-selector',
            'xstyle',
            {
                name: 'highcharts',
                location: './highcharts-release',
                main: 'highcharts'
            },{
                name: 'bootstrap',
                location: './bootstrap',
                main: 'dist/js/bootstrap'
            },{
                name: 'jquery',
                location: './jquery/dist',
                main: 'jquery'
            },{
                name: 'ladda',
                location: './ladda-bootstrap',
                main: 'dist/ladda'
            },{
                name: 'mustache',
                location: './mustache',
                main: 'mustache'
            },{
                name: 'spin',
                location: './spinjs',
                main: 'spin'
            },{
                name: 'stubmodule',
                location: './stubmodule',
                main: 'src/stub-module'
            }
        ],
        map: {
            'app/AttributeEditor': {
                'esri/dijit/AttributeInspector':
                'app/patch/AttributeInspector'
            }
        }
    };
    require(config, ['dojo/parser', 'jquery', 'dojo/domReady!'], function (parser) {
        parser.parse();
    });
})());
<|endoftext|>