<commit_before>'use strict'

/* @flow */

import invariant from 'assert'

export class PoolWorker {
  active: boolean;
  startIndex: number;
  limitIndex: number;
  currentIndex: number;

  constructor(startIndex: number, limitIndex: number) {
    invariant(typeof startIndex === 'number', 'startIndex is not a number')
    invariant(typeof limitIndex === 'number', 'limitIndex is not a number')
    invariant(startIndex !== Infinity, 'startIndex should not be inifinite')
    invariant(startIndex > -1, 'startIndex should be at least zero')
    invariant(limitIndex > 0, 'limitIndex should be greater than zero')
    invariant(limitIndex - startIndex > 0, 'startIndex and limitIndex difference should be more than zero')

    this.active = false
    this.startIndex = startIndex
    this.limitIndex = limitIndex
    this.currentIndex = this.startIndex
  }
  serialize(): string {
    return JSON.stringify({
      active: this.active,
      startIndex: this.startIndex,
      limitIndex: this.limitIndex,
      currentIndex: this.currentIndex,
    })
  }
  activate(): PoolWorker {
    this.active = true
    return this
  }
  advance(steps: number) {
    const remaining = this.getRemaining()
    if (steps > remaining) {
      throw new Error('Cannot advance worker more than maximum')
    }
    this.currentIndex += steps
  }
  getCompletionPercentage(): number {
    return Math.round(((this.currentIndex - this.startIndex) / (this.limitIndex - this.startIndex)) * 100)
  }
  getRemaining(): number {
    return this.limitIndex - this.currentIndex
  }
  getCurrentIndex(): number {
    return this.currentIndex
  }
  getStartIndex(): number {
    return this.startIndex
  }
  getIndexLimit(): number {
    return this.limitIndex
  }
  hasCompleted(): boolean {
    return this.getRemaining() === 0
  }
  isActive(): boolean {
    return this.active
  }
  dispose() {
    this.active = false
  }
}
<commit_msg>:new: Add unserialize to worker<commit_after>'use strict'

/* @flow */

import invariant from 'assert'

export type PoolWorker$Serialized = {
  active: boolean,
  startIndex: number,
  limitIndex: number,
  currentIndex: number
}

export class PoolWorker {
  active: boolean;
  startIndex: number;
  limitIndex: number;
  currentIndex: number;

  constructor(startIndex: number, limitIndex: number) {
    invariant(typeof startIndex === 'number', 'startIndex is not a number')
    invariant(typeof limitIndex === 'number', 'limitIndex is not a number')
    invariant(startIndex !== Infinity, 'startIndex should not be inifinite')
    invariant(startIndex > -1, 'startIndex should be at least zero')
    invariant(limitIndex > 0, 'limitIndex should be greater than zero')
    invariant(limitIndex - startIndex > 0, 'startIndex and limitIndex difference should be more than zero')

    this.active = false
    this.startIndex = startIndex
    this.limitIndex = limitIndex
    this.currentIndex = this.startIndex
  }
  serialize(): PoolWorker$Serialized {
    return {
      active: this.active,
      startIndex: this.startIndex,
      limitIndex: this.limitIndex,
      currentIndex: this.currentIndex,
    }
  }
  activate(): PoolWorker {
    this.active = true
    return this
  }
  advance(steps: number) {
    const remaining = this.getRemaining()
    if (steps > remaining) {
      throw new Error('Cannot advance worker more than maximum')
    }
    this.currentIndex += steps
  }
  getCompletionPercentage(): number {
    return Math.round(((this.currentIndex - this.startIndex) / (this.limitIndex - this.startIndex)) * 100)
  }
  getRemaining(): number {
    return this.limitIndex - this.currentIndex
  }
  getCurrentIndex(): number {
    return this.currentIndex
  }
  getStartIndex(): number {
    return this.startIndex
  }
  getIndexLimit(): number {
    return this.limitIndex
  }
  hasCompleted(): boolean {
    return this.getRemaining() === 0
  }
  isActive(): boolean {
    return this.active
  }
  dispose() {
    this.active = false
  }
  static unserialize(serialized: PoolWorker$Serialized): PoolWorker {
    const worker = new PoolWorker(serialized.startIndex, serialized.limitIndex)
    worker.active = serialized.active
    worker.currentIndex = serialized.currentIndex
    return worker
  }
}
<|endoftext|>


<commit_before><commit_msg>Update app.js<commit_after><|endoftext|>


<commit_before>var cheapSeatApp = angular.module('cheapSeatApp', []);

cheapSeatApp.controller('DealListController', ['$scope', '$http', function($scope, $http) {
    $http.jsonp('http://iwantthatflight.com.au/deals.aspx?format=xml&afid=2361', {jsonpCallbackParam: 'callback'})
    .then(function(response) {
        console.log(response.data);
        console.log(xml2json(response.data));
        $scope.deals = xml2json(response.data, " ");
    });
}]);

function xml2json(xml, tab) {
   var X = {
      toObj: function(xml) {
         var o = {};
         if (xml.nodeType==1) {   // element node ..
            if (xml.attributes.length)   // element with attributes  ..
               for (var i=0; i<xml.attributes.length; i++)
                  o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString();
            if (xml.firstChild) { // element has child nodes ..
               var textChild=0, cdataChild=0, hasElementChild=false;
               for (var n=xml.firstChild; n; n=n.nextSibling) {
                  if (n.nodeType==1) hasElementChild = true;
                  else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
                  else if (n.nodeType==4) cdataChild++; // cdata section node
               }
               if (hasElementChild) {
                  if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                     X.removeWhite(xml);
                     for (var n=xml.firstChild; n; n=n.nextSibling) {
                        if (n.nodeType == 3)  // text node
                           o["#text"] = X.escape(n.nodeValue);
                        else if (n.nodeType == 4)  // cdata node
                           o["#cdata"] = X.escape(n.nodeValue);
                        else if (o[n.nodeName]) {  // multiple occurence of element ..
                           if (o[n.nodeName] instanceof Array)
                              o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                           else
                              o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                        }
                        else  // first occurence of element..
                           o[n.nodeName] = X.toObj(n);
                     }
                  }
                  else { // mixed content
                     if (!xml.attributes.length)
                        o = X.escape(X.innerXml(xml));
                     else
                        o["#text"] = X.escape(X.innerXml(xml));
                  }
               }
               else if (textChild) { // pure text
                  if (!xml.attributes.length)
                     o = X.escape(X.innerXml(xml));
                  else
                     o["#text"] = X.escape(X.innerXml(xml));
               }
               else if (cdataChild) { // cdata
                  if (cdataChild > 1)
                     o = X.escape(X.innerXml(xml));
                  else
                     for (var n=xml.firstChild; n; n=n.nextSibling)
                        o["#cdata"] = X.escape(n.nodeValue);
               }
            }
            if (!xml.attributes.length && !xml.firstChild) o = null;
         }
         else if (xml.nodeType==9) { // document.node
            o = X.toObj(xml.documentElement);
         }
         else
            alert("unhandled node type: " + xml.nodeType);
         return o;
      },
      toJson: function(o, name, ind) {
         var json = name ? ("\""+name+"\"") : "";
         if (o instanceof Array) {
            for (var i=0,n=o.length; i<n; i++)
               o[i] = X.toJson(o[i], "", ind+"\t");
            json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]";
         }
         else if (o == null)
            json += (name&&":") + "null";
         else if (typeof(o) == "object") {
            var arr = [];
            for (var m in o)
               arr[arr.length] = X.toJson(o[m], m, ind+"\t");
            json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}";
         }
         else if (typeof(o) == "string")
            json += (name&&":") + "\"" + o.toString() + "\"";
         else
            json += (name&&":") + o.toString();
         return json;
      },
      innerXml: function(node) {
         var s = ""
         if ("innerHTML" in node)
            s = node.innerHTML;
         else {
            var asXml = function(n) {
               var s = "";
               if (n.nodeType == 1) {
                  s += "<" + n.nodeName;
                  for (var i=0; i<n.attributes.length;i++)
                     s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\"";
                  if (n.firstChild) {
                     s += ">";
                     for (var c=n.firstChild; c; c=c.nextSibling)
                        s += asXml(c);
                     s += "</"+n.nodeName+">";
                  }
                  else
                     s += "/>";
               }
               else if (n.nodeType == 3)
                  s += n.nodeValue;
               else if (n.nodeType == 4)
                  s += "<![CDATA[" + n.nodeValue + "]]>";
               return s;
            };
            for (var c=node.firstChild; c; c=c.nextSibling)
               s += asXml(c);
         }
         return s;
      },
      escape: function(txt) {
         return txt.replace(/[\\]/g, "\\\\")
                   .replace(/[\"]/g, '\\"')
                   .replace(/[\n]/g, '\\n')
                   .replace(/[\r]/g, '\\r');
      },
      removeWhite: function(e) {
         e.normalize();
         for (var n = e.firstChild; n; ) {
            if (n.nodeType == 3) {  // text node
               if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                  var nxt = n.nextSibling;
                  e.removeChild(n);
                  n = nxt;
               }
               else
                  n = n.nextSibling;
            }
            else if (n.nodeType == 1) {  // element node
               X.removeWhite(n);
               n = n.nextSibling;
            }
            else                      // any other node
               n = n.nextSibling;
         }
         return e;
      }
   };
   if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
   var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
   return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
}
<commit_msg>Update app.js<commit_after>var cheapSeatApp = angular.module('cheapSeatApp', []);

cheapSeatApp.controller('DealListController', ['$scope', '$http', function($scope, $http) {
    $http.get('https://cors-anywhere.herokuapp.com/http://iwantthatflight.com.au/deals.aspx?format=xml&afid=2361')
    .then(function(response) {
        console.log(response.data);
        console.log(xml2json(response.data));
        $scope.deals = xml2json(response.data, " ");
    });
}]);

function xml2json(xml, tab) {
   var X = {
      toObj: function(xml) {
         var o = {};
         if (xml.nodeType==1) {   // element node ..
            if (xml.attributes.length)   // element with attributes  ..
               for (var i=0; i<xml.attributes.length; i++)
                  o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString();
            if (xml.firstChild) { // element has child nodes ..
               var textChild=0, cdataChild=0, hasElementChild=false;
               for (var n=xml.firstChild; n; n=n.nextSibling) {
                  if (n.nodeType==1) hasElementChild = true;
                  else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
                  else if (n.nodeType==4) cdataChild++; // cdata section node
               }
               if (hasElementChild) {
                  if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                     X.removeWhite(xml);
                     for (var n=xml.firstChild; n; n=n.nextSibling) {
                        if (n.nodeType == 3)  // text node
                           o["#text"] = X.escape(n.nodeValue);
                        else if (n.nodeType == 4)  // cdata node
                           o["#cdata"] = X.escape(n.nodeValue);
                        else if (o[n.nodeName]) {  // multiple occurence of element ..
                           if (o[n.nodeName] instanceof Array)
                              o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                           else
                              o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                        }
                        else  // first occurence of element..
                           o[n.nodeName] = X.toObj(n);
                     }
                  }
                  else { // mixed content
                     if (!xml.attributes.length)
                        o = X.escape(X.innerXml(xml));
                     else
                        o["#text"] = X.escape(X.innerXml(xml));
                  }
               }
               else if (textChild) { // pure text
                  if (!xml.attributes.length)
                     o = X.escape(X.innerXml(xml));
                  else
                     o["#text"] = X.escape(X.innerXml(xml));
               }
               else if (cdataChild) { // cdata
                  if (cdataChild > 1)
                     o = X.escape(X.innerXml(xml));
                  else
                     for (var n=xml.firstChild; n; n=n.nextSibling)
                        o["#cdata"] = X.escape(n.nodeValue);
               }
            }
            if (!xml.attributes.length && !xml.firstChild) o = null;
         }
         else if (xml.nodeType==9) { // document.node
            o = X.toObj(xml.documentElement);
         }
         else
            alert("unhandled node type: " + xml.nodeType);
         return o;
      },
      toJson: function(o, name, ind) {
         var json = name ? ("\""+name+"\"") : "";
         if (o instanceof Array) {
            for (var i=0,n=o.length; i<n; i++)
               o[i] = X.toJson(o[i], "", ind+"\t");
            json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]";
         }
         else if (o == null)
            json += (name&&":") + "null";
         else if (typeof(o) == "object") {
            var arr = [];
            for (var m in o)
               arr[arr.length] = X.toJson(o[m], m, ind+"\t");
            json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}";
         }
         else if (typeof(o) == "string")
            json += (name&&":") + "\"" + o.toString() + "\"";
         else
            json += (name&&":") + o.toString();
         return json;
      },
      innerXml: function(node) {
         var s = ""
         if ("innerHTML" in node)
            s = node.innerHTML;
         else {
            var asXml = function(n) {
               var s = "";
               if (n.nodeType == 1) {
                  s += "<" + n.nodeName;
                  for (var i=0; i<n.attributes.length;i++)
                     s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\"";
                  if (n.firstChild) {
                     s += ">";
                     for (var c=n.firstChild; c; c=c.nextSibling)
                        s += asXml(c);
                     s += "</"+n.nodeName+">";
                  }
                  else
                     s += "/>";
               }
               else if (n.nodeType == 3)
                  s += n.nodeValue;
               else if (n.nodeType == 4)
                  s += "<![CDATA[" + n.nodeValue + "]]>";
               return s;
            };
            for (var c=node.firstChild; c; c=c.nextSibling)
               s += asXml(c);
         }
         return s;
      },
      escape: function(txt) {
         return txt.replace(/[\\]/g, "\\\\")
                   .replace(/[\"]/g, '\\"')
                   .replace(/[\n]/g, '\\n')
                   .replace(/[\r]/g, '\\r');
      },
      removeWhite: function(e) {
         e.normalize();
         for (var n = e.firstChild; n; ) {
            if (n.nodeType == 3) {  // text node
               if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                  var nxt = n.nextSibling;
                  e.removeChild(n);
                  n = nxt;
               }
               else
                  n = n.nextSibling;
            }
            else if (n.nodeType == 1) {  // element node
               X.removeWhite(n);
               n = n.nextSibling;
            }
            else                      // any other node
               n = n.nextSibling;
         }
         return e;
      }
   };
   if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
   var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
   return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
}
<|endoftext|>


<commit_before>'use strict';

const names = [
  [
    // Month: January
    ['Laimnesis','Solvita','Solvija'],
    ['Indulis','Ivo','Iva','Ivis'],
    ['Miervaldis','Miervalda','Ringolds'],
    ['Spodra','Ilva','Ilvita'],
    ['Sīmanis','Zintis'],
    ['Spulga','Arnita'],
    ['Rota','Zigmārs','Juliāns','Digmārs'],
    ['Gatis','Ivanda'],
    ['Kaspars','Aksels','Alta'],
    ['Tatjana','Dorisa'],
    ['Smaida','Franciska'],
    ['Reinis','Reina','Reinholds','Renāts'],
    ['Harijs','Ārijs','Āris','Aira'],
    ['Roberts','Roberta','Raitis','Raits'],
    ['Fēlikss','Felicita'],
    ['Lidija','Lida'],
    ['Tenis','Dravis'],
    ['Antons','Antis','Antonijs'],
    ['Andulis','Alnis'],
    ['Oļģerts','Orests','Aļģirds','Aļģis'],
    ['Agnese','Agnija','Agne'],
    ['Austris'],
    ['Grieta','Strauta','Rebeka'],
    ['Krišs','Ksenija','Eglons','Egle'],
    ['Zigurds','Sigurds','Sigvards'],
    ['Ansis','Agnis','Agneta'],
    ['Ilze','Ildze','Izolde'],
    ['Kārlis','Spodris'],
    ['Aivars','Valērijs','Bille'],
    ['Tīna','Valentīna','Pārsla'],
    ['Tekla','Violeta']
  ],
  [
    // Month: February
    ['Brigita','Indra','Indars','Indris'],
    ['Spīdola','Sonora'],
    ['Aīda','Ida','Vida'],
    ['Daila','Veronika','Dominiks'],
    ['Agate','Selga','Silga','Sinilga'],
    ['Dace','Dārta','Dora'],
    ['Nelda','Rihards','Ričards','Rišards'],
    ['Aldona','Česlavs'],
    ['Simona','Apolonija'],
    ['Paulīne','Paula','Jasmīna'],
    ['Laima','Laimdota'],
    ['Karlīna','Līna'],
    ['Malda','Melita'],
    ['Valentīns'],
    ['Alvils','Olafs','Aloizs','Olavs'],
    ['Jūlija','Džuljeta'],
    ['Donats','Konstance'],
    ['Kora','Kintija'],
    ['Zane','Zuzanna'],
    ['Vitauts','Smuidra','Smuidris'],
    ['Eleonora','Ariadne'],
    ['Ārija','Rigonda','Adrians','Adriāna','Adrija'],
    ['Haralds','Almants'],
    ['Diāna','Dina','Dins'],
    ['Alma','Annemarija'],
    ['Evelīna','Aurēlija','Mētra'],
    ['Līvija','Līva','Andra'],
    ['Skaidrīte','Justs','Skaidra'],
    ['–']
  ],
  [
    // Month: March
    ['Ivars','Ilgvars'],
    ['Lavīze','Luīze','Laila'],
    ['Tālis','Tālavs','Marts'],
    ['Alise','Auce','Enija'],
    ['Austra','Aurora'],
    ['Vents','Centis','Gotfrīds'],
    ['Ella','Elmīra'],
    ['Dagmāra','Marga','Margita'],
    ['Ēvalds'],
    ['Silvija','Laimrota','Liliāna'],
    ['Konstantīns','Agita'],
    ['Aija','Aiva','Aivis'],
    ['Ernests','Balvis'],
    ['Matilde','Ulrika'],
    ['Amilda','Amalda','Imalda'],
    ['Guntis','Guntars','Guntris'],
    ['Ģertrūde','Gerda'],
    ['Ilona','Adelīna'],
    ['Jāzeps','Juzefa'],
    ['Made','Irbe'],
    ['Una','Unigunde','Dzelme','Benedikts','Benedikta'],
    ['Tamāra','Dziedra','Gabriels','Gabriela'],
    ['Mirdza','Žanete','Žanna'],
    ['Kazimirs','Izidors'],
    ['Māra','Mārīte','Marita','Mare','Ģedimins'],
    ['Eiženija','Ženija'],
    ['Gustavs','Gusts','Tālrīts','Saulis'],
    ['Gunta','Ginta','Gunda'],
    ['Aldonis','Agija'],
    ['Nanija','Ilgmārs'],
    ['Gvido','Atvars']
  ],
  [
    // Month: April
    ['Dagnis','Dagne'],
    ['Irmgarde'],
    ['Daira','Dairis','Daiva','Daivis'],
    ['Valda','Herta','Ārvalda','Ārvalds','Ārvaldis'],
    ['Vija','Vidaga','Aivija'],
    ['Zinta','Vīlips','Filips','Dzinta'],
    ['Zina','Zinaīda','Helmuts'],
    ['Edgars','Danute','Dana','Dans'],
    ['Valērija','Žubīte','Alla'],
    ['Anita','Anitra','Zīle','Annika'],
    ['Hermanis','Vilmārs'],
    ['Jūlijs','Ainis'],
    ['Egils','Egīls','Nauris'],
    ['Strauja','Gudrīte'],
    ['Aelita','Gastons'],
    ['Mintauts','Alfs','Bernadeta'],
    ['Rūdolfs','Viviāna','Rūdis'],
    ['Laura','Jadviga'],
    ['Vēsma','Fanija'],
    ['Mirta','Ziedīte'],
    ['Marģers','Anastasija'],
    ['Armands','Armanda'],
    ['Jurģis','Juris','Georgs'],
    ['Visvaldis','Nameda','Ritvaldis','Ritums'],
    ['Līksma','Bārbala'],
    ['Alīna','Sandris','Rūsiņš'],
    ['Tāle','Raimonda','Raina','Klementīne'],
    ['Gundega','Terēze'],
    ['Vilnis','Raimonds','Laine'],
    ['Lilija','Liāna']
  ],
  [
    // Month: May
    ['Ziedonis'],
    ['Zigmunds','Sigmunds','Zigismunds'],
    ['Gints','Uvis'],
    ['Vizbulīte','Viola','Vijolīte'],
    ['Ģirts','Ģederts'],
    ['Gaidis','Didzis'],
    ['Henriete','Henrijs','Jete','Enriko'],
    ['Staņislavs','Staņislava','Stefānija'],
    ['Klāvs','Einārs','Ervīns'],
    ['Maija','Paija'],
    ['Milda','Karmena','Manfreds'],
    ['Valija','Ināra','Ina','Inārs'],
    ['Irēna','Irīna','Ira','Iraīda'],
    ['Krišjānis','Elfa','Aivita','Elvita'],
    ['Sofija','Taiga','Airita','Arita'],
    ['Edvīns','Edijs'],
    ['Herberts','Dailis','Umberts'],
    ['Inese','Inesis','Ēriks'],
    ['Lita','Sibilla','Teika'],
    ['Venta','Salvis','Selva'],
    ['Ernestīne','Ingmārs','Akvelīna'],
    ['Emīlija'],
    ['Leontīne','Leokādija','Lonija','Ligija'],
    ['Ilvija','Marlēna','Ziedone'],
    ['Anšlavs','Junora'],
    ['Edvards','Edvarts','Eduards','Varis'],
    ['Dzidra','Gunita','Loreta','Dzidris'],
    ['Vilis','Vilhelms'],
    ['Maksis','Maksims','Raivis','Raivo'],
    ['Vitolds','Lolita','Letīcija'],
    ['Alīda','Jūsma']
  ],
  [
    // Month: June
    ['Biruta','Mairita','Bernedīne'],
    ['Lība','Emma'],
    ['Inta','Ineta','Intra'],
    ['Elfrīda','Sintija','Sindija'],
    ['Igors','Margots','Ingvars'],
    ['Ingrīda','Ardis'],
    ['Gaida','Arnis','Arno'],
    ['Frīdis','Frīda','Mundra'],
    ['Ligita','Gita'],
    ['Malva','Anatols','Anatolijs'],
    ['Ingus','Mairis','Vidvuds'],
    ['Nora','Lenora','Ija'],
    ['Zigfrīds','Ainārs','Uva'],
    ['Tija','Saiva','Sentis','Santis','Saivis'],
    ['Baņuta','Žermēna','Vilija','Vits'],
    ['Justīne','Juta'],
    ['Artūrs','Artis'],
    ['Alberts','Madis'],
    ['Viktors','Nils'],
    ['Rasma','Rasa','Maira'],
    ['Emīls','Egita','Monvīds'],
    ['Ludmila','Laimdots','Laimiņš'],
    ['Līga'],
    ['Jānis'],
    ['Milija','Maiga'],
    ['Ausma','Inguna','Ingūna','Inguns','Ausmis'],
    ['Malvīne','Malvis'],
    ['Viesturs','Kitija','Viestards'],
    ['Pēteris','Pāvils','Pauls','Paulis'],
    ['Tālivaldis','Mareks']
  ]
];
<commit_msg>Add - jul. & aug. names<commit_after>'use strict';

const names = [
  [
    // Month: January
    ['Laimnesis','Solvita','Solvija'],
    ['Indulis','Ivo','Iva','Ivis'],
    ['Miervaldis','Miervalda','Ringolds'],
    ['Spodra','Ilva','Ilvita'],
    ['Sīmanis','Zintis'],
    ['Spulga','Arnita'],
    ['Rota','Zigmārs','Juliāns','Digmārs'],
    ['Gatis','Ivanda'],
    ['Kaspars','Aksels','Alta'],
    ['Tatjana','Dorisa'],
    ['Smaida','Franciska'],
    ['Reinis','Reina','Reinholds','Renāts'],
    ['Harijs','Ārijs','Āris','Aira'],
    ['Roberts','Roberta','Raitis','Raits'],
    ['Fēlikss','Felicita'],
    ['Lidija','Lida'],
    ['Tenis','Dravis'],
    ['Antons','Antis','Antonijs'],
    ['Andulis','Alnis'],
    ['Oļģerts','Orests','Aļģirds','Aļģis'],
    ['Agnese','Agnija','Agne'],
    ['Austris'],
    ['Grieta','Strauta','Rebeka'],
    ['Krišs','Ksenija','Eglons','Egle'],
    ['Zigurds','Sigurds','Sigvards'],
    ['Ansis','Agnis','Agneta'],
    ['Ilze','Ildze','Izolde'],
    ['Kārlis','Spodris'],
    ['Aivars','Valērijs','Bille'],
    ['Tīna','Valentīna','Pārsla'],
    ['Tekla','Violeta']
  ],
  [
    // Month: February
    ['Brigita','Indra','Indars','Indris'],
    ['Spīdola','Sonora'],
    ['Aīda','Ida','Vida'],
    ['Daila','Veronika','Dominiks'],
    ['Agate','Selga','Silga','Sinilga'],
    ['Dace','Dārta','Dora'],
    ['Nelda','Rihards','Ričards','Rišards'],
    ['Aldona','Česlavs'],
    ['Simona','Apolonija'],
    ['Paulīne','Paula','Jasmīna'],
    ['Laima','Laimdota'],
    ['Karlīna','Līna'],
    ['Malda','Melita'],
    ['Valentīns'],
    ['Alvils','Olafs','Aloizs','Olavs'],
    ['Jūlija','Džuljeta'],
    ['Donats','Konstance'],
    ['Kora','Kintija'],
    ['Zane','Zuzanna'],
    ['Vitauts','Smuidra','Smuidris'],
    ['Eleonora','Ariadne'],
    ['Ārija','Rigonda','Adrians','Adriāna','Adrija'],
    ['Haralds','Almants'],
    ['Diāna','Dina','Dins'],
    ['Alma','Annemarija'],
    ['Evelīna','Aurēlija','Mētra'],
    ['Līvija','Līva','Andra'],
    ['Skaidrīte','Justs','Skaidra'],
    ['–']
  ],
  [
    // Month: March
    ['Ivars','Ilgvars'],
    ['Lavīze','Luīze','Laila'],
    ['Tālis','Tālavs','Marts'],
    ['Alise','Auce','Enija'],
    ['Austra','Aurora'],
    ['Vents','Centis','Gotfrīds'],
    ['Ella','Elmīra'],
    ['Dagmāra','Marga','Margita'],
    ['Ēvalds'],
    ['Silvija','Laimrota','Liliāna'],
    ['Konstantīns','Agita'],
    ['Aija','Aiva','Aivis'],
    ['Ernests','Balvis'],
    ['Matilde','Ulrika'],
    ['Amilda','Amalda','Imalda'],
    ['Guntis','Guntars','Guntris'],
    ['Ģertrūde','Gerda'],
    ['Ilona','Adelīna'],
    ['Jāzeps','Juzefa'],
    ['Made','Irbe'],
    ['Una','Unigunde','Dzelme','Benedikts','Benedikta'],
    ['Tamāra','Dziedra','Gabriels','Gabriela'],
    ['Mirdza','Žanete','Žanna'],
    ['Kazimirs','Izidors'],
    ['Māra','Mārīte','Marita','Mare','Ģedimins'],
    ['Eiženija','Ženija'],
    ['Gustavs','Gusts','Tālrīts','Saulis'],
    ['Gunta','Ginta','Gunda'],
    ['Aldonis','Agija'],
    ['Nanija','Ilgmārs'],
    ['Gvido','Atvars']
  ],
  [
    // Month: April
    ['Dagnis','Dagne'],
    ['Irmgarde'],
    ['Daira','Dairis','Daiva','Daivis'],
    ['Valda','Herta','Ārvalda','Ārvalds','Ārvaldis'],
    ['Vija','Vidaga','Aivija'],
    ['Zinta','Vīlips','Filips','Dzinta'],
    ['Zina','Zinaīda','Helmuts'],
    ['Edgars','Danute','Dana','Dans'],
    ['Valērija','Žubīte','Alla'],
    ['Anita','Anitra','Zīle','Annika'],
    ['Hermanis','Vilmārs'],
    ['Jūlijs','Ainis'],
    ['Egils','Egīls','Nauris'],
    ['Strauja','Gudrīte'],
    ['Aelita','Gastons'],
    ['Mintauts','Alfs','Bernadeta'],
    ['Rūdolfs','Viviāna','Rūdis'],
    ['Laura','Jadviga'],
    ['Vēsma','Fanija'],
    ['Mirta','Ziedīte'],
    ['Marģers','Anastasija'],
    ['Armands','Armanda'],
    ['Jurģis','Juris','Georgs'],
    ['Visvaldis','Nameda','Ritvaldis','Ritums'],
    ['Līksma','Bārbala'],
    ['Alīna','Sandris','Rūsiņš'],
    ['Tāle','Raimonda','Raina','Klementīne'],
    ['Gundega','Terēze'],
    ['Vilnis','Raimonds','Laine'],
    ['Lilija','Liāna']
  ],
  [
    // Month: May
    ['Ziedonis'],
    ['Zigmunds','Sigmunds','Zigismunds'],
    ['Gints','Uvis'],
    ['Vizbulīte','Viola','Vijolīte'],
    ['Ģirts','Ģederts'],
    ['Gaidis','Didzis'],
    ['Henriete','Henrijs','Jete','Enriko'],
    ['Staņislavs','Staņislava','Stefānija'],
    ['Klāvs','Einārs','Ervīns'],
    ['Maija','Paija'],
    ['Milda','Karmena','Manfreds'],
    ['Valija','Ināra','Ina','Inārs'],
    ['Irēna','Irīna','Ira','Iraīda'],
    ['Krišjānis','Elfa','Aivita','Elvita'],
    ['Sofija','Taiga','Airita','Arita'],
    ['Edvīns','Edijs'],
    ['Herberts','Dailis','Umberts'],
    ['Inese','Inesis','Ēriks'],
    ['Lita','Sibilla','Teika'],
    ['Venta','Salvis','Selva'],
    ['Ernestīne','Ingmārs','Akvelīna'],
    ['Emīlija'],
    ['Leontīne','Leokādija','Lonija','Ligija'],
    ['Ilvija','Marlēna','Ziedone'],
    ['Anšlavs','Junora'],
    ['Edvards','Edvarts','Eduards','Varis'],
    ['Dzidra','Gunita','Loreta','Dzidris'],
    ['Vilis','Vilhelms'],
    ['Maksis','Maksims','Raivis','Raivo'],
    ['Vitolds','Lolita','Letīcija'],
    ['Alīda','Jūsma']
  ],
  [
    // Month: June
    ['Biruta','Mairita','Bernedīne'],
    ['Lība','Emma'],
    ['Inta','Ineta','Intra'],
    ['Elfrīda','Sintija','Sindija'],
    ['Igors','Margots','Ingvars'],
    ['Ingrīda','Ardis'],
    ['Gaida','Arnis','Arno'],
    ['Frīdis','Frīda','Mundra'],
    ['Ligita','Gita'],
    ['Malva','Anatols','Anatolijs'],
    ['Ingus','Mairis','Vidvuds'],
    ['Nora','Lenora','Ija'],
    ['Zigfrīds','Ainārs','Uva'],
    ['Tija','Saiva','Sentis','Santis','Saivis'],
    ['Baņuta','Žermēna','Vilija','Vits'],
    ['Justīne','Juta'],
    ['Artūrs','Artis'],
    ['Alberts','Madis'],
    ['Viktors','Nils'],
    ['Rasma','Rasa','Maira'],
    ['Emīls','Egita','Monvīds'],
    ['Ludmila','Laimdots','Laimiņš'],
    ['Līga'],
    ['Jānis'],
    ['Milija','Maiga'],
    ['Ausma','Inguna','Ingūna','Inguns','Ausmis'],
    ['Malvīne','Malvis'],
    ['Viesturs','Kitija','Viestards'],
    ['Pēteris','Pāvils','Pauls','Paulis'],
    ['Tālivaldis','Mareks']
  ],
  [
    // Month: July
    ['Imants','Rimants','Ingars','Intars'],
    ['Lauma','Ilvars','Halina'],
    ['Benita','Everita','Verita','Emerita'],
    ['Ulvis','Uldis','Sandis','Sandijs'],
    ['Andžs','Andžejs','Edīte','Esmeralda'],
    ['Anrijs','Arkādijs'],
    ['Alda','Maruta'],
    ['Antra','Adele','Ada'],
    ['Zaiga','Asne','Asna'],
    ['Lija','Olīvija','Olivers','Odrija'],
    ['Leonora','Svens'],
    ['Indriķis','Ints','Namejs'],
    ['Margrieta','Margarita'],
    ['Oskars','Ritvars','Anvars'],
    ['Egons','Egmonts','Egija','Henriks','Heinrihs'],
    ['Hermīne','Estere','Liepa'],
    ['Aleksis','Aleksejs','Alekss'],
    ['Rozālija','Roze'],
    ['Jautrīte','Kamila','Digna','Sāra'],
    ['Ritma','Ramona'],
    ['Meldra','Meldris','Melisa'],
    ['Marija','Marika','Marina'],
    ['Magda','Magone','Mērija','Magdalēna'],
    ['Kristīne','Kristīna','Krista','Kristiāna','Kristiāns'],
    ['Jēkabs','Žaklīna'],
    ['Anna','Ance','Annija'],
    ['Marta','Dita','Dite'],
    ['Cecīlija','Cilda'],
    ['Edmunds','Edžus','Vidmants'],
    ['Valters','Renārs','Regnārs'],
    ['Rūta','Ruta','Angelika','Sigita']
  ],
  [
    // Month: August
    ['Albīns','Albīna'],
    ['Normunds','Stefans'],
    ['Augusts'],
    ['Romāns','Romualds','Romualda'],
    ['Osvalds','Arvils'],
    ['Askolds','Aisma'],
    ['Alfrēds','Madars','Fredis'],
    ['Mudīte','Vladislavs','Vladislava'],
    ['Madara','Genoveva','Genovefa'],
    ['Brencis','Audris','Inuta','Audra'],
    ['Olga','Zita','Liega','Zigita'],
    ['Vizma','Klāra'],
    ['Elvīra','Velga','Rēzija'],
    ['Zelma','Zemgus','Virma'],
    ['Zenta','Dzelde','Zelda'],
    ['Astra','Astrīda'],
    ['Vineta','Oļegs'],
    ['Liene','Helēna','Elena','Ellena','Liena'],
    ['Melānija','Imanta'],
    ['Bernhards','Boriss','Rojs'],
    ['Janīna','Linda'],
    ['Rudīte','Everts'],
    ['Vitālijs','Ralfs','Valgudis'],
    ['Bērtulis','Boļeslavs'],
    ['Ludvigs','Ludis','Ivonna','Patrīcija','Patriks'],
    ['Natālija','Tālija','Broņislavs','Broņislava'],
    ['Žanis','Jorens','Alens'],
    ['Auguste','Guste'],
    ['Armīns','Vismants','Aiga'],
    ['Alvis','Jolanta','Samanta'],
    ['Vilma','Aigars']
  ]
];
<|endoftext|>


<commit_before>var x;
var y;
var squares;
var maze;
var walls;
var halls;
var unproccessed;
var proccessed;
var walked;
var current;
var startTime;
var endTime;
var mazeReady = false;
var points

$(document).ready(function() {
	$('#suggestedForm').submit(function() {
		go();
		return fasle;
	});
	$('#customForm').submit(function() {
		go();
		return fasle;
	});
});
var newMaze = function() {
	$('#loading').hide();
	$('ul.tabs').tabs('select_tab', 'suggested');
	$('#suggested').show();
	$('#top').slideDown();
	$('#bottom').hide();
	$('body').css('overflow', 'scroll');
}

var go = function() {
	var suggested = ($('ul.tabs .active').attr('href') == '#suggested');
	// console.log(suggested);
	if (suggested) {
		var xy = parseInt($('input[name="size"]:checked').val());
		// console.log(xy);

		$('#suggested').hide();
		$('#custom').hide();
		$('#loading').show();
		generateMaze(xy, xy);
	} else{
		var newX = parseInt($('#width').val());
		var newY = parseInt($('#height').val());
		var valid = (newX > 2 && newY > 2);
		if (valid) {
			$('#suggested').hide();
			$('#custom').hide();
			$('#loading').show();
			generateMaze(newX, newY);
		};
	};
}

var generateMaze = function(givenX,givenY) {
	mazeReady = false;
	points = 0;
	$('#score').text(points);
	x = givenX;
	y = givenY;
	squares = x * y;
	maze = [];
	walls = [];
	halls = [];
	unproccessed = [];
	proccessed = [];
	walked = [1];
	current = 1;

	for (var i = 1; i <= squares; i++) {
		maze.push([i]);
	};
	// console.log(maze);

	for (var a = 1; a <= squares; a++) {
		// console.log('a ' + a);
		var b = [a-x,a+x];
		if (a % x != 0) {b.push(a+1)};
		if (a % x != 1) {b.push(a-1)};
		for (var i = 0; i  0 && b[i] <= squares) {
				// console.log('used');
				// console.log(unproccessed);
				// console.log(arrayIndex(unproccessed,[a,b[i]]));
				// console.log(arrayIndex(unproccessed,[b[i],a]));
				// console.log(a);
				// console.log(b[i]);
				if (arrayIndex(unproccessed,[a,b[i]]) == -1 && arrayIndex(unproccessed,[b[i],a]) == -1) {
					unproccessed.push([a,b[i]]);
				};
			};
		};
	};

	// console.log(unproccessed);

	while (maze.length > 1) {
		var i = Math.floor(Math.random() * unproccessed.length);
		// console.log('a ' + a);
		var a = unproccessed[i][0];
		var b = unproccessed[i][1]
		unproccessed.splice(i,1);
		proccess(a,b);
		proccessed.push([a,b]);
	}
	while(unproccessed.length > 0) {
		walls.push(unproccessed[0]);
		unproccessed.splice(0,1);
	};

	// console.log(unproccessed);
	// console.log(maze);
	// console.log(walls);
	var index = 1
	var table = $('#mazeTable');
	table.html('');
	for (var i = 0; i < y; i++) {
		var row = $('
');
		for (var j = 0; j < x; j++) {
			var tuple = $('');
			tuple.attr('id', index);
			tuple.attr('class','cell');
			// tuple.text(index);
			index++;
			row.append(tuple);
		};
		table.append(row);
		// console.log(row);
	};
	for (var i = 0; i < walls.length; i++) {
		// console.log(walls[i][0] +' '+ walls[i][1]);
		// console.log(Math.min(walls[i][0] , walls[i][1]));
		if ([-1,1].indexOf(walls[i][0] - walls[i][1]) != -1) {
			// console.log('sameline');
			$('#'+Math.min(walls[i][0] , walls[i][1])).css("border-right", "solid black 5px");
		} else if ([-x,x].indexOf(walls[i][0] - walls[i][1]) != -1) {
			// console.log('next line');
			$('#'+Math.min(walls[i][0] , walls[i][1])).css("border-bottom", "solid black 5px");
		};
	};
	for (var i = 1; i <= x; i++) {
		$('#'+i).css("border-top", "solid black 5px");
		$('#'+(i+((y-1)*x))).css("border-bottom", "solid black 5px");
	};
	for (var i = 1; i <= y; i++) {
		$('#'+(i*x-(x-1))).css("border-left", "solid black 5px");
		$('#'+(i*x)).css("border-right", "solid black 5px");
	};
	$('#1').css("border-left", "0").css('background-color', 'green');
	$('#'+squares).css("border-right", "0");
	$('#top').slideUp();
	$('#bottom').show();
	$('body').css('overflow', 'hidden');
	mazeReady = true;
	$('td').mouseover(function(){
  	//console.log(this.id);
  	move(parseInt(this.id));
	}).bind('touchend', function(e) {
    e.preventDefault();
    //console.log(this.id);
    move(parseInt(this.id));
  });
}

$(document).on('keydown', function(e) {
	// console.log(e.keyCode);
	if (mazeReady && [37,38,39,40].indexOf(e.keyCode) != -1) {
		key(e.keyCode);
	};
});

var key = function(k) {
	var next;
	switch (k) {
		case 37:
			// console.log('left');
			next = current - 1;
			break;
		case 38:
			// console.log('up');
			next = current - x;
			break;
		case 39:
			// console.log('right');
			next = current + 1;
			break;
		case 40:
			// console.log('down');
			next = current + x;
			break;
	}
	move(next);
}
var move = function(next) {
	if (current == 1) {
		var d = new Date();
		startTime = d.getTime();
	};
	// console.log(next);
	// console.log(arrayIndex(halls, [current,next]));
	// console.log(arrayIndex(halls, [next,current]));
	var can = (arrayIndex(halls, [current,next]) != -1 || arrayIndex(halls, [next,current]) != -1);
	// console.log(can);
	if (can) {

		$('#'+current).css('background-color', '#98FB98');
		$('#'+next).css('background-color', 'green');
		if (walked.indexOf(next) != -1) {
			$('#'+current).css('background-color', 'yellow');
			points++;
			$('#score').text(points);
		};
		walked.push(next);
		current = next;
		if (current == squares) {
			var d = new Date();
			endTime = d.getTime();
			end();
		};
	};
}

var end = function() {
	mazeReady = false;
	var games = new Firebase('https://maze-generator.firebaseio.com/games');
	vex.dialog.prompt({
	  message: 'You win!!! it took you only ' + ((endTime - startTime)/1000) + ' seconds and you made ' + points + ' mistake' + ((points == 1) ? '' : 's') + '
Woulds you like to save this to a username?' ,
	  placeholder: 'User Name',
	  callback: function(value) {
	    games.push({
			'start': startTime,
			'end': endTime,
			'time': ((endTime -startTime)/1000),
			'walls': walls,
			'halls': halls,
			'walked': walked,
			'points': points,
			'x':x,
			'y':y,
			'user': value
			});
	  }
	});
}

var find = function(a) {
	var item;
	for (var i = 0; i < maze.length; i++) {
		if (maze[i].indexOf(a) != -1) {
			item = maze[i];
		};
	};
	return item;
}
var proccess = function(numA,numB) {
	if (numA==numB) {return};
	var a = find(numA);
	var b = find(numB);
	// console.log('----');
	// console.log(numA);
	// console.log(a);
	// console.log(numB);
	// console.log(b);
	if (a === b) {
		// console.log('wall');
		walls.push([numA, numB]);
	} else {
		// console.log('hall');
		halls.push([numA, numB]);
		union(a,b);
		// console.log(a);
	};
	// console.log('----');
	return maze;
}
var union = function(a,b) {
	if (a !== b) {
		for (var i = 0; i < b.length; i++) {
			a.push(b[i]);
		};
		maze.splice(maze.indexOf(b),1);
		//remove(numB);
	};
	return maze;
}

function arrayIndex(a,b) {
	for (var i = 0; i < a.length; i++) {
		if (arraysEqual(a[i], b)) { return i;};
	};
	return -1;
}

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;

    // If you don't care about the order of the elements inside
    // the array, you should sort both arrays here.

    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}<commit_msg>touch support<commit_after>var x;
var y;
var squares;
var maze;
var walls;
var halls;
var unproccessed;
var proccessed;
var walked;
var current;
var startTime;
var endTime;
var mazeReady = false;
var points

$(document).ready(function() {
	$('#suggestedForm').submit(function() {
		go();
		return fasle;
	});
	$('#customForm').submit(function() {
		go();
		return fasle;
	});
});
var newMaze = function() {
	$('#loading').hide();
	$('ul.tabs').tabs('select_tab', 'suggested');
	$('#suggested').show();
	$('#top').slideDown();
	$('#bottom').hide();
	$('body').css('overflow', 'scroll');
}

var go = function() {
	var suggested = ($('ul.tabs .active').attr('href') == '#suggested');
	// console.log(suggested);
	if (suggested) {
		var xy = parseInt($('input[name="size"]:checked').val());
		// console.log(xy);

		$('#suggested').hide();
		$('#custom').hide();
		$('#loading').show();
		generateMaze(xy, xy);
	} else{
		var newX = parseInt($('#width').val());
		var newY = parseInt($('#height').val());
		var valid = (newX > 2 && newY > 2);
		if (valid) {
			$('#suggested').hide();
			$('#custom').hide();
			$('#loading').show();
			generateMaze(newX, newY);
		};
	};
}

var generateMaze = function(givenX,givenY) {
	mazeReady = false;
	points = 0;
	$('#score').text(points);
	x = givenX;
	y = givenY;
	squares = x * y;
	maze = [];
	walls = [];
	halls = [];
	unproccessed = [];
	proccessed = [];
	walked = [1];
	current = 1;

	for (var i = 1; i <= squares; i++) {
		maze.push([i]);
	};
	// console.log(maze);

	for (var a = 1; a <= squares; a++) {
		// console.log('a ' + a);
		var b = [a-x,a+x];
		if (a % x != 0) {b.push(a+1)};
		if (a % x != 1) {b.push(a-1)};
		for (var i = 0; i  0 && b[i] <= squares) {
				// console.log('used');
				// console.log(unproccessed);
				// console.log(arrayIndex(unproccessed,[a,b[i]]));
				// console.log(arrayIndex(unproccessed,[b[i],a]));
				// console.log(a);
				// console.log(b[i]);
				if (arrayIndex(unproccessed,[a,b[i]]) == -1 && arrayIndex(unproccessed,[b[i],a]) == -1) {
					unproccessed.push([a,b[i]]);
				};
			};
		};
	};

	// console.log(unproccessed);

	while (maze.length > 1) {
		var i = Math.floor(Math.random() * unproccessed.length);
		// console.log('a ' + a);
		var a = unproccessed[i][0];
		var b = unproccessed[i][1]
		unproccessed.splice(i,1);
		proccess(a,b);
		proccessed.push([a,b]);
	}
	while(unproccessed.length > 0) {
		walls.push(unproccessed[0]);
		unproccessed.splice(0,1);
	};

	// console.log(unproccessed);
	// console.log(maze);
	// console.log(walls);
	var index = 1
	var table = $('#mazeTable');
	table.html('');
	for (var i = 0; i < y; i++) {
		var row = $('
');
		for (var j = 0; j < x; j++) {
			var tuple = $('');
			tuple.attr('id', index);
			tuple.attr('class','cell');
			// tuple.text(index);
			index++;
			row.append(tuple);
		};
		table.append(row);
		// console.log(row);
	};
	for (var i = 0; i < walls.length; i++) {
		// console.log(walls[i][0] +' '+ walls[i][1]);
		// console.log(Math.min(walls[i][0] , walls[i][1]));
		if ([-1,1].indexOf(walls[i][0] - walls[i][1]) != -1) {
			// console.log('sameline');
			$('#'+Math.min(walls[i][0] , walls[i][1])).css("border-right", "solid black 5px");
		} else if ([-x,x].indexOf(walls[i][0] - walls[i][1]) != -1) {
			// console.log('next line');
			$('#'+Math.min(walls[i][0] , walls[i][1])).css("border-bottom", "solid black 5px");
		};
	};
	for (var i = 1; i <= x; i++) {
		$('#'+i).css("border-top", "solid black 5px");
		$('#'+(i+((y-1)*x))).css("border-bottom", "solid black 5px");
	};
	for (var i = 1; i <= y; i++) {
		$('#'+(i*x-(x-1))).css("border-left", "solid black 5px");
		$('#'+(i*x)).css("border-right", "solid black 5px");
	};
	$('#1').css("border-left", "0").css('background-color', 'green');
	$('#'+squares).css("border-right", "0");
	$('#top').slideUp();
	$('#bottom').show();
	$('body').css('overflow', 'hidden');
	mazeReady = true;
	$('td').mouseover(function(){
  	//console.log(this.id);
  	move(parseInt(this.id));
	}).bind('touchend', function(e) {
    e.preventDefault();
    //console.log(this.id);
    move(parseInt(this.id));
  }).bind('touchmove', function(e){
		e.preventDefault();
		//console.log("(" + e.originalEvent.changedTouches[0].pageX + ", " + e.originalEvent.changedTouches[0].pageY + ")");
		//console.log(document.elementFromPoint(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY).id);
		move(parseInt(document.elementFromPoint(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY).id));
	});
}

$(document).on('keydown', function(e) {
	// console.log(e.keyCode);
	if (mazeReady && [37,38,39,40].indexOf(e.keyCode) != -1) {
		key(e.keyCode);
	};
});

var key = function(k) {
	var next;
	switch (k) {
		case 37:
			// console.log('left');
			next = current - 1;
			break;
		case 38:
			// console.log('up');
			next = current - x;
			break;
		case 39:
			// console.log('right');
			next = current + 1;
			break;
		case 40:
			// console.log('down');
			next = current + x;
			break;
	}
	move(next);
}
var move = function(next) {
	if (current == 1) {
		var d = new Date();
		startTime = d.getTime();
	};
	// console.log(next);
	// console.log(arrayIndex(halls, [current,next]));
	// console.log(arrayIndex(halls, [next,current]));
	var can = (arrayIndex(halls, [current,next]) != -1 || arrayIndex(halls, [next,current]) != -1);
	// console.log(can);
	if (can) {

		$('#'+current).css('background-color', '#98FB98');
		$('#'+next).css('background-color', 'green');
		if (walked.indexOf(next) != -1) {
			$('#'+current).css('background-color', 'yellow');
			points++;
			$('#score').text(points);
		};
		walked.push(next);
		current = next;
		if (current == squares) {
			var d = new Date();
			endTime = d.getTime();
			end();
		};
	};
}

var end = function() {
	mazeReady = false;
	var games = new Firebase('https://maze-generator.firebaseio.com/games');
	vex.dialog.prompt({
	  message: 'You win!!! it took you only ' + ((endTime - startTime)/1000) + ' seconds and you made ' + points + ' mistake' + ((points == 1) ? '' : 's') + '
Woulds you like to save this to a username?' ,
	  placeholder: 'User Name',
	  callback: function(value) {
	    games.push({
			'start': startTime,
			'end': endTime,
			'time': ((endTime -startTime)/1000),
			'walls': walls,
			'halls': halls,
			'walked': walked,
			'points': points,
			'x':x,
			'y':y,
			'user': value
			});
	  }
	});
}

var find = function(a) {
	var item;
	for (var i = 0; i < maze.length; i++) {
		if (maze[i].indexOf(a) != -1) {
			item = maze[i];
		};
	};
	return item;
}
var proccess = function(numA,numB) {
	if (numA==numB) {return};
	var a = find(numA);
	var b = find(numB);
	// console.log('----');
	// console.log(numA);
	// console.log(a);
	// console.log(numB);
	// console.log(b);
	if (a === b) {
		// console.log('wall');
		walls.push([numA, numB]);
	} else {
		// console.log('hall');
		halls.push([numA, numB]);
		union(a,b);
		// console.log(a);
	};
	// console.log('----');
	return maze;
}
var union = function(a,b) {
	if (a !== b) {
		for (var i = 0; i < b.length; i++) {
			a.push(b[i]);
		};
		maze.splice(maze.indexOf(b),1);
		//remove(numB);
	};
	return maze;
}

function arrayIndex(a,b) {
	for (var i = 0; i < a.length; i++) {
		if (arraysEqual(a[i], b)) { return i;};
	};
	return -1;
}

function arraysEqual(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;

    // If you don't care about the order of the elements inside
    // the array, you should sort both arrays here.

    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
}<|endoftext|>


<commit_before>$(document).on("click", ".feature-row", function(e) {
  sidebarClick(parseInt($(this).attr('id')),layerControl);
});

$("#full-extent-btn").click(function() {
  map.setView(startCenter, startZoom);
  return false;
});

$("#legend-btn").click(function() {
  //TODO: add all the currently added layers here, not just one...
  var text = "";
  if(currentBaseLayer) {
    text += "" + featureLayersName[currentLayerIndex] + "

";
  }
  $("#legend").html(text);
  $('#legendModal').modal('show');
  return false;
});

$("#list-btn").click(function() {
  $('#sidebar').toggle();
  map.invalidateSize();
  return false;
});

$("#nav-btn").click(function() {
  $(".navbar-collapse").collapse("toggle");
  return false;
});

$("#sidebar-toggle-btn").click(function() {
  $("#sidebar").toggle();
  map.invalidateSize();
  return false;
});

$("#sidebar-hide-btn").click(function() {
  $('#sidebar').hide();
  map.invalidateSize();
});

$('#search-form').submit(function(e) {
    alert("Working....");
});

var map, featureLayers = [], featureLayersName = [];

//Native projection from GeoServer WFS
var src = new Proj4js.Proj('EPSG:4326');
var dst = new Proj4js.Proj('EPSG:28355');

//Attribution, get from WMS?
var layerAttribution = 'Data &copy GCC, Data to be used for Council related purposes only.';

var startCenter = new L.LatLng(-42.8232,147.2555);
var startZoom = 12;
var searchBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-42.9063,147.1335),
    new google.maps.LatLng(-42.7167, 147.3444));

owsURL = "https://maps.gcc.tas.gov.au/geoserver/ows";
wmsURL = "https://maps.gcc.tas.gov.au/geoserver/gwc/service/wms";

var PScheme_BaseLabels = new L.TileLayer.WMS(wmsURL, {
        layers: 'gcc_ips:PScheme_BaseLabels',
        format: 'image/png',
        transparent: true,
        maxZoom: 20,
        attribution: 'Base data from the LIST, &copy State of Tasmania.'
    });

var image = new L.tileLayer("https://services.thelist.tas.gov.au/arcgis/rest/services/Basemaps/Orthophoto/ImageServer/tile/{z}/{y}/{x}", {
    attribution: "Base Imagery from the LIST &copy State of Tasmania",
    maxZoom: 20,
    maxNativeZoom: 19,
    opacity: 0.6,
    transparent: true
});

var ps = new L.TileLayer.WMS(wmsURL, {
    layers: 'gcc_ips:Pscheme_ZoningGroup',
    format: 'image/png',
    transparent: true,
    maxZoom: 20,
    attribution: layerAttribution
});

var ie = L.Browser.ie;

var baseLayers = {
  'Zoning': ps
};

var overlays = {
    "Aerial Image": image,
    "Labels and Boundaries": PScheme_BaseLabels
};

var overlaysList = {
    "E3 Landslide Code": 'PScheme_Oly_Landslide',
    "E8 Electricity Transmission Infrastructure Protection Code": 'PScheme_Oly_ElecTransInfraProtection',
    "E10 Biodiversity Code": 'PScheme_Oly_Biodiversity',
    "E11 Waterway and Coastal Protection Code": 'PScheme_Oly_WaterwayCoastalProtectionA',
    "E14 Scenic Landscapes Code": 'PScheme_Oly_ScenicLandscapes',
    "E15 Inundation Prone Areas Code": 'PScheme_Oly_InundationProneAreas',
    "E16 Coastal Erosion Hazard Code": 'PScheme_Oly_CoastalErosionHazard',
    "E20 Acid Sulfate Soils Code": 'PScheme_Oly_AcidSulfateSoils',
    "E21 Dispersive Soils Code": 'PScheme_Oly_DispersiveSoils',
    "E24 Significant Trees Code": 'PScheme_Oly_SignificantTrees',
    "F Specific Area Plans": 'PScheme_SpecificAreaPlans'
};

var referenceLayersList = {
  "E9.0 Attenuation Reference": 'Pscheme_Ref_Attenuation',
  "E13.0 Heritage Reference": 'Pscheme_Ref_Heritage',
  "E10.0 Priority Biodiversity Values Reference": 'PScheme_Ref_PriorityBiodiversityValues',
  "E15.0 Riverine Hazard Reference": 'Pscheme_Ref_RiverineHazard',
  "Title Reference": 'PScheme_Ref_Title',
  "F3 Wellington Park Reference": 'PScheme_Ref_WellingtonPark'
}

var layerIndex = 1;

//Add zoning to list
$("#feature-list tbody").append('
\
    	Zoning	\

');
featureLayers.push("gcc_ips:Pscheme_ZoningGroup")
featureLayersName.push('Zoning')

for (layer in overlaysList) {
  featureLayers.push("gcc_ips:"+overlaysList[layer])
  featureLayersName.push(layer)
  $("#feature-list tbody").append('
\
    	'+layer+'	\

');
  layerIndex = layerIndex + 1;
};

for (layer in referenceLayersList) {
  featureLayers.push("gcc_ips:"+referenceLayersList[layer])
  featureLayersName.push(layer)
  $("#feature-list tbody").append('
\
    	'+layer+'	\

');
  layerIndex = layerIndex + 1;
};

//this is where I add the layer. Primed with Zoning.
var currentBaseLayer = ps;
var currentLayerIndex = 0;

function sidebarClick(id) {
  if(currentBaseLayer) {
    map.removeLayer(currentBaseLayer);
  }
  currentLayerIndex = id;
  //TODO: change this to remove other layers.
  addLayer(featureLayers[id]);
}

function addLayer(layer) {
  var id = $.inArray(layer, featureLayers);
  if(id === -1) {
    return;
  }
  var newLayer = new L.TileLayer.WMS(wmsURL + "?SERVICE=WMS&", {
          layers: layer,
          format: 'image/png',
          transparent: true,
          maxZoom: 20,
          attribution: layerAttribution
  });

  currentBaseLayer = newLayer;

  map.removeControl(layerControl);
  baseLayers = {}
  baseLayers[featureLayersName[id]] = newLayer;
  layerControl = L.control.layers(baseLayers, overlays, {
    collapsed: isCollapsed
  }).addTo(map);

  map.addLayer(newLayer);
  /* Hide sidebar and go to the map on small screens */
  if (document.body.clientWidth <= 767) {
    $("#sidebar").hide();
    map.invalidateSize();
  }
}

map = L.map("map", {
  zoom: startZoom,
  center: startCenter,
  layers: [PScheme_BaseLabels],
  zoomControl: false,
  attributionControl: false
});

//Start with Zoning.
map.addLayer(ps);

//Query layer functionality.
var selectedFeature;
var queryCoordinates;

function highlightFeature(e) {
    var layer = e.target;
    layer.setStyle({
        fillColor: "yellow",
        color: "yellow",
        weight: 5,
        opacity: 1
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }
}

function resetHighlight(e) {
    var layer = e.target;
    layer.setStyle({
        radius: 5,
        fillColor: "yellow",
        color: "yellow",
        weight: 5,
        opacity: 0.6,
        fillOpacity: 0.2
    });
}

function handleJson(data) {
  if (selectedFeature) {
    map.removeLayer(selectedFeature);
  };
  selectedFeature = L.geoJson(data, {
    style: function (feature) {
        return {color: 'blue'};
    },
    onEachFeature: function (feature, layer) {
	var head = '
'
		+'
Address	'+((feature.properties.address) ? feature.properties.address : "")+'
'
		+'
PID	'+((feature.properties.pid != -9999) ? feature.properties.pid : "")+'
'
		+'
Zones	'+feature.properties.zones+'
';
	var mid = '
Zone Boundary	'+((feature.properties.zonebdy) ? feature.properties.zonebdy : "none")+'
';
	var tail = '
Overlays	'+((feature.properties.overlays) ? feature.properties.overlays : "none")+'
'
		+'
Reference Layers	'+((feature.properties.reflayers) ? feature.properties.reflayers : "")+'
'
		+'
Note	Other codes may be triggered by description, refer to "Application" section in each code.
'
		+'
';
	if (feature.properties.zonebdy) {
		var content = head + mid + tail;
	} else { var content = head + tail;}

    var popup = L.popup()
        .setLatLng(queryCoordinates)
        .setContent(content)
        .openOn(map);
        layer.bindPopup(content);
    queryAddress = feature.properties.address;
    }
  });
  selectedFeature.addTo(map);
}

map.on('click', function(e) {
  var p = new Proj4js.Point(e.latlng.lng,e.latlng.lat);
  Proj4js.transform(src, dst, p);
  queryCoordinates = e.latlng

  var defaultParameters = {
    service : 'WFS',
    version : '1.1.1',
    request : 'GetFeature',
    typeName : 'gcc_ips:PScheme_Summary',
    maxFeatures : 100,
    outputFormat : 'text/javascript',
    format_options : 'callback:getJson',
    SrsName : 'EPSG:4326'
  };

  var customParams = {
    //bbox : map.getBounds().toBBoxString(),
    cql_filter:'CONTAINS(geom, POINT(' + p.x + ' ' + p.y + '))'
  };

  var parameters = L.Util.extend(defaultParameters, customParams);

  //console.log(owsURL+L.Util.getParamString(parameters));

  $.ajax({
      url : owsURL + L.Util.getParamString(parameters),
      dataType : 'jsonp',
      jsonpCallback : 'getJson',
      success : handleJson
  });
});

/* Attribution control */
function updateAttribution(e) {
  var attributiontext = "";
  var attributions = []
  $.each(map._layers, function(index, layer) {
    if (layer.getAttribution) {
      if($.inArray(layer.getAttribution(), attributions) === -1) {
        attributiontext = attributiontext + layer.getAttribution() + '
'
        attributions.push(layer.getAttribution())
      }
    }
  });
  $("#attribution").html((attributiontext));
}
map.on("layeradd", updateAttribution);
map.on("layerremove", updateAttribution);

var attributionControl = L.control({
  position: "bottomright"
});

attributionControl.onAdd = function (map) {
  var div = L.DomUtil.create("div", "leaflet-control-attribution");
  div.innerHTML = "Developed by agl | Dataset Attribution";
  return div;
};

map.addControl(attributionControl);

var zoomControl = L.control.zoom({
  position: "topleft"
}).addTo(map);

L.control.locate({
  position: 'bottomright',
  drawCircle: false,
  follow: true
}).addTo(map);

//Ok, got to get the searching working...
$(document).ready(function () {
    (function ($) {
        $('#layerfilter').keyup(function () {
            var rex = new RegExp($(this).val(), 'i');
            $('.searchable tr').hide();
            $('.searchable tr').filter(function () {
                return rex.test($(this).text());
            }).show();
        })
    }(jQuery));
});
$("#searchclear").click(function(){
    $("#layerfilter").val('');
    $('.searchable tr').show();
});

var options = {
  bounds: searchBounds
};
var searchinput = document.getElementById("searchbox");
var autocomplete = new google.maps.places.Autocomplete(searchinput, options);
var leafMarker;
google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      input.className = 'notfound';
      return;
    }
    if(leafMarker){
        map.removeLayer(leafMarker);
    }
    var leafLocation = new L.LatLng(place.geometry.location.lat(),place.geometry.location.lng())
    leafMarker = L.marker(leafLocation, {title: place.formatted_address}).bindPopup(place.formatted_address).addTo(map);
    map.setView(leafLocation, 18)
});

/* Larger screens get expanded layer control and visible sidebar */
if (document.body.clientWidth <= 767) {
  var isCollapsed = true;
} else {
  var isCollapsed = false;
}

var layerControl = L.control.layers(baseLayers, overlays, {
    collapsed: isCollapsed
  }).addTo(map);

/* Highlight search box text on click */
$("#searchbox").click(function () {
  $(this).select();
});
$("#loading").hide();

<commit_msg>Changed WaterwayCoastalProtection<commit_after>$(document).on("click", ".feature-row", function(e) {
  sidebarClick(parseInt($(this).attr('id')),layerControl);
});

$("#full-extent-btn").click(function() {
  map.setView(startCenter, startZoom);
  return false;
});

$("#legend-btn").click(function() {
  //TODO: add all the currently added layers here, not just one...
  var text = "";
  if(currentBaseLayer) {
    text += "" + featureLayersName[currentLayerIndex] + "

";
  }
  $("#legend").html(text);
  $('#legendModal').modal('show');
  return false;
});

$("#list-btn").click(function() {
  $('#sidebar').toggle();
  map.invalidateSize();
  return false;
});

$("#nav-btn").click(function() {
  $(".navbar-collapse").collapse("toggle");
  return false;
});

$("#sidebar-toggle-btn").click(function() {
  $("#sidebar").toggle();
  map.invalidateSize();
  return false;
});

$("#sidebar-hide-btn").click(function() {
  $('#sidebar').hide();
  map.invalidateSize();
});

$('#search-form').submit(function(e) {
    alert("Working....");
});

var map, featureLayers = [], featureLayersName = [];

//Native projection from GeoServer WFS
var src = new Proj4js.Proj('EPSG:4326');
var dst = new Proj4js.Proj('EPSG:28355');

//Attribution, get from WMS?
var layerAttribution = 'Data &copy GCC, Data to be used for Council related purposes only.';

var startCenter = new L.LatLng(-42.8232,147.2555);
var startZoom = 12;
var searchBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-42.9063,147.1335),
    new google.maps.LatLng(-42.7167, 147.3444));

owsURL = "https://maps.gcc.tas.gov.au/geoserver/ows";
wmsURL = "https://maps.gcc.tas.gov.au/geoserver/gwc/service/wms";

var PScheme_BaseLabels = new L.TileLayer.WMS(wmsURL, {
        layers: 'gcc_ips:PScheme_BaseLabels',
        format: 'image/png',
        transparent: true,
        maxZoom: 20,
        attribution: 'Base data from the LIST, &copy State of Tasmania.'
    });

var image = new L.tileLayer("https://services.thelist.tas.gov.au/arcgis/rest/services/Basemaps/Orthophoto/ImageServer/tile/{z}/{y}/{x}", {
    attribution: "Base Imagery from the LIST &copy State of Tasmania",
    maxZoom: 20,
    maxNativeZoom: 19,
    opacity: 0.6,
    transparent: true
});

var ps = new L.TileLayer.WMS(wmsURL, {
    layers: 'gcc_ips:Pscheme_ZoningGroup',
    format: 'image/png',
    transparent: true,
    maxZoom: 20,
    attribution: layerAttribution
});

var ie = L.Browser.ie;

var baseLayers = {
  'Zoning': ps
};

var overlays = {
    "Aerial Image": image,
    "Labels and Boundaries": PScheme_BaseLabels
};

var overlaysList = {
    "E3 Landslide Code": 'PScheme_Oly_Landslide',
    "E8 Electricity Transmission Infrastructure Protection Code": 'PScheme_Oly_ElecTransInfraProtection',
    "E10 Biodiversity Code": 'PScheme_Oly_Biodiversity',
    "E11 Waterway and Coastal Protection Code": 'PScheme_Oly_WaterwayCoastalProtection',
    "E14 Scenic Landscapes Code": 'PScheme_Oly_ScenicLandscapes',
    "E15 Inundation Prone Areas Code": 'PScheme_Oly_InundationProneAreas',
    "E16 Coastal Erosion Hazard Code": 'PScheme_Oly_CoastalErosionHazard',
    "E20 Acid Sulfate Soils Code": 'PScheme_Oly_AcidSulfateSoils',
    "E21 Dispersive Soils Code": 'PScheme_Oly_DispersiveSoils',
    "E24 Significant Trees Code": 'PScheme_Oly_SignificantTrees',
    "F Specific Area Plans": 'PScheme_SpecificAreaPlans'
};

var referenceLayersList = {
  "E9.0 Attenuation Reference": 'Pscheme_Ref_Attenuation',
  "E13.0 Heritage Reference": 'Pscheme_Ref_Heritage',
  "E10.0 Priority Biodiversity Values Reference": 'PScheme_Ref_PriorityBiodiversityValues',
  "E15.0 Riverine Hazard Reference": 'Pscheme_Ref_RiverineHazard',
  "Title Reference": 'PScheme_Ref_Title',
  "F3 Wellington Park Reference": 'PScheme_Ref_WellingtonPark'
}

var layerIndex = 1;

//Add zoning to list
$("#feature-list tbody").append('
\
    	Zoning	\

');
featureLayers.push("gcc_ips:Pscheme_ZoningGroup")
featureLayersName.push('Zoning')

for (layer in overlaysList) {
  featureLayers.push("gcc_ips:"+overlaysList[layer])
  featureLayersName.push(layer)
  $("#feature-list tbody").append('
\
    	'+layer+'	\

');
  layerIndex = layerIndex + 1;
};

for (layer in referenceLayersList) {
  featureLayers.push("gcc_ips:"+referenceLayersList[layer])
  featureLayersName.push(layer)
  $("#feature-list tbody").append('
\
    	'+layer+'	\

');
  layerIndex = layerIndex + 1;
};

//this is where I add the layer. Primed with Zoning.
var currentBaseLayer = ps;
var currentLayerIndex = 0;

function sidebarClick(id) {
  if(currentBaseLayer) {
    map.removeLayer(currentBaseLayer);
  }
  currentLayerIndex = id;
  //TODO: change this to remove other layers.
  addLayer(featureLayers[id]);
}

function addLayer(layer) {
  var id = $.inArray(layer, featureLayers);
  if(id === -1) {
    return;
  }
  var newLayer = new L.TileLayer.WMS(wmsURL + "?SERVICE=WMS&", {
          layers: layer,
          format: 'image/png',
          transparent: true,
          maxZoom: 20,
          attribution: layerAttribution
  });

  currentBaseLayer = newLayer;

  map.removeControl(layerControl);
  baseLayers = {}
  baseLayers[featureLayersName[id]] = newLayer;
  layerControl = L.control.layers(baseLayers, overlays, {
    collapsed: isCollapsed
  }).addTo(map);

  map.addLayer(newLayer);
  /* Hide sidebar and go to the map on small screens */
  if (document.body.clientWidth <= 767) {
    $("#sidebar").hide();
    map.invalidateSize();
  }
}

map = L.map("map", {
  zoom: startZoom,
  center: startCenter,
  layers: [PScheme_BaseLabels],
  zoomControl: false,
  attributionControl: false
});

//Start with Zoning.
map.addLayer(ps);

//Query layer functionality.
var selectedFeature;
var queryCoordinates;

function highlightFeature(e) {
    var layer = e.target;
    layer.setStyle({
        fillColor: "yellow",
        color: "yellow",
        weight: 5,
        opacity: 1
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }
}

function resetHighlight(e) {
    var layer = e.target;
    layer.setStyle({
        radius: 5,
        fillColor: "yellow",
        color: "yellow",
        weight: 5,
        opacity: 0.6,
        fillOpacity: 0.2
    });
}

function handleJson(data) {
  if (selectedFeature) {
    map.removeLayer(selectedFeature);
  };
  selectedFeature = L.geoJson(data, {
    style: function (feature) {
        return {color: 'blue'};
    },
    onEachFeature: function (feature, layer) {
	var head = '
'
		+'
Address	'+((feature.properties.address) ? feature.properties.address : "")+'
'
		+'
PID	'+((feature.properties.pid != -9999) ? feature.properties.pid : "")+'
'
		+'
Zones	'+feature.properties.zones+'
';
	var mid = '
Zone Boundary	'+((feature.properties.zonebdy) ? feature.properties.zonebdy : "none")+'
';
	var tail = '
Overlays	'+((feature.properties.overlays) ? feature.properties.overlays : "none")+'
'
		+'
Reference Layers	'+((feature.properties.reflayers) ? feature.properties.reflayers : "")+'
'
		+'
Note	Other codes may be triggered by description, refer to "Application" section in each code.
'
		+'
';
	if (feature.properties.zonebdy) {
		var content = head + mid + tail;
	} else { var content = head + tail;}

    var popup = L.popup()
        .setLatLng(queryCoordinates)
        .setContent(content)
        .openOn(map);
        layer.bindPopup(content);
    queryAddress = feature.properties.address;
    }
  });
  selectedFeature.addTo(map);
}

map.on('click', function(e) {
  var p = new Proj4js.Point(e.latlng.lng,e.latlng.lat);
  Proj4js.transform(src, dst, p);
  queryCoordinates = e.latlng

  var defaultParameters = {
    service : 'WFS',
    version : '1.1.1',
    request : 'GetFeature',
    typeName : 'gcc_ips:PScheme_Summary',
    maxFeatures : 100,
    outputFormat : 'text/javascript',
    format_options : 'callback:getJson',
    SrsName : 'EPSG:4326'
  };

  var customParams = {
    //bbox : map.getBounds().toBBoxString(),
    cql_filter:'CONTAINS(geom, POINT(' + p.x + ' ' + p.y + '))'
  };

  var parameters = L.Util.extend(defaultParameters, customParams);

  //console.log(owsURL+L.Util.getParamString(parameters));

  $.ajax({
      url : owsURL + L.Util.getParamString(parameters),
      dataType : 'jsonp',
      jsonpCallback : 'getJson',
      success : handleJson
  });
});

/* Attribution control */
function updateAttribution(e) {
  var attributiontext = "";
  var attributions = []
  $.each(map._layers, function(index, layer) {
    if (layer.getAttribution) {
      if($.inArray(layer.getAttribution(), attributions) === -1) {
        attributiontext = attributiontext + layer.getAttribution() + '
'
        attributions.push(layer.getAttribution())
      }
    }
  });
  $("#attribution").html((attributiontext));
}
map.on("layeradd", updateAttribution);
map.on("layerremove", updateAttribution);

var attributionControl = L.control({
  position: "bottomright"
});

attributionControl.onAdd = function (map) {
  var div = L.DomUtil.create("div", "leaflet-control-attribution");
  div.innerHTML = "Developed by agl | Dataset Attribution";
  return div;
};

map.addControl(attributionControl);

var zoomControl = L.control.zoom({
  position: "topleft"
}).addTo(map);

L.control.locate({
  position: 'bottomright',
  drawCircle: false,
  follow: true
}).addTo(map);

//Ok, got to get the searching working...
$(document).ready(function () {
    (function ($) {
        $('#layerfilter').keyup(function () {
            var rex = new RegExp($(this).val(), 'i');
            $('.searchable tr').hide();
            $('.searchable tr').filter(function () {
                return rex.test($(this).text());
            }).show();
        })
    }(jQuery));
});
$("#searchclear").click(function(){
    $("#layerfilter").val('');
    $('.searchable tr').show();
});

var options = {
  bounds: searchBounds
};
var searchinput = document.getElementById("searchbox");
var autocomplete = new google.maps.places.Autocomplete(searchinput, options);
var leafMarker;
google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      input.className = 'notfound';
      return;
    }
    if(leafMarker){
        map.removeLayer(leafMarker);
    }
    var leafLocation = new L.LatLng(place.geometry.location.lat(),place.geometry.location.lng())
    leafMarker = L.marker(leafLocation, {title: place.formatted_address}).bindPopup(place.formatted_address).addTo(map);
    map.setView(leafLocation, 18)
});

/* Larger screens get expanded layer control and visible sidebar */
if (document.body.clientWidth <= 767) {
  var isCollapsed = true;
} else {
  var isCollapsed = false;
}

var layerControl = L.control.layers(baseLayers, overlays, {
    collapsed: isCollapsed
  }).addTo(map);

/* Highlight search box text on click */
$("#searchbox").click(function () {
  $(this).select();
});
$("#loading").hide();

<|endoftext|>


<commit_before>export const getSettings = () => ({
    url: 'settings',
    method: 'get'
});

export const updatePassword = (data) => ({
    url: 'settings/password',
    method: 'put',
    data
});

export const upgradePassword = (data) => ({
    url: 'settings/password/upgrade',
    method: 'put',
    data
});

export const updateLocale = (Locale) => ({
    url: 'settings/locale',
    method: 'put',
    data: { Locale }
});

export const updateNews = (News) => ({
    url: 'settings/news',
    method: 'put',
    data: { News }
});

export const updateInvoiceText = (InvoiceText) => ({
    url: 'settings/invoicetext',
    method: 'put',
    data: { InvoiceText }
});

export const updateLogAuth = (LogAuth) => ({
    url: 'settings/logauth',
    method: 'put',
    data: { LogAuth }
});

export const updateEmail = (data) => ({
    url: 'settings/email',
    method: 'put',
    data
});

export const updateNotifyEmail = (Notify) => ({
    url: 'settings/email/notify',
    method: 'put',
    data: { Notify }
});

export const updateResetEmail = (Reset) => ({
    url: 'settings/email/reset',
    method: 'put',
    data: { Reset }
});

export const verifyEmail = (Token) => ({
    url: 'settings/email/verify',
    method: 'post',
    data: { Token }
});

export const updatePhone = (data) => ({
    url: 'settings/phone',
    method: 'put',
    data
});

export const updateNotifyPhone = (Notify) => ({
    url: 'settings/phone/notify',
    method: 'put',
    data: { Notify }
});

export const updateResetPhone = (data) => ({
    url: 'settings/phone/reset',
    method: 'put',
    data
});

export const verifyPhone = (Token) => ({
    url: 'settings/phone/verify',
    method: 'post',
    data: { Token }
});

export const setupTotp = (TOTPSharedSecret, TOTPConfirmation) => ({
    url: 'settings/2fa/totp',
    method: 'post',
    data: { TOTPSharedSecret, TOTPConfirmation }
});

export const disableTotp = () => ({
    url: 'settings/2fa',
    method: 'put'
});
<commit_msg>Add wrong totp code error<commit_after>export const TOTP_WRONG_ERROR = 12060;

export const getSettings = () => ({
    url: 'settings',
    method: 'get'
});

export const updatePassword = (data) => ({
    url: 'settings/password',
    method: 'put',
    data
});

export const upgradePassword = (data) => ({
    url: 'settings/password/upgrade',
    method: 'put',
    data
});

export const updateLocale = (Locale) => ({
    url: 'settings/locale',
    method: 'put',
    data: { Locale }
});

export const updateNews = (News) => ({
    url: 'settings/news',
    method: 'put',
    data: { News }
});

export const updateInvoiceText = (InvoiceText) => ({
    url: 'settings/invoicetext',
    method: 'put',
    data: { InvoiceText }
});

export const updateLogAuth = (LogAuth) => ({
    url: 'settings/logauth',
    method: 'put',
    data: { LogAuth }
});

export const updateEmail = (data) => ({
    url: 'settings/email',
    method: 'put',
    data
});

export const updateNotifyEmail = (Notify) => ({
    url: 'settings/email/notify',
    method: 'put',
    data: { Notify }
});

export const updateResetEmail = (Reset) => ({
    url: 'settings/email/reset',
    method: 'put',
    data: { Reset }
});

export const verifyEmail = (Token) => ({
    url: 'settings/email/verify',
    method: 'post',
    data: { Token }
});

export const updatePhone = (data) => ({
    url: 'settings/phone',
    method: 'put',
    data
});

export const updateNotifyPhone = (Notify) => ({
    url: 'settings/phone/notify',
    method: 'put',
    data: { Notify }
});

export const updateResetPhone = (data) => ({
    url: 'settings/phone/reset',
    method: 'put',
    data
});

export const verifyPhone = (Token) => ({
    url: 'settings/phone/verify',
    method: 'post',
    data: { Token }
});

export const setupTotp = (TOTPSharedSecret, TOTPConfirmation) => ({
    url: 'settings/2fa/totp',
    method: 'post',
    data: { TOTPSharedSecret, TOTPConfirmation }
});

export const disableTotp = () => ({
    url: 'settings/2fa',
    method: 'put'
});
<|endoftext|>


<commit_before>;(function () {
  if (window.AppUrl == undefined) {
    window.AppUrl = {
      free4lab: 'http://www.free4lab.com/',
      account: 'http://account.free4lab.com/users/',
      iaas: 'http://iaas.free4lab.com/',
      paas: 'http://paas.free4lab.com/',
      freeshare: 'http://freeshare.free4lab.com/',
      listword: 'http://listworld.free4lab.com/',
      newfront: 'http://newfront.free4lab.com/'
    };
  }
})();<commit_msg>MOD：free4lab to free4inno<commit_after>;(function () {
  if (window.AppUrl == undefined) {
    window.AppUrl = {
      free4lab: 'http://www.free4inno.com/',
      account: 'http://account.free4inno.com/users/',
      iaas: 'http://iaas.free4inno.com/',
      paas: 'http://paas.free4inno.com/',
      freeshare: 'http://freeshare.free4inno.com/',
      listword: 'http://listworld.free4inno.com/',
      newfront: 'http://newfront.free4inno.com/'
    };
  }
})();<|endoftext|>


<commit_before><commit_msg>renamed timers to 'first' and 'second' in thymio_set_variable dropdown<commit_after><|endoftext|>