<commit_before>;(function (global) {

if ("EventSource" in global) return;

var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;

var EventSource = function (url) {
  var eventsource = this,
      interval = 500, // polling interval
      lastEventId = null,
      cache = '';

  if (!url || typeof url != 'string') {
    throw new SyntaxError('Not enough arguments');
  }

  this.URL = url;
  this.readyState = this.CONNECTING;
  this._pollTimer = null;
  this._xhr = null;

  function pollAgain(interval) {
    eventsource._pollTimer = setTimeout(function () {
      poll.call(eventsource);
    }, interval);
  }

  function poll() {
    try { // force hiding of the error message... insane?
      if (eventsource.readyState == eventsource.CLOSED) return;

      // NOTE: IE7 and upwards support
      var xhr = new XMLHttpRequest();
      xhr.open('GET', eventsource.URL, true);
      xhr.setRequestHeader('Accept', 'text/event-stream');
      xhr.setRequestHeader('Cache-Control', 'no-cache');
      // we must make use of this on the server side if we're working with Android - because they don't trigger
      // readychange until the server connection is closed
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

      if (lastEventId != null) xhr.setRequestHeader('Last-Event-ID', lastEventId);
      cache = '';

      xhr.timeout = 50000;
      xhr.onreadystatechange = function () {
        if ((this.readyState == 3 || this.readyState == 4) && this.status == 200) {
          // on success
          if (eventsource.readyState == eventsource.CONNECTING) {
            eventsource.readyState = eventsource.OPEN;
            eventsource.dispatchEvent('open', { type: 'open' });
          }

          var responseText = '';
          try {
            responseText = this.responseText || '';
          } catch (e) {}

          // process this.responseText
          var parts = responseText.substr(cache.length).split("\n"),
              eventType = 'message',
              data = [],
              i = 0,
              line = '';

          cache = responseText;

          // TODO handle 'event' (for buffer name), retry
          for (; i < parts.length; i++) {
            line = parts[i].replace(reTrim, '');
            if (line.indexOf('event') == 0) {
              eventType = line.replace(/event:?\s*/, '');
            } else if (line.indexOf('retry') == 0) {
              retry = parseInt(line.replace(/retry:?\s*/, ''));
              if(!isNaN(retry)) { interval = retry; }
            } else if (line.indexOf('data') == 0) {
              data.push(line.replace(/data:?\s*/, ''));
            } else if (line.indexOf('id:') == 0) {
              lastEventId = line.replace(/id:?\s*/, '');
            } else if (line.indexOf('id') == 0) { // this resets the id
              lastEventId = null;
            } else if (line == '') {
              if (data.length) {
                var event = new MessageEvent(data.join('\n'), eventsource.url, lastEventId);
                eventsource.dispatchEvent(eventType, event);
                data = [];
                eventType = 'message';
              }
            }
          }

          if (this.readyState == 4) pollAgain(interval);
          // don't need to poll again, because we're long-loading
        } else if (eventsource.readyState !== eventsource.CLOSED) {
          if (this.readyState == 4) { // and some other status
            // dispatch error
            eventsource.readyState = eventsource.CONNECTING;
            eventsource.dispatchEvent('error', { type: 'error' });
            pollAgain(interval);
          } else if (this.readyState == 0) { // likely aborted
            pollAgain(interval);
          } else {
          }
        }
      };

      xhr.send();

      setTimeout(function () {
        if (true || xhr.readyState == 3) xhr.abort();
      }, xhr.timeout);

      eventsource._xhr = xhr;

    } catch (e) { // in an attempt to silence the errors
      eventsource.dispatchEvent('error', { type: 'error', data: e.message }); // ???
    }
  };

  poll(); // init now
};

EventSource.prototype = {
  close: function () {
    // closes the connection - disabling the polling
    this.readyState = this.CLOSED;
    clearInterval(this._pollTimer);
    this._xhr.abort();
  },
  CONNECTING: 0,
  OPEN: 1,
  CLOSED: 2,
  dispatchEvent: function (type, event) {
    var handlers = this['_' + type + 'Handlers'];
    if (handlers) {
      for (var i = 0; i < handlers.length; i++) {
        handlers[i].call(this, event);
      }
    }

    if (this['on' + type]) {
      this['on' + type].call(this, event);
    }
  },
  addEventListener: function (type, handler) {
    if (!this['_' + type + 'Handlers']) {
      this['_' + type + 'Handlers'] = [];
    }

    this['_' + type + 'Handlers'].push(handler);
  },
  removeEventListener: function () {
    // TODO
  },
  onerror: null,
  onmessage: null,
  onopen: null,
  readyState: 0,
  URL: ''
};

var MessageEvent = function (data, origin, lastEventId) {
  this.data = data;
  this.origin = origin;
  this.lastEventId = lastEventId || '';
};

MessageEvent.prototype = {
  data: null,
  type: 'message',
  lastEventId: '',
  origin: ''
};

if ('module' in global) module.exports = EventSource;
global.EventSource = EventSource;

})(this);
<commit_msg>Change to Yaffle polyfill<commit_after>/**
 * eventsource.js
 * Available under MIT License (MIT)
 * https://github.com/Yaffle/EventSource/
 */

/*jslint indent: 2, vars: true */
/*global setTimeout, clearTimeout, navigator */

(function (global) {
  "use strict";

  function Map() {
    this.data = Object.create ? Object.create(null) : {};
  }

  var hasOwnProperty = Object.prototype.hasOwnProperty;

  var escapeKey = function (key) {
    return key.slice(0, 1) === "_" ? key + "~" : key;
  };

  Map.prototype = {
    get: function (key) {
      var k = escapeKey(key);
      var data = this.data;
      return hasOwnProperty.call(data, k) ? data[k] : undefined;
    },
    set: function (key, value) {
      this.data[escapeKey(key)] = value;
    },
    "delete": function (key) {
      delete this.data[escapeKey(key)];
    }
  };

  function Event(type) {
    this.type = type;
    this.eventPhase = 0;
    this.currentTarget = null;
    this.target = null;
  }

  Event.CAPTURING_PHASE = 1;
  Event.AT_TARGET = 2;
  Event.BUBBLING_PHASE = 3;

  function EventTarget() {
    this.listeners = new Map();
  }

  function throwError(e) {
    setTimeout(function () {
      throw e;
    }, 0);
  }

  EventTarget.prototype = {
    hasListeners: function (type) {
      return this.listeners.get(String(type)) !== undefined;
    },
    invokeEvent: function (event) {
      var type = String(event.type);
      var phase = event.eventPhase;
      var listeners = this.listeners;
      var typeListeners = listeners.get(type);
      if (!typeListeners) {
        return;
      }
      var length = typeListeners.length;
      var i = phase === Event.BUBBLING_PHASE ? 1 : 0;
      var increment = phase === Event.CAPTURING_PHASE || phase === Event.BUBBLING_PHASE ? 2 : 1;
      while (i < length) {
        event.currentTarget = this;
        var listener = typeListeners[i];
        if (listener !== null) {
          try {
            listener.call(this, event);
          } catch (e) {
            throwError(e);
          }
        }
        event.currentTarget = null;
        i += increment;
      }
    },
    dispatchEvent: function (event) {
      event.eventPhase = Event.AT_TARGET;
      this.invokeEvent(event);
    },
    addEventListener: function (type, callback, capture) {
      type = String(type);
      capture = Boolean(capture);
      var listeners = this.listeners;
      var typeListeners = listeners.get(type);
      if (!typeListeners) {
        listeners.set(type, typeListeners = []); // CAPTURING BUBBLING
      }
      var i = typeListeners.length - (capture ? 2 : 1);
      while (i >= 0) {
        if (typeListeners[i] === callback) {
          return;
        }
        i -= 2;
      }
      typeListeners.push(capture ? callback : null);
      typeListeners.push(capture ? null : callback);
    },
    removeEventListener: function (type, callback, capture) {
      type = String(type);
      capture = Boolean(capture);
      var listeners = this.listeners;
      var typeListeners = listeners.get(type);
      if (!typeListeners) {
        return;
      }
      var length = typeListeners.length;
      var filtered = [];
      var i = 0;
      while (i < length) {
        if (typeListeners[i + (capture ? 0 : 1)] !== callback) {
          filtered.push(typeListeners[i]);
          filtered.push(typeListeners[i + 1]);
        }
        i += 2;
      }
      if (filtered.length === 0) {
        listeners["delete"](type);
      } else {
        listeners.set(type, filtered);
      }
    }
  };

  function queue(callback, arg) {
    try {
      callback(arg);
    } catch (e) {
      throwError(e);
    }
  }

  // http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/comet-streaming-in-internet-explorer-with-xmlhttprequest-and-xdomainrequest.aspx?PageIndex=1#comments
  // XDomainRequest does not have a binary interface. To use with non-text, first base64 to string.
  // http://cometdaily.com/2008/page/3/

  var XHR = global.XMLHttpRequest;
  var xhr2 = Boolean(XHR && global.ProgressEvent && ((new XHR()).withCredentials !== undefined));
  var Transport = xhr2 ? XHR : global.XDomainRequest;
  var CONNECTING = 0;
  var OPEN = 1;
  var CLOSED = 2;
  var digits = /^\d+$/;
  var contentTypeRegExp = /^text\/event\-stream/i;
  var crlf = /[\r\n]/;

  function empty() {}

  function getDuration(value, def) {
    if (digits.test(value)) {
      var n = Number(value);
      return n < 1 ? 1 : (n > 18000000 ? 18000000 : n);
    }
    return def;
  }

  function MessageEvent(type, options) {
    Event.call(this, type);
    this.data = options.data;
    this.lastEventId = options.lastEventId;
  }

  var E = function () {};
  E.prototype = Event.prototype;
  MessageEvent.prototype = new E();

  function abort(xhr) {
    xhr.onload = xhr.onerror = xhr.onprogress = xhr.onreadystatechange = empty;
    xhr.abort();
  }

  function EventSource(url, options) {
    url = String(url);

    var that = this;
    var initialRetry = 1000;
    var retry = initialRetry;
    var retryLimit = 300000;
    var heartbeatTimeout = 45000;
    var wasActivity = false;
    var lastEventId = "";
    var xhr = new Transport();
    var timeout = 0;
    var withCredentials = Boolean(xhr2 && options && options.withCredentials);
    var charOffset = 0;
    var opened = false;
    var dataBuffer = [];
    var lastEventIdBuffer = "";
    var eventTypeBuffer = "";
    var wasCR = false;
    var responseBuffer = [];
    var readyState = CONNECTING;

    options = null;

    function close() {
      // http://dev.w3.org/html5/eventsource/ The close() method must close the connection, if any; must abort any instances of the fetch algorithm started for this EventSource object; and must set the readyState attribute to CLOSED.
      if (xhr !== null) {
        abort(xhr);
        xhr = null;
      }
      if (timeout !== 0) {
        clearTimeout(timeout);
        timeout = 0;
      }
      readyState = CLOSED;
      that.readyState = CLOSED;
    }

    function setConnectingState(event) {
      if (readyState !== CLOSED) {
        // setTimeout will wait before previous setTimeout(0) have completed
        if (retry > retryLimit) {
          retry = retryLimit;
        }
        timeout = setTimeout(openConnection, retry);
        retry = retry * 2 + 1;

        readyState = CONNECTING;
        that.readyState = CONNECTING;
        event.target = that;
        that.dispatchEvent(event);
        if (typeof that.onerror === "function") {
          that.onerror(event);
        }
      }
    }

    function onError() {
      if (timeout !== 0) {
        clearTimeout(timeout);
        timeout = 0;
      }
      queue(setConnectingState, new Event("error"));
    }

    function onXHRTimeout() {
      timeout = 0;
      onProgress();
      if (wasActivity) {
        wasActivity = false;
        timeout = setTimeout(onXHRTimeout, heartbeatTimeout);
      } else {
        abort(xhr);
        onError();
      }
    }

    function setOpenState(event) {
      if (readyState !== CLOSED) {
        readyState = OPEN;
        that.readyState = OPEN;
        event.target = that;
        that.dispatchEvent(event);
        if (typeof that.onopen === "function") {
          that.onopen(event);
        }
      }
    }

    function dispatchEvent(event) {
      if (readyState !== CLOSED) {
        var type = String(event.type);
        event.target = that;
        that.dispatchEvent(event);
        if (type === "message" && typeof that.onmessage === "function") {
          that.onmessage(event);
        }
      }
    }

    function onProgress() {
      if (!opened) {
        var contentType = "";
        try {
          contentType = xhr.getResponseHeader ? xhr.getResponseHeader("Content-Type") : xhr.contentType;
        } catch (error) {
          // invalid state error when xhr.getResponseHeader called after xhr.abort in Chrome 18
          throwError(error);
        }
        if (contentType && contentTypeRegExp.test(contentType)) {
          opened = true;
          wasActivity = true;
          retry = initialRetry;
          queue(setOpenState, new Event("open"));
        }
      }

      if (opened && readyState !== CLOSED) {
        var responseText = xhr.responseText || "";
        var part = responseText.slice(charOffset);
        if (part.length > 0) {
          wasActivity = true;
        }
        if (wasCR && part.length > 0) {
          if (part.slice(0, 1) === "\n") {
            part = part.slice(1);
          }
          wasCR = false;
        }
        var i = 0;
        while ((i = part.search(crlf)) !== -1) {
          var field = responseBuffer.join("") + part.slice(0, i);
          responseBuffer.length = 0;
          if (part.length > i + 1) {
            part = part.slice(i + (part.slice(i, i + 2) === "\r\n" ? 2 : 1));
          } else {
            if (part.slice(i, i + 1) === "\r") {
              wasCR = true;
            }
            part = "";
          }

          if (field !== "") {
            var value = "";
            var j = field.indexOf(":");
            if (j !== -1) {
              value = field.slice(j + (field.slice(j + 1, j + 2) === " " ? 2 : 1));
              field = field.slice(0, j);
            }

            if (field === "data") {
              dataBuffer.push(value);
            } else if (field === "id") {
              lastEventIdBuffer = value;
            } else if (field === "event") {
              eventTypeBuffer = value;
            } else if (field === "retry") {
              initialRetry = getDuration(value, initialRetry);
              retry = initialRetry;
              if (retryLimit < initialRetry) {
                retryLimit = initialRetry;
              }
            } else if (field === "retryLimit") {//!
              retryLimit = getDuration(value, retryLimit);
            } else if (field === "heartbeatTimeout") {//!
              heartbeatTimeout = getDuration(value, heartbeatTimeout);
              if (timeout !== 0) {
                clearTimeout(timeout);
                timeout = setTimeout(onXHRTimeout, heartbeatTimeout);
              }
            }

          } else {
            // dispatch the event
            if (dataBuffer.length !== 0) {
              lastEventId = lastEventIdBuffer;
              queue(dispatchEvent, new MessageEvent(eventTypeBuffer || "message", {
                data: dataBuffer.join("\n"),
                lastEventId: lastEventIdBuffer
              }));
            }
            // Set the data buffer and the event name buffer to the empty string.
            dataBuffer.length = 0;
            eventTypeBuffer = "";
          }
        }
        if (part !== "") {
          responseBuffer.push(part);
        }
        charOffset = responseText.length;
      }
    }

    function onProgress2() {
      onProgress();
      if (opened && readyState !== CLOSED) {
        var responseText = xhr.responseText || "";
        if (responseText.length > 1024 * 1024) {
          abort(xhr);
          onError();
        }
      }
    }

    function onLoad() {
      onProgress();
      onError();
    }

    function onReadyStateChange() {
      if (xhr.readyState === 3) {
        onProgress2();
      }
    }

    function openConnection() {
      timeout = 0;
      if (navigator.onLine === false) {
        // "online" event is not supported under Web Workers
        timeout = setTimeout(openConnection, 500);
        return;
      }
      // XDomainRequest#abort removes onprogress, onerror, onload

      xhr.onload = xhr.onerror = onLoad;

      // onprogress fires multiple times while readyState === 3
      // onprogress should be setted before calling "open" for Firefox 3.6
      if (xhr.mozAnon === undefined) {// Firefox shows loading indicator
        xhr.onprogress = onProgress2;
      }

      // Firefox 3.6
      // onreadystatechange fires more often, than "progress" in Chrome and Firefox
      xhr.onreadystatechange = onReadyStateChange;

      wasActivity = false;
      timeout = setTimeout(onXHRTimeout, heartbeatTimeout);

      charOffset = 0;
      opened = false;
      dataBuffer.length = 0;
      eventTypeBuffer = "";
      lastEventIdBuffer = lastEventId;//resets to last successful
      wasCR = false;
      responseBuffer.length = 0;

      // with GET method in FF xhr.onreadystatechange with readyState === 3 does not work + POST = no-cache
      xhr.open("POST", url, true);

      // withCredentials should be setted after "open" for Safari and Chrome (< 19 ?)
      xhr.withCredentials = withCredentials;

      xhr.responseType = "text";

      if (xhr.setRequestHeader) { // !XDomainRequest
        // http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html
        // Cache-Control is not a simple header
        // Request header field Cache-Control is not allowed by Access-Control-Allow-Headers.
        //xhr.setRequestHeader("Cache-Control", "no-cache");

        // Chrome bug:
        // http://code.google.com/p/chromium/issues/detail?id=71694
        // If you force Chrome to have a whitelisted content-type, either explicitly with setRequestHeader(), or implicitly by sending a FormData, then no preflight is done.
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Accept", "text/event-stream");

        // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
        // +setRequestHeader should not be used to avoid preflight requests
        //if (lastEventId !== "") {
        //  xhr.setRequestHeader("Last-Event-ID", lastEventId);
        //}
      }
      xhr.send(lastEventId !== "" ? "Last-Event-ID=" + encodeURIComponent(lastEventId) : "");
    }

    EventTarget.call(this);
    this.close = close;
    this.url = url;
    this.readyState = readyState;
    this.withCredentials = withCredentials;

    openConnection();
  }

  function F() {
    this.CONNECTING = CONNECTING;
    this.OPEN = OPEN;
    this.CLOSED = CLOSED;
  }
  F.prototype = EventTarget.prototype;

  EventSource.prototype = new F();
  EventSource.CONNECTING = CONNECTING;
  EventSource.OPEN = OPEN;
  EventSource.CLOSED = CLOSED;

  if (Transport) {
    global.EventSource = EventSource;
  }

}(this));
<|endoftext|>


<commit_before>var $ = require('jquery')
var _ = require('lodash')
var DateTime = require('dateutils').DateTime
var DateFormat = require('dateutils').DateFormat
var DateLocale = require('dateutils').DateLocale
var attachFastClick = require('fastclick')
var locationTable = require('./locationTable')
var navigation = require('./navigation')
attachFastClick(document.body)
var activeDate = DateTime.today()
var $window = $(window)
var $document = $(document)

var didScroll = false
var alreadyLoadingMoreResults = false
$(window).scroll(function () { didScroll = true });

setInterval(function () {
    if (didScroll) {
        didScroll = false;
        if (!alreadyLoadingMoreResults && $window.scrollTop() + $window.height() > $document.height() - 400) {
            loadMoreResults()
        }
    }
}, 250)

navigation.init()
locationTable.init()
listAvailabilityForDate(activeDate, 30)
initJumpToDate()

$('#schedule').on('click', '.locationBoxes', function (e) {
    var $locationBoxes = $(e.currentTarget)
    $locationBoxes.toggleClass('showDetails')
})

function loadMoreResults() {
    if (!alreadyLoadingMoreResults) {
        alreadyLoadingMoreResults = true
        activeDate = activeDate.plusDays(1)
        listAvailabilityForDate(activeDate, 2)
    }
}

function listAvailabilityForDate(requestedDateTime, days) {
    var requestedDate = requestedDateTime.toISODateString()
    $('#schedule').addClass('loading')
    return $.getJSON('/courts?date=' + requestedDate + '&days=' + days, function (allDataWithDates) {
        alreadyLoadingMoreResults = false

        $('#schedule').removeClass('loading')
            //.append($timeStamp)
            .append(allDataWithDates.map(function (allDataWithDate) {
                var deltaMin = parseInt((new Date().getTime() - allDataWithDate.timestamp) / 60000, 10)
                var timeStamp = 'päivitetty ' + deltaMin + ' minuuttia sitten'
                var currentDate = allDataWithDate.date.split('T')[0]
                var data = allDataWithDate.freeCourts
                return groupBySortedAsList(data, 'date').filter(function (x) {
                    return x.key === currentDate
                }).map(function (dateObject) {
                    return toDateSection(dateObject, timeStamp)
                }).join('')
            }).join(''))
        if ($window.height() === $document.height()) loadMoreResults()
    })
}

function toDateSection(dateObject, timeStamp) {
    var isoDate = dateObject.key
    var times = dateObject.val.filter(function (reservation) {
        var startingDateTime = DateTime.fromIsoDateTime(reservation.date + 'T' + reservation.time)
        return startingDateTime.compareTo(new DateTime().minusMinutes(60)) >= 0
    })

    var dateTime = DateTime.fromIsoDate(isoDate)
    return '

' + DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI) + '
' +
        '
' + timeStamp + '

' +
        groupBySortedAsList(times, 'time').map(toTimeRow).join('')
}

function toTimeRow(timeObject) {
    var isoTime = timeObject.key
    var fields = timeObject.val
    var hm = isoTime.split(':')
    return '
' + isoTime + '' +
        groupBySortedAsList(fields, 'location').map(toLocationButtonGroup).join('') + '
'
}

function toLocationButtonGroup(locationFields) {
    var location = locationFields.key
    var fields = locationFields.val
    return '' + collapsedButtons(location, fields) + modal(fields) + ''
}

function modal(fields) {
    var dateTime = DateTime.fromIsoDate(fields[0].date)
    return '
' +
        '
' + fields[0].location + ' ' + DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI) + ' klo ' + fields[0].time + '
'
        + fields.map(function (field) {
            return '
<button class="'+field.type+' '+ field.location +'">  </button> ' + field.field + ', ' + field.price + '€
'
        }).join('') + '
×

'
}
function collapsedButtons(location, fields) {
    return groupBySortedAsList(fields, 'type').filter(function (fieldsForType) {
        return fieldsForType.val.length > 0
    }).map(function (fieldsForType) {
        var type = fieldsForType.key
        var field = fieldsForType.val[0]
        var hasDoubleLessons = fieldsForType.val.some(function (field) { return field.doubleLesson })
        return '<button type="button" class="locationLabel btn ' + location + ' ' + field.type + ' '+ (hasDoubleLessons ? 'double': 'single') +' btn-xs">' + (field.price ? field.price + '€' : '  ') + '</button>'
    }).join(' ')
}

function toButtonMarkup(field) {
    return '<button type="button" class="fieldLabel ' + field.location + ' ' + field.type + (field.doubleLesson ? ' double' : ' single') + '">' + field.field + '</button>'
}

function groupBySortedAsList(list, key) {
    return _.sortBy(_.map(_.groupBy(list, key), objectToArray), 'key')
}

function objectToArray(val, key) {
    return {key: key, val: val}
}

function initJumpToDate() {
    $('.jumpToDate').html(_.range(1, 60).map(function (delta) {
        var dateTime = new DateTime().plusDays(delta)
        var format = DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI)
        return '<option value="' + dateTime.toISODateString() + '">' + format + '</option>'
    }).join('\n')).change(function () {
        activeDate = DateTime.fromIsoDate($(this).val())
        $('#schedule').empty()
        alreadyLoadingMoreResults = true
        listAvailabilityForDate(activeDate, 2)
    })
}
<commit_msg>Improve modal styles<commit_after>var $ = require('jquery')
var _ = require('lodash')
var DateTime = require('dateutils').DateTime
var DateFormat = require('dateutils').DateFormat
var DateLocale = require('dateutils').DateLocale
var attachFastClick = require('fastclick')
var locationTable = require('./locationTable')
var navigation = require('./navigation')
attachFastClick(document.body)
var activeDate = DateTime.today()
var $window = $(window)
var $document = $(document)

var didScroll = false
var alreadyLoadingMoreResults = false
$(window).scroll(function () { didScroll = true });

setInterval(function () {
    if (didScroll) {
        didScroll = false;
        if (!alreadyLoadingMoreResults && $window.scrollTop() + $window.height() > $document.height() - 400) {
            loadMoreResults()
        }
    }
}, 250)

navigation.init()
locationTable.init()
listAvailabilityForDate(activeDate, 30)
initJumpToDate()

$('#schedule').on('click', '.locationBoxes', function (e) {
    var $locationBoxes = $(e.currentTarget)
    $locationBoxes.toggleClass('showDetails')
})

function loadMoreResults() {
    if (!alreadyLoadingMoreResults) {
        alreadyLoadingMoreResults = true
        activeDate = activeDate.plusDays(1)
        listAvailabilityForDate(activeDate, 2)
    }
}

function listAvailabilityForDate(requestedDateTime, days) {
    var requestedDate = requestedDateTime.toISODateString()
    $('#schedule').addClass('loading')
    return $.getJSON('/courts?date=' + requestedDate + '&days=' + days, function (allDataWithDates) {
        alreadyLoadingMoreResults = false

        $('#schedule').removeClass('loading')
            //.append($timeStamp)
            .append(allDataWithDates.map(function (allDataWithDate) {
                var deltaMin = parseInt((new Date().getTime() - allDataWithDate.timestamp) / 60000, 10)
                var timeStamp = 'päivitetty ' + deltaMin + ' minuuttia sitten'
                var currentDate = allDataWithDate.date.split('T')[0]
                var data = allDataWithDate.freeCourts
                return groupBySortedAsList(data, 'date').filter(function (x) {
                    return x.key === currentDate
                }).map(function (dateObject) {
                    return toDateSection(dateObject, timeStamp)
                }).join('')
            }).join(''))
        if ($window.height() === $document.height()) loadMoreResults()
    })
}

function toDateSection(dateObject, timeStamp) {
    var isoDate = dateObject.key
    var times = dateObject.val.filter(function (reservation) {
        var startingDateTime = DateTime.fromIsoDateTime(reservation.date + 'T' + reservation.time)
        return startingDateTime.compareTo(new DateTime().minusMinutes(60)) >= 0
    })

    var dateTime = DateTime.fromIsoDate(isoDate)
    return '

' + DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI) + '
' +
        '
' + timeStamp + '

' +
        groupBySortedAsList(times, 'time').map(toTimeRow).join('')
}

function toTimeRow(timeObject) {
    var isoTime = timeObject.key
    var fields = timeObject.val
    var hm = isoTime.split(':')
    return '
' + isoTime + '' +
        groupBySortedAsList(fields, 'location').map(toLocationButtonGroup).join('') + '
'
}

function toLocationButtonGroup(locationFields) {
    var location = locationFields.key
    var fields = locationFields.val
    return '' + collapsedButtons(location, fields) + modal(fields) + ''
}

function modal(fields) {
    var dateTime = DateTime.fromIsoDate(fields[0].date)
    return '
' +
        '
' + fields[0].location + ' ' + DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI) + ' klo ' + fields[0].time + '
'
        + fields.map(toButtonMarkup).join('') + '
×

'
}
function collapsedButtons(location, fields) {
    return groupBySortedAsList(fields, 'type').filter(function (fieldsForType) {
        return fieldsForType.val.length > 0
    }).map(function (fieldsForType) {
        var type = fieldsForType.key
        var field = fieldsForType.val[0]
        var hasDoubleLessons = fieldsForType.val.some(function (field) { return field.doubleLesson })
        return '<button type="button" class="locationLabel btn ' + location + ' ' + field.type + ' '+ (hasDoubleLessons ? 'double': 'single') +' btn-xs">' + (field.price ? field.price + '€' : '  ') + '</button>'
    }).join(' ')
}

function toButtonMarkup(field) {
    return '<button type="button" class="fieldLabel ' + field.location + ' ' + field.type + (field.doubleLesson ? ' double' : ' single') + '">' + field.field + ', ' + field.price + '€</button>'
}

function groupBySortedAsList(list, key) {
    return _.sortBy(_.map(_.groupBy(list, key), objectToArray), 'key')
}

function objectToArray(val, key) {
    return {key: key, val: val}
}

function initJumpToDate() {
    $('.jumpToDate').html(_.range(1, 60).map(function (delta) {
        var dateTime = new DateTime().plusDays(delta)
        var format = DateFormat.format(dateTime, DateFormat.patterns.FiWeekdayDatePattern, DateLocale.FI)
        return '<option value="' + dateTime.toISODateString() + '">' + format + '</option>'
    }).join('\n')).change(function () {
        activeDate = DateTime.fromIsoDate($(this).val())
        $('#schedule').empty()
        alreadyLoadingMoreResults = true
        listAvailabilityForDate(activeDate, 2)
    })
}
<|endoftext|>


<commit_before>"use strict";

var gameState = {
    board : [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    player1 : '',
    player2 : 'H',
    challenge : '',
    round : 1,
    clickedPosition : ''
}

var currentTurn = 'player1';

var game = document.getElementsByClassName("game")[0];
var challengeContainer = document.getElementsByClassName("pick-game__container")[0];
var symbolContainer = document.getElementsByClassName("pick-game__symbol-container")[0];
var pickChallenge = document.getElementsByClassName("pick-game__challenge");
var challengeButton = document.getElementsByClassName("pick-game__symbol");
var player = document.getElementsByClassName("player")[0];

for(var i = 0; i < challengeButton.length; i++) {
  addListenerToChallengeButtons(i);
}

function addListenerToChallengeButtons(i){
  challengeButton[i].addEventListener("click", function() {

    var symbol = event.target.innerHTML;

    if (gameState.player1 === '' && gameState.challenge === 'Human vs. Human'){
      addSymbol(symbol, 'player1');
      player.innerHTML = 'Player 2';
    }
    else if (gameState.player1 === ''){
      addSymbol(symbol, 'player1');
      swapVisibility(symbolContainer, game);
      startMessage()
    }
    else if (gameState.player1 === symbol){
      player.innerHTML = 'That symbol has been taken!';
    }
    else {
      addSymbol(symbol, 'player2');
      swapVisibility(symbolContainer, game);
      startMessage()
    }
  });
}

for(var i = 0; i < pickChallenge.length; i++) {
  addListenerToSymbolButtons();
}

function addListenerToSymbolButtons(){
  pickChallenge[i].addEventListener("click", function() {
    var challenge = event.target.innerHTML;

    if (challenge === 'Human vs. Human'){
      player.innerHTML = 'Player 1';
    }

    swapVisibility(challengeContainer, symbolContainer);
    addChallenge(challenge);
  });
}

function addChallenge(challenge){
  gameState.challenge = challenge;
}

function addSymbol(symbol, player){
  gameState[player] = symbol;
}

function swapVisibility(visible, hidden){
  hide(visible);
  show(hidden);
}

function hide(element){
  element.classList.add("hidden");
  element.classList.remove("visible");
}

function show(element){
  element.classList.add("visible");
  element.classList.remove("hidden");
}

/////////////////////////////game logic below //////////////////////////////////

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

(function(){
  var box = document.getElementsByClassName("box");

  box[0].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[0]);
      startGame();
    }
  });

  box[1].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[1]);
      gameState.clickedPosition = 1;
      startGame();
    }
  });

  box[2].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[2]);
      gameState.clickedPosition = 2;
      startGame();
    }
  });

  box[3].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[3]);
      gameState.clickedPosition = 3;
      startGame();
    }
  });

  box[4].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[4]);
      gameState.clickedPosition = 4;
      startGame();
    }
  });

  box[5].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[5]);
      gameState.clickedPosition = 5;
      startGame();
    }
  });

  box[6].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[6]);
      gameState.clickedPosition = 6;
      startGame();
    }
  });

  box[7].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[7]);
      gameState.clickedPosition = 7;
      startGame();
    }
  });

  box[8].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      markBox(box[8]);
      gameState.clickedPosition = 8;
      startGame();
    }
  });

})();

function markBox(box){
  box.innerHTML = gameState.player1;
};

var round = 1;

function startMessage(){
  console.log("Click a square to make your first move!"); // log this to screen
}

var startGame = function(){

  logRound();
  var board = gameState.board;

  if(makeMove(gameState.clickedPosition, 'player1')){
    if(hasSomeoneWon(gameState.board)[0] || isBoardFilled(board)) {
      endGame();
    }
    findNextMove(board);
    if(hasSomeoneWon(board)[0] || isBoardFilled(board)) {
      endGame();
    } else {
      logBoardToConsole(board);
    }
  }

};

var logRound = function(){
  console.log('  Round ' + round); // print this on screen
  round++
};

var makeMove = function(pos, player){
  var play = gameState[currentTurn];
  if(player !== currentTurn){return false;}
  if(pos >= 0 && pos <= 8 && !isNaN(pos) && gameState.board[pos] === ' '){
    gameState.board.splice(pos, 1, play);
    currentTurn = (currentTurn === 'player1') ? 'player2' : 'player1';
    return true;
  }
  return false;
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(board){
  var board_string = gameState.board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    logBoardToConsole();
    console.log('Game over.', theWinner, 'is the winner!');
    return [true, theWinner];
  }
  return [false, null];
};

// return true if the board is filled
var isBoardFilled = function(){
  if(gameState.board.indexOf(' ') === -1){
    console.log("Game over, it's a draw!");
    return true;
  }
  return false;
};

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run defaultMove()
var findNextMove = function(board){
  var nextPos = makeWinningMove(board);
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    if(nextPos === -1){
      nextPos = defaultMove(board);
    }
  }
  makeMove(nextPos, gameState.player2);
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var defaultMove = function(board){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var logBoardToConsole = function(board){
  console.log(board_display(board));
};

var board_display = function(board){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};
<commit_msg>Add correct logic for X vs O. Human vs Human.<commit_after>"use strict";

var gameState = {
    board : [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    player1 : '',
    player2 : 'O',
    challenge : '',
    round : 1,
    clickedPosition : ''
}

var currentTurn = 'player1';

var game = document.getElementsByClassName("game")[0];
var challengeContainer = document.getElementsByClassName("pick-game__container")[0];
var symbolContainer = document.getElementsByClassName("pick-game__symbol-container")[0];
var pickChallenge = document.getElementsByClassName("pick-game__challenge");
var challengeButton = document.getElementsByClassName("pick-game__symbol");
var player = document.getElementsByClassName("player")[0];

for(var i = 0; i < challengeButton.length; i++) {
  addListenerToChallengeButtons(i);
}

function addListenerToChallengeButtons(i){
  challengeButton[i].addEventListener("click", function() {

    var symbol = event.target.innerHTML;

    if (gameState.player1 === '' && gameState.challenge === 'Human vs. Human'){
      addSymbol(symbol, 'player1');
      player.innerHTML = 'Player 2';
    }
    else if (gameState.player1 === ''){
      addSymbol(symbol, 'player1');
      swapVisibility(symbolContainer, game);
      startMessage()
    }
    else if (gameState.player1 === symbol){
      player.innerHTML = 'That symbol has been taken!';
    }
    else {
      addSymbol(symbol, 'player2');
      swapVisibility(symbolContainer, game);
      startMessage()
    }
  });
}

for(var i = 0; i < pickChallenge.length; i++) {
  addListenerToSymbolButtons();
}

function addListenerToSymbolButtons(){
  pickChallenge[i].addEventListener("click", function() {
    var challenge = event.target.innerHTML;

    if (challenge === 'Human vs. Human'){
      player.innerHTML = 'Player 1';
    }

    swapVisibility(challengeContainer, symbolContainer);
    addChallenge(challenge);
  });
}

function addChallenge(challenge){
  gameState.challenge = challenge;
}

function addSymbol(symbol, player){
  gameState[player] = symbol;
}

function swapVisibility(visible, hidden){
  hide(visible);
  show(hidden);
}

function hide(element){
  element.classList.add("hidden");
  element.classList.remove("visible");
}

function show(element){
  element.classList.add("visible");
  element.classList.remove("hidden");
}

/////////////////////////////game logic below //////////////////////////////////

// regex matches if current player is 1 move away from winning & supplies winning move
var winningMovePatterns = [
                           [(/ OO....../),0],[(/O..O.. ../),6],[(/......OO /),8],
                           [(/.. ..O..O/),2],[(/ ..O..O../),0],[(/...... OO/),6],
                           [(/..O..O.. /),8],[(/OO ....../),2],[(/ ...O...O/),0],
                           [(/..O.O. ../),6],[(/O...O... /),8],[(/.. .O.O../),2],
                           [(/O O....../),1],[(/O.. ..O../),3],[(/......O O/),7],
                           [(/..O.. ..O/),5],[(/. ..O..O./),1],[(/... OO.../),3],
                           [(/.O..O.. ./),7],[(/...OO .../),5]
                          ];

// regex matches if opponent is 1 move away from winning & supplies blocking move
var blockingPatterns = [
                        [(/  X . X  /),1],[(/ XX....../),0],[(/X..X.. ../),6],
                        [(/......XX /),8],[(/.. ..X..X/),2],[(/ ..X..X../),0],
                        [(/...... XX/),6],[(/..X..X.. /),8],[(/XX ....../),2],
                        [(/.. .X...X/),2],[(/..X.X. ../),6],[(/X...X... /),8],
                        [(/.. .X.X../),2],[(/X X....../),1],[(/X.. ..X../),3],
                        [(/......X X/),7],[(/..X.. ..X/),5],[(/. ..X..X./),1],
                        [(/... XX.../),3],[(/.X..X.. ./),7],[(/...XX .../),5],
                        [(/ X X.. ../),0],[(/ ..X.. X /),6],[(/.. ..X X /),8],
                        [(/ X ..X.. /),2],[(/  XX.. ../),0],[(/X.. .. X /),6],
                        [(/.. .XX   /),8],[(/X  ..X.. /),2],[(/ X  ..X../),0],
                        [(/ ..X..  X/),6],[(/..X..  X /),8],[(/X  ..X.. /),2]
                       ];

// regex matches if a player has won & supplies the winning player
var hasWonPatterns = [
                      [(/OOO....../),'O'],[(/...OOO.../),'O'],[(/......OOO/),'O'],
                      [(/O..O..O../),'O'],[(/.O..O..O./),'O'],[(/..O..O..O/),'O'],
                      [(/O...O...O/),'O'],[(/..O.O.O../),'O'],[(/XXX....../),'X'],
                      [(/...XXX.../),'X'],[(/......XXX/),'X'],[(/X..X..X../),'X'],
                      [(/.X..X..X./),'X'],[(/..X..X..X/),'X'],[(/X...X...X/),'X'],
                      [(/..X.X.X../),'X']
                     ];

  var box = document.getElementsByClassName("box");

  box[0].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 0;
      startGame(gameState.clickedPosition);
    }
  });

  box[1].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 1;
      startGame(gameState.clickedPosition);
    }
  });

  box[2].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 2;
      startGame(gameState.clickedPosition);
    }
  });

  box[3].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 3;
      startGame(gameState.clickedPosition);
    }
  });

  box[4].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 4;
      startGame(gameState.clickedPosition);
    }
  });

  box[5].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 5;
      startGame(gameState.clickedPosition);
    }
  });

  box[6].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 6;
      startGame(gameState.clickedPosition);
    }
  });

  box[7].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 7;
      startGame(gameState.clickedPosition);
    }
  });

  box[8].addEventListener("click", function() {
    if (currentTurn === 'player1'){
      gameState.clickedPosition = 8;
      startGame(gameState.clickedPosition);
    }
  });

function markBox(pos, player){
  box[pos].innerHTML = gameState[player];
};

var round = 1;

function startMessage(){
  console.log("Click a square to make your first move!"); // log this to screen
}

var startGame = function(pos){
  makeMove(pos, gameState.player1);
  hasSomeoneWon()[0];
  if (isBoardFilled()){
    return;
  };
  findNextMove(gameState.board);
  hasSomeoneWon()[0];
  if (isBoardFilled()){
    return;
  };
};

var makeMove = function(pos, symbol){
  if(pos >= 0 && pos <= 8 && gameState.board[pos] === ' '){
    gameState.board.splice(pos, 1, symbol);
    currentTurn = (currentTurn === 'player1') ? 'player2' : 'player1';
    logBoardToConsole(gameState.board);
    console.log(gameState.board);
  }
};

// this searches winningMovePatterns then blockingPatterns and if there is no
// match run defaultMove()
var findNextMove = function(board){
  var nextPos = makeWinningMove(board);
  console.log(nextPos, 'winning move');
  if(nextPos === -1){
    nextPos = makeBlockingMove(board);
    console.log(nextPos, 'blocking move');
    if(nextPos === -1){
      nextPos = defaultMove(board);
      console.log(nextPos, 'default move');
    }
  }
  makeMove(nextPos, gameState.player2);
};

var logRound = function(){
  console.log('  Round ' + round); // print this on screen
  round++
};

// if the board matches a pattern from hasWonPatterns, return the winner
var hasSomeoneWon = function(){
  var board_string = gameState.board.join('');
  var theWinner = null;
  for(var i = 0;i < hasWonPatterns.length;i++){
    var array = board_string.match(hasWonPatterns[i][0]);
    if(array){
      theWinner = hasWonPatterns[i][1];
    }
  }
  if(theWinner){
    var board = gameState.board
    logBoardToConsole(board);
    console.log('Game over.', theWinner, 'is the winner!');
    return [true, theWinner];
  }
  return [false, null];
};

// return true if the board is filled
var isBoardFilled = function(){
  if(gameState.board.indexOf(' ') === -1){
    console.log("Game over, it's a draw!");
    return true;
  }
  return false;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeWinningMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < winningMovePatterns.length;i++){
    var array = board_string.match(winningMovePatterns[i][0]);
    if(array){ // this is only truthy when someone wins
      return winningMovePatterns[i][1];
    }
  }
  return -1;
};

// return the next move by matching a pattern from winningMovePatterns and returning the number
// (the second value in the array)
var makeBlockingMove = function(board){
  var board_string = board.join('');
  for(var i = 0;i < blockingPatterns.length;i++){
    var array = board_string.match(blockingPatterns[i][0]);
      if(array){return blockingPatterns[i][1];}
  }
  return -1;
};

// if the center of board is free, go there, if not go to position 0
var defaultMove = function(board){
  return board[4] === ' ' ? 4 : board.indexOf(' ');
};

var logBoardToConsole = function(board){
  console.log(board_display(board));
};

var board_display = function(board){
  return ' '+board[0]+' |'+' '+board[1]+' |'+' '+board[2]+'\n===+===+===\n'+' '+
             board[3]+' |'+' '+board[4]+' |'+' '+board[5]+'\n===+===+===\n'+' '+
             board[6]+' |'+' '+board[7]+' |'+' '+board[8];
};
<|endoftext|>


<commit_before>function error() {
    alert("YOU HAZ ERRORS");
    debugger;
}
function hideLoadingScreen() {
    document.getElementById("loadingElement").style.display = "none";
}
$(function () { return hideLoadingScreen(); });
var animations = [
    "spin",
    "zoom",
    "bg",
    "invert",
    "blur",
    "rainbow"
];
function displayLoadingScreen() {
    var animationToUse = animations[Math.floor(Math.random() * animations.length)];
    document.getElementById("loadingElement").style.display = "block";
    document.getElementById("loadingTrollFaceScreen").style.animationName = animationToUse;
}
var pusher;
$(function () {
    pusher = new Pusher($('meta[name="pusher"]').attr('content'), {
        cluster: "eu"
    });
});
function getImages(query) {
    $.post({
        url: "/lol",
        data: {
            text: query
        }
    }).done(function (httpDataStr) {
        var httpData = JSON.parse(httpDataStr);
        if (httpData["error"] != undefined) {
            error();
        }
        var channel = pusher.subscribe(httpData.data.task);
        channel.bind("lol", function (pusherData) {
            var imageCont = document.createElement("div");
            pusherData.message.ids.forEach(function (id) {
                var newImage = document.createElement("img");
                newImage.src = "result/" + id;
                imageCont.appendChild(newImage);
            });
            document.getElementById("downloadedImageCont").appendChild(imageCont);
        });
    }).fail(function (error) {
        error();
    });
}
function postForm() {
    if (document.getElementById("inputBox").value != "") {
        getImages(document.getElementById("inputBox").value);
    }
    else {
        alert("Enter a value");
    }
}
<commit_msg>Updated class name<commit_after>function error() {
    alert("YOU HAZ ERRORS");
    debugger;
}
function hideLoadingScreen() {
    document.getElementById("loadingElement").style.display = "none";
}
$(function () { return hideLoadingScreen(); });
var animations = [
    "spin",
    "zoom",
    "bg",
    "invert",
    "blur",
    "rainbow"
];
function displayLoadingScreen() {
    var animationToUse = animations[Math.floor(Math.random() * animations.length)];
    document.getElementById("loadingElement").style.display = "block";
    document.getElementById("loadingTrollFaceScreen").style.animationName = animationToUse;
}
var pusher;
$(function () {
    pusher = new Pusher($('meta[name="pusher"]').attr('content'), {
        cluster: "eu"
    });
});
function getImages(query) {
    $.post({
        url: "/lol",
        data: {
            text: query
        }
    }).done(function (httpDataStr) {
        var httpData = JSON.parse(httpDataStr);
        if (httpData["error"] != undefined) {
            error();
        }
        var channel = pusher.subscribe(httpData.data.task);
        channel.bind("lol", function (pusherData) {
            var imageCont = document.createElement("div");
            pusherData.message.ids.forEach(function (id) {
                var newImage = document.createElement("img");
                newImage.src = "result/" + id;
                imageCont.appendChild(newImage);
            });
            document.getElementById("downloadedImageOuter").appendChild(imageCont);
        });
    }).fail(function (error) {
        error();
    });
}
function postForm() {
    if (document.getElementById("inputBox").value != "") {
        getImages(document.getElementById("inputBox").value);
    }
    else {
        alert("Enter a value");
    }
}
<|endoftext|>


<commit_before>var settings_ui = (function () {

var exports = {};

exports.display_checkmark = function ($elem) {
    var check_mark = document.createElement("img");
    check_mark.src = "/static/images/checkbox-green.svg";
    $elem.prepend(check_mark);
    $(check_mark).css("width", "13px");
};

exports.strings = {};
function _initialize() {
    exports.strings = {
        success: i18n.t("Saved"),
        failure: i18n.t("Save failed"),
        saving: i18n.t("Saving"),
    };

    settings_bots.setup_bot_creation_policy_values();
    settings_org.setup_time_limit_dropdown_values();
}

exports.initialize = function () {
    i18n.ensure_i18n(_initialize);
};

// Generic function for informing users about changes to the settings
// UI.  Intended to replace the old system that was built around
// direct calls to `ui_report`.
exports.do_settings_change = function (request_method, url, data, status_element, opts) {
    var spinner = $(status_element).expectOne();
    spinner.fadeTo(0, 1);
    loading.make_indicator(spinner, {text: exports.strings.saving});
    var success_msg;
    var success_continuation;
    var error_continuation;
    var remove_after = 1000;
    var appear_after = 500;

    if (opts !== undefined) {
        success_msg = opts.success_msg;
        success_continuation = opts.success_continuation;
        error_continuation = opts.error_continuation;
        if (opts.sticky) {
            remove_after = null;
        }
    }
    if (success_msg === undefined) {
        success_msg = exports.strings.success;
    }

    request_method({
        url: url,
        data: data,
        success: function (reponse_data) {
            setTimeout(function () {
                ui_report.success(success_msg, spinner, null, remove_after);
                settings_ui.display_checkmark(spinner);
            }, appear_after);
            if (success_continuation !== undefined) {
                success_continuation(reponse_data);
            }
        },
        error: function (xhr) {
            ui_report.error(exports.strings.failure, xhr, spinner);
            if (error_continuation !== undefined) {
                error_continuation(xhr);
            }
        },
    });
};

// This function is used to disable sub-setting when main setting is checked or unchecked
// or two settings are inter-dependent on their values values.
// * is_checked is boolean, shows if the main setting is checked or not.
// * sub_setting_id is sub setting or setting which depend on main setting,
//   string id of setting.
// * disable_on_uncheck is boolean, true if sub setting should be disabled
//   when main setting unchecked.
exports.disable_sub_setting_onchange = function (is_checked, sub_setting_id, disable_on_uncheck) {
    if ((is_checked && disable_on_uncheck) || (!is_checked && !disable_on_uncheck)) {
        $("#" + sub_setting_id).attr("disabled", false);
        $("#" + sub_setting_id + "_label").parent().removeClass("control-label-disabled");
    } else if ((is_checked && !disable_on_uncheck) || (!is_checked && disable_on_uncheck)) {
        $("#" + sub_setting_id).attr("disabled", "disabled");
        $("#" + sub_setting_id + "_label").parent().addClass("control-label-disabled");
    }
};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = settings_ui;
}
<commit_msg>settings_ui: Remove now-unnecessary ensure_i18n.<commit_after>var settings_ui = (function () {

var exports = {};

exports.display_checkmark = function ($elem) {
    var check_mark = document.createElement("img");
    check_mark.src = "/static/images/checkbox-green.svg";
    $elem.prepend(check_mark);
    $(check_mark).css("width", "13px");
};

exports.strings = {
    success: i18n.t("Saved"),
    failure: i18n.t("Save failed"),
    saving: i18n.t("Saving"),
};

exports.initialize = function () {
    // TODO: Probably both of the functions this calls should just be
    // run at module initialization time now that ensure_i18n is dead.
    settings_bots.setup_bot_creation_policy_values();
    settings_org.setup_time_limit_dropdown_values();
};

// Generic function for informing users about changes to the settings
// UI.  Intended to replace the old system that was built around
// direct calls to `ui_report`.
exports.do_settings_change = function (request_method, url, data, status_element, opts) {
    var spinner = $(status_element).expectOne();
    spinner.fadeTo(0, 1);
    loading.make_indicator(spinner, {text: exports.strings.saving});
    var success_msg;
    var success_continuation;
    var error_continuation;
    var remove_after = 1000;
    var appear_after = 500;

    if (opts !== undefined) {
        success_msg = opts.success_msg;
        success_continuation = opts.success_continuation;
        error_continuation = opts.error_continuation;
        if (opts.sticky) {
            remove_after = null;
        }
    }
    if (success_msg === undefined) {
        success_msg = exports.strings.success;
    }

    request_method({
        url: url,
        data: data,
        success: function (reponse_data) {
            setTimeout(function () {
                ui_report.success(success_msg, spinner, null, remove_after);
                settings_ui.display_checkmark(spinner);
            }, appear_after);
            if (success_continuation !== undefined) {
                success_continuation(reponse_data);
            }
        },
        error: function (xhr) {
            ui_report.error(exports.strings.failure, xhr, spinner);
            if (error_continuation !== undefined) {
                error_continuation(xhr);
            }
        },
    });
};

// This function is used to disable sub-setting when main setting is checked or unchecked
// or two settings are inter-dependent on their values values.
// * is_checked is boolean, shows if the main setting is checked or not.
// * sub_setting_id is sub setting or setting which depend on main setting,
//   string id of setting.
// * disable_on_uncheck is boolean, true if sub setting should be disabled
//   when main setting unchecked.
exports.disable_sub_setting_onchange = function (is_checked, sub_setting_id, disable_on_uncheck) {
    if ((is_checked && disable_on_uncheck) || (!is_checked && !disable_on_uncheck)) {
        $("#" + sub_setting_id).attr("disabled", false);
        $("#" + sub_setting_id + "_label").parent().removeClass("control-label-disabled");
    } else if ((is_checked && !disable_on_uncheck) || (!is_checked && disable_on_uncheck)) {
        $("#" + sub_setting_id).attr("disabled", "disabled");
        $("#" + sub_setting_id + "_label").parent().addClass("control-label-disabled");
    }
};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = settings_ui;
}
<|endoftext|>


<commit_before>(function ($) {
  "use strict";

  addAnswersToSessionStorage();
  updateAvatar('introduction', 'sleeping-lion');
  updateAvatar('finish', 'finish__lion');

  $('.carousel').carousel({
    indicators: true,
    shift: 100
  });

  [
    'lion',
    'bear',
    'monkey'
  ].forEach(function (avatar) {
    var node = document.getElementsByClassName(avatar)[0];
    if (!node ) return;
    node.addEventListener('click', function () {
      var checkmark = node.getElementsByClassName('checkmark')[0];
      if ( !checkmark ) {
        addCheckmark(node);
        location.href = '/introduction';
      } else {
        node.removeChild(checkmark);
      }
    });
  });

  function addCheckmark (node) {
    var checkmark = document.createElement('IMG');
    checkmark.classList.add('checkmark');
    checkmark.src = 'assets/checkmark.svg';
    node.appendChild(checkmark);
  }

  function updateAvatar (selector, avatarSelector) {
    var page = document.getElementsByClassName(selector)[0];
    if (!page) return;
    var avatarImg = page.getElementsByClassName(avatarSelector)[0];
    var avatar = sessionStorage.getItem('avatar');
    avatarImg.src = 'assets/' + avatar + '.svg';
  }

  [
    "send-email-button"
  ].forEach(function(button){
    var node = document.getElementsByClassName(button)[0];
    if (node){
      node.addEventListener('click', function(){ sendMail() });
    }
  });

  function addAnswersToSessionStorage(){
    var personality = [];
    var hobbies = [];
    var likesAndDislikes = [];

    [
      'lion',
      'bear',
      'monkey'
    ].forEach(function (avatar) {
      var node = document.getElementsByClassName(avatar)[0];
      addClickEventSingle('avatar', node, avatar);
    });

    [
      "strange",
      "happy",
      "angry",
      "fun",
      "boring",
      "kind",
      "sad"
    ].forEach(function(emotion){
      var node = document.getElementById(emotion);
      addClassToNode(node, 'pop');
      addClickEventArray('personality', node, emotion, personality);
    });

    [
      "sad-emoji",
      "happy-emoji",
      "indifferent-emoji"
    ].forEach(function(emoji){
      var node = document.getElementsByClassName(emoji)[0];
      addClickEventSingle('feelings', node, emoji.match(/^[a-z]+/));
    });

    [
      "name",
      "age"
    ].forEach(function(inputField){
      var node = document.getElementsByClassName(inputField)[0];
      addKeyupEvent(inputField, node);
    });

    [
      "football",
      "tennis",
      "gymnastics",
      "dance",
      "drawing",
      "photography",
      "cooking",
      "gardening",
      "puzzles",
      "camping",
      "fishing",
      "walking",
      "gymnastics-mobile",
      "photography-mobile",
      "walking-mobile",
      "puzzles-mobile"
    ].forEach(function(hobby){
      var node = document.getElementsByClassName(hobby)[0];
      addClassToNode(node, 'js-chosen');
      addClickEventArray('hobbies', node, hobby, hobbies);
    });

    [
      "school__range",
      "friends__range",
      "sleep__range"
    ].forEach(function(range){
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value){
        if (range === "sleep__range") {
          sleepingLion();
        } else {
          emojiSprite();
        }
        addSingleValueToStorage(key, value);
      });
    });

    [
      "eating__range"
    ].forEach(function(range) {
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value) {
        addSingleValueToStorage(key, value);
      });
    });

    [
      "frineds__like",
      "frineds__dislike",
      "school__like",
      "school__dislike"
    ].forEach(function(textarea){
      var node = document.getElementsByClassName(textarea)[0];
      addKeyupEvent(textarea, node);
    });

    function addKeyupEvent(key, element){
      if(!element){ return; }
      element.addEventListener("keyup", function(){
        addSingleValueToStorage(key, element.value);
      });
    }

    function addClickEventSingle(key, element, value){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addSingleValueToStorage(key, value);
      });
    }

    function addClickEventArray(key, element, value, array){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addValueToArray(key, value, array);
      });
    }

    function addValueToArray(key, value, array){
      array.push(value);
      addArrayToStorage(key, array);
    }

    function addSingleValueToStorage(key, value){
      sessionStorage.setItem(key, value);
    }

    // JSON.stringify() is used here as session storage only supports strings
    function addArrayToStorage(key, array){
      sessionStorage.setItem(key, JSON.stringify(array));
    }
  }

  // Adds a class to node
  function addClassToNode(node, className){
    if (!node){ return; }
    node.addEventListener("click", function(){
      node.classList.add(className);
    });
  }

  function sleepingLion(){
    var value = document.getElementsByClassName("sleep__range")[0].value;
    var element = document.getElementsByClassName("sleep__sleeping-lion")[0];
    changeBackgroundPosition(element, value, -332);
  }

  function changeBackgroundPosition(element, value, illustrationSize){
    element.style.backgroundPosition = parseInt(value) * illustrationSize + "px";
  }

  function addOnInputToElement(element, func){
    if (!element){ return; }
    element.oninput = function(){ func(element.name, this.value) }
  }

  function emojiSprite(){
    var value = document.getElementsByClassName("range")[0].value -1;
    var element = document.getElementsByClassName("friends__emoji-sprite")[0];
    changeBackgroundPosition(element, value, -180);
  }

  function emailValidator(emailAddress){
    var regex = RegExp(
      '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".' +
      '+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-z' +
      'A-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
    );
    return regex.test(emailAddress);
  }

  function sendMail(){
    var emailRecipient = document.getElementsByClassName("finish__email-input")[0];
    if (!emailValidator(emailRecipient.value)){
      emailRecipient.value = 'Please enter a valid email address.';
      return;
    }
    var emailAddress = emailRecipient.value;
    var http = new XMLHttpRequest();
    http.open("POST", '/finished', true);
    http.send(emailAddress);
  }
})(jQuery);
<commit_msg>Remove unused varaible<commit_after>(function ($) {
  "use strict";

  addAnswersToSessionStorage();
  updateAvatar('introduction', 'sleeping-lion');
  updateAvatar('finish', 'finish__lion');

  $('.carousel').carousel({
    indicators: true,
    shift: 100
  });

  [
    'lion',
    'bear',
    'monkey'
  ].forEach(function (avatar) {
    var node = document.getElementsByClassName(avatar)[0];
    if (!node ) return;
    node.addEventListener('click', function () {
      var checkmark = node.getElementsByClassName('checkmark')[0];
      if ( !checkmark ) {
        addCheckmark(node);
        location.href = '/introduction';
      } else {
        node.removeChild(checkmark);
      }
    });
  });

  function addCheckmark (node) {
    var checkmark = document.createElement('IMG');
    checkmark.classList.add('checkmark');
    checkmark.src = 'assets/checkmark.svg';
    node.appendChild(checkmark);
  }

  function updateAvatar (selector, avatarSelector) {
    var page = document.getElementsByClassName(selector)[0];
    if (!page) return;
    var avatarImg = page.getElementsByClassName(avatarSelector)[0];
    var avatar = sessionStorage.getItem('avatar');
    avatarImg.src = 'assets/' + avatar + '.svg';
  }

  [
    "send-email-button"
  ].forEach(function(button){
    var node = document.getElementsByClassName(button)[0];
    if (node){
      node.addEventListener('click', function(){ sendMail() });
    }
  });

  function addAnswersToSessionStorage(){
    var personality = [];
    var hobbies = [];

    [
      'lion',
      'bear',
      'monkey'
    ].forEach(function (avatar) {
      var node = document.getElementsByClassName(avatar)[0];
      addClickEventSingle('avatar', node, avatar);
    });

    [
      "strange",
      "happy",
      "angry",
      "fun",
      "boring",
      "kind",
      "sad"
    ].forEach(function(emotion){
      var node = document.getElementById(emotion);
      addClassToNode(node, 'pop');
      addClickEventArray('personality', node, emotion, personality);
    });

    [
      "sad-emoji",
      "happy-emoji",
      "indifferent-emoji"
    ].forEach(function(emoji){
      var node = document.getElementsByClassName(emoji)[0];
      addClickEventSingle('feelings', node, emoji.match(/^[a-z]+/));
    });

    [
      "name",
      "age"
    ].forEach(function(inputField){
      var node = document.getElementsByClassName(inputField)[0];
      addKeyupEvent(inputField, node);
    });

    [
      "football",
      "tennis",
      "gymnastics",
      "dance",
      "drawing",
      "photography",
      "cooking",
      "gardening",
      "puzzles",
      "camping",
      "fishing",
      "walking",
      "gymnastics-mobile",
      "photography-mobile",
      "walking-mobile",
      "puzzles-mobile"
    ].forEach(function(hobby){
      var node = document.getElementsByClassName(hobby)[0];
      addClassToNode(node, 'js-chosen');
      addClickEventArray('hobbies', node, hobby, hobbies);
    });

    [
      "school__range",
      "friends__range",
      "sleep__range"
    ].forEach(function(range){
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value){
        if (range === "sleep__range") {
          sleepingLion();
        } else {
          emojiSprite();
        }
        addSingleValueToStorage(key, value);
      });
    });

    [
      "eating__range"
    ].forEach(function(range) {
      var node = document.getElementsByClassName(range)[0];
      addOnInputToElement(node, function(key, value) {
        addSingleValueToStorage(key, value);
      });
    });

    [
      "frineds__like",
      "frineds__dislike",
      "school__like",
      "school__dislike"
    ].forEach(function(textarea){
      var node = document.getElementsByClassName(textarea)[0];
      addKeyupEvent(textarea, node);
    });

    function addKeyupEvent(key, element){
      if(!element){ return; }
      element.addEventListener("keyup", function(){
        addSingleValueToStorage(key, element.value);
      });
    }

    function addClickEventSingle(key, element, value){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addSingleValueToStorage(key, value);
      });
    }

    function addClickEventArray(key, element, value, array){
      if(!element){ return; }
      element.addEventListener("click", function(){
        addValueToArray(key, value, array);
      });
    }

    function addValueToArray(key, value, array){
      array.push(value);
      addArrayToStorage(key, array);
    }

    function addSingleValueToStorage(key, value){
      sessionStorage.setItem(key, value);
    }

    // JSON.stringify() is used here as session storage only supports strings
    function addArrayToStorage(key, array){
      sessionStorage.setItem(key, JSON.stringify(array));
    }
  }

  // Adds a class to node
  function addClassToNode(node, className){
    if (!node){ return; }
    node.addEventListener("click", function(){
      node.classList.add(className);
    });
  }

  function sleepingLion(){
    var value = document.getElementsByClassName("sleep__range")[0].value;
    var element = document.getElementsByClassName("sleep__sleeping-lion")[0];
    changeBackgroundPosition(element, value, -332);
  }

  function changeBackgroundPosition(element, value, illustrationSize){
    element.style.backgroundPosition = parseInt(value) * illustrationSize + "px";
  }

  function addOnInputToElement(element, func){
    if (!element){ return; }
    element.oninput = function(){ func(element.name, this.value) }
  }

  function emojiSprite(){
    var value = document.getElementsByClassName("range")[0].value -1;
    var element = document.getElementsByClassName("friends__emoji-sprite")[0];
    changeBackgroundPosition(element, value, -180);
  }

  function emailValidator(emailAddress){
    var regex = RegExp(
      '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".' +
      '+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-z' +
      'A-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'
    );
    return regex.test(emailAddress);
  }

  function sendMail(){
    var emailRecipient = document.getElementsByClassName("finish__email-input")[0];
    if (!emailValidator(emailRecipient.value)){
      emailRecipient.value = 'Please enter a valid email address.';
      return;
    }
    var emailAddress = emailRecipient.value;
    var http = new XMLHttpRequest();
    http.open("POST", '/finished', true);
    http.send(emailAddress);
  }
})(jQuery);
<|endoftext|>


<commit_before>$(function(){
	$('.gamenu .plane').on('click', function(){
		var plane = $(this).data('plane');
		console.log(plane);
		planeMaker.switch(plane);
		planePicked = plane;

		$('.gamenu').fadeOut();
		$('.info').addClass('slide_down');
	})

	$('.choose_button').on('click', function(){
		var id = $(this).attr('id');
		$('.info .title').html('How do you play?')
		$('.back-button').show();
		switch(id){
			case 'socket' :
				// playingWithPhone = true;
				$('.buttons').hide();
				$('.chose_socket').show();
				// socketController.updateInstructions();
				break;
			case 'leap':
				// playingWithLeap = true;
				$('.buttons').hide();
				$('.chose_leap').show();
				controls.leapControl = true;
				break;
			case 'computer':
				// playingWithKeys = true;
				$('.buttons').hide();
				$('.chose_computer').show();
				break;
		}
	})

	$('.back-button').on('click', function(){
		$('.info .title').html('Which controller do you want to use?')
		$('.chose_socket').hide();
		$('.chose_leap').hide();
		$('.chose_computer').hide();

		$('.buttons').show();
		$('.back-button').hide()

		controls.leapControl = false;
	});

	$('.play').on('click', function(){
		game.start();
	})

	$('.score-submit').on('click', function(){

		var name = $('.user-name').val();
		var score = game.score;
		var plane = planePicked;
		var rings = game.totalRingsGame;
		var stars = game.totalStarsGame;
		var crashes = game.crashes;

		$.post( "http://kermisdatabasevanbartenrobbert.herokuapp.com/addhighscore/fly",
			{ 	name: name,
				score: score,
				plane: plane,
				rings: rings,
				stars: stars,
				crashes: crashes
			} )
		.done(function(){
			$('.score-submit').hide();
			$('.game-over').append('score succesully shared.')

		}).fail(function(){
			$('.game-over').append('something went wrong, please try again')
		});
	})
})

function showNotification(text){
	$('.notification').html(text);

	$('.notification').addClass('active');
	setTimeout(function(){
		$('.notification').removeClass('active');
	}, 1500)
}<commit_msg>highscores<commit_after>$(function(){
	$('.gamenu .plane').on('click', function(){
		var plane = $(this).data('plane');
		console.log(plane);
		planeMaker.switch(plane);
		planePicked = plane;

		$('.gamenu').fadeOut();
		$('.info').addClass('slide_down');
	})

	$('.choose_button').on('click', function(){
		var id = $(this).attr('id');
		$('.info .title').html('How do you play?')
		$('.back-button').show();
		switch(id){
			case 'socket' :
				// playingWithPhone = true;
				$('.buttons').hide();
				$('.chose_socket').show();
				// socketController.updateInstructions();
				break;
			case 'leap':
				// playingWithLeap = true;
				$('.buttons').hide();
				$('.chose_leap').show();
				controls.leapControl = true;
				break;
			case 'computer':
				// playingWithKeys = true;
				$('.buttons').hide();
				$('.chose_computer').show();
				break;
		}
	})

	$('.back-button').on('click', function(){
		$('.info .title').html('Which controller do you want to use?')
		$('.chose_socket').hide();
		$('.chose_leap').hide();
		$('.chose_computer').hide();

		$('.buttons').show();
		$('.back-button').hide()

		controls.leapControl = false;
	});

	$('.play').on('click', function(){
		game.start();
	})

	$('.score-submit').on('click', function(){

		$('.score-submit').hide();
		$('.game-over').append('Sharing Score');

		var name = $('.user-name').val();
		var score = game.score;
		var plane = planePicked;
		var rings = game.totalRingsGame;
		var stars = game.totalStarsGame;
		var crashes = game.crashes;

		$.post( "http://kermisdatabasevanbartenrobbert.herokuapp.com/addhighscore/fly",
			{ 	name: name,
				score: score,
				plane: plane,
				rings: rings,
				stars: stars,
				crashes: crashes
			} )
		.done(function(){
			$('.score-submit').hide();
			$('.score-message').html('score succesully shared.')

		}).fail(function(){
			$('.score-message').html('something went wrong, please try again');
			$('.score-submit').show();
		});
	})
})

function showNotification(text){
	$('.notification').html(text);

	$('.notification').addClass('active');
	setTimeout(function(){
		$('.notification').removeClass('active');
	}, 1500)
}<|endoftext|>


<commit_before>/**
 * `modules/adsense` data store: Ad Units tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import {
	createTestRegistry,
	unsubscribeFromAll,
	untilResolved,
} from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/adsense Ad Units', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'actions', () => {

	} );

	describe( 'selectors', () => {
		describe( 'getAdUnits', () => {
			it( 'uses a resolver to make a network request', async () => {
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/adunits/,
					{ body: fixtures.adunits, status: 200 }
				);

				const accountID = '123';
				const clientID = '456';

				const initialAdUnits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				expect( initialAdUnits ).toBeUndefined();
				await untilResolved( registry, STORE_NAME ).getAdUnits( accountID, clientID );

				const adunits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( adunits ).toEqual( fixtures.adunits );
			} );

			it( 'does not make a network request if adunits for this account + client are already present', async () => {
				const accountID = 'pub-12345';
				const clientID = fixtures.clients[ 0 ].id;

				// Load data into this store so there are matches for the data we're about to select,
				// even though the selector hasn't fulfilled yet.
				registry.dispatch( STORE_NAME ).receiveGetAdUnits( fixtures.adunits, { accountID, clientID } );

				const adunits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				await untilResolved( registry, STORE_NAME ).getAdUnits( accountID, clientID );

				expect( fetchMock ).not.toHaveFetched();
				expect( adunits ).toEqual( fixtures.adunits );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/adunits/,
					{ body: response, status: 500 }
				);

				const fakeAccountID = '789';
				const fakeClientID = '012';

				registry.select( STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				await untilResolved( registry, STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const adunits = registry.select( STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				expect( adunits ).toEqual( undefined );
				expect( console ).toHaveErrored();
			} );
		} );
	} );
} );
<commit_msg>Update assets/js/modules/adsense/datastore/adunits.test.js<commit_after>/**
 * `modules/adsense` data store: Ad Units tests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import API from 'googlesitekit-api';
import { STORE_NAME } from './constants';
import {
	createTestRegistry,
	unsubscribeFromAll,
	untilResolved,
} from 'tests/js/utils';
import * as fixtures from './__fixtures__';

describe( 'modules/adsense Ad Units', () => {
	let registry;

	beforeAll( () => {
		API.setUsingCache( false );
	} );

	beforeEach( () => {
		registry = createTestRegistry();
	} );

	afterAll( () => {
		API.setUsingCache( true );
	} );

	afterEach( () => {
		unsubscribeFromAll( registry );
	} );

	describe( 'actions', () => {

	} );

	describe( 'selectors', () => {
		describe( 'getAdUnits', () => {
			it( 'uses a resolver to make a network request', async () => {
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/adunits/,
					{ body: fixtures.adunits, status: 200 }
				);

				const accountID = '123';
				const clientID = '456';

				const initialAdUnits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				expect( initialAdUnits ).toBeUndefined();
				await untilResolved( registry, STORE_NAME ).getAdUnits( accountID, clientID );

				const adunits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				expect( fetchMock ).toHaveFetchedTimes( 1 );
				expect( adunits ).toEqual( fixtures.adunits );
			} );

			it( 'does not make a network request if adunits for this account + client are already present', async () => {
				const accountID = 'pub-12345';
				const clientID = fixtures.clients[ 0 ].id;

				// Load data into this store so there are matches for the data we're about to select,
				// even though the selector hasn't fulfilled yet.
				registry.dispatch( STORE_NAME ).receiveGetAdUnits( fixtures.adunits, { accountID, clientID } );

				const adunits = registry.select( STORE_NAME ).getAdUnits( accountID, clientID );

				await untilResolved( registry, STORE_NAME ).getAdUnits( accountID, clientID );

				expect( fetchMock ).not.toHaveFetched();
				expect( adunits ).toEqual( fixtures.adunits );
			} );

			it( 'dispatches an error if the request fails', async () => {
				const response = {
					code: 'internal_server_error',
					message: 'Internal server error',
					data: { status: 500 },
				};
				fetchMock.getOnce(
					/^\/google-site-kit\/v1\/modules\/adsense\/data\/adunits/,
					{ body: response, status: 500 }
				);

				const fakeAccountID = '789';
				const fakeClientID = '012';

				registry.select( STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				await untilResolved( registry, STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				expect( fetchMock ).toHaveFetchedTimes( 1 );

				const adunits = registry.select( STORE_NAME ).getAdUnits( fakeAccountID, fakeClientID );
				expect( adunits ).toBeUndefined();
				expect( console ).toHaveErrored();
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>var leechQuery = "";
var leechSearchId = "";
var leechHits = 0;
var leechLatency = 0;
var leechTimeoutId = 0;

var log = function(msg) {
  console.log("app=leech ns=js " + msg);
}

var millis = function() {
  return (new Date).getTime();
}

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function uuid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

function leechInflate(ev) {
  return "
" + ev.line + "
";
}

function leechApply(evs) {
  if (leechSearchId != "") {
    log("fn=apply at=start num=" + evs.length);
    var results = $("#results");
    $.each(evs, function(i, ev) {
      results.append(leechInflate(ev));
    });
    $("#status").text("(" + leechLatency + " / " + leechHits + ")");
    log("fn=apply at=finish");
  }
}

function leechUpdate() {
  if (leechSearchId != "") {
    log("fn=update at=start search_id=" + leechSearchId);
    var start = millis();
    $.ajax({
      data: {"search_id": leechSearchId, "query": leechQuery},
      dataType: "json",
      type: "GET",
      url: "/search",
      success: function(data, status, xhr) {
        log("fn=update at=finish search_id=" + leechSearchId + " num=" + data.length);
        leechApply(data);
      },
      complete: function(status, xhr) {
        var elapsed = millis() - start;
        log("fn=update at=finish search_id=" + leechSearchId + " elapsed=" + elapsed);
        leechHits += 1;
        leechLatency = elapsed;
        leechTimeoutId = setTimeout(leechUpdate, 500);
      }
    });
  }
}

function leechUpdateNow() {
  log("fn=update_now at=start");
  clearTimeout(leechTimeoutId);
  leechUpdate();
  log("fn=update_now at=finish");
}

function leechSubmit() {
  log("fn=submit at=start");
  var leechQueryNew = $("#query input").val();
  if (leechQueryNew.match(/^\s*$/)) {
    leechSearchId = "";
    $("#results").empty();
    $("#status").text("(_ / _)");
  } else if (leechQueryNew != leechQuery) {
    leechQuery = leechQueryNew;
    leechSearchId = uuid();
    leechHits = 0;
    leechLatency = 0;
    $("#results").empty();
    $("#status").text("(0 / 0)");
    leechUpdateNow();
  }
  log("fn=submit at=finish");
  return false;
}

function leechStart() {
  log("fn=start at=start");
  $("#query form").ajaxForm({beforeSubmit: leechSubmit});
  leechUpdate();
  log("fn=start at=finish");
}

$(document).ready(leechStart);
<commit_msg>generalize to source<commit_after>var leechQuery = "";
var leechSearchId = "";
var leechHits = 0;
var leechLatency = 0;
var leechTimeoutId = 0;

var log = function(msg) {
  console.log("app=leech ns=js " + msg);
}

var millis = function() {
  return (new Date).getTime();
}

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function uuid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

function leechInflate(ev) {
  return "
" + ev.line + "
";
}

function leechApply(evs) {
  if (leechSearchId != "") {
    log("fn=apply at=start num=" + evs.length);
    var results = $("#results");
    $.each(evs, function(i, ev) {
      results.append(leechInflate(ev));
    });
    $("#status").text("(" + leechLatency + " / " + leechHits + ")");
    log("fn=apply at=finish");
  }
}

function leechUpdate() {
  if (leechSearchId != "") {
    log("fn=update at=start search_id=" + leechSearchId);
    var start = millis();
    $.ajax({
      data: {"search_id": leechSearchId, "query": leechQuery},
      dataType: "json",
      type: "GET",
      url: "/search",
      success: function(data, status, xhr) {
        log("fn=update at=finish search_id=" + leechSearchId + " num=" + data.length);
        leechApply(data);
      },
      complete: function(status, xhr) {
        var elapsed = millis() - start;
        log("fn=update at=finish search_id=" + leechSearchId + " elapsed=" + elapsed);
        leechHits += 1;
        leechLatency = elapsed;
        leechTimeoutId = setTimeout(leechUpdate, 500);
      }
    });
  }
}

function leechUpdateNow() {
  log("fn=update_now at=start");
  clearTimeout(leechTimeoutId);
  leechUpdate();
  log("fn=update_now at=finish");
}

function leechSubmit() {
  log("fn=submit at=start");
  var leechQueryNew = $("#query input").val();
  if (leechQueryNew.match(/^\s*$/)) {
    leechSearchId = "";
    $("#results").empty();
    $("#status").text("(_ / _)");
  } else if (leechQueryNew != leechQuery) {
    leechQuery = leechQueryNew;
    leechSearchId = uuid();
    leechHits = 0;
    leechLatency = 0;
    $("#results").empty();
    $("#status").text("(0 / 0)");
    leechUpdateNow();
  }
  log("fn=submit at=finish");
  return false;
}

function leechStart() {
  log("fn=start at=start");
  $("#query form").ajaxForm({beforeSubmit: leechSubmit});
  leechUpdate();
  log("fn=start at=finish");
}

$(document).ready(leechStart);
<|endoftext|>