<commit_before>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feed: ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  feeds: {
    // Linjeforeninger
    'berg': {
      'feed': 'http://bergstud.no/feed/',
      'logo': 'img/logos/berg.png',
      'image': 'img/placeholders/berg.png',
    },
    'delta': {
      'feed': 'http://org.ntnu.no/delta/wp/?feed=rss2',
      'logo': 'img/logos/delta.png',
      'image': 'img/placeholders/delta.png',
    },
    'emil': {
      'feed': 'http://emilweb.no/feed/',
      'logo': 'img/logos/emil.png',
      'image': 'img/placeholders/emil.png',
    },
    'online': {
      'feed': 'https://online.ntnu.no/feeds/news/',
      'logo': 'img/logos/online.png',
      'image': 'img/placeholders/online.png',
    },
    'nabla': {
      'feed': 'http://nabla.no/feed/',
      'logo': 'img/logos/nabla.png',
      'image': 'img/placeholders/nabla.png',
    },
    'spanskrøret': {
      'feed': 'http://spanskroret.no/feed/',
      'logo': 'img/logos/spanskrøret.png',
      'image': 'img/placeholders/spanskrøret.png',
    },
    // Medier
    'dusken': {
      'feed': 'http://dusken.no/feed/',
      'logo': 'img/logos/dusken.png',
      'image': 'img/placeholders/dusken.png',
    },
    'universitetsavisa': {
      'feed': 'http://www.universitetsavisa.no/?service=rss',
      'logo': 'img/logos/universitetsavisa.png',
      'image': 'img/placeholders/universitetsavisa.png',
    },
    // Store studentorganisasjoner
    'samfundet': {
      'feed': 'http://www.samfundet.no/arrangement/rss',
      'logo': 'img/logos/samfundet.png',
      'image': 'img/placeholders/samfundet.png',
    },
    // Studentdemokrati
    'studenttinget': {
      'feed': 'http://www.studenttinget.no/feed/',
      'logo': 'img/logos/studenttinget.png',
      'image': 'img/placeholders/studenttinget.png',
    },
    'velferdstinget': {
      'feed': 'http://www.velferdstinget.no/feed/rss/',
      'logo': 'img/logos/velferdstinget.png',
      'image': 'img/placeholders/velferdstinget.png',
    },
    // NTNU
    'ntnu': {
      'feed': 'https://www.retriever-info.com/feed/2002900/generell_arkiv166/index.xml',
      'logo': 'img/logos/ntnu.png',
      'image': 'img/placeholders/ntnu.png',
    },
    'rektoratet': {
      'feed': 'http://www.ntnu.no/blogger/rektoratet/feed/',
      'logo': 'img/logos/rektoratet.png',
      'image': 'img/placeholders/rektoratet.png',
    },
  },

  // Get is called by background.html periodically, with News.unreadCount as
  // callback. Fetchfeed is also called by popup.html when requested, but
  // without the callback as we already know the amount of unread posts.
  get: function(feedName, limit, callback) {
    if (this.feeds[feedName] === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (!isNumber(limit) || (limit < 1 && 20 < limit)) {
      if (this.debug) console.log('ERROR:', this.msgNewsLimit);
      callback(this.msgNewsLimit);
      return;
    }
    if (callback == undefined) {
      console.log('ERROR:', this.msgCallbackRequired);
      callback(this.msgCallbackRequired);
      return;
    }

    feedName = feedName.toLowerCase();
    var rssUrl = this.feeds[feedName].url;

    var self = this;
    $.ajax({
      url: rssUrl, // permission to use url granted in manifest.json
      dataType: 'xml',
      success: function(xml) {
        // ls.lastResponseData = xmlstring;
        self.parseFeed(xml, feedName, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, feedName);
        callback(self.msgConnectionError);
      },
    });
  },

  parseFeed: function(xml, feedName, limit, callback) {
    var items = [];
    var self = this;
    var count = 0;
    $(xml).find('item').each( function() {
      if (count++ < limit) {
        var item = self.parseItem(this, feedName);
        items.push(item);
      }
    });
    callback(items);
  },

  parseItem: function(item, feedName) {
    var post = {};
    // The popular fields
    post.title = $(item).find("title").text();
    post.link = $(item).find("link").text();
    post.description = $(item).find("description").text();
    // Less used fields
    post.creator = $(item).find("dc:creator").text();
    post.date = $(item).find("pubDate").text().substr(5, 11);
    // Locally stored
    post.image = this.feeds[feedName].image;
    post.feed = feedName;

    // Check for alternative links in description
    post.altLink = this.checkForAltLink(post.description);

    // Shorten 'bedriftspresentasjon' to 'bedpres'
    post.title = post.title.replace(/edrift(s)?presentasjon/gi, 'edpres');
    post.description = post.description.replace(/edrift(s)?presentasjon/gi, 'edpres');

    // Remove excessive whitespace...
    if (post.description.match(/<\w+>|<\/\w+>/g) !== null) { // Check if string contains markup
      // ...and ludicrous formatting (HTML)
      post.description = $.trim($(post.description).text());
    }
    else {
      post.description = post.description.trim();
    }

    // In case browser does not grok tags with colons, stupid browser
    if (post.creator == '') {
      var tag = ("dc\\:creator").replace( /.*(\:)(.*)/, "$2" );
      $(item).find(tag).each(function(){
        post.creator = $(this).text().trim();
      });
    }
    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = feedName.capitalize();
    }
    // Abbreviate long creator names
    post.creator = this.abbreviateName(post.creator);

    // In case pubDate didn't exist, set to null
    if (post.date == '') {
      post.date = null;
    }

    // title + description must not exceed 5 lines
    var line = 50; // conservative estimation
    var desclength = line * 3;
    // double line titles will shorten the description by 1 line
    if (line <= post.title.length)
      desclength -= line;
    // shorten description according to desclength
    if (desclength < post.description.length)
      post.description = post.description.substr(0, desclength) + '...';

    return post;
  },

  unreadCount: function(items) {
    var unreadCount = 0;
    var linkList = []; // New || Updated

    // Count feed items
    $.each items, (index, item) ->

      var link = item.link;

      // Counting...
      if (link != localStorage.newsMostRecentRead) {
        unreadCount++;
        linkList.push(link); // New || Updated
        // Send a desktop notification about the first unread item
        if (unreadCount == 1) {
          if (localStorage.newsLastNotified != link) {
            this.showNotification(item);
          }
          localStorage.newsMostRecentUnread = link;
        }
      }
      // All counted :)
      else {
        if (unreadCount == 0) {
          if (this.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (unreadCount >= this.maxNewsAmount) {
          if (this.debug) console.log(this.maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(this.maxNewsAmount + '+');
        }
        else {
          if (this.debug) console.log('1-' + (this.maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unreadCount));
        }
        localStorage.unreadCount = unreadCount;
        localStorage.mostRecentLinkList = JSON.stringify(linkList); // New || Updated
        return false;
      }

      // Stop counting if unread number is greater than 9
      if (index > (this.maxNewsAmount - 1)) { // Remember index is counting 0
        if (this.debug) console.log(this.maxNewsAmount + '+ unread posts (stopped counting)');
        Browser.setBadgeText(this.maxNewsAmount + '+');
        localStorage.unreadCount = this.maxNewsAmount;
        // New or updated?
        localStorage.mostRecentLinkList = JSON.stringify(linkList); // New || Updated
        return false;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      var post = this.parseItem(item);
      // Remember this
      localStorage.newsLastNotified = post.link;
      // Get content
      localStorage.notificationTitle = post.title;
      localStorage.notificationLink = post.link;
      localStorage.notificationDescription = post.description;
      localStorage.notificationCreator = post.creator;
      localStorage.notificationImage = post.image;
      localStorage.notificationFeedName = post.feedName;
      // Show desktop notification
      Browser.createNotification('notification.html');
    }
  },

  checkForAltLink: function(description) {
    // Looking for alternative link, find the first and best full link
    var altLink = description.match(/href="(http.*)"/);
    if (altLink != null) {
      if (typeof altLink[1] == 'string') {
        return altLink[1];
      }
    }
    return null;
  },

  abbreviateName: function(oldName) {
    if (oldName != undefined) {
      // Abbreviate middle names if name is long
      if (18 < oldName.length) {
        var pieces = oldName.split(' ');
        if (2 < pieces.length) {
          // Add first name
          var newName = pieces[0];
          // Add one letter per middle name
          for (var i = 1; i < pieces.length - 1; i++)
            newName += ' ' + pieces[i].charAt(0).toUpperCase() + '.';
          // Add last name
          newName += ' ' + pieces[pieces.length-1];
          return newName;
        }
      }
    }
    else {
      if (this.debug) console.log('ERROR: cannot abbreviate an undefined name');
    }
    return oldName;
  },

  // Organization specific functions

  online_getImage: function(link, callback) {
    var id = link.split('/')[4]; // id is stored in the link
    var image = 'undefined';
    var api = 'https://online.ntnu.no/api/f5be90e5ec1d2d454ae9/news_image_by_id/';
    $.getJSON(api + id, function(json) {
      if (json['online_news_image']) {
        image = json['online_news_image']['0']['image'];
        callback(link, image);
      }
      else {
        image = this.images['online'].image;
        if (this.debug) console.log('ERROR: no image exists for id: ' + id);
        callback(link, image);
      }
    })
    .error(function() {
      image = this.images['online'].image;
      if (this.debug) console.log('ERROR: couldn\'t connect API to get image links, returning default image');
      callback(link, image);
    });
  },

}
<commit_msg>news: tweaking, fixing and smoothing things over<commit_after>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feed: ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  feeds: {
    // Linjeforeninger
    'berg': {
      'feed': 'http://bergstud.no/feed/',
      'logo': 'img/logos/berg.png',
      'image': 'img/placeholders/berg.png',
    },
    'delta': {
      'feed': 'http://org.ntnu.no/delta/wp/?feed=rss2',
      'logo': 'img/logos/delta.png',
      'image': 'img/placeholders/delta.png',
    },
    'emil': {
      'feed': 'http://emilweb.no/feed/',
      'logo': 'img/logos/emil.png',
      'image': 'img/placeholders/emil.png',
    },
    'online': {
      'feed': 'https://online.ntnu.no/feeds/news/',
      'logo': 'img/logos/online.png',
      'image': 'img/placeholders/online.png',
    },
    'nabla': {
      'feed': 'http://nabla.no/feed/',
      'logo': 'img/logos/nabla.png',
      'image': 'img/placeholders/nabla.png',
    },
    'spanskrøret': {
      'feed': 'http://spanskroret.no/feed/',
      'logo': 'img/logos/spanskrøret.png',
      'image': 'img/placeholders/spanskrøret.png',
    },
    // Medier
    'dusken': {
      'feed': 'http://dusken.no/feed/',
      'logo': 'img/logos/dusken.png',
      'image': 'img/placeholders/dusken.png',
    },
    'universitetsavisa': {
      'feed': 'http://www.universitetsavisa.no/?service=rss',
      'logo': 'img/logos/universitetsavisa.png',
      'image': 'img/placeholders/universitetsavisa.png',
    },
    // Store studentorganisasjoner
    'samfundet': {
      'feed': 'http://www.samfundet.no/arrangement/rss',
      'logo': 'img/logos/samfundet.png',
      'image': 'img/placeholders/samfundet.png',
    },
    // Studentdemokrati
    'studenttinget': {
      'feed': 'http://www.studenttinget.no/feed/',
      'logo': 'img/logos/studenttinget.png',
      'image': 'img/placeholders/studenttinget.png',
    },
    'velferdstinget': {
      'feed': 'http://www.velferdstinget.no/feed/rss/',
      'logo': 'img/logos/velferdstinget.png',
      'image': 'img/placeholders/velferdstinget.png',
    },
    // NTNU
    'ntnu': {
      'feed': 'https://www.retriever-info.com/feed/2002900/generell_arkiv166/index.xml',
      'logo': 'img/logos/ntnu.png',
      'image': 'img/placeholders/ntnu.png',
    },
    'rektoratet': {
      'feed': 'http://www.ntnu.no/blogger/rektoratet/feed/',
      'logo': 'img/logos/rektoratet.png',
      'image': 'img/placeholders/rektoratet.png',
    },
  },

  // Get is called by background.html periodically, with News.unreadCount as
  // callback. Fetchfeed is also called by popup.html when requested, but
  // without the callback as we already know the amount of unread posts.
  get: function(feedName, limit, callback) {
    if (this.feeds[feedName] === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (!isNumber(limit) || (limit < 1 && 20 < limit)) {
      if (this.debug) console.log('ERROR:', this.msgNewsLimit);
      callback(this.msgNewsLimit);
      return;
    }
    if (callback == undefined) {
      console.log('ERROR:', this.msgCallbackRequired);
      callback(this.msgCallbackRequired);
      return;
    }

    feedName = feedName.toLowerCase();
    var rssUrl = this.feeds[feedName].feed;

    var self = this;
    $.ajax({
      url: rssUrl, // permission to use url granted in manifest.json
      dataType: 'xml',
      success: function(xml) {
        // ls.lastResponseData = xmlstring;
        self.parseFeed(xml, feedName, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, feedName);
        callback(self.msgConnectionError);
      },
    });
  },

  parseFeed: function(xml, feedName, limit, callback) {
    var items = [];
    var self = this;
    var count = 0;
    $(xml).find('item').each( function() {
      if (count++ < limit) {
        var item = self.parseItem(this, feedName);
        items.push(item);
      }
    });
    callback(items);
  },

  parseItem: function(item, feedName) {
    var post = {};
    // The popular fields
    post.title = $(item).find("title").text();
    post.link = $(item).find("link").text();
    post.description = $(item).find("description").text();
    // Less used fields
    post.creator = $(item).find("dc:creator").text();
    post.date = $(item).find("pubDate").text().substr(5, 11);
    // Locally stored
    post.image = this.feeds[feedName]['image'];
    post.feedName = feedName;

    // Check for alternative links in description
    post.altLink = this.checkForAltLink(post.description);

    // Shorten 'bedriftspresentasjon' to 'bedpres'
    post.title = post.title.replace(/edrift(s)?presentasjon/gi, 'edpres');
    post.description = post.description.replace(/edrift(s)?presentasjon/gi, 'edpres');

    // Remove excessive whitespace...
    if (post.description.match(/<\w+>|<\/\w+>/g) !== null) { // Check if string contains markup
      // ...and ludicrous formatting (HTML)
      post.description = $.trim($(post.description).text());
    }
    else {
      post.description = post.description.trim();
    }

    // In case browser does not grok tags with colons, stupid browser
    if (post.creator == '') {
      var tag = ("dc\\:creator").replace( /.*(\:)(.*)/, "$2" );
      $(item).find(tag).each(function(){
        post.creator = $(this).text().trim();
      });
    }
    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = feedName.capitalize();
    }
    // Abbreviate long creator names
    post.creator = this.abbreviateName(post.creator);

    // In case pubDate didn't exist, set to null
    if (post.date == '') {
      post.date = null;
    }

    // title + description must not exceed 5 lines
    var line = 50; // conservative estimation
    var desclength = line * 3;
    // double line titles will shorten the description by 1 line
    if (line <= post.title.length)
      desclength -= line;
    // shorten description according to desclength
    if (desclength < post.description.length)
      post.description = post.description.substr(0, desclength) + '...';

    return post;
  },

  unreadCount: function(items) {
    var unreadCount = 0;
    var linkList = []; // New || Updated

    // Count feed items
    var self = this;
    items.forEach(function(item, index) {

      var link = item.link;

      // Counting...
      if (link != localStorage.newsMostRecentRead) {
        unreadCount++;
        linkList.push(link); // New || Updated
        // Send a desktop notification about the first unread item
        if (unreadCount == 1) {
          if (localStorage.newsLastNotified != link) {
            self.showNotification(item);
          }
          localStorage.newsMostRecentUnread = link;
        }
      }
      // All counted :)
      else {
        if (unreadCount == 0) {
          if (this.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (unreadCount >= this.maxNewsAmount) {
          if (this.debug) console.log(this.maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(this.maxNewsAmount + '+');
        }
        else {
          if (this.debug) console.log('1-' + (this.maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unreadCount));
        }
        localStorage.unreadCount = unreadCount;
        localStorage.mostRecentLinkList = JSON.stringify(linkList); // New || Updated
        return false;
      }

      // Stop counting if unread number is greater than 9
      if (index > (this.maxNewsAmount - 1)) { // Remember index is counting 0
        if (this.debug) console.log(this.maxNewsAmount + '+ unread posts (stopped counting)');
        Browser.setBadgeText(this.maxNewsAmount + '+');
        localStorage.unreadCount = this.maxNewsAmount;
        // New or updated?
        localStorage.mostRecentLinkList = JSON.stringify(linkList); // New || Updated
        return false;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      // Remember this
      localStorage.newsLastNotified = item.link;
      // Get content
      localStorage.notificationTitle = item.title;
      localStorage.notificationLink = item.link;
      localStorage.notificationDescription = item.description;
      localStorage.notificationCreator = item.creator;
      localStorage.notificationImage = item.image;
      localStorage.notificationFeedName = item.feedName;
      // Show desktop notification
      Browser.createNotification('notification.html');
    }
  },

  checkForAltLink: function(description) {
    // Looking for alternative link, find the first and best full link
    var altLink = description.match(/href="(http.*)"/);
    if (altLink != null) {
      if (typeof altLink[1] == 'string') {
        return altLink[1];
      }
    }
    return null;
  },

  abbreviateName: function(oldName) {
    if (oldName != undefined) {
      // Abbreviate middle names if name is long
      if (18 < oldName.length) {
        var pieces = oldName.split(' ');
        if (2 < pieces.length) {
          // Add first name
          var newName = pieces[0];
          // Add one letter per middle name
          for (var i = 1; i < pieces.length - 1; i++)
            newName += ' ' + pieces[i].charAt(0).toUpperCase() + '.';
          // Add last name
          newName += ' ' + pieces[pieces.length-1];
          return newName;
        }
      }
    }
    else {
      if (this.debug) console.log('ERROR: cannot abbreviate an undefined name');
    }
    return oldName;
  },

  // Organization specific functions

  online_getImage: function(link, callback) {
    var id = link.split('/')[4]; // id is stored in the link
    var image = 'undefined';
    var api = 'https://online.ntnu.no/api/f5be90e5ec1d2d454ae9/news_image_by_id/';
    $.getJSON(api + id, function(json) {
      if (json['online_news_image']) {
        image = json['online_news_image']['0']['image'];
        callback(link, image);
      }
      else {
        image = this.images['online'].image;
        if (this.debug) console.log('ERROR: no image exists for id: ' + id);
        callback(link, image);
      }
    })
    .error(function() {
      image = this.images['online'].image;
      if (this.debug) console.log('ERROR: couldn\'t connect API to get image links, returning default image');
      callback(link, image);
    });
  },

}
<|endoftext|>


<commit_before>define('./page.js');
require('./inline');
require('./remote');

;(function() {

  var inline, remote;

  inline = require('inline');
  remote = require('remote');

  module.exports = s; function s() {

  }

  global.console && console.log('page.js');

}());
<commit_msg>Update page.js<commit_after>define('./page.js');
require('./inline');
//require('./remote');

;(function() {

  var inline, remote;

  inline = require('./inline');
  //remote = require('./remote');

  module.exports = s; function s() {

  }

  global.console && console.log('page.js');

}());
<|endoftext|>


<commit_before>var map, places, score;

function randInt(max, min) {
    return Math.floor((Math.random() * (max - min)) + min);
}

function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function getOptions(navigable, x, y, z) {
    var mapOptions = {
        //disableDefaultUI:       !navigable,
        //disableDoubleClickZoom: !navigable,
        //draggable:              !navigable,
        //keyboardShortcuts:      !navigable,
        //scrollWheel:            !navigable,
        //panControl:             !navigable,
        //zoomControl:            !navigable,
        mapTypeId:              google.maps.MapTypeId.SATELLITE,
        //overviewMapControl:     false,
        //rotateControl:          false,
        //scaleControl:           false,
        //streetViewControl:      false,
        //minZoom: z,
        //maxZoom: z * 10,
        zoom: z*10000,
        center: new google.maps.LatLng(x, y),
        //tilt:                   0
    };
    console.log("x: " + x + ", y: " + y + ", z: " + z);
    return mapOptions;
}

function updateScore(correct){
    $('.option').off();
    if(correct) {
        score++;
        $('#score').text(score);
    }
    goPlay();
}

function askQuestion() {
    var answers = arguments;
    var correct = arguments[0];

    shuffle(answers);

    $('#Op1').text(answers[0])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[0]);
             })

    $('#Op2').text(answers[1])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[1]);
             })

    $('#Op3').text(answers[2])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[2]);
             })
}

function goPlay() {
    var Country = Object.keys(places)[randInt(1, Object.size(places))];
    var CountryVars = places[Country];
    delete places[Country];

    var False1 = Object.keys(places)[randInt(1, Object.size(places))];
    var False2 = False1;

    while(False1 == False2){
        False2 = Object.keys(places)[randInt(1, Object.size(places))];
    }

    map.setOptions(getOptions(true,
                              CountryVars[0],
                              CountryVars[1],
                              CountryVars[2]));

    console.log(Country);

    askQuestion(Country, False1, False2);
}

function init() {
    score = 0;
    $('#score').text(score);

    $.getJSON('../places.json',function(json){
        places = json;

        map = new google.maps.Map($('#map')[0],
                                         getOptions(true, 0, 0, 0));

        goPlay();

    });
}

$(document).ready(init);

<commit_msg>attempting to implement better place management. Is a working progress.<commit_after>var map, places, score, answers;

function randInt(max, min) {
    return Math.floor((Math.random() * (max - min)) + min);
}

function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function getOptions(navigable, x, y, z) {
    var mapOptions = {
        //disableDefaultUI:       !navigable,
        //disableDoubleClickZoom: !navigable,
        //draggable:              !navigable,
        //keyboardShortcuts:      !navigable,
        //scrollWheel:            !navigable,
        //panControl:             !navigable,
        //zoomControl:            !navigable,
        mapTypeId:              google.maps.MapTypeId.SATELLITE,
        //overviewMapControl:     false,
        //rotateControl:          false,
        //scaleControl:           false,
        //streetViewControl:      false,
        //minZoom: z,
        //maxZoom: z * 10,
        zoom: z*10000,
        center: new google.maps.LatLng(x, y),
        //tilt:                   0
    };
    console.log("x: " + x + ", y: " + y + ", z: " + z);
    return mapOptions;
}

function updateScore(correct){
    $('.option').off();
    console.log('correct: ' + correct);
    if(correct) {
        score++;
        $('#score').text(score);
        delete places[answers[0]];
        goPlay();
    } else {
        console.log('asking question: ' + answers[0], answers[1], answers[2]);
        askQuestion(answers[0], answers[1], answers[2]);
    }
}

function askQuestion() {
    answers = arguments;
    var correct = arguments[0];

    shuffle(answers);

    $('#Op1').text(answers[0])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[0]);
             })

    $('#Op2').text(answers[1])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[1]);
             })

    $('#Op3').text(answers[2])
             .click(function(){
                $('option').text("")
                updateScore(correct == answers[2]);
             })
}

function goPlay() {
    var Country = Object.keys(places)[randInt(1, Object.size(places))];
    var CountryVars = places[Country];

    var False1 = Country;
    while(False1 == Country){
        False1 = Object.keys(places)[randInt(1, Object.size(places))];
    }

    var False2 = False1;
    while((False1 == False2) || (False2 == Country)){
        False2 = Object.keys(places)[randInt(1, Object.size(places))];
    }

    map.setOptions(getOptions(true,
                              CountryVars[0],
                              CountryVars[1],
                              CountryVars[2]));

    console.log(Country);

    askQuestion(Country, False1, False2);
}

function init() {
    score = 0;
    $('#score').text(score);

    $.getJSON('../places.json',function(json){
        places = json;

        first = places['Barbados']

        map = new google.maps.Map($('#map')[0],
                                         getOptions(true, first[0], first[1], first[2]));

        goPlay();

    });
}

$(document).ready(init);

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013 Peter Lejeck <peter.lejeck@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/* jshint browser:true, jquery:true */
$(function() {
  var uploadInput = $('#upload-input'),
      uploadBtn = $('#upload-btn'),
      uploadFiles = $('#upload-filelist');

  var btnContent = '';

  if (!$.hasFileAPI()) {
    $('#no-file-api').show();
    uploadBtn.hide();
  }

  uploadBtn.cabinet(uploadInput);

  uploadBtn.on('dragenter', function(e) {
    if (this === e.target) {
      $(this).addClass('drop');
      btnContent = $(this).html();
      $(this).html('Drop it here~');
    }
  });

  uploadBtn.on('drop', function(e) {
    $(this).trigger('dragleave');
  });

  uploadBtn.on('dragleave', function(e) {
    node = e.target;
    do {
      if (node === this) {
        $(this).removeClass('drop');
        $(this).html(btnContent);
        break;
      }
    } while (node = node.parentNode);
  });

  var MAX_SIZE = (function(node) {
    var max = node.attr('data-max-size') || '120MiB';
    var num = parseInt(/([0-9,]+).*/.exec(max)[1].replace(',', ''));
    var unit = /(?:([KMGTPEZY])(i)?B|([BKMGTPEZY]))/.exec(max) || ['B', '', ''];

    var oneUnit = Math.pow(
      (unit[2] === 'i' ? 1024 : 1000),
      'BKMGTPEZY'.indexOf(unit[1])
    );

    return num * oneUnit;
  })(uploadInput);

  var createRow = function(filename, size, extra) {
    var rowItem = $('
'),
        rowName = $(''),
        rowProg = $('
'),
        rowSize = $(''),
        rowUrl = $('');

    rowItem.addClass(extra || '');

    $('
').appendTo(rowProg);

    rowItem.attr('data-filename', escape(filename));
    rowName.text(filename);
    rowSize.text(size);

    rowItem.append(rowName, rowProg, rowSize, rowUrl);

    return rowItem;
  };

  uploadBtn.on('change', function(e) {
    uploadFiles.empty().removeClass('error completed');

    var files = uploadInput[0].filelist;

    files.forEach(function(file) {
      createRow(file.name, file.humanSize).appendTo(uploadFiles);
    });

    var totalRow = createRow('', files.humanSize, 'total');
    totalRow.appendTo(uploadFiles);

    if (files.size > MAX_SIZE) {
      uploadFiles.addClass('error');

      $('.file-name', totalRow).html('onii-chan y-your upload is t-too ' +
        'big…');
      return;
    }

    var up = files.upload('upload.php');

    var eachRow = function(files, fn) {
      var hits = {};
      files.forEach(function(file) {
        ++hits[file.name] || (hits[file.name] = 0);
        var row = $($('li[data-filename="' +
              escape(file.name) + '"]')[hits[file.name] || 0]);
        fn.call(row, row, file, files);
      });
    };

    var totalName = $('.file-name', totalRow);

    up.on('uploadprogress', function(e, files) {
      eachRow(files, function(row, file, files) {
        $('.progress-inner', row).width((file.percentUploaded * 100) + '%');
      });
      $('.progress-inner', totalRow).width((files.percentUploaded * 100) + '%');
    });

    up.on('uploadcomplete', function(e) {
      $('.progress-inner').width('100%');
      totalName.text('Grabbing URLs...');
    });

    up.on('load', function(e, res) {
      switch (e.target.status) {
        case 200:
          var res = JSON.parse(res);
          if (!res.success) {
            uploadFiles.addClass('error');
            $('.file-name', totalRow).text('Something went wrong; try again ' +
              'later.');
            break;
          }
          eachRow(res.files, function(row, file, files) {
            var link = $('');

            link.attr('href', file.url)
                .attr('target', '_BLANK')
                .text(file.url.replace('http://', '').replace('https://', ''));

            $('.file-url', row).append(link);
          });
          uploadFiles.addClass('completed');
          totalName.text('Done!');
          break;
        case 413:
          uploadFiles.addClass('error completed');
          // Terrible work-around, but necessary since otherwise the '…'
          // entity is left decoded.
          totalName.html($('
').html('onii-chan, y-your upload is t-too ' +
            'big…').text());
          break;
        default:
          uploadFiles.addClass('error completed');
          totalName.text('Something went wrong; try again later.');
      }
    });
    up.upload();
  });
});
<commit_msg>Fix indentation to 2 spaces to comply with airbnb https://github.com/airbnb/javascript<commit_after>/**
 * Copyright (c) 2013 Peter Lejeck <peter.lejeck@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/* jshint browser:true, jquery:true */
$(function() {
  var uploadInput = $('#upload-input'),
      uploadBtn = $('#upload-btn'),
      uploadFiles = $('#upload-filelist');

  var btnContent = '';

  if (!$.hasFileAPI()) {
    $('#no-file-api').show();
    uploadBtn.hide();
  }

  uploadBtn.cabinet(uploadInput);

  uploadBtn.on('dragenter', function(e) {
    if (this === e.target) {
      $(this).addClass('drop');
      btnContent = $(this).html();
      $(this).html('Drop it here~');
    }
  });

  uploadBtn.on('drop', function(e) {
    $(this).trigger('dragleave');
  });

  uploadBtn.on('dragleave', function(e) {
    node = e.target;
    do {
      if (node === this) {
        $(this).removeClass('drop');
        $(this).html(btnContent);
        break;
      }
    } while (node = node.parentNode);
  });

  var MAX_SIZE = (function(node) {
    var max = node.attr('data-max-size') || '120MiB';
    var num = parseInt(/([0-9,]+).*/.exec(max)[1].replace(',', ''));
    var unit = /(?:([KMGTPEZY])(i)?B|([BKMGTPEZY]))/.exec(max) || ['B', '', ''];

    var oneUnit = Math.pow(
      (unit[2] === 'i' ? 1024 : 1000),
      'BKMGTPEZY'.indexOf(unit[1])
    );

    return num * oneUnit;
  })(uploadInput);

  var createRow = function(filename, size, extra) {
    var rowItem = $('
'),
        rowName = $(''),
        rowProg = $('
'),
        rowSize = $(''),
        rowUrl = $('');

    rowItem.addClass(extra || '');

    $('
').appendTo(rowProg);

    rowItem.attr('data-filename', escape(filename));
    rowName.text(filename);
    rowSize.text(size);

    rowItem.append(rowName, rowProg, rowSize, rowUrl);

    return rowItem;
  };

  uploadBtn.on('change', function(e) {
    uploadFiles.empty().removeClass('error completed');

    var files = uploadInput[0].filelist;

    files.forEach(function(file) {
      createRow(file.name, file.humanSize).appendTo(uploadFiles);
    });

    var totalRow = createRow('', files.humanSize, 'total');
    totalRow.appendTo(uploadFiles);

    if (files.size > MAX_SIZE) {
      uploadFiles.addClass('error');

      $('.file-name', totalRow).html('onii-chan y-your upload is t-too ' +
        'big…');
      return;
    }

    var up = files.upload('upload.php');

    var eachRow = function(files, fn) {
      var hits = {};
      files.forEach(function(file) {
        ++hits[file.name] || (hits[file.name] = 0);
        var row = $($('li[data-filename="' +
          escape(file.name) + '"]')[hits[file.name] || 0]);
        fn.call(row, row, file, files);
      });
    };

    var totalName = $('.file-name', totalRow);

    up.on('uploadprogress', function(e, files) {
      eachRow(files, function(row, file, files) {
        $('.progress-inner', row).width((file.percentUploaded * 100) + '%');
      });
      $('.progress-inner', totalRow).width((files.percentUploaded * 100) + '%');
    });

    up.on('uploadcomplete', function(e) {
      $('.progress-inner').width('100%');
      totalName.text('Grabbing URLs...');
    });

    up.on('load', function(e, res) {
      switch (e.target.status) {
        case 200:
          var res = JSON.parse(res);
          if (!res.success) {
            uploadFiles.addClass('error');
            $('.file-name', totalRow).text('Something went wrong; try again ' +
              'later.');
            break;
          }
          eachRow(res.files, function(row, file, files) {
            var link = $('');

            link.attr('href', file.url)
                .attr('target', '_BLANK')
                .text(file.url.replace('http://', '').replace('https://', ''));

            $('.file-url', row).append(link);
          });
          uploadFiles.addClass('completed');
          totalName.text('Done!');
          break;
        case 413:
          uploadFiles.addClass('error completed');
          // Terrible work-around, but necessary since otherwise the '…'
          // entity is left decoded.
          totalName.html($('
').html('onii-chan, y-your upload is t-too ' +
            'big…').text());
          break;
        default:
          uploadFiles.addClass('error completed');
          totalName.text('Something went wrong; try again later.');
      }
    });
    up.upload();
  });
});
<|endoftext|>


<commit_before>var perturb = peturb

function incRandInt(low, high){
  //Inclusive RandInt
  return Math.floor(Math.random()* ((high+1) -low)) + low
}

function rand() {
  return Math.random()
}

// Takes in vectors and finds the closest to a point.
function closest(list, vertex){

    cMin = null
    cScore = null
    for(var i = 0; i < list.length; i++){
      score = vertex.distanceTo(list[i])
      if ((cMin == null)||( score < cScore)){
        cMin = list[i]
        cScore = score
      }
    }
    return cMin
}

function basicRockFactory( width, height, depth, attributes ) {
    var geometry = new THREE.BoxGeometry( width, height, 0.01, width*2, height * 2, 10 );

    var axis = new THREE.Vector3( perturb( 0, width ), perturb( 0, height ), 0 );
    var maxDist = Math.sqrt( width * width + height * height );

    for ( var i = 0; i < geometry.vertices.length; i++ ) {
        var vertex = geometry.vertices[i];
        vertex.x = perturb( vertex.x, 0.1 );
        vertex.y = perturb( vertex.y, 0.1 );

        if ( vertex.z == 0.005 ) {
            vertex.z = perturb( ( maxDist - vertex.distanceTo( axis ) ) * 3 * depth / 4, depth / 4 );
        }
    }

    var material = new THREE.MeshPhongMaterial( { color : 0x505050,
                                                  shading : THREE.FlatShading,
                                                  shininess : 20,
                                                  refractionRatio : 0.1 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.receiveShadow = true;
    mesh.castShadow = true;

    return mesh;

}

function SpireRockFactory( width, height, depth, attributes ) {
    var depth  =  depth
    var bRadius = width / 2.0;
    var tRadius = Math.random() * (width/3.0);
    var faces = incRandInt(4,6);
    var stories = Math.floor(depth + 1) * incRandInt(3,7);

    // var geometry = new THREE.CylinderGeometry( tRadius, bRadius, depth,
    //   faces, stories, false, 0, 2.01*Math.PI);
    var geometry = new THREE.CylinderGeometry( tRadius, bRadius, depth,faces, stories, false, 0, 2.01*Math.PI);
    var numInternalVectors = faces
    var axisVectors =[];

    for (var v = 0; v < numInternalVectors; v++){
      axisVectors[v] = new THREE.Vector3(
        rand()*bRadius, rand()*bRadius, rand()*depth)
    }

    for (var i = 0; i < geometry.vertices.length; i++ ) {
        var vertex = geometry.vertices[i];
        // find closest internal vector

        internal = closest(axisVectors, vertex)

        var vectorMag =0.3
        console.log(vectorMag * (internal.x))

         vertex.x  = vertex.x - vectorMag * (internal.x);
         vertex.y  = vertex.y - vectorMag * (internal.y );
         vertex.z  = vertex.z - vectorMag * (internal.z  );
        // vertex.x = perturb( vertex.x, 0.1 );
        // vertex.y = perturb( vertex.y, 0.1 );
        // vertex.z = perturb( vertex.z, 0.1 );

    }
    geometry.computeFaceNormals();
    geometry.computeVertexNormals();

     geometry.rotateX(90* Math.PI / 180)
    // geometry.rotateZ(90* Math.PI / 180)

    var material = new THREE.MeshPhongMaterial( { color : 0x505050,
                                                  shading : THREE.FlatShading,
                                                  shininess : 20,
                                                  refractionRatio : 0.1 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.receiveShadow = true;
    mesh.castShadow = true;

    return mesh;

}
<commit_msg>Rocks look good<commit_after>var perturb = peturb

function incRandInt(low, high){
  //Inclusive RandInt
  return Math.floor(Math.random()* ((high+1) -low)) + low
}

function randRange(low, high){
  return Math.random()*(high -low) + low
}

function rand() {
  return Math.random()
}

// Takes in vectors and finds the closest to a point.
function closest(list, vertex){

    cMin = null
    cScore = null
    for(var i = 0; i < list.length; i++){
      score = vertex.distanceTo(list[i])
      if ((cMin == null)||( score < cScore)){
        cMin = list[i]
        cScore = score
      }
    }
    return cMin
}

function basicRockFactory( width, height, depth, attributes ) {
    var geometry = new THREE.BoxGeometry( width, height, 0.01, width*2, height * 2, 10 );

    var axis = new THREE.Vector3( perturb( 0, width ), perturb( 0, height ), 0 );
    var maxDist = Math.sqrt( width * width + height * height );

    for ( var i = 0; i < geometry.vertices.length; i++ ) {
        var vertex = geometry.vertices[i];
        vertex.x = perturb( vertex.x, 0.1 );
        vertex.y = perturb( vertex.y, 0.1 );

        if ( vertex.z == 0.005 ) {
            vertex.z = perturb( ( maxDist - vertex.distanceTo( axis ) ) * 3 * depth / 4, depth / 4 );
        }
    }

    var material = new THREE.MeshPhongMaterial( { color : 0x505050,
                                                  shading : THREE.FlatShading,
                                                  shininess : 20,
                                                  refractionRatio : 0.1 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.receiveShadow = true;
    mesh.castShadow = true;

    return mesh;

}

function SpireRockFactory( width, height, depth) {
    var depth  =  depth
    var bRadius = width / 2.0;
    var tRadius = randRange(0.6,0.85) * (width/2.0);
    var faces = incRandInt(4,6);
    var stories = Math.floor(depth + 1) * incRandInt(1,4);

    // var geometry = new THREE.CylinderGeometry( tRadius, bRadius, depth,
    //   faces, stories, false, 0, 2.01*Math.PI);
    var geometry = new THREE.CylinderGeometry( tRadius, bRadius, depth,faces, stories, false, 0, 2.01*Math.PI);
    var numInternalVectors = faces
    var axisVectors =[];

    for (var v = 0; v < numInternalVectors; v++){
      axisVectors[v] = new THREE.Vector3(
        rand()*bRadius, rand()*bRadius, rand()*depth)
    }

    for (var i = 0; i < geometry.vertices.length; i++ ) {
        var vertex = geometry.vertices[i];

        internal = closest(axisVectors, vertex)

        var vectorMag =0.3
         vertex.x  = vertex.x - vectorMag * (internal.x);
         vertex.y  = vertex.y - vectorMag * (internal.y);
         vertex.z  = vertex.z - vectorMag * (internal.z);
    }

    // Make top slanted

    for (var i = 0; i < geometry.vertices.length; i++ ) {
        var vertex = geometry.vertices[i];
        if ((vertex.z < depth + 0.1)&&(vertex.z > depth - 0.1))
          console.log(vertex.z, depth)
          vertex.z = perturb(vertex.z, 0.2)

    }

    geometry.computeFaceNormals();
    geometry.computeVertexNormals();

     geometry.rotateX(90* Math.PI / 180)

    var material = new THREE.MeshPhongMaterial( { color : 0x505050,
                                                  shading : THREE.FlatShading,
                                                  shininess : 20,
                                                  refractionRatio : 0.1 } );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.receiveShadow = true;
    mesh.castShadow = true;

    return mesh;

}
<|endoftext|>


<commit_before>var geojson = {}
var fields = []
var styleOpts = ['fill', 'fill-opacity', 'stroke', 'stroke-opacity', 'marker-color', 'stroke-width', 'marker-size', 'marker-symbol']

$(function(){
  // Setup codemirror
  var textarea = $('#styles')[0]
  var editor = CodeMirror.fromTextArea(textarea,{
    mode: 'application/json',
    matchBrackets: true,
    tabSize: 2,
    lineNumbers: true
  })
  //editor.setSize(300, 100);
  editor.setValue('{\n  \n}')

  // Setup help popups
  setupHelp()

  // Load Sample
  $('#sample').click(function(){
    geojson = sample
    fields = Object.keys(geojson.features[0].properties)
    populateZSelect('jenksZSelect')
    populateZSelect('quantilesZSelect')
    populateZSelect('equalIntervalsZSelect')
    populateZSelect('customZSelect')

    map.featureLayer.setGeoJSON(geojson)
    map.fitBounds(map.featureLayer.getBounds());
    map.featureLayer.eachLayer(setPopups)

    $('#classification').val('Quantiles')
    $('#classification').trigger('change')
    $('#quantilesZSelect').val('density')
    $('#quantilesColor1').val('green')
    $('#quantilesColor2').val('yellow')
    $('#quantilesColor3').val('red')
    $('#colorize').trigger('click')
  })

  // Upload File
  $('#dropFile').on('change', function(evt){
    var reader = new FileReader();
    reader.readAsText(evt.currentTarget.files[0]);
    reader.onload = function(e) {
      geojson = JSON.parse(e.target.result)
      fields = Object.keys(geojson.features[0].properties)
      populateZSelect('jenksZSelect')
      populateZSelect('quantilesZSelect')
      populateZSelect('equalIntervalsZSelect')
      populateZSelect('customZSelect')

      map.featureLayer.setGeoJSON(geojson)
      map.fitBounds(map.featureLayer.getBounds());
      map.featureLayer.eachLayer(setPopups)
    }
  })

  // Select Classification Options
  $('#classification').change(function(){
    var classification = $('#classification').val()
    if(classification === 'Jenks'){
      $('#jenksControls').show()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Quantiles'){
      $('#quantilesControls').show()
      $('#jenksControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Equal Interval'){
      $('#equalIntervalsControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Random'){
      $('#randomControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'All'){
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Custom'){
      $('#customControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
    }
  })

  // Colorize Features
  $('#colorize').click(function(){
    var classification = $('#classification').val()
    var styles = JSON.parse(editor.getValue())
    var colors = []

    if(classification === 'Jenks'){
      var z = $('#jenksZSelect option:selected').text()
      colors.push($('#jenksColor1 option:selected').text())
      if(!($('#jenksColor2 option:selected').text() === '--')){
        colors.push($('#jenksColor2 option:selected').text())
      }
      colors.push($('#jenksColor3 option:selected').text())
      var numBreaks = parseFloat($('#jenksNumBreaks').val())

      geojson = geocolor.jenks(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Quantiles'){
      var z = $('#quantilesZSelect option:selected').text()
      colors.push($('#quantilesColor1 option:selected').text())
      if(!($('#quantilesColor2 option:selected').text() === '--')){
        colors.push($('#quantilesColor2 option:selected').text())
      }
      colors.push($('#quantilesColor3 option:selected').text())
      var numBreaks = parseFloat($('#quantilesNumBreaks').val())

      geojson = geocolor.quantiles(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Equal Interval'){
      var z = $('#equalIntervalsZSelect option:selected').text()
      colors.push($('#equalIntervalsColor1 option:selected').text())
      if(!($('#equalIntervalsColor2 option:selected').text() === '--')){
        colors.push($('#equalIntervalsColor2 option:selected').text())
      }
      colors.push($('#equalIntervalsColor3 option:selected').text())
      var numBreaks = parseFloat($('#equalIntervalsNumBreaks').val())

      geojson = geocolor.equalIntervals(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Random'){
      if(!($('#randomColor1 option:selected').text() === '--')){
        colors.push($('#randomColor1 option:selected').text())
      }
      if(!($('#randomColor2 option:selected').text() === '--')){
        colors.push($('#randomColor2 option:selected').text())
      }
      if(!($('#randomColor3 option:selected').text() === '--')){
        colors.push($('#randomColor3 option:selected').text())
      }
      if(!($('#randomColor4 option:selected').text() === '--')){
        colors.push($('#randomColor4 option:selected').text())
      }
      if(!($('#randomColor5 option:selected').text() === '--')){
        colors.push($('#randomColor5 option:selected').text())
      }

      geojson = geocolor.random(geojson, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'All'){
      geojson = geocolor.all(geojson, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Custom'){
      var z = $('#customZSelect option:selected').text()
      colors.push($('#customColor1 option:selected').text())
      if(!($('#customColor2 option:selected').text() === '--')){
        colors.push($('#customColor2 option:selected').text())
      }
      colors.push($('#customColor3 option:selected').text())
      var breaks = $('#customBreaks').val().split(',').map(function(x){return parseFloat(x)})

      geojson = geocolor.custom(geojson, z, breaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
  })

  // Export Geojson
  $('#export').click(function(){
    var content = '
Geojson

'
    content+= '<textarea id="geojsonExport" rows="8" cols="40" class="form-control">'+JSON.stringify(geojson)+'</textarea>'
    vex.dialog.alert(content)
  })

  // Create Gist
  $('#gist').click(function(){
    var template
    var gist = {
      "description": "geocolor map",
      "public": true,
      "files": {
        "geocolor.geojson": {
          "content": JSON.stringify(geojson, null, 2)
        },
        "index.html": {
          "content": shareTemplate
        }
      }
    }

    $.post('https://api.github.com/gists', JSON.stringify(gist), function(res){
      var content = '
Share

'
      content+= '
http://bl.ocks.org/anonymous/raw/'+res.id+''
      vex.dialog.alert(content)
    })
  })
})

function setPopups(layer){
  var content = '
'
  content += '
'
  fields.forEach(function(field){
    if(!contains(styleOpts, field)){
      content += '
'
      content+=''+field+'	'+layer.feature.properties[field]+'	'
      content += '
'
    }
  })
  content += '
'
  content += '
'

  layer.bindPopup(content);
}

function populateZSelect(id){
  $('#'+id).empty()
  fields.forEach(function(field){
    if(!contains(styleOpts, field)){
      $('#'+id).append('<option>'+field+'</option>')
    }
  })
}

function setupHelp(){
  $('#geojsonFileHelp').click(function(){
    var help = '
Geojson File

'
    help+= '
Input a valid geojson file containing a FeatureCollection.'
    vex.dialog.alert(help)
  })

  $('#classificationHelp').click(function(){
    var help = '
Classification

'
    help+= '
The classification option determines how colors will be assigned. '
    help+= 'Jenks'
    help+= ', Quantiles'
    help+= ', and Equal Intervals '
    help+= 'all work well for graduated color ramps.'
    vex.dialog.alert(help)
  })

  $('.zFieldHelp').click(function(){
    var help = '
Z Field

'
    help+= '
The z field is what determines a feature\'s relative color. This could be anything from population, to density of cats.'
    vex.dialog.alert(help)
  })

  $('.breaksHelp').click(function(){
    var help = '
Breaks

'
    help+= '
Breaks are the values at which data is divided. More breaks means more subtle color shifts.'
    vex.dialog.alert(help)
  })

  $('#stylesHelp').click(function(){
    var help = '
Styles

'
    help+= '
The Styles field allows you to enter any valid simplestyle-spec styles. '
    help+= 'These styles will be applied across all features.'
    help+= '
If you had a set of polygons and wanted to change the stroke width and fill opacity, you could enter the following:'
    help+= '
{\n  "stroke:thickness": "1",\n  "fill-opacity": 0.4\n}
'
    vex.dialog.alert(help)
  })

  $('#aboutLink').click(function(){
    var help = '
About Geocolor

'
    help+= '
Geocolor is a web app and javascript library for creating quick geographic data visualizations such as '
    help+= 'choloropleths. '
    help+= '
Geocolor is open source, and '
    help+= 'was created by @morganherlocker.'
    vex.dialog.alert(help)
  })
}

function contains(a, obj) {
  var i = a.length;
  while (i--) {
   if (a[i] === obj) {
      return true;
   }
  }
  return false;
}<commit_msg>save export working with gist and cdn<commit_after>var geojson = {}
var fields = []
var styleOpts = ['fill', 'fill-opacity', 'stroke', 'stroke-opacity', 'marker-color', 'stroke-width', 'marker-size', 'marker-symbol']

$(function(){
  // Setup codemirror
  var textarea = $('#styles')[0]
  var editor = CodeMirror.fromTextArea(textarea,{
    mode: 'application/json',
    matchBrackets: true,
    tabSize: 2,
    lineNumbers: true
  })
  //editor.setSize(300, 100);
  editor.setValue('{\n  \n}')

  // Setup help popups
  setupHelp()

  // Load Sample
  $('#sample').click(function(){
    geojson = sample
    fields = Object.keys(geojson.features[0].properties)
    populateZSelect('jenksZSelect')
    populateZSelect('quantilesZSelect')
    populateZSelect('equalIntervalsZSelect')
    populateZSelect('customZSelect')

    map.featureLayer.setGeoJSON(geojson)
    map.fitBounds(map.featureLayer.getBounds());
    map.featureLayer.eachLayer(setPopups)

    $('#classification').val('Quantiles')
    $('#classification').trigger('change')
    $('#quantilesZSelect').val('density')
    $('#quantilesColor1').val('green')
    $('#quantilesColor2').val('yellow')
    $('#quantilesColor3').val('red')
    $('#colorize').trigger('click')
  })

  // Upload File
  $('#dropFile').on('change', function(evt){
    var reader = new FileReader();
    reader.readAsText(evt.currentTarget.files[0]);
    reader.onload = function(e) {
      geojson = JSON.parse(e.target.result)
      fields = Object.keys(geojson.features[0].properties)
      populateZSelect('jenksZSelect')
      populateZSelect('quantilesZSelect')
      populateZSelect('equalIntervalsZSelect')
      populateZSelect('customZSelect')

      map.featureLayer.setGeoJSON(geojson)
      map.fitBounds(map.featureLayer.getBounds());
      map.featureLayer.eachLayer(setPopups)
    }
  })

  // Select Classification Options
  $('#classification').change(function(){
    var classification = $('#classification').val()
    if(classification === 'Jenks'){
      $('#jenksControls').show()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Quantiles'){
      $('#quantilesControls').show()
      $('#jenksControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Equal Interval'){
      $('#equalIntervalsControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Random'){
      $('#randomControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'All'){
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
      $('#customControls').hide()
    }
    else if(classification === 'Custom'){
      $('#customControls').show()
      $('#jenksControls').hide()
      $('#quantilesControls').hide()
      $('#equalIntervalsControls').hide()
      $('#randomControls').hide()
    }
  })

  // Colorize Features
  $('#colorize').click(function(){
    var classification = $('#classification').val()
    var styles = JSON.parse(editor.getValue())
    var colors = []

    if(classification === 'Jenks'){
      var z = $('#jenksZSelect option:selected').text()
      colors.push($('#jenksColor1 option:selected').text())
      if(!($('#jenksColor2 option:selected').text() === '--')){
        colors.push($('#jenksColor2 option:selected').text())
      }
      colors.push($('#jenksColor3 option:selected').text())
      var numBreaks = parseFloat($('#jenksNumBreaks').val())

      geojson = geocolor.jenks(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Quantiles'){
      var z = $('#quantilesZSelect option:selected').text()
      colors.push($('#quantilesColor1 option:selected').text())
      if(!($('#quantilesColor2 option:selected').text() === '--')){
        colors.push($('#quantilesColor2 option:selected').text())
      }
      colors.push($('#quantilesColor3 option:selected').text())
      var numBreaks = parseFloat($('#quantilesNumBreaks').val())

      geojson = geocolor.quantiles(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Equal Interval'){
      var z = $('#equalIntervalsZSelect option:selected').text()
      colors.push($('#equalIntervalsColor1 option:selected').text())
      if(!($('#equalIntervalsColor2 option:selected').text() === '--')){
        colors.push($('#equalIntervalsColor2 option:selected').text())
      }
      colors.push($('#equalIntervalsColor3 option:selected').text())
      var numBreaks = parseFloat($('#equalIntervalsNumBreaks').val())

      geojson = geocolor.equalIntervals(geojson, z, numBreaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Random'){
      if(!($('#randomColor1 option:selected').text() === '--')){
        colors.push($('#randomColor1 option:selected').text())
      }
      if(!($('#randomColor2 option:selected').text() === '--')){
        colors.push($('#randomColor2 option:selected').text())
      }
      if(!($('#randomColor3 option:selected').text() === '--')){
        colors.push($('#randomColor3 option:selected').text())
      }
      if(!($('#randomColor4 option:selected').text() === '--')){
        colors.push($('#randomColor4 option:selected').text())
      }
      if(!($('#randomColor5 option:selected').text() === '--')){
        colors.push($('#randomColor5 option:selected').text())
      }

      geojson = geocolor.random(geojson, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'All'){
      geojson = geocolor.all(geojson, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
    else if(classification === 'Custom'){
      var z = $('#customZSelect option:selected').text()
      colors.push($('#customColor1 option:selected').text())
      if(!($('#customColor2 option:selected').text() === '--')){
        colors.push($('#customColor2 option:selected').text())
      }
      colors.push($('#customColor3 option:selected').text())
      var breaks = $('#customBreaks').val().split(',').map(function(x){return parseFloat(x)})

      geojson = geocolor.custom(geojson, z, breaks, colors, styles)
      map.featureLayer.setGeoJSON(geojson)
      map.featureLayer.eachLayer(setPopups)
    }
  })

  // Export Geojson
  $('#export').click(function(){
    //var content = '
Geojson

'
    //content+= '<textarea id="geojsonExport" rows="8" cols="40" class="form-control">'+JSON.stringify(geojson)+'</textarea>'
    //vex.dialog.alert(content)
    var gist = {
      "description": "geocolor.geojson",
      "public": true,
      "files": {
        "geocolor.geojson": {
          "content": JSON.stringify(geojson, null, 2)
        }
      }
    }

    $.post('https://api.github.com/gists', JSON.stringify(gist), function(res){
      window.open('https://cdn.rawgit.com/anonymous/'+res.id+'/raw/geocolor.geojson', '_self')
    })
  })

  // Create Gist
  $('#gist').click(function(){
    var gist = {
      "description": "geocolor map",
      "public": true,
      "files": {
        "geocolor.geojson": {
          "content": JSON.stringify(geojson, null, 2)
        },
        "index.html": {
          "content": shareTemplate
        }
      }
    }

    $.post('https://api.github.com/gists', JSON.stringify(gist), function(res){
      var content = '
Share

'
      content+= '
http://bl.ocks.org/anonymous/raw/'+res.id+''
      vex.dialog.alert(content)
    })
  })
})

function setPopups(layer){
  var content = '
'
  content += '
'
  fields.forEach(function(field){
    if(!contains(styleOpts, field)){
      content += '
'
      content+=''+field+'	'+layer.feature.properties[field]+'	'
      content += '
'
    }
  })
  content += '
'
  content += '
'

  layer.bindPopup(content);
}

function populateZSelect(id){
  $('#'+id).empty()
  fields.forEach(function(field){
    if(!contains(styleOpts, field)){
      $('#'+id).append('<option>'+field+'</option>')
    }
  })
}

function setupHelp(){
  $('#geojsonFileHelp').click(function(){
    var help = '
Geojson File

'
    help+= '
Input a valid geojson file containing a FeatureCollection.'
    vex.dialog.alert(help)
  })

  $('#classificationHelp').click(function(){
    var help = '
Classification

'
    help+= '
The classification option determines how colors will be assigned. '
    help+= 'Jenks'
    help+= ', Quantiles'
    help+= ', and Equal Intervals '
    help+= 'all work well for graduated color ramps.'
    vex.dialog.alert(help)
  })

  $('.zFieldHelp').click(function(){
    var help = '
Z Field

'
    help+= '
The z field is what determines a feature\'s relative color. This could be anything from population, to density of cats.'
    vex.dialog.alert(help)
  })

  $('.breaksHelp').click(function(){
    var help = '
Breaks

'
    help+= '
Breaks are the values at which data is divided. More breaks means more subtle color shifts.'
    vex.dialog.alert(help)
  })

  $('#stylesHelp').click(function(){
    var help = '
Styles

'
    help+= '
The Styles field allows you to enter any valid simplestyle-spec styles. '
    help+= 'These styles will be applied across all features.'
    help+= '
If you had a set of polygons and wanted to change the stroke width and fill opacity, you could enter the following:'
    help+= '
{\n  "stroke:thickness": "1",\n  "fill-opacity": 0.4\n}
'
    vex.dialog.alert(help)
  })

  $('#aboutLink').click(function(){
    var help = '
About Geocolor

'
    help+= '
Geocolor is a web app and javascript library for creating quick geographic data visualizations such as '
    help+= 'choloropleths. '
    help+= '
Geocolor is open source, and '
    help+= 'was created by @morganherlocker.'
    vex.dialog.alert(help)
  })
}

function contains(a, obj) {
  var i = a.length;
  while (i--) {
   if (a[i] === obj) {
      return true;
   }
  }
  return false;
}<|endoftext|>


<commit_before>var findme_map = L.map('findme-map')
    .setView([37.7, -97.3], 3),
    osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = 'Map data © OpenStreetMap contributors',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib}).addTo(findme_map),
    category_data = [];

var findme_marker = L.marker([0,0], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

if (location.hash) location.hash = '';

var successString,loadingText;

i18n.init({ fallbackLng: 'en-US', postAsync: 'false' }, function() {
    $("body").i18n();

    successString=i18n.t('messages.success', { escapeInterpolation: false });
    loadingText=i18n.t('messages.loadingText');

    var detectedLang = i18n.lng();
    var buildSelectControl = function(data) {
        $("#category").select2({data: data});
    };

    $.getJSON('./locales/' + detectedLang + '/categories.json', buildSelectControl).fail(function () {
        // 404? Fall back to en-US
         $.getJSON('./locales/en-US/categories.json', buildSelectControl);
    });
});

function zoom_to_point(chosen_place, map, marker) {
    console.log(chosen_place);

    marker.setOpacity(1);
    marker.setLatLng([chosen_place.lat, chosen_place.lon]);

    map.setView(chosen_place, 18, {animate: true});
}
$("#use_my_location").click(function (e) {
    $("#couldnt-find").hide();
    $("#success").hide();
    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var point = {
                lat: position.coords.latitude,
                lon: position.coords.longitude
            }

            zoom_to_point(point, findme_map, findme_marker);

            $('#success').html(successString);
            $('#success').show();
            window.scrollTo(0, $('#address').position().top - 30);
            $('.step-2 a').attr('href', '#details');
        }, function (error) {
            $("#couldnt-find").show();
        });
    } else {
      $("#couldnt-find").show();
    }
});
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    $("#success").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;
    var qwarg = {
        format: 'json',
        q: address_to_find
    };
    var url = "https://nominatim.openstreetmap.org/search?" + $.param(qwarg);
    $("#findme h4").text(loadingText);
    $("#findme").addClass("loading");
    $.getJSON(url, function(data) {
        if (data.length > 0) {
            zoom_to_point(data[0], findme_map, findme_marker);

            $('#success').html(successString);
            $('#success').show();
            window.scrollTo(0, $('#address').position().top - 30);
            $('.step-2 a').attr('href', '#details');
        } else {
            $("#couldnt-find").show();
        }
        $("#findme").removeClass("loading");
    });
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "onosm.org submitted note from a business:\n" +
        "name: " + $("#name").val() + "\n" +
        "phone: " + $("#phone").val() + "\n" +
        "website: " + $("#website").val() + "\n" +
        "twitter: " + $("#twitter").val() + "\n" +
        "hours: " + $("#opening_hours").val() + "\n" +
        "category: " + $("#category").val().join(", ") + "\n" +
        "address: " + $("#address").val(),
        latlon = findme_marker.getLatLng(),
        qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('https://api.openstreetmap.org/api/0.6/notes.json', qwarg);
});

function clearFields() {
    $("#name").val('');
    $("#phone").val('');
    $("#website").val('');
    $("#social").val('');
    $("#opening_hours").val('');
    $("#category").val('');
    $("#address").val('');
}
<commit_msg>The category is already comma-separated<commit_after>var findme_map = L.map('findme-map')
    .setView([37.7, -97.3], 3),
    osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = 'Map data © OpenStreetMap contributors',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib}).addTo(findme_map),
    category_data = [];

var findme_marker = L.marker([0,0], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

if (location.hash) location.hash = '';

var successString,loadingText;

i18n.init({ fallbackLng: 'en-US', postAsync: 'false' }, function() {
    $("body").i18n();

    successString=i18n.t('messages.success', { escapeInterpolation: false });
    loadingText=i18n.t('messages.loadingText');

    var detectedLang = i18n.lng();
    var buildSelectControl = function(data) {
        $("#category").select2({data: data});
    };

    $.getJSON('./locales/' + detectedLang + '/categories.json', buildSelectControl).fail(function () {
        // 404? Fall back to en-US
         $.getJSON('./locales/en-US/categories.json', buildSelectControl);
    });
});

function zoom_to_point(chosen_place, map, marker) {
    console.log(chosen_place);

    marker.setOpacity(1);
    marker.setLatLng([chosen_place.lat, chosen_place.lon]);

    map.setView(chosen_place, 18, {animate: true});
}
$("#use_my_location").click(function (e) {
    $("#couldnt-find").hide();
    $("#success").hide();
    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var point = {
                lat: position.coords.latitude,
                lon: position.coords.longitude
            }

            zoom_to_point(point, findme_map, findme_marker);

            $('#success').html(successString);
            $('#success').show();
            window.scrollTo(0, $('#address').position().top - 30);
            $('.step-2 a').attr('href', '#details');
        }, function (error) {
            $("#couldnt-find").show();
        });
    } else {
      $("#couldnt-find").show();
    }
});
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    $("#success").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;
    var qwarg = {
        format: 'json',
        q: address_to_find
    };
    var url = "https://nominatim.openstreetmap.org/search?" + $.param(qwarg);
    $("#findme h4").text(loadingText);
    $("#findme").addClass("loading");
    $.getJSON(url, function(data) {
        if (data.length > 0) {
            zoom_to_point(data[0], findme_map, findme_marker);

            $('#success').html(successString);
            $('#success').show();
            window.scrollTo(0, $('#address').position().top - 30);
            $('.step-2 a').attr('href', '#details');
        } else {
            $("#couldnt-find").show();
        }
        $("#findme").removeClass("loading");
    });
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "onosm.org submitted note from a business:\n" +
        "name: " + $("#name").val() + "\n" +
        "phone: " + $("#phone").val() + "\n" +
        "website: " + $("#website").val() + "\n" +
        "twitter: " + $("#twitter").val() + "\n" +
        "hours: " + $("#opening_hours").val() + "\n" +
        "category: " + $("#category").val() + "\n" +
        "address: " + $("#address").val(),
        latlon = findme_marker.getLatLng(),
        qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('https://api.openstreetmap.org/api/0.6/notes.json', qwarg);
});

function clearFields() {
    $("#name").val('');
    $("#phone").val('');
    $("#website").val('');
    $("#social").val('');
    $("#opening_hours").val('');
    $("#category").val('');
    $("#address").val('');
}
<|endoftext|>


<commit_before>jQuery(function($) {

	var action = $('#action').val();
	showTestFields( action );

	$('#action').change( function() {

		var action = $(this).val();
		showTestFields( action );

	});

	function showTestFields( action ) {

		var aclEntityField = '
ACL Entity Type
<select id="aclEntityType" name="aclEntityType" class="form-control"><option value="user-">User</option><option value="group-">group</option><option value="domain-">Domain</option><option value="project-">Project</option><option value="allUsers">All Users</option><option value="allAuthenticatedUsers">All Authenticated Users</option></select>

Acl Entity
<input id="aclEntityValue" name="aclEntityValue" type="text" placeholder="Acl::role" class="form-control input-md" >Enter the ACL role

';
		var aclRoleField = '
ACL Role
<select id="aclRole" name="aclRole" class="form-control"><option value="OWNER">Owner</option><option value="READER">Reader</option><option value="WRITER">Writer</option></select>

';
		clearTestFields();
		switch (action) {

			case '2':
				$('#action-select').after(aclRoleField);
				$('#action-select').after(aclEntityField);
				break;
			case '3':
				$('#action-select').after(aclEntityField);
				break;

		}

	}

	function clearTestFields() {

		var allFieldSelectors = '#aclEntityField, #aclRoleField';
		$(allFieldSelectors).remove();

	}

});
<commit_msg>html inserting is... iffy.<commit_after>jQuery(function($) {

	var action = $('#action').val();
	showTestFields( action );

	$('#action').change( function() {

		var action = $(this).val();
		showTestFields( action );

	});

	function showTestFields( action ) {

		var aclEntityField = '
ACL Entity Type
<select id="aclEntityType" name="aclEntityType" class="form-control"><option value="user-">User</option><option value="group-">group</option><option value="domain-">Domain</option><option value="project-">Project</option><option value="allUsers">All Users</option><option value="allAuthenticatedUsers">All Authenticated Users</option></select>

Acl Entity
<input id="aclEntityValue" name="aclEntityValue" type="text" placeholder="entity id or email" class="form-control input-md" >

';
		var aclRoleField = '
ACL Role
<select id="aclRole" name="aclRole" class="form-control"><option value="OWNER">Owner</option><option value="READER">Reader</option><option value="WRITER">Writer</option></select>

';
		clearTestFields();
		switch (action) {

			case '2':
				$('#action-select').after(aclRoleField);
				$('#action-select').after(aclEntityField);
				break;
			case '3':
				$('#action-select').after(aclEntityField);
				break;

		}

	}

	function clearTestFields() {

		var allFieldSelectors = '#aclEntityField-entity, #aclEntityField-type, #aclRoleField';
		$(allFieldSelectors).remove();

	}

});
<|endoftext|>


<commit_before>'use strict';

var user = {
    name: '',
    color: '',
    mood: '',
    particle: '',
    marsupial: '',
    fontSize: 0,
    pFont: 0,
    margin: 0,
    float: '',

    color1: '',
    color2: '',
    color3: '',

    //methods

    //input for each property()
    //localStorage set()
};<commit_msg>comment in stevens radio solution<commit_after>'use strict';

var user = {
    name: '',
    color: '',
    mood: '',
    particle: '',
    marsupial: '',
    fontSize: 0,
    pFont: 0,
    margin: 0,
    float: '',

    color1: '',
    color2: '',
    color3: '',

    //methods

    //document.querySelector('input[name = "marsupial"]').value;

    //input for each property()
    //localStorage set()
};<|endoftext|>


<commit_before>/*!
 * zoom.js 0.3
 * http://lab.hakim.se/zoom-js
 * MIT licensed
 *
 * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se
 */
var zoom = (function(){

	// The current zoom level (scale)
	var level = 1;

	// The current mouse position, used for panning
	var mouseX = 0,
		mouseY = 0;

	// Timeout before pan is activated
	var panEngageTimeout = -1,
		panUpdateInterval = -1;

	// Check for transform support so that we can fallback otherwise
	var supportsTransforms = 	'WebkitTransform' in document.body.style ||
								'MozTransform' in document.body.style ||
								'msTransform' in document.body.style ||
								'OTransform' in document.body.style ||
								'transform' in document.body.style;

	if( supportsTransforms ) {
		// The easing that will be applied when we zoom in/out
		document.body.style.transition = 'transform 0.8s ease';
		document.body.style.OTransition = '-o-transform 0.8s ease';
		document.body.style.msTransition = '-ms-transform 0.8s ease';
		document.body.style.MozTransition = '-moz-transform 0.8s ease';
		document.body.style.WebkitTransition = '-webkit-transform 0.8s ease';
	}

	// Zoom out if the user hits escape
	document.addEventListener( 'keyup', function( event ) {
		if( level !== 1 && event.keyCode === 27 ) {
			zoom.out();
		}
	} );

	// Monitor mouse movement for panning
	document.addEventListener( 'mousemove', function( event ) {
		if( level !== 1 ) {
			mouseX = event.clientX;
			mouseY = event.clientY;
		}
	} );

	/**
	 * Applies the CSS required to zoom in, prefers the use of CSS3
	 * transforms but falls back on zoom for IE.
	 *
	 * @param {Object} rect
	 * @param {Number} scale
	 */
	function magnify( rect, scale ) {

		var scrollOffset = getScrollOffset();

		// Ensure a width/height is set
		rect.width = rect.width || 1;
		rect.height = rect.height || 1;

		// Center the rect within the zoomed viewport
		rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2;
		rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2;

		if( supportsTransforms ) {
			// Reset
			if( scale === 1 ) {
				document.body.style.transform = '';
				document.body.style.OTransform = '';
				document.body.style.msTransform = '';
				document.body.style.MozTransform = '';
				document.body.style.WebkitTransform = '';
			}
			// Scale
			else {
				var origin = scrollOffset.x +'px '+ scrollOffset.y +'px',
					transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')';

				document.body.style.transformOrigin = origin;
				document.body.style.OTransformOrigin = origin;
				document.body.style.msTransformOrigin = origin;
				document.body.style.MozTransformOrigin = origin;
				document.body.style.WebkitTransformOrigin = origin;

				document.body.style.transform = transform;
				document.body.style.OTransform = transform;
				document.body.style.msTransform = transform;
				document.body.style.MozTransform = transform;
				document.body.style.WebkitTransform = transform;
			}
		}
		else {
			// Reset
			if( scale === 1 ) {
				document.body.style.position = '';
				document.body.style.left = '';
				document.body.style.top = '';
				document.body.style.width = '';
				document.body.style.height = '';
				document.body.style.zoom = '';
			}
			// Scale
			else {
				document.body.style.position = 'relative';
				document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px';
				document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px';
				document.body.style.width = ( scale * 100 ) + '%';
				document.body.style.height = ( scale * 100 ) + '%';
				document.body.style.zoom = scale;
			}
		}

		level = scale;
	}

	/**
	 * Pan the document when the mosue cursor approaches the edges
	 * of the window.
	 */
	function pan() {
		var range = 0.12,
			rangeX = window.innerWidth * range,
			rangeY = window.innerHeight * range,
			scrollOffset = getScrollOffset();

		// Up
		if( mouseY < rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
		}
		// Down
		else if( mouseY > window.innerHeight - rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
		}

		// Left
		if( mouseX < rangeX ) {
			window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
		}
		// Right
		else if( mouseX > window.innerWidth - rangeX ) {
			window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
		}
	}

	function getScrollOffset() {
		return {
			x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
			y: window.scrollY !== undefined ? window.scrollY : window.pageYOffset
		}
	}

	return {
		/**
		 * Zooms in on either a rectangle or HTML element.
		 *
		 * @param {Object} options
		 *   - element: HTML element to zoom in on
		 *   OR
		 *   - x/y: coordinates in non-transformed space to zoom in on
		 *   - width/height: the portion of the screen to zoom in on
		 *   - scale: can be used instead of width/height to explicitly set scale
		 */
		to: function( options ) {

			// Due to an implementation limitation we can't zoom in
			// to another element without zooming out first
			if( level !== 1 ) {
				zoom.out();
			}
			else {
				options.x = options.x || 0;
				options.y = options.y || 0;

				// If an element is set, that takes precedence
				if( !!options.element ) {
					// Space around the zoomed in element to leave on screen
					var padding = 20;
					var bounds = options.element.getBoundingClientRect();

					options.x = bounds.left - padding;
					options.y = bounds.top - padding;
					options.width = bounds.width + ( padding * 2 );
					options.height = bounds.height + ( padding * 2 );
				}

				// If width/height values are set, calculate scale from those values
				if( options.width !== undefined && options.height !== undefined ) {
					options.scale = Math.max( Math.min( window.innerWidth / options.width, window.innerHeight / options.height ), 1 );
				}

				if( options.scale > 1 ) {
					options.x *= options.scale;
					options.y *= options.scale;

					magnify( options, options.scale );

					if( options.pan !== false ) {

						// Wait with engaging panning as it may conflict with the
						// zoom transition
						panEngageTimeout = setTimeout( function() {
							panUpdateInterval = setInterval( pan, 1000 / 60 );
						}, 800 );

					}
				}
			}
		},

		/**
		 * Resets the document zoom state to its default.
		 */
		out: function() {
			clearTimeout( panEngageTimeout );
			clearInterval( panUpdateInterval );

			magnify( { x: 0, y: 0 }, 1 );

			level = 1;
		},

		// Alias
		magnify: function( options ) { this.to( options ) },
		reset: function() { this.out() },

		zoomLevel: function() {
			return level;
		}
	}

})();

<commit_msg>Add call back when zooming ends<commit_after>/*!
 * zoom.js 0.3
 * http://lab.hakim.se/zoom-js
 * MIT licensed
 *
 * Copyright (C) 2011-2014 Hakim El Hattab, http://hakim.se
 */
var zoom = (function(){

	// The current zoom level (scale)
	var level = 1;

	// The current mouse position, used for panning
	var mouseX = 0,
		mouseY = 0;

	// Timeout before pan is activated
	var panEngageTimeout = -1,
		panUpdateInterval = -1;

	// Timeout for call back function
	var callbackTimeout = -1;

	// Check for transform support so that we can fallback otherwise
	var supportsTransforms = 	'WebkitTransform' in document.body.style ||
								'MozTransform' in document.body.style ||
								'msTransform' in document.body.style ||
								'OTransform' in document.body.style ||
								'transform' in document.body.style;

	if( supportsTransforms ) {
		// The easing that will be applied when we zoom in/out
		document.body.style.transition = 'transform 0.8s ease';
		document.body.style.OTransition = '-o-transform 0.8s ease';
		document.body.style.msTransition = '-ms-transform 0.8s ease';
		document.body.style.MozTransition = '-moz-transform 0.8s ease';
		document.body.style.WebkitTransition = '-webkit-transform 0.8s ease';
	}

	// Zoom out if the user hits escape
	document.addEventListener( 'keyup', function( event ) {
		if( level !== 1 && event.keyCode === 27 ) {
			zoom.out();
		}
	} );

	// Monitor mouse movement for panning
	document.addEventListener( 'mousemove', function( event ) {
		if( level !== 1 ) {
			mouseX = event.clientX;
			mouseY = event.clientY;
		}
	} );

	/**
	 * Applies the CSS required to zoom in, prefers the use of CSS3
	 * transforms but falls back on zoom for IE.
	 *
	 * @param {Object} rect
	 * @param {Number} scale
	 */
	function magnify( rect, scale ) {

		var scrollOffset = getScrollOffset();

		// Ensure a width/height is set
		rect.width = rect.width || 1;
		rect.height = rect.height || 1;

		// Center the rect within the zoomed viewport
		rect.x -= ( window.innerWidth - ( rect.width * scale ) ) / 2;
		rect.y -= ( window.innerHeight - ( rect.height * scale ) ) / 2;

		if( supportsTransforms ) {
			// Reset
			if( scale === 1 ) {
				document.body.style.transform = '';
				document.body.style.OTransform = '';
				document.body.style.msTransform = '';
				document.body.style.MozTransform = '';
				document.body.style.WebkitTransform = '';
			}
			// Scale
			else {
				var origin = scrollOffset.x +'px '+ scrollOffset.y +'px',
					transform = 'translate('+ -rect.x +'px,'+ -rect.y +'px) scale('+ scale +')';

				document.body.style.transformOrigin = origin;
				document.body.style.OTransformOrigin = origin;
				document.body.style.msTransformOrigin = origin;
				document.body.style.MozTransformOrigin = origin;
				document.body.style.WebkitTransformOrigin = origin;

				document.body.style.transform = transform;
				document.body.style.OTransform = transform;
				document.body.style.msTransform = transform;
				document.body.style.MozTransform = transform;
				document.body.style.WebkitTransform = transform;
			}
		}
		else {
			// Reset
			if( scale === 1 ) {
				document.body.style.position = '';
				document.body.style.left = '';
				document.body.style.top = '';
				document.body.style.width = '';
				document.body.style.height = '';
				document.body.style.zoom = '';
			}
			// Scale
			else {
				document.body.style.position = 'relative';
				document.body.style.left = ( - ( scrollOffset.x + rect.x ) / scale ) + 'px';
				document.body.style.top = ( - ( scrollOffset.y + rect.y ) / scale ) + 'px';
				document.body.style.width = ( scale * 100 ) + '%';
				document.body.style.height = ( scale * 100 ) + '%';
				document.body.style.zoom = scale;
			}
		}

		level = scale;
	}

	/**
	 * Pan the document when the mosue cursor approaches the edges
	 * of the window.
	 */
	function pan() {
		var range = 0.12,
			rangeX = window.innerWidth * range,
			rangeY = window.innerHeight * range,
			scrollOffset = getScrollOffset();

		// Up
		if( mouseY < rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
		}
		// Down
		else if( mouseY > window.innerHeight - rangeY ) {
			window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
		}

		// Left
		if( mouseX < rangeX ) {
			window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
		}
		// Right
		else if( mouseX > window.innerWidth - rangeX ) {
			window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
		}
	}

	function getScrollOffset() {
		return {
			x: window.scrollX !== undefined ? window.scrollX : window.pageXOffset,
			y: window.scrollY !== undefined ? window.scrollY : window.pageYOffset
		}
	}

	return {
		/**
		 * Zooms in on either a rectangle or HTML element.
		 *
		 * (necessary)
		 * @param {Object} options
		 *
		 *   (necessary)
		 *   - element: HTML element to zoom in on
		 *   OR
		 *   - x/y: coordinates in non-transformed space to zoom in on
		 *   - width/height: the portion of the screen to zoom in on
		 *   - scale: can be used instead of width/height to explicitly set scale
		 *
		 *   (optional)
		 *   - callback: call back when zooming in ends
		 */
		to: function( options ) {

			// Due to an implementation limitation we can't zoom in
			// to another element without zooming out first
			if( level !== 1 ) {
				zoom.out();
			}
			else {
				options.x = options.x || 0;
				options.y = options.y || 0;

				// If an element is set, that takes precedence
				if( !!options.element ) {
					// Space around the zoomed in element to leave on screen
					var padding = 20;
					var bounds = options.element.getBoundingClientRect();

					options.x = bounds.left - padding;
					options.y = bounds.top - padding;
					options.width = bounds.width + ( padding * 2 );
					options.height = bounds.height + ( padding * 2 );
				}

				// If width/height values are set, calculate scale from those values
				if( options.width !== undefined && options.height !== undefined ) {
					options.scale = Math.max( Math.min( window.innerWidth / options.width, window.innerHeight / options.height ), 1 );
				}

				if( options.scale > 1 ) {
					options.x *= options.scale;
					options.y *= options.scale;

					magnify( options, options.scale );

					if( options.pan !== false ) {

						// Wait with engaging panning as it may conflict with the
						// zoom transition
						panEngageTimeout = setTimeout( function() {
							panUpdateInterval = setInterval( pan, 1000 / 60 );
						}, 800 );

					}

					if ( !!options.callback ) {
	 						callbackTimeout = setTimeout ( function () {
	    					options.callback();
						}, 800);
					}
				}
			}
		},

		/**
		 * Resets the document zoom state to its default.
		 *
		 * (optional)
		 * @param {Object} options
		 *   - callback: call back when zooming out ends
		 *
		 */
		out: function( options ) {
			clearTimeout( panEngageTimeout );
			clearInterval( panUpdateInterval );
			clearTimeout( callbackTimeout );

			magnify( { x: 0, y: 0 }, 1 );

			if( typeof options !== "undefined" && typeof options.callback !== "undefined"){
       			setTimeout ( function () {
            		options.callback();
        		}, 800);
      		}

			level = 1;
		},

		// Alias
		magnify: function( options ) { this.to( options ) },
		reset: function() { this.out() },

		zoomLevel: function() {
			return level;
		}
	}

})();

<|endoftext|>