<commit_before>// Define functions

function dataReloaded() {
  // Fire a notification that the data has been successfully reloaded

  var successNoty = noty({
    text: 'Refresh complete!',
    layout: 'bottomRight',
    type: 'success',
    animation: {
      open: {
        height: 'toggle'
      },
      close: {
        height: 'toggle'
      },
      easing: 'swing',
      speed: 300 // opening & closing animation speed
    },
    timeout: 1000
  });

}

//TODO Refactor so it wont calculate it with frontend shit. Use the data from the backend

function calculateOnlinePlayers(){
  $("#server-list tr td:nth-child(5)").each(function(){
    sumPlayers = sumPlayers + parseInt($(this).html());
  });
  $(".online-players").html(sumPlayers);
}

// Define variables

var serverList;
var url = "http://supraverse.net:8990/list";
var data;
var sumPlayers = 0;

//on DOM ready

$(function () {

  // So after DOM loads setup the Ajax request and the datatable

  function queryServer(){
    $.ajax({
      url: url,
      type: "POST",
      crossDomain: true,
      contentType : 'application/json',
      data: "{}",
      processData:true,
      success: function (result) {
        launchTable(result);
      },
      error: function (xhr, ajaxOptions, thrownError) {
          console.log("Error: " ,xhr, ", " ,thrownError);
      }
    });
  }

  function launchTable(result){
    if (serverList != null){
      serverList.clear().rows.add(result.servers).draw(false);
      //TODO: callback for this
      dataReloaded();
    }else{
      serverList = $('#server-list').DataTable({
        data: result.servers,
        autoWidth: false,
        lengthMenu: [ [100, -1], [100, "All"] ],
        order: [
          [8, "desc"]
        ],
        displayLength: 100,
        columns: [{
          data: 'ip'
        }, {
          data: 'port'
        }, {
          data: 'title'
        }, {
          data: 'description'
        }, {
          data: 'max_players'
        }, {
          data: 'max_spectators'
        }, {
          data: 'max_duration'
        }, {
          data: 'max_goals'
        }, {
          data: 'current_players'
        }, {
          data: 'current_duration'
        }, {
          data: 'current_goals_red'
        }, {
          data: 'current_goals_blue'
        }, {
          data: 'map'
        }, {
          data: 'training'
        }],
        createdRow: function ( row, data, index ) {
          if (data.max_players == data.current_players) {
            $(row).addClass('danger');
          }else if (data.max_players - 2 <= data.current_players) {
            $(row).addClass('warning');
          }else if (data.current_players > 0) {
            $(row).addClass('success');
          }
        },
        columnDefs: [
        {
          render: function ( data, type, row ) {
            return row.current_players + '/' + data;
          },
          targets: 4
        },
        {
          "targets": [13,9,5,7,8],
          "visible": false,
          "searchable": false
        }
        ]
      });
      calculateOnlinePlayers();
      serverList.on( 'draw', function () {
        sumPlayers = 0;
        calculateOnlinePlayers();
      });
    }
  }

  //Start the show
  queryServer();

  //Autorefresh in every 5 secs

  window.setInterval(function () {
    queryServer();
  }, 8000);

  //Event listeners

});<commit_msg>Specifically send "all" version<commit_after>// Define functions

function dataReloaded() {
  // Fire a notification that the data has been successfully reloaded

  var successNoty = noty({
    text: 'Refresh complete!',
    layout: 'bottomRight',
    type: 'success',
    animation: {
      open: {
        height: 'toggle'
      },
      close: {
        height: 'toggle'
      },
      easing: 'swing',
      speed: 300 // opening & closing animation speed
    },
    timeout: 1000
  });

}

//TODO Refactor so it wont calculate it with frontend shit. Use the data from the backend

function calculateOnlinePlayers(){
  $("#server-list tr td:nth-child(5)").each(function(){
    sumPlayers = sumPlayers + parseInt($(this).html());
  });
  $(".online-players").html(sumPlayers);
}

// Define variables

var serverList;
var url = "http://supraverse.net:8990/list";
var data;
var sumPlayers = 0;

//on DOM ready

$(function () {

  // So after DOM loads setup the Ajax request and the datatable

  function queryServer(){
    $.ajax({
      url: url,
      type: "POST",
      crossDomain: true,
      contentType : 'application/json',
      data: JSON.stringify({ ver : "all" }),
      processData:true,
      success: function (result) {
        launchTable(result);
      },
      error: function (xhr, ajaxOptions, thrownError) {
          console.log("Error: " ,xhr, ", " ,thrownError);
      }
    });
  }

  function launchTable(result){
    if (serverList != null){
      serverList.clear().rows.add(result.servers).draw(false);
      //TODO: callback for this
      dataReloaded();
    }else{
      serverList = $('#server-list').DataTable({
        data: result.servers,
        autoWidth: false,
        lengthMenu: [ [100, -1], [100, "All"] ],
        order: [
          [8, "desc"]
        ],
        displayLength: 100,
        columns: [{
          data: 'ip'
        }, {
          data: 'port'
        }, {
          data: 'title'
        }, {
          data: 'description'
        }, {
          data: 'max_players'
        }, {
          data: 'max_spectators'
        }, {
          data: 'max_duration'
        }, {
          data: 'max_goals'
        }, {
          data: 'current_players'
        }, {
          data: 'current_duration'
        }, {
          data: 'current_goals_red'
        }, {
          data: 'current_goals_blue'
        }, {
          data: 'map'
        }, {
          data: 'training'
        }],
        createdRow: function ( row, data, index ) {
          if (data.max_players == data.current_players) {
            $(row).addClass('danger');
          }else if (data.max_players - 2 <= data.current_players) {
            $(row).addClass('warning');
          }else if (data.current_players > 0) {
            $(row).addClass('success');
          }
        },
        columnDefs: [
        {
          render: function ( data, type, row ) {
            return row.current_players + '/' + data;
          },
          targets: 4
        },
        {
          "targets": [13,9,5,7,8],
          "visible": false,
          "searchable": false
        }
        ]
      });
      calculateOnlinePlayers();
      serverList.on( 'draw', function () {
        sumPlayers = 0;
        calculateOnlinePlayers();
      });
    }
  }

  //Start the show
  queryServer();

  //Autorefresh in every 5 secs

  window.setInterval(function () {
    queryServer();
  }, 8000);

  //Event listeners

});
<|endoftext|>


<commit_before>//Canvassy stuff
var canvas = document.getElementById("canvas");
canvas.width = Math.floor((window.innerWidth-40)/16)*16;
canvas.height = Math.floor((window.innerHeight-40)/16)*16;
var ctx = canvas.getContext("2d");
var char = document.getElementById("char");
var rock = document.getElementById("rock");
var grass = document.getElementById("grass");
var charx = 1.0;
var chary = 0.0;
var chunkx = 0;
var chunky = 0;
var chunkmap = [];
var protomap = [];
var tempmaprow = [];
var protorow = [];

//Map Gen
function genMap(xlim, ylim) {
	for (k=0; k<ylim; k++) {
		for (l=0; l<xlim; l++) {
			tempmaprow.push(Math.round((Math.random()*3/4)+0.25));
		}
		protomap.push(tempmaprow);
		tempmaprow = [];
	}
}
genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
chunkmap.push([chunkx, chunky, protomap]);
drawMap(protomap);
ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
//Keyboardy stuff
function keys(event) {
	switch (event.keyCode) {
		case 87: //W
			if ((chary > 0) && (protomap[(chary-16)/16][(charx-1)/16] == 1)) {
				chary-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) != false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protoline = protomap[0];
				protomap = chunkExists(chunkx, chunky);
				protomap.push(protoline);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) == false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protoline = protomap[0];
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16)-1);
				chunkmap.push([chunkx, chunky, protomap]);
				protomap.push(protoline);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 65: //A
			if ((charx > 16) && (protomap[chary/16][(charx-17)/16] == 1)) {
				charx-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) != false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protoline = [];
				for (var h = 0; h < protomap.length; h++) {
					protoline.push(protomap[h][0]);
				}
				protomap = chunkExists(chunkx, chunky);
				for (var g = 0; g < protomap; g++) {
					protomap[g].push(protoline[g]);
				}
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) == false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protoline = [];
				for (var f = 0; f < protomap.length; f++) {
					protoline.push(protomap[f][0]);
				}
				protomap = [];
				genMap(Math.floor(canvas.width/16)-1, Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				for (var e = 0; e < protomap; e++) {
					protomap[e].push(protoline[e]);
				}
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 83: //S
			if ((chary+16 < canvas.height) && (protomap[(chary+16)/16][(charx-1)/16] == 1)) {
				chary+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) != false)) {
				chunky+=1;
				chary=0;
				protoline = protomap[protomap.length-1];
				protomap = chunkExists(chunkx, chunky);
				protomap.splice(0, 0, protoline);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) == false)) {
				chunky+=1;
				chary=0;
				protoline = protomap[protomap.length-1];
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16)-1);
				chunkmap.push([chunkx, chunky, protomap]);
				protomap.splice(0, 0, protoline);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 68: //D
			if ((charx+1 < canvas.width) && (protomap[chary/16][(charx+15)/16] == 1)) {
				charx+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) != false)) {
				chunkx+=1;
				charx=1;
				protoline = [];
				for (var d = 0; d < protomap.length; d++) {
					protoline.push(protomap[d][protomap[d].length-1]);
				}
				protomap = chunkExists(chunkx, chunky);
				for (var c = 0; c < protomap; c++) {
					protomap[c].splice(0, 0, protoline[c]);
				}
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) == false)) {
				chunkx+=1;
				charx=1;
				protoline = [];
				for (var b = 0; b < protomap.length; b++) {
					protoline.push(protomap[b][protomap[b].length-1]);
				}
				protomap = [];
				genMap(Math.floor(canvas.width/16)-1, Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				for (var a = 0; a < protomap; a++) {
					protomap[a].splice(0, 0, protoline[a]);
				}
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
	}
}
window.addEventListener('keydown', keys, false);

//Map drawing
function drawMap(map) {
	for (var i=0; i<map.length; i++) {
		for (var j=0; j<map[i].length; j++) {
			if (map[i][j] == 0) {
				ctx.drawImage(rock, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
			if (map[i][j] == 1) {
				ctx.drawImage(grass, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
		}
	}
}
function chunkExists(x, y) {
	for (var i = 0; i < chunkmap.length; i++) {
		if ((chunkmap[i][0] == x) && (chunkmap[i][1] == y)) {
			return chunkmap[i][2];
		}
	}
	return false;
}<commit_msg>Fixed bugs from previous commit<commit_after>//Canvassy stuff
var canvas = document.getElementById("canvas");
canvas.width = Math.floor((window.innerWidth-40)/16)*16;
canvas.height = Math.floor((window.innerHeight-40)/16)*16;
var ctx = canvas.getContext("2d");
var char = document.getElementById("char");
var rock = document.getElementById("rock");
var grass = document.getElementById("grass");
var charx = 1.0;
var chary = 0.0;
var chunkx = 0;
var chunky = 0;
var chunkmap = [];
var protomap = [];
var tempmaprow = [];

//Map Gen
function genMap(xlim, ylim) {
	for (k=0; k<ylim; k++) {
		for (l=0; l<xlim; l++) {
			tempmaprow.push(Math.round((Math.random()*3/4)+0.25));
		}
		protomap.push(tempmaprow);
		tempmaprow = [];
	}
}
genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
chunkmap.push([chunkx, chunky, protomap]);
drawMap(protomap);
ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
//Keyboardy stuff
function keys(event) {
	switch (event.keyCode) {
		case 87: //W
			if ((chary > 0) && (protomap[(chary-16)/16][(charx-1)/16] == 1)) {
				chary-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) != false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) == false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 65: //A
			if ((charx > 16) && (protomap[chary/16][(charx-17)/16] == 1)) {
				charx-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) != false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) == false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 83: //S
			if ((chary+16 < canvas.height) && (protomap[(chary+16)/16][(charx-1)/16] == 1)) {
				chary+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) != false)) {
				chunky+=1;
				chary=0;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) == false)) {
				chunky+=1;
				chary=0;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 68: //D
			if ((charx+1 < canvas.width) && (protomap[chary/16][(charx+15)/16] == 1)) {
				charx+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) != false)) {
				chunkx+=1;
				charx=1;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) == false)) {
				chunkx+=1;
				charx=1;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
	}
}
window.addEventListener('keydown', keys, false);

//Map drawing
function drawMap(map) {
	for (var i=0; i<map.length; i++) {
		for (var j=0; j<map[i].length; j++) {
			if (map[i][j] == 0) {
				ctx.drawImage(rock, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
			if (map[i][j] == 1) {
				ctx.drawImage(grass, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
		}
	}
}
function chunkExists(x, y) {
	for (var i = 0; i < chunkmap.length; i++) {
		if ((chunkmap[i][0] == x) && (chunkmap[i][1] == y)) {
			return chunkmap[i][2];
		}
	}
	return false;
}<|endoftext|>


<commit_before>/* Create the scene and basic camera. |||FOR LATER||| Build and render camera through OrthographicCamera class bassed on delta cube positioning provided from server */
var obj = this;
var id = 1;
var camId = id + "Cam";
var cubeId = id + "Cube";
var camObjId = id + "CamObj";
var cubeObjId = id + "CubeObj";
var sceneObjId = id + "SceneObj";

obj[sceneObjId] = new THREE.Scene();
obj[camObjId] = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

/* Launch connection to socket.io server, wait for conection before loading */
obj[sceneObjId].socket = io.connect('http://localhost:8080');
obj[sceneObjId].socket.on('connect', function() {
	//console.log("connected!");

	function CubeObject(x, y, z, w, h, d, color) {
		this.x = x;
		this.y = y;
		this.z = z;
		this.w = w;
		this.h = h;
		this.d = d;
		this.color = color;
	}

	function CameraObject(x, y, z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	obj[sceneObjId].socket.emit("newObj", {
		"id": id
	});

	obj[camId] = new CameraObject(0, 0, 4);
	obj[cubeId] = new CubeObject(0, 0, 0, 1, 1, 1, "rgb(174, 129, 255)");

/* var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 1000);
scene.add(camera); */ // Ortho. Camera test

/* WebGL Renderer provided through three.js engine */
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

/* Base Grid, I am just gonna be using 100 by 10 to produce a line representing 2D grid in background */
var scale = 100;
var sections = 10;
var baseGrid = new THREE.GridHelper(scale, sections);
obj[sceneObjId].add(baseGrid);

var cWidth = obj[cubeId].w;
var cHeight = obj[cubeId].h;
var cDepth = obj[cubeId].d;
var cColor = obj[cubeId].color;
var camZ = obj[camId].z;

/* Cube dynamics and aesthetics */
var cubeColorRGB = new THREE.Color(cColor);
var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth);
var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB });
obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeColor);

//scene.add(camera);
obj[sceneObjId].add(obj[cubeObjId]);
obj[camObjId].position.z = camZ;

/* Key Press -> Append 38, 40, 39, 37 key codes to a var speed = 10; -> server updated cube object constructor pos -> client recieves new x and y and renders camera / cube through camera.rotation.x camera.rotation.y camera.translateZ (for basic non orthographic camera class) -- cube.translateZ cube.translateY cube.translateX */
var render = function () {
	requestAnimationFrame(render);
	renderer.render(obj[sceneObjId], obj[camObjId]);
};

render();

document.onkeypress = function (e) {
	e = e || window.event;
	//console.log(e.key);
	var xx = 0;
	var zz = 0;
	var speed = 2;

			if (e.key == 'w') {
				zz = -speed;
			}

			if (e.key == 's') {

				zz = speed;
			}

			if (e.key == 'a') {
				xx = -speed;
			}

			if (e.key == 'd') {
				xx = speed;
			}

			obj[sceneObjId].socket.emit('updatePos', {
				'x': xx,
				'z': zz,
				'id': 1
			});
};

obj[sceneObjId].socket.on('move', function(data) {
	var newCamZ = data[0].z;
	var newCubeZ = data[1].z;

	var render = function () {
		requestAnimationFrame(render);
		//obj[cubeObjId].translateZ(newCubeZ);
		//obj[camObjId].translateZ(newCamZ);
		obj[cubeObjId].position.z = newCubeZ;
		obj[camObjId].position.z = newCamZ;

		renderer.render(obj[sceneObjId], obj[camObjId]);
	};

	render();
	//console.log("Moved!");
});

});
<commit_msg>Started work on CubeCamera implementation and x/y index translations<commit_after>/* Create the scene and basic camera. |||FOR LATER||| Build and render camera through OrthographicCamera class bassed on delta cube positioning provided from server */
var obj = this;
var id = 1;
var camId = id + "Cam";
var cubeId = id + "Cube";
var camObjId = id + "CamObj";
var cubeObjId = id + "CubeObj";
var sceneObjId = id + "SceneObj";

obj[sceneObjId] = new THREE.Scene();
obj[camObjId] = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); //new THREE.CubeCamera( 1, 100000, 128 );
obj[sceneObjId].add( obj[camObjId] );

/* Launch connection to socket.io server, wait for conection before loading */
obj[sceneObjId].socket = io.connect('http://localhost:8080');
obj[sceneObjId].socket.on('connect', function() {
	//console.log("connected!");

	function CubeObject(x, y, z, w, h, d, color) {
		this.x = x;
		this.y = y;
		this.z = z;
		this.w = w;
		this.h = h;
		this.d = d;
		this.color = color;
	}

	function CameraObject(x, y, z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	obj[sceneObjId].socket.emit("newObj", {
		"id": id
	});

	obj[camId] = new CameraObject(0, 0, 4);
	obj[cubeId] = new CubeObject(0, 0, 0, 1, 1, 1, "rgb(174, 129, 255)");

/* var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 1000);
scene.add(camera); */ // Ortho. Camera test

/* WebGL Renderer provided through three.js engine */
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

/* Base Grid, I am just gonna be using 100 by 10 to produce a line representing 2D grid in background */
var scale = 100;
var sections = 10;
var baseGrid = new THREE.GridHelper(scale, sections);
obj[sceneObjId].add(baseGrid);

var cWidth = obj[cubeId].w;
var cHeight = obj[cubeId].h;
var cDepth = obj[cubeId].d;
var cColor = obj[cubeId].color;
var camZ = obj[camId].z;

/* Cube dynamics and aesthetics */
var cubeColorRGB = new THREE.Color(cColor);
var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth);
var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB/*, envMap: obj[camObjId].renderTarget*/ });
obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeColor);

//scene.add(camera);
obj[sceneObjId].add(obj[cubeObjId]);
obj[camObjId].position.z = camZ;

/* Key Press -> Append 38, 40, 39, 37 key codes to a var speed = 10; -> server updated cube object constructor pos -> client recieves new x and y and renders camera / cube through camera.rotation.x camera.rotation.y camera.translateZ (for basic non orthographic camera class) -- cube.translateZ cube.translateY cube.translateX */
var render = function () {
	requestAnimationFrame(render);

	/* Cube Camera Implementation for later
	obj[camObjId].position.copy( obj[cubeObjId].position );
	obj[camObjId].updateCubeMap( renderer, obj[sceneObjId] );
	*/

	renderer.render(obj[sceneObjId], obj[camObjId]);
};

render();

document.onkeypress = function (e) {
	e = e || window.event;
	//console.log(e.key);
	var xx = 0;
	var zz = 0;
	var speed = 20;

			if (e.key == 'w') {
				zz = -speed;
			}

			if (e.key == 's') {

				zz = speed;
			}

			if (e.key == 'a') {
				xx = -speed;
			}

			if (e.key == 'd') {
				xx = speed;
			}

			obj[sceneObjId].socket.emit('updatePos', {
				'x': xx,
				'z': zz,
				'id': 1
			});
};

obj[sceneObjId].socket.on('move', function(data) {
	var newCamZ = data[0].z;
	var newCubeZ = data[1].z;

	var newCamX = data[0].x;
	var newCubeX = data[1].x;

	var render = function () {
		requestAnimationFrame(render);
		obj[cubeObjId].position.z = newCubeZ;
		obj[camObjId].position.z = newCamZ;
		//obj[cubeObjId].position.x = newCubeX;
		//obj[camObjId].position.x = newCamX;

		/* Cube Camera Implementation for later
		obj[camObjId].position.copy( obj[cubeObjId].position );
		obj[camObjId].updateCubeMap( renderer, obj[sceneObjId] );
		*/

		renderer.render(obj[sceneObjId], obj[camObjId]);
	};

	render();
	//console.log("Moved!");
});

});
<|endoftext|>


<commit_before><commit_msg>Update main.js<commit_after>window.onload = function() {
  return $.ajax({
    url: "https://api.github.com/users/sargeant45",
    type: "GET",
    dataType: "JSONP",
    success: function(userdata) {
      document.getElementById("repos").innerHTML = userdata.data["public_repos"];
      document.getElementById("gists").innerHTML = userdata.data["public_gists"];
      $("#profile").css("background-image", "url(" + userdata.data['avatar_url'] + ")");
    },
    error: function(e) {
      console.log(e);
    }
  });
};

// ---
// generated by coffee-script 1.9.2
<|endoftext|>


<commit_before>(function() {
	var map;
	function initialize() {
		// Pan to a nice view over Umea
		var mapOptions = {
			zoom: 8,
			center: new google.maps.LatLng(63.825847,20.263035),
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById('map_canvas'),
			mapOptions);

		plot_facilities();
	}
	function plot_facilities() {
		// First, figure out which file we should fetch
		// Read the package-datastructure from ckan and pick out the newest resource in it.
		var dataset = "anlaggningsdata";
		$.ajax({
			url: "http://openumea.se/api/action/package_show",
			type: "POST",
			data: JSON.stringify({id: dataset}),
			success: function(data, textStatus, jqXHR) {
				var resources = data.result.resources;
				var url = resources[0].url;
				var created = new Date(resources[0].created);
				for (i=1; i < resources.length ; i+=1) {
					var tmp_created = new Date(resources[i].created);
					if (tmp_created > created) {
						created = tmp_created;
						url = resources[i].url;
					}
				}
				if (url !== undefined) {
					load_data(url);
				} else {
					alert("No url found from ckan!");
				}
			}
		})
	}
	function load_data(url) {
		$.ajax({ url: url, success: load_dots});
	}
	function load_dots(data, textStatus, jqXHR) {
		//Parse the xml we got
		var xml = $.parseXML(data);
		var data = xml.childNodes[0];
		var serializer = new XMLSerializer();

		for (i = 0; i < data.childNodes.length; i += 1) {
			// We only know how to handle Facility-nodes
			var f = data.childNodes[i];
			if (f.tagName === "Facility") {
				var lu_x, lu_y, name;

				for (j = 0; j < f.childNodes.length ; j += 1) {
					var n = f.childNodes[j];
					if (n.tagName === "Name") {
						name = n.textContent
					}
					if (n.tagName === "Coordinate") {
						for (k = 0; k < n.childNodes.length ; k += 1){
							var c = n.childNodes[k];
							if (c.tagName === "LU_X") {
								lu_x = c.textContent
							}
							if (c.tagName === "LU_Y") {
								lu_y = c.textContent
							}
						}
					}
				}
				if (lu_x !== undefined && lu_y !== undefined &&
						lu_x !== "" && lu_y !== "" &&
						lu_x !== " " && lu_y !== " " &&
						name !== undefined) {
					create_dot(lu_x, lu_y, name,
							"
"
							+
							$('
').text(serializer.serializeToString(f)).html()
							+
							"
"
							);
				}
			}
		}
	}
	function create_dot(LU_X, LU_Y, Name, data) {
		//Convert from grid
		var geodetic = grid_to_geodetic(LU_X, LU_Y);

		//Create a marker
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(geodetic[0], geodetic[1]),
			map: map,
			title: Name
		});

		//Create a infowindow
		var infowindow = new google.maps.InfoWindow({content: data});

		//Attatch infowindow to marker
		google.maps.event.addListener(marker, 'click', function() {
			  infowindow.open(map,marker);
		});
	}

	//Build the map and everything in it
	google.maps.event.addDomListener(window, 'load', initialize);

	//Set gausskruger parameters to what we expect from data
	swedish_params("sweref_99_2015");
})();
<commit_msg>Plot Polyline and Polygon to<commit_after>(function() {
	var map;
	var created_polygon = false;
	function initialize() {
		// Pan to a nice view over Umea
		var mapOptions = {
			zoom: 8,
			center: new google.maps.LatLng(63.825847,20.263035),
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

		plot_facilities();
	}
	function plot_facilities() {
		// First, figure out which file we should fetch
		// Read the package-datastructure from ckan and pick out the newest resource in it.
		var dataset = "anlaggningsdata";
		$.ajax({
			url: "http://openumea.se/api/action/package_show",
			type: "POST",
			data: JSON.stringify({id: dataset}),
			success: function(data, textStatus, jqXHR) {
				if (typeof data === "string") {
					data = JSON.parse(data);
				}
				var resources = data.result.resources;
				var url = resources[0].url;
				var created = new Date(resources[0].created);
				for (var i=1; i < resources.length ; i+=1) {
					var tmp_created = new Date(resources[i].created);
					if (tmp_created > created) {
						created = tmp_created;
						url = resources[i].url;
					}
				}
				if (url !== undefined) {
					load_data(url);
				} else {
					alert("No url found from ckan!");
				}
			}
		});
	}
	function load_data(url) {
		$.ajax({ url: url, success: load_dots});
	}
	function load_dots(data, textStatus, jqXHR) {
		//Parse the xml we got
		var xml = $.parseXML(data);
		var nodes = xml.childNodes[0];
		var serializer = new XMLSerializer();

		for (var i = 0; i < nodes.childNodes.length; i += 1) {
			// We only know how to handle Facility-nodes
			var f = nodes.childNodes[i];
			if (f.tagName === "Facility") {
				var lu_x, lu_y, name;

				for (var j = 0; j < f.childNodes.length ; j += 1) {
					var n = f.childNodes[j];
					//Find and plot the thingie, if it has a position
					if (n.tagName === "Name") {
						name = n.textContent;
					}
					if (n.tagName === "Coordinate") {
						for (var k = 0; k < n.childNodes.length ; k += 1){
							if (n.childNodes[k].tagName === "LU_X") {
								lu_x = n.childNodes[k].textContent;
							}
							if (n.childNodes[k].tagName === "LU_Y") {
								lu_y = n.childNodes[k].textContent;
							}
						}
					}
					// If it got more Polygons, plot them also
					if (n.tagName === "Polygons" && n.childNodes.length > 1) {
						//<Polygon Name="Bjensjöns FVO" Type="Polygon">
						//<Coordinates>
						//<Coordinate LU_X="7074682,7689" LU_Y="138955,2227"/>
						//or
						//<Polygon Name="Gimonäs 9 km" Type="Polyline">
						//<Coordinates>
						//<Coordinate LU_X="7076417,8288" LU_Y="154605,6126"/>
						for (var b = 0; b < n.childNodes.length ; b += 1){
							if (n.childNodes[b].tagName === "Polygon") {
								var p = n.childNodes[b];
								var cordinates = [];
								for (var l = 1 ; l < p.childNodes.length; l += 1){
									if (p.childNodes[l].tagName === "Coordinates") {
										var c = p.childNodes[l];
										for (var m = 1 ; m < c.childNodes.length; m += 1){
											if (c.childNodes[m].tagName === "Coordinate") {
												var cord_attr = c.childNodes[m].attributes;
												cordinates.push({
													lu_x: parseFloat(cord_attr.LU_X.nodeValue),
													lu_y: parseFloat(cord_attr.LU_Y.nodeValue)
												});
											}
										}
									}
								}
								if (cordinates.length > 0) {
									create_polygon(p.attributes.Name.nodeValue, p.attributes.Type.nodeValue, cordinates);
								}
							}
						}
					}
				}
				if (lu_x !== undefined && lu_y !== undefined &&
						lu_x !== "" && lu_y !== "" &&
						lu_x !== " " && lu_y !== " " &&
						name !== undefined) {
					create_dot(lu_x, lu_y, name, "
" + $('
').text(serializer.serializeToString(f)).html() + "
");
				}
			}
		}
	}
	function create_dot(LU_X, LU_Y, Name, data) {
		//Convert from grid
		var geodetic = grid_to_geodetic(LU_X, LU_Y);

		//Create a marker
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(geodetic[0], geodetic[1]),
			map: map,
			title: Name
		});

		//Create a infowindow
		var infowindow = new google.maps.InfoWindow({content: data});

		//Attatch infowindow to marker
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
	function create_polygon(name, type, cords) {
		var poly;
		//convert cords to wsg84 for google maps
		for (var a=0; a < cords.length ; a += 1) {
			var geodetic = grid_to_geodetic(cords[a].lu_x, cords[a].lu_y);
			cords[a] = new google.maps.LatLng(geodetic[0], geodetic[1]);
		}
		if (type === "Polygon") {
			poly = new google.maps.Polygon({
				paths: cords,
				strokeColor: "#FF0000",
				strokeOpacity: 0.8,
				strokeWeight: 2,
				fillColor: "#FF0000",
				fillOpacity: 0.35
			});
		} else if (type === "Polyline") {
			poly = new google.maps.Polyline({
				path: cords,
				strokeColor: "#000000",
				strokeOpacity: 1.0,
				strokeWeight: 2
			});
		} else {
			console.log("WTF IS : " + type + " typeof " + typeof type);
		}
		poly.setMap(map);
	}

	//Build the map and everything in it
	google.maps.event.addDomListener(window, 'load', initialize);

	//Set gausskruger parameters to what we expect from data
	swedish_params("sweref_99_2015");
})();
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});

function getData(){

    $.get("https://mixer.com/api/v1/channels/" + $('#inputText').val(), "", function(data){
         var Avatar = "https://mixer.com/api/v1/users/" + data['user']['id'] + "/avatars";
       // var Avatar = data['user']['avatar'];
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var cover = data['cover']['url'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var HostID = data['hosteeId'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var levelRestrict = data['preferences']['channel:users:levelRestrict'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
        var Hypezone = data['preferences']['hypezone:allow'];
         var TotalViews = data['viewersTotal'];
         var transcoding = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         if(HostID = null){
            var HostID = null;
         }else{
            var HostID = "No ID";
         }
         if(Tetrisid = undefined){
            var Tetrisid = undefined;
         }else{
            var Tetrisid = "No ID";
         }
         if(transcoding = undefined){
            var transcoding = "Off";
         }else{
            var transcoding = "On";
         }
         if(Partnered = false){
            var Partnered = "No";
         }else{
            var Partnered = "Yes";
         }
         if(Tetris = false){
            var Tetris = "No";
         }else{
            var Tetris = "Yes";
         }
         if(StreamMute = false){
            var StreamMute = "Off";
         }else{
            var StreamMute = "On";
         }
         if(SubscribeNotify = false){
            var SubscribeNotify = "Off";
         }else{
            var SubscribeNotify = "On";
         }
         if(TweetNotify = false){
            var TweetNotify = "Off";
         }else{
            var TweetNotify = "On";
         }
         if(FollowNotify = false){
            var FollowNotify = "Off";
         }else{
            var FollowNotify = "On";
         }
                if(Hypezone = false){
            var Hypezone = "No";
         }else{
            var Hypezone = "Yes";
         }
console.log("Someone Pressed The Button \nFollowers:"+Followers+"\nLevels:"+lvls+"\Sparks:"+Sparks+"\nLive:"+Online)
         var joined = data['createdAt'];
         var html = '';
          html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Mixer.com/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Host ID: ' + HostID+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
HypeBot FollowNotify:' + FollowNotify +'';
         html += '
HypeBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + transcoding +'';
         html+= '
Hypezone:'+Hypezone+'';
        html+= '
Chat Level Restrict:'+levelRestrict+'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Mixer user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Updated Avatars Maybe?<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});

function getData(){

    $.get("https://mixer.com/api/v1/channels/" + $('#inputText').val(), "", function(data){
         var Avatar = "https://mixer.com/api/v1/users/" + data['user']['id'] + "/avatar";
       // var Avatar = data['user']['avatar'];
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var cover = data['cover']['url'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var HostID = data['hosteeId'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var levelRestrict = data['preferences']['channel:users:levelRestrict'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
        var Hypezone = data['preferences']['hypezone:allow'];
         var TotalViews = data['viewersTotal'];
         var transcoding = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         if(HostID = null){
            var HostID = null;
         }else{
            var HostID = "No ID";
         }
         if(Tetrisid = undefined){
            var Tetrisid = undefined;
         }else{
            var Tetrisid = "No ID";
         }
         if(transcoding = undefined){
            var transcoding = "Off";
         }else{
            var transcoding = "On";
         }
         if(Partnered = false){
            var Partnered = "No";
         }else{
            var Partnered = "Yes";
         }
         if(Tetris = false){
            var Tetris = "No";
         }else{
            var Tetris = "Yes";
         }
         if(StreamMute = false){
            var StreamMute = "Off";
         }else{
            var StreamMute = "On";
         }
         if(SubscribeNotify = false){
            var SubscribeNotify = "Off";
         }else{
            var SubscribeNotify = "On";
         }
         if(TweetNotify = false){
            var TweetNotify = "Off";
         }else{
            var TweetNotify = "On";
         }
         if(FollowNotify = false){
            var FollowNotify = "Off";
         }else{
            var FollowNotify = "On";
         }
                if(Hypezone = false){
            var Hypezone = "No";
         }else{
            var Hypezone = "Yes";
         }
console.log("Someone Pressed The Button \nFollowers:"+Followers+"\nLevels:"+lvls+"\Sparks:"+Sparks+"\nLive:"+Online)
         var joined = data['createdAt'];
         var html = '';
          html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Mixer.com/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Host ID: ' + HostID+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
HypeBot FollowNotify:' + FollowNotify +'';
         html += '
HypeBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + transcoding +'';
         html+= '
Hypezone:'+Hypezone+'';
        html+= '
Chat Level Restrict:'+levelRestrict+'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Mixer user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<commit_msg>Now with more slack handles on the webs<commit_after>$(function () {
  var light_style = [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}];

  var map;
  var infowindow;
  var loadDataLayer = function(data, z_index, click_content_fn) {
    var markers = [];
    var clickable = false;
    if (click_content_fn !== null) {
      clickable = true;
    }

    var showInfoWindow = function() {
      var content = click_content_fn(this.data);
      infowindow.close();
      infowindow.setContent(content);
      infowindow.open(map, this);
    };

    for (var i in data) {
      var rec = data[i];
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(rec.latitude, rec.longitude),
        zIndex: z_index,
        clickable: clickable
      });

      marker.data = rec;

      if (clickable) {
        marker.addListener('click', showInfoWindow);
      }

      markers.push(marker);
    }

    var len = markers.length;
    var setMap = function(m, filterFn) {
      for (var i = 0; i < len; i++) {
        if (filterFn) {
          if (filterFn(markers[i].data)) {
            markers[i].setMap(m);
          } else {
            markers[i].setMap(null);
          }
        } else {
          markers[i].setMap(m);
        }
      }
    };

    return {
      show: function() {
        setMap(map);
      },
      hide: function() {
        setMap(null);
      },
      filter: function(fn) {
        setMap(map, fn);
      }
    };
  };

  var initMap = function() {
    var mapCanvas = document.getElementById('map');
    var mapOptions = {
      center: new google.maps.LatLng(35.16899709632771, -89.85338676720858),
      zoom: 6,
      panControl: false,
      streetViewControl: false,
      mapTypeControl: true,
      mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
        position: google.maps.ControlPosition.RIGHT_TOP,
        mapTypeIds: [
          google.maps.MapTypeId.ROADMAP,
          google.maps.MapTypeId.HYBRID,
          'style_light'
        ]
      }
    };
    map = new google.maps.Map(mapCanvas, mapOptions);
    var style = new google.maps.StyledMapType(light_style, {name:"Light"});
    map.mapTypes.set('style_light', style);
    map.setMapTypeId('style_light');

    var input = /** @type {!HTMLInputElement} */(document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({map: map});
    infowindow = new google.maps.InfoWindow();
    var geocoder = new google.maps.Geocoder();
    autocomplete.addListener('place_changed', function() {
      marker.setVisible(false);
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        geocoder.geocode({
          address: input.value
        }, function(result) {
          if (result.length > 0) {
            search_result(result[0]);
          } else {
            alert("No results found.");
          }
        });
      } else {
        search_result(place);
      }
    });

    var search_result = function(result) {
      if (result.geometry.viewport) {
        map.fitBounds(result.geometry.viewport);
      } else {
        map.setCenter(result.geometry.location);
        map.setZoom(17);
      }
      marker.setPosition(result.geometry.location);
      marker.setVisible(true);
    };

    var memtech = loadDataLayer(locations, 999, function(data) {
      return "" + data.name + "
" +
             "" + data.origin + "
";
             "" + data.slack_handle || "??" + " on MTF Slack
";
    });
    memtech.show();

    /* uncomment if you want to show heatmap
    var heatmap_data = jQuery.map(locations, function(record) {
      return new google.maps.LatLng(record.latitude, record.longitude);
    });
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: heatmap_data
    });
    heatmap.setMap(map);
    */

  };
  google.maps.event.addDomListener(window, 'load', initMap);
});
<|endoftext|>


<commit_before>data = [
    {
        "question_number": "0",
        "question_value": "V2hhdCBpcyAxICsxPw==",
        "question_type": "text",
        "answer_value": "Mg==",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "question_number": "1",
        "question_value": "V2hhdCBpcyAxICsxPw==", //always add '==' at the end
        "question_type": "text",
        "answer_value": "Mg==", //always add '==' at the end
        "answer_type": "text",
        "story_value": "PHA+TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gRG9uZWMgbm9uIGdyYXZpZGEgZXJhdC4gQWVuZWFuIG5vbiBsaWJlcm8gZGFwaWJ1cywgdGluY2lkdW50IGFudGUgZXVpc21vZCwgZWZmaWNpdHVyIHRlbGx1cy4gRnVzY2UgZXUgcGVsbGVudGVzcXVlIG5pYmguIFNlZCBzZW1wZXIgbWF4aW11cyBvZGlvLCBpZCBjb25kaW1lbnR1bSBtYWduYSBzb2xsaWNpdHVkaW4gdXQuIEFlbmVhbiBtb2xsaXMgbnVuYyBkaWN0dW0gY3Vyc3VzIHNvbGxpY2l0dWRpbi4gUHJvaW4gZmV1Z2lhdCBtYXNzYSBldSByaG9uY3VzIHJ1dHJ1bS4gTnVsbGEgcXVpcyBsaWJlcm8gYWMgYW50ZSBwb3J0YSBmaW5pYnVzIHZlbCB2ZWwgZXJhdC4gVmVzdGlidWx1bSBlZ2V0IHJpc3VzIHNpdCBhbWV0IG51bGxhIGxvYm9ydGlzIGN1cnN1cy4gU3VzcGVuZGlzc2Ugc2l0IGFtZXQgaW1wZXJkaWV0IHVybmEsIHNlZCBtb2xsaXMgZXJhdC4gQWxpcXVhbSBldSBkdWkgbm9uIGxhY3VzIGxvYm9ydGlzIGxhb3JlZXQuIFZlc3RpYnVsdW0gZXUganVzdG8gZGljdHVtLCBzdXNjaXBpdCBuaXNsIHF1aXMsIGdyYXZpZGEgc2VtLiBNb3JiaSBlZmZpY2l0dXIgcGxhY2VyYXQgZXgsIGV0IGxhY2luaWEgbGFjdXMgdmVzdGlidWx1bSBub24uIFZpdmFtdXMgdmVoaWN1bGEsIGlwc3VtIHZlbCBmaW5pYnVzIHZlc3RpYnVsdW0sIG5pYmggYXVndWUgZ3JhdmlkYSBuaXNpLCBzZWQgY29uc2VxdWF0IG1pIHVybmEgdXQgbWV0dXMuPC9wPg0KDQo8cD5WZXN0aWJ1bHVtIGRpY3R1bSBkYXBpYnVzIG5pYmggc2l0IGFtZXQgZWZmaWNpdHVyLiBBZW5lYW4gZWZmaWNpdHVyIG1hdXJpcyBxdWlzIGVzdCBmZXVnaWF0LCBlZ2V0IGNvbnZhbGxpcyByaXN1cyBtYWxlc3VhZGEuIEludGVnZXIgdGVtcG9yIHZhcml1cyBpcHN1bSwgaW4gY29uZ3VlIGlwc3VtIHB1bHZpbmFyIHZlaGljdWxhLiBJbiBzZWQgdG9ydG9yIG5lYyBqdXN0byB2ZXN0aWJ1bHVtIGFsaXF1YW0gYWMgdXQgdXJuYS4gQ3VyYWJpdHVyIG5pYmggZXN0LCBiaWJlbmR1bSBpZCBuZXF1ZSBncmF2aWRhLCBncmF2aWRhIHZpdmVycmEgbGliZXJvLiBDcmFzIGNvbmd1ZSB0ZWxsdXMgaW4gZXggZXVpc21vZCwgZXUgZXVpc21vZCBwdXJ1cyBtb2xsaXMuIFBoYXNlbGx1cyB1bGxhbWNvcnBlciBlcmF0IHNhcGllbiwgYWMgY29uZ3VlIG5pYmggcG9ydHRpdG9yIGEuIFV0IG5vbiBsaWJlcm8gdXJuYS4gU2VkIHN1c2NpcGl0IGxvcmVtIGFjY3Vtc2FuIGVsaXQgcG9zdWVyZSwgdml0YWUgdGluY2lkdW50IGVsaXQgZGljdHVtLiBOdWxsYSBlbGVtZW50dW0gc2VtIHF1aXMgaXBzdW0gZWxlbWVudHVtIHVsdHJpY2VzLiBQcmFlc2VudCBldCBpbnRlcmR1bSBqdXN0by4gQWVuZWFuIGlkIG1hZ25hIG1pLiBWZXN0aWJ1bHVtIGEgc3VzY2lwaXQgbGlndWxhLCBzZWQgZWxlbWVudHVtIGVyYXQuPC9wPg0KDQo8cD5BbGlxdWFtIGVyYXQgdm9sdXRwYXQuIEFlbmVhbiBoZW5kcmVyaXQgbWFzc2EgYWMgYXVndWUgbWF0dGlzLCBpZCBkaWN0dW0gdHVycGlzIHNjZWxlcmlzcXVlLiBGdXNjZSBuZWMgbWkgZW5pbS4gRG9uZWMgYmxhbmRpdCB2ZXN0aWJ1bHVtIHN1c2NpcGl0LiBOdWxsYSBvcm5hcmUgbGVvIHNlZCBwdWx2aW5hciBhbGlxdWFtLiBDbGFzcyBhcHRlbnQgdGFjaXRpIHNvY2lvc3F1IGFkIGxpdG9yYSB0b3JxdWVudCBwZXIgY29udWJpYSBub3N0cmEsIHBlciBpbmNlcHRvcyBoaW1lbmFlb3MuIE51bmMgc2FnaXR0aXMgc2VkIGxvcmVtIGV1IHNlbXBlci48L3A+",
        "story_type": "html"
    }
];

var questionIndex = data.length - 1;

// this function decides which data item to show
function render(){
    $('#question').text(atob(data[questionIndex]["question_value"]));
}

// this function checks if an answer is correct
function toggleFields(){
    var wrongAnswer = "
Not quite there...
";
    var userAnswer = $('#answer-input').val();
    var comparisonAnswer = atob(data[questionIndex]["answer_value"]);
    if (userAnswer == comparisonAnswer) {
        $('#story').html(atob(data[questionIndex]["story_value"]));
        $('#story').show();
    }
    else {
        $('#story').html(wrongAnswer);
    }
}

// this function sets up things so the page actually does things
$(document).ready(function () {

    render();

    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
    //this will call our toggleFields function every time the answer changes
    $('#answer').change(function () {
        toggleFields();
    });

});
<commit_msg>have the story text be hidden first<commit_after>data = [
    {
        "question_number": "0",
        "question_value": "V2hhdCBpcyAxICsxPw==",
        "question_type": "text",
        "answer_value": "Mg==",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "question_number": "1",
        "question_value": "V2hhdCBpcyAxICsxPw==", //always add '==' at the end
        "question_type": "text",
        "answer_value": "Mg==", //always add '==' at the end
        "answer_type": "text",
        "story_value": "PHA+TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gRG9uZWMgbm9uIGdyYXZpZGEgZXJhdC4gQWVuZWFuIG5vbiBsaWJlcm8gZGFwaWJ1cywgdGluY2lkdW50IGFudGUgZXVpc21vZCwgZWZmaWNpdHVyIHRlbGx1cy4gRnVzY2UgZXUgcGVsbGVudGVzcXVlIG5pYmguIFNlZCBzZW1wZXIgbWF4aW11cyBvZGlvLCBpZCBjb25kaW1lbnR1bSBtYWduYSBzb2xsaWNpdHVkaW4gdXQuIEFlbmVhbiBtb2xsaXMgbnVuYyBkaWN0dW0gY3Vyc3VzIHNvbGxpY2l0dWRpbi4gUHJvaW4gZmV1Z2lhdCBtYXNzYSBldSByaG9uY3VzIHJ1dHJ1bS4gTnVsbGEgcXVpcyBsaWJlcm8gYWMgYW50ZSBwb3J0YSBmaW5pYnVzIHZlbCB2ZWwgZXJhdC4gVmVzdGlidWx1bSBlZ2V0IHJpc3VzIHNpdCBhbWV0IG51bGxhIGxvYm9ydGlzIGN1cnN1cy4gU3VzcGVuZGlzc2Ugc2l0IGFtZXQgaW1wZXJkaWV0IHVybmEsIHNlZCBtb2xsaXMgZXJhdC4gQWxpcXVhbSBldSBkdWkgbm9uIGxhY3VzIGxvYm9ydGlzIGxhb3JlZXQuIFZlc3RpYnVsdW0gZXUganVzdG8gZGljdHVtLCBzdXNjaXBpdCBuaXNsIHF1aXMsIGdyYXZpZGEgc2VtLiBNb3JiaSBlZmZpY2l0dXIgcGxhY2VyYXQgZXgsIGV0IGxhY2luaWEgbGFjdXMgdmVzdGlidWx1bSBub24uIFZpdmFtdXMgdmVoaWN1bGEsIGlwc3VtIHZlbCBmaW5pYnVzIHZlc3RpYnVsdW0sIG5pYmggYXVndWUgZ3JhdmlkYSBuaXNpLCBzZWQgY29uc2VxdWF0IG1pIHVybmEgdXQgbWV0dXMuPC9wPg0KDQo8cD5WZXN0aWJ1bHVtIGRpY3R1bSBkYXBpYnVzIG5pYmggc2l0IGFtZXQgZWZmaWNpdHVyLiBBZW5lYW4gZWZmaWNpdHVyIG1hdXJpcyBxdWlzIGVzdCBmZXVnaWF0LCBlZ2V0IGNvbnZhbGxpcyByaXN1cyBtYWxlc3VhZGEuIEludGVnZXIgdGVtcG9yIHZhcml1cyBpcHN1bSwgaW4gY29uZ3VlIGlwc3VtIHB1bHZpbmFyIHZlaGljdWxhLiBJbiBzZWQgdG9ydG9yIG5lYyBqdXN0byB2ZXN0aWJ1bHVtIGFsaXF1YW0gYWMgdXQgdXJuYS4gQ3VyYWJpdHVyIG5pYmggZXN0LCBiaWJlbmR1bSBpZCBuZXF1ZSBncmF2aWRhLCBncmF2aWRhIHZpdmVycmEgbGliZXJvLiBDcmFzIGNvbmd1ZSB0ZWxsdXMgaW4gZXggZXVpc21vZCwgZXUgZXVpc21vZCBwdXJ1cyBtb2xsaXMuIFBoYXNlbGx1cyB1bGxhbWNvcnBlciBlcmF0IHNhcGllbiwgYWMgY29uZ3VlIG5pYmggcG9ydHRpdG9yIGEuIFV0IG5vbiBsaWJlcm8gdXJuYS4gU2VkIHN1c2NpcGl0IGxvcmVtIGFjY3Vtc2FuIGVsaXQgcG9zdWVyZSwgdml0YWUgdGluY2lkdW50IGVsaXQgZGljdHVtLiBOdWxsYSBlbGVtZW50dW0gc2VtIHF1aXMgaXBzdW0gZWxlbWVudHVtIHVsdHJpY2VzLiBQcmFlc2VudCBldCBpbnRlcmR1bSBqdXN0by4gQWVuZWFuIGlkIG1hZ25hIG1pLiBWZXN0aWJ1bHVtIGEgc3VzY2lwaXQgbGlndWxhLCBzZWQgZWxlbWVudHVtIGVyYXQuPC9wPg0KDQo8cD5BbGlxdWFtIGVyYXQgdm9sdXRwYXQuIEFlbmVhbiBoZW5kcmVyaXQgbWFzc2EgYWMgYXVndWUgbWF0dGlzLCBpZCBkaWN0dW0gdHVycGlzIHNjZWxlcmlzcXVlLiBGdXNjZSBuZWMgbWkgZW5pbS4gRG9uZWMgYmxhbmRpdCB2ZXN0aWJ1bHVtIHN1c2NpcGl0LiBOdWxsYSBvcm5hcmUgbGVvIHNlZCBwdWx2aW5hciBhbGlxdWFtLiBDbGFzcyBhcHRlbnQgdGFjaXRpIHNvY2lvc3F1IGFkIGxpdG9yYSB0b3JxdWVudCBwZXIgY29udWJpYSBub3N0cmEsIHBlciBpbmNlcHRvcyBoaW1lbmFlb3MuIE51bmMgc2FnaXR0aXMgc2VkIGxvcmVtIGV1IHNlbXBlci48L3A+",
        "story_type": "html"
    }
];

var questionIndex = data.length - 1;
$('#story').hide();

// this function decides which data item to show
function render(){
    $('#question').text(atob(data[questionIndex]["question_value"]));
}

// this function checks if an answer is correct
function toggleFields(){
    var wrongAnswer = "
Not quite there...
";
    var userAnswer = $('#answer-input').val();
    var comparisonAnswer = atob(data[questionIndex]["answer_value"]);
    if (userAnswer == comparisonAnswer) {
        $('#story').html(atob(data[questionIndex]["story_value"]));
        $('#story').show();
    }
    else {
        $('#story').html(wrongAnswer);
    }
}

// this function sets up things so the page actually does things
$(document).ready(function () {

    render();

    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
    //this will call our toggleFields function every time the answer changes
    $('#answer').change(function () {
        toggleFields();
    });

});
<|endoftext|>


<commit_before>'use strict';

function repo_init(){
    core_repo_init({
      'globals': {
        'interval': 0,
        'running': true,
      },
      'info-events': {
        'add': {
          'todo': function(){
              add(100);
          },
        },
      },
      'storage': {
        'countdown': 10,
        'score': 0,
      },
      'title': 'Countdown.htm',
    });

    core_storage_update();

    window.clearInterval(interval);
    interval = window.setInterval(
      countdown,
      1000
    );
    running = true;
}
<commit_msg>changed info-events to events<commit_after>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'add': {
          'onclick': function(){
              add(100);
          },
        },
      },
      'globals': {
        'interval': 0,
        'running': true,
      },
      'storage': {
        'countdown': 10,
        'score': 0,
      },
      'title': 'Countdown.htm',
    });

    core_storage_update();

    window.clearInterval(interval);
    interval = window.setInterval(
      countdown,
      1000
    );
    running = true;
}
<|endoftext|>


<commit_before>'use strict';

function mapToObject(thing) {
  let obj = {};
  obj.id = thing.id;
  obj.name = thing.name.value;
  return obj;
}

export function getThingsById(db, id, cb) {
  let Thing = db.factory('Thing');
  return new Promise(function (resolve, reject) {
    Thing.find({user_id: id}, function (err, thingIds) {
      if (err) return cb(err, null);
      let things = [];
      if (!thingIds.length) return resolve(cb(null, things));
      let count = 0;
      thingIds.forEach(function (thingId) {
        Thing.load(thingId, function (thingErr, props) {
          if (thingErr) return reject(cb(thingErr, null));
          let thing = props;
          thing.id = thingId;
          things.push(thing);
          if (++count === thingIds.length) {
            return resolve(cb(null, things));
          }
        });
      });
    });
  });
}

export function addThingToUser(db, payload, cb) {
  let Thing = db.factory('Thing');
  Thing.p('name', payload.thing.name);
  Thing.p('user_id', payload.user.id);
  Thing.save(function (err) {
    if (err) cb(err, null);
    const thingWithId = mapToObject(Thing.properties);
    cb(null, thingWithId);
  });

}

export function deleteThing(db, id, cb) {
  let Thing = db.factory('Thing');
  Thing.id = id;
  Thing.remove(function (err) {
    if (err) {
      cb(err);
    } else {
      cb(null);
    }
  });
}

export function updateThing(db, payload, cb) {
  const Thing = db.factory('Thing');
  Thing.id = payload.thingId;
  Thing.load(payload.thingId, function (err) {
    if (err) cb(err, null);
    Thing.p('name', payload.thing.name);
    Thing.save(function (saveErr) {
      if (saveErr) cb(saveErr, null);
      const thingWithId = mapToObject(Thing.properties);
      cb(null, thingWithId);
    });
  });

}
<commit_msg>Started implementing ThingRepo.<commit_after>'use strict';

function mapToObject(thing) {
  let obj = {};
  obj.id = thing.id;
  obj.name = thing.name.value;
  return obj;
}

export function getThingsById(db, id, cb) {
  return new Promise(function (resolve, reject) {
    db.models.user.read(id, function (err, user) {
      if (err) return reject(cb(err, null));
      return resolve(cb(null, user.things));
    });
  });
}

export function addThingToUser(db, payload, cb) {
  db.models.user.read(payload.user.id, function (err, user) {
    if (err) cb(err, null);
    if (!user.things) user.things = [];
    user.things.push({
      name: payload.thing.name
    });
    db.models.user.saveComposition(user.id, 'things', user.things, function (compositionErr, things) {
      if (compositionErr) cb(compositionErr, null);
      cb(null, things[0]);
    });
  });
}

export function deleteThing(db, id, cb) {
  let Thing = db.factory('Thing');
  Thing.id = id;
  Thing.remove(function (err) {
    if (err) {
      cb(err);
    } else {
      cb(null);
    }
  });
}

export function updateThing(db, payload, cb) {
  const Thing = db.factory('Thing');
  Thing.id = payload.thingId;
  Thing.load(payload.thingId, function (err) {
    if (err) cb(err, null);
    Thing.p('name', payload.thing.name);
    Thing.save(function (saveErr) {
      if (saveErr) cb(saveErr, null);
      const thingWithId = mapToObject(Thing.properties);
      cb(null, thingWithId);
    });
  });

}
<|endoftext|>


<commit_before>const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

const ipcMain = electron.ipcMain;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
	// Create the browser window.
	mainWindow = new BrowserWindow({
		width: 870,
		height: 475,
		icon: __dirname + '../images/logo/logo.png'
	});

	// and load the index.html of the app.
	mainWindow.loadURL(`file://${__dirname}/../index.html`);

	// Emitted when the window is closed.
	mainWindow.on('closed', function() {
		// Dereference window object
		mainWindow = null;
	});
}

// Called when Electron has finished initialization.
app.on('ready', createWindow);

ipcMain.on('renderData', function(event, arg) {
	var dataWindow = new BrowserWindow({
		width: 1000,
		height: 500
	});
	// Load options page
	dataWindow.loadURL(`file://${__dirname}/../data.html`);

	dataWindow.on('closed', function() {
		// Dereference window object
		dataWindow = null;
	});
});
<commit_msg>Change window size to fit content<commit_after>const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

const ipcMain = electron.ipcMain;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
	// Create the browser window.
	mainWindow = new BrowserWindow({
		width: 750,
		height: 600,
		icon: __dirname + '../images/logo/logo.png'
	});

	// and load the index.html of the app.
	mainWindow.loadURL(`file://${__dirname}/../index.html`);

	// Emitted when the window is closed.
	mainWindow.on('closed', function() {
		// Dereference window object
		mainWindow = null;
	});
}

// Called when Electron has finished initialization.
app.on('ready', createWindow);

ipcMain.on('renderData', function(event, arg) {
	var dataWindow = new BrowserWindow({
		width: 1000,
		height: 500
	});
	// Load options page
	dataWindow.loadURL(`file://${__dirname}/../data.html`);

	dataWindow.on('closed', function() {
		// Dereference window object
		dataWindow = null;
	});
});
<|endoftext|>


<commit_before>var bg_canvas = document.getElementById('background'),
		bg_ctx = bg_canvas && bg_canvas.getContext('2d'),
		player_canvas = document.getElementById('player'),
		player_ctx = player_canvas.getContext('2d'),
		hunter = new DrawableObject('img/hunter.png', player_ctx, 48, 64),
		weapon_canvas = document.getElementById('weapon'),
		weapon_ctx = weapon_canvas.getContext('2d'),
		bg1 = new DrawableObject('img/bg.png', bg_ctx, window.innerWidth, window.innerHeight);
		bg2 = new DrawableObject('img/bg.png', bg_ctx, window.innerWidth, window.innerHeight);
		bg2.x = window.innerWidth;

if (bg_ctx) {
	bg_ctx.canvas.width  = window.innerWidth;
	bg_ctx.canvas.height = window.innerHeight;
	bg1.loop(-4, 0);
	bg2.loop(-4, 0);
}
if (player_ctx) {
	player_ctx.canvas.width  = window.innerWidth;
	player_ctx.canvas.height = window.innerHeight;
}
if (weapon_ctx) {
	weapon_ctx.canvas.width  = window.innerWidth;
	weapon_ctx.canvas.height = window.innerHeight;
}
hunter.x = 200;
hunter.y = window.innerHeight - 180;

var drawPlayer;

function RenderQueue() {
	this.stop = false;
	this.queue = [];
	this.ctxQueue = [];
};
RenderQueue.prototype.push = function(drawableObject) {
	this.queue.push(drawableObject);
};
RenderQueue.prototype.pushCtx = function(ctx) {
	this.ctxQueue.push(ctx);
};
RenderQueue.prototype.remove = function(drawableObject) {
	q = this.queue;
	var idx = q.indexOf(drawableObject);
	if (idx >= 0) {
		q.splice(idx, 1);
	}
};
RenderQueue.prototype.run = function() {
	var routine;
	(routine = function() {
		this.render();
		if (this.stop) return;
		setTimeout(routine, 33);
	}.bind(this))();
};
RenderQueue.prototype.render = function() {
	this.ctxQueue.forEach( function(ctx) {
		ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
	});
	this.queue.forEach( function(o) {
		o.paint();
	});
};
queue = new RenderQueue;
queue.pushCtx(player_ctx);
queue.pushCtx(weapon_ctx);
queue.push(hunter);
queue.run();

// functions
function move(obj, vx, vy) {
	obj.x = obj.x + vx,
	obj.y = obj.y + vy;
}
function trigger(queue, owner, weapon, vx, vy) {
	weapon.x = owner.x;
	weapon.y = owner.y;
	queue.push(weapon);
	var moveWeapon;
	(moveWeapon = function() {
		weapon.x = weapon.x + vx;
		weapon.y = weapon.y + vy;
		if (weapon.x > window.innerWidth || weapon.x < weapon.width || weapon.y > window.innerHeight ||  weapon.y < weapon.height) {
			queue.remove(weapon);
			return;
		}
		setTimeout( moveWeapon, 33);
	})();
}
function fire(owner, weapon, vx, vy) {
	weapon.x = owner.x;
	weapon.y = owner.y;
	var moveWeapon;
	(moveWeapon = function() {
		weapon.x = weapon.x + vx;
		weapon.y = weapon.y + vy;
		weapon.paint();
		if (weapon.x > window.innerWidth || weapon.x < weapon.width || weapon.y > window.innerHeight ||  weapon.y < weapon.height) return;
		setTimeout( moveWeapon, 33);
	})();
}

var pressedKeys = [];
function onKeydown(e) {
	pressedKeys[e.keyCode] = true;
	if (pressedKeys[37]) {
		move(hunter, -10, 0);
	} else if (pressedKeys[38]) {
		move(hunter, 0, -10);
	} else if (pressedKeys[39]) {
		move(hunter, 10, 0);
	} else if (pressedKeys[40]) {
		move(hunter, 0, 10);
	}
	// fire weapon whilst pressed space
	if (pressedKeys[32]) {
		dagger = new DrawableObject('img/dagger.gif', weapon_ctx, 30, 12);
		trigger(queue, hunter, dagger, 20, 0);
	}
};

function onKeyup(e) {
	pressedKeys[e.keyCode] = false;
};

// event bindings
window.addEventListener('keydown', onKeydown, true);
window.addEventListener('keyup', onKeyup, true);<commit_msg>add bg in render queue<commit_after>var bg_canvas = document.getElementById('background'),
		bg_ctx = bg_canvas && bg_canvas.getContext('2d'),
		player_canvas = document.getElementById('player'),
		player_ctx = player_canvas.getContext('2d'),
		hunter = new DrawableObject('img/hunter.png', player_ctx, 48, 64),
		weapon_canvas = document.getElementById('weapon'),
		weapon_ctx = weapon_canvas.getContext('2d'),
		bg1 = new DrawableObject('img/bg.png', bg_ctx, window.innerWidth, window.innerHeight);
		bg2 = new DrawableObject('img/bg.png', bg_ctx, window.innerWidth, window.innerHeight);
		bg2.x = window.innerWidth;

if (bg_ctx) {
	bg_ctx.canvas.width  = window.innerWidth;
	bg_ctx.canvas.height = window.innerHeight;
	bg1.loop(-4, 0);
	bg2.loop(-4, 0);
}
if (player_ctx) {
	player_ctx.canvas.width  = window.innerWidth;
	player_ctx.canvas.height = window.innerHeight;
}
if (weapon_ctx) {
	weapon_ctx.canvas.width  = window.innerWidth;
	weapon_ctx.canvas.height = window.innerHeight;
}
hunter.x = 200;
hunter.y = window.innerHeight - 180;

var drawPlayer;

function RenderQueue() {
	this.stop = false;
	this.queue = [];
	this.ctxQueue = [];
};
RenderQueue.prototype.push = function(drawableObject) {
	this.queue.push(drawableObject);
};
RenderQueue.prototype.pushCtx = function(ctx) {
	this.ctxQueue.push(ctx);
};
RenderQueue.prototype.remove = function(drawableObject) {
	q = this.queue;
	var idx = q.indexOf(drawableObject);
	if (idx >= 0) {
		q.splice(idx, 1);
	}
};
RenderQueue.prototype.run = function() {
	var routine;
	(routine = function() {
		this.render();
		if (this.stop) return;
		setTimeout(routine, 33);
	}.bind(this))();
};
RenderQueue.prototype.render = function() {
	this.ctxQueue.forEach( function(ctx) {
		ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
	});
	this.queue.forEach( function(o) {
		o.paint();
	});
};
queue = new RenderQueue;
queue.pushCtx(player_ctx);
queue.pushCtx(weapon_ctx);
queue.push(hunter);
queue.push(bg1);
queue.push(bg2);
queue.run();

// functions
function move(obj, vx, vy) {
	obj.x = obj.x + vx,
	obj.y = obj.y + vy;
}
function trigger(queue, owner, weapon, vx, vy) {
	weapon.x = owner.x;
	weapon.y = owner.y;
	queue.push(weapon);
	var moveWeapon;
	(moveWeapon = function() {
		weapon.x = weapon.x + vx;
		weapon.y = weapon.y + vy;
		if (weapon.x > window.innerWidth || weapon.x < weapon.width || weapon.y > window.innerHeight ||  weapon.y < weapon.height) {
			queue.remove(weapon);
			return;
		}
		setTimeout( moveWeapon, 33);
	})();
}
function fire(owner, weapon, vx, vy) {
	weapon.x = owner.x;
	weapon.y = owner.y;
	var moveWeapon;
	(moveWeapon = function() {
		weapon.x = weapon.x + vx;
		weapon.y = weapon.y + vy;
		weapon.paint();
		if (weapon.x > window.innerWidth || weapon.x < weapon.width || weapon.y > window.innerHeight ||  weapon.y < weapon.height) return;
		setTimeout( moveWeapon, 33);
	})();
}

var pressedKeys = [];
function onKeydown(e) {
	pressedKeys[e.keyCode] = true;
	if (pressedKeys[37]) {
		move(hunter, -10, 0);
	} else if (pressedKeys[38]) {
		move(hunter, 0, -10);
	} else if (pressedKeys[39]) {
		move(hunter, 10, 0);
	} else if (pressedKeys[40]) {
		move(hunter, 0, 10);
	}
	// fire weapon whilst pressed space
	if (pressedKeys[32]) {
		dagger = new DrawableObject('img/dagger.gif', weapon_ctx, 30, 12);
		trigger(queue, hunter, dagger, 20, 0);
	}
};

function onKeyup(e) {
	pressedKeys[e.keyCode] = false;
};

// event bindings
window.addEventListener('keydown', onKeydown, true);
window.addEventListener('keyup', onKeyup, true);<|endoftext|>


<commit_before>(function(window, $, undefined) {

/**
 * CodeIgniter's CSRF cookie must be sent with each AJAX request.
 */
var settings = { 'data': {} };
settings['data'][BOOKSWAP.csrf_token_name] = $.cookie(BOOKSWAP.csrf_cookie_name);
$.ajaxSetup(settings);

$(function() {
  // When the page loads, focus the search bar
  // and set the insertion pointer to the end of the search query.
  $searchInput = $('#search-input').focus();
  var searchValue = $searchInput.val();
  $searchInput.val('').val(searchValue);

  // Prevent empty search queries.
  $('#search-button').click(function(event) {
    if ($searchInput.val() === '') {
      event.preventDefault();
    }
  });

  $('#login-modal').on('shown', function() {
    $('#netid-field').focus();
  });

  $('.login.btn').click(function(event) {
    $('#login-modal').modal('show');
    event.preventDefault();
  });

  $('td.more-info-button a').click(function(event) {
    $(this).find('i').toggleClass('icon-plus icon-minus');
    event.preventDefault();
  });

  // Toggle Bootstrap form-validation classes when form fields are validated.
  $('#post-form')
    .h5Validate()
    .on('validated', function(event, v) {
      $(v.element)
        .parents('.control-group')
          .toggleClass('error', ( ! v.valid))
          .toggleClass('success', v.valid);
    });
});

})(window, jQuery);
<commit_msg>Added JS animation for post deactivation<commit_after>(function(window, $, undefined) {

/**
 * CodeIgniter's CSRF cookie must be sent with each AJAX request.
 */
var settings = { 'data': {} };
settings['data'][BOOKSWAP.csrf_token_name] = $.cookie(BOOKSWAP.csrf_cookie_name);
$.ajaxSetup(settings);

/**
 * Updates a post via AJAX.
 *
 * @param pid The ID of the post to update.
 * @param data The data attributes to save to the database.
 */
function updatePost(pid, data) {
  return $.ajax({
      'url': BOOKSWAP.base_url + 'api/v1/posts/' + pid,
      'method': 'POST',
      'data': data
    })
    .fail(function() {
      alert('There was a problem updating your post.');
    });
}

/**
 * Deactivates the post associated with the specified post element.
 *
 * @param post A jQuery selector
 */
function deactivatePost(post) {
  var $post = $(post),
    pid = $post.data('pid');
  updatePost(pid, { 'active': false })
    .done(function(data) {
      // Create a hidden copy of the post in the "Deactivated Posts" section.
      var $deactivatedPost = $post.clone()
        .css({
          'height': 0,
          'margin-top': 0,
          'margin-bottom': 0,
          'opacity': 0,
          'padding-top': 0,
          'padding-bottom': 0
        })
        .find('.post-actions')
          .remove()
          .end()
        .prependTo('#deactivated-posts');
      // Save the post's vertical dimensions.
      var cssProps = $post.css(['margin-top', 'margin-bottom', 'padding-top', 'padding-bottom']);
      // The deactivated post does not have action buttons,
      // so the buttons' height must be subtracted from the post's height.
      cssProps['height'] = ($post.height() - $post.find('.post-actions').outerHeight(true));
      // Animate in 3 steps:
      // 1. Fade out the active post.
      // 2. "Slide up" the active post while "sliding down" the deactivated post.
      // 3. Fade in the deactivated post.
      $('#deactivated-posts').removeClass('no-posts');
      $post.fadeTo(500, 0, function() {
        $deactivatedPost.animate(cssProps, 500, 'swing');
        $post.slideUp(500, 'swing');
        $.when($post.promise(), $deactivatedPost.promise()).done(function() {
          $activePosts = $('#active-posts');
          $activePosts.toggleClass('no-posts', ($activePosts.children().length == 2));
          $deactivatedPost.fadeTo(500, 1);
          $post.remove();
        });
      });
    })
}

$(function() {
  // When the page loads, focus the search bar
  // and set the insertion pointer to the end of the search query.
  $searchInput = $('#search-input').focus();
  var searchValue = $searchInput.val();
  $searchInput.val('').val(searchValue);

  // Prevent empty search queries.
  $('#search-button').click(function(event) {
    if ($searchInput.val() === '') {
      event.preventDefault();
    }
  });

  $('#login-modal').on('shown', function() {
    $('#netid-field').focus();
  });

  $('.login.btn').click(function(event) {
    $('#login-modal').modal('show');
    event.preventDefault();
  });

  $('td.more-info-button a').click(function(event) {
    $(this).find('i').toggleClass('icon-plus icon-minus');
    event.preventDefault();
  });

  $('.deactivate-post').click(function() {
    BOOKSWAP.postToDeactivate = $(this).parents('.post');
  });

  $('#confirm-post-deactivation').click(function(event) {
    deactivatePost(BOOKSWAP.postToDeactivate);
  });

  // Toggle Bootstrap form-validation classes when form fields are validated.
  $('#post-form')
    .h5Validate()
    .on('validated', function(event, v) {
      $(v.element)
        .parents('.control-group')
          .toggleClass('error', ( ! v.valid))
          .toggleClass('success', v.valid);
    });
});

})(window, jQuery);
<|endoftext|>


<commit_before>/* ==========================================================================
   Released Under the MIT Licence -- http://opensource.org/licenses/MIT
   ========================================================================== */

var minutes, second, seconds; // "second" is the interval and "seconds" is part of the secToMin(); function
var counter = 1500;

//-------------------- Time Unit Conversion Code ------------------------------------------------//

var secToMin = function (input) {
    "use strict";
    minutes = String(Math.floor(input / 60));
    seconds = input % 60;
    // Leading zero for second values under 10
    if (seconds < 10) {
        String(seconds);
        seconds = "0" + seconds;
    } else {
        String(seconds);
    }
    return minutes + ":" + seconds;
};

var minToSec = function (input) {
    "use strict";
    return input * 60;
};

//-------------------- Timer Code ---------------------------------------------------------------//

var stopTimer = function () {
    "use strict";
    window.clearInterval(second);
};

var timer = function () {
    "use strict";
    counter -= 1;
    $("title, #time").text(secToMin(counter));
    if (counter === 0) {
        stopTimer();
        document.getElementById("alarm").play();
    }
};

var startTimer = function () {
    "use strict";
    window.clearInterval(second); // To ensure that there is only one timer running, cancel any previous ones.
    second = window.setInterval("timer()", 1000);
};

//-------------------- Pomomdoro Code -----------------------------------------------------------//

var pomodorino = function () {
    "use strict";
    counter = 1500; // 25 Minutes
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

var shortBreak = function () {
    "use strict";
    counter = 300; // 5 Minutes
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

var longBreak = function () {
    "use strict";
    counter = 900; // 15 Minutes
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

//-------------------- User Interaction Code ----------------------------------------------------//

$(document).ready(function () {
    "use strict";
    $("#pomodorino").click(function () {
        pomodorino();
    });
    $("#sb").click(function () {
        shortBreak();
    });
    $("#lb").click(function () {
        longBreak();
    });
    $("#start").click(function () {
        startTimer();
        $("#start").css("display", "none");
        $("#stop").css("display", "inline");
    });
    $("#stop").click(function () {
        stopTimer();
        $("#stop").css("display", "none");
        $("#start").css("display", "inline");
    });
});<commit_msg>1.1.1 Bug-fix<commit_after>/* ==========================================================================
   Released Under the MIT Licence -- http://opensource.org/licenses/MIT
   ========================================================================== */

var minutes, second, seconds; // "second" is the interval and "seconds" is part of the secToMin(); function
var counter = 1500;

//-------------------- Time Unit Conversion Code ------------------------------------------------//

var secToMin = function (input) {
    "use strict";
    minutes = String(Math.floor(input / 60));
    seconds = input % 60;
    // Leading zero for second values under 10
    if (seconds < 10) {
        String(seconds);
        seconds = "0" + seconds;
    } else {
        String(seconds);
    }
    return minutes + ":" + seconds;
};

var minToSec = function (input) {
    "use strict";
    return input * 60;
};

//-------------------- Timer Code ---------------------------------------------------------------//

var stopTimer = function () {
    "use strict";
    window.clearInterval(second);
};

var timer = function () {
    "use strict";
    counter -= 1;
    $("title, #time").text(secToMin(counter));
    if (counter === 0) {
        stopTimer();
        document.getElementById("alarm").play();
    }
};

var startTimer = function () {
    "use strict";
    window.clearInterval(second); // To ensure that there is only one timer running, cancel any previous ones.
    second = window.setInterval("timer()", 1000);
};

//-------------------- Pomomdoro Code -----------------------------------------------------------//

var pomodorino = function () {
    "use strict";
    counter = 1500; // 25 Minutes
    $("title, #time").text(secToMin(counter));
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

var shortBreak = function () {
    "use strict";
    counter = 300; // 5 Minutes
    $("title, #time").text(secToMin(counter));
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

var longBreak = function () {
    "use strict";
    counter = 900; // 15 Minutes
    $("title, #time").text(secToMin(counter));
    startTimer();
    $("#start").css("display", "none");
    $("#stop").css("display", "inline");
};

//-------------------- User Interaction Code ----------------------------------------------------//

$(document).ready(function () {
    "use strict";
    $("#pomodorino").click(function () {
        pomodorino();
    });
    $("#sb").click(function () {
        shortBreak();
    });
    $("#lb").click(function () {
        longBreak();
    });
    $("#start").click(function () {
        startTimer();
        $("#start").css("display", "none");
        $("#stop").css("display", "inline");
    });
    $("#stop").click(function () {
        stopTimer();
        $("#stop").css("display", "none");
        $("#start").css("display", "inline");
    });
});<|endoftext|>


<commit_before>/**
* ownCloud - News app
*
* @author Bernhard Posselt
* Copyright (c) 2012 - Bernhard Posselt <nukeawhale@gmail.com>
*
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file
*
*/

var News = News || {};

$(document).ready(function(){

    // config values
    var menuUpdateIntervalMiliseconds = 30000;

    // global object array for accessing instances
    News.Objects = {};
    News.Objects.Items = new News.Items('#feed_items');
    News.Objects.Menu = new News.Menu(menuUpdateIntervalMiliseconds, News.Objects.Items);
    News.Objects.Menu.bindOn('#feeds > ul');

    /* first run script begins */
    $('#browsebtn_firstrun, #cloudbtn_firstrun, #importbtn_firstrun').hide();

    /* first run script ends */

    $('#addfeed').click(function() {
        $('#addfeed_dialog').dialog('open');
        $('#feed_add_url').html('');

        // populate folderlist
        $('#addfeed_dialog .menu').empty();

        // http://9gag.com/trending

        var $rootFolder = $('<li>').addClass('menuItem').html($('<b>').html(t('News', 'None')));
        $rootFolder.click(function(){
            News.DropDownMenu.selectItem(this, 0);
        });
        $('#addfeed_dialog .menu').append($rootFolder);

        $('#feeds .folder').each(function(){
            var title = $(this).children('.title').html();
            var id = parseInt($(this).data('id'));
            var $folder = $('<li>').addClass('menuItem').html(title);
            $folder.click(function(){
                News.DropDownMenu.selectItem(this, id);
            });
            $('#addfeed_dialog .menu').append($folder);
        });
    });

    $('#addfolder').click(function() {
        $('#addfolder_dialog').dialog('open');
        $('#folder_add_name').val('');
    });

    $('#addfeedbtn').click(function() {
        $(this).hide();
        $('#addfeed_dialog_firstrun').show();
    });

    $('#addfeedfolder').click(function(event) {
        News.DropDownMenu.fade($(this).children('ul'));
        event.stopPropagation();
    });

    $('#settingsbtn').on('click keydown', function() {
        try {
            OC.appSettings({appid:'news', loadJS:true, cache:false});
        } catch(e) {
            alert(e);
        }
    });

    $('#addfolder_dialog,#addfeed_dialog,#changefolder_dialog').dialog({
        dialogClass:'dialog',
        minWidth: 600,
        autoOpen: false
    });

    $('#changefolder_dialog input[type=submit]').click(function(){
        News.Folder.changeName(this);
    });

    $('#folder_add_submit').click(function(){
        News.Folder.submit(this);
    });

    $('.dropdownBtn').click(function(){
        News.DropDownMenu.dropdown(this);
    });

    $('#feed_add_submit').click(function(){
        News.Feed.submit(this);
    });

    $('#view').click(function(){
        var data = {};
        var showAll;
        if($(this).hasClass('show_all')){
            data.showAll = false;
            $(this).addClass('show_unread').removeClass('show_all');
            $(this).attr('title', t('news', 'Show only unread'));
        } else {
            data.showAll = true;
            $(this).addClass('show_all').removeClass('show_unread');
            $(this).attr('title', t('news', 'Show everything'));
        }

        News.Objects.Menu.triggerHideRead();

        $.post(OC.filePath('news', 'ajax', 'usersettings.php'), data, function(jsondata){
            if(jsondata.status == 'success'){
                News.Objects.Menu.setShowAll(data.showAll);
            } else {
                OC.dialogs.alert(jsonData.data.message, t('news', 'Error'));
            }
        });
    });

    $(document).click(function(event) {
        $('#feedfoldermenu').hide();
    });

    $(document).keyup(function(e) {
        if ((e.keyCode || e.which) == 74 || (e.keyCode || e.which) == 39) { // 'j' key shortcut
            if(!$('.dialog').is(':visible')){
                News.Objects.Items.jumpToNext();
            }
        }
        if ((e.keyCode || e.which) == 75 || (e.keyCode || e.which) == 37) { // 'k' key shortcut
            if(!$('.dialog').is(':visible')){
                News.Objects.Items.jumpToPrevious();
            }
        }
    });

    $('.dialog input[type=text]').keyup(function(e){
        if((e.keyCode || e.which) == 13) { // 'enter' key shortcut
            $(this).parent().parent().find('input[type=submit]').trigger('click');
        }
    });

    $('#addfeed_dialog_firstrun input[type=text]').keyup(function(e){
        if((e.keyCode || e.which) == 13) { // 'enter' key shortcut
            $(this).siblings('input[type=submit]').trigger('click');
        }
    });

});
<commit_msg>reduced update cycle to 1 minute<commit_after>/**
* ownCloud - News app
*
* @author Bernhard Posselt
* Copyright (c) 2012 - Bernhard Posselt <nukeawhale@gmail.com>
*
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file
*
*/

var News = News || {};

$(document).ready(function(){

    // config values
    var menuUpdateIntervalMiliseconds = 60000;

    // global object array for accessing instances
    News.Objects = {};
    News.Objects.Items = new News.Items('#feed_items');
    News.Objects.Menu = new News.Menu(menuUpdateIntervalMiliseconds, News.Objects.Items);
    News.Objects.Menu.bindOn('#feeds > ul');

    /* first run script begins */
    $('#browsebtn_firstrun, #cloudbtn_firstrun, #importbtn_firstrun').hide();

    /* first run script ends */

    $('#addfeed').click(function() {
        $('#addfeed_dialog').dialog('open');
        $('#feed_add_url').html('');

        // populate folderlist
        $('#addfeed_dialog .menu').empty();

        // http://9gag.com/trending

        var $rootFolder = $('<li>').addClass('menuItem').html($('<b>').html(t('News', 'None')));
        $rootFolder.click(function(){
            News.DropDownMenu.selectItem(this, 0);
        });
        $('#addfeed_dialog .menu').append($rootFolder);

        $('#feeds .folder').each(function(){
            var title = $(this).children('.title').html();
            var id = parseInt($(this).data('id'));
            var $folder = $('<li>').addClass('menuItem').html(title);
            $folder.click(function(){
                News.DropDownMenu.selectItem(this, id);
            });
            $('#addfeed_dialog .menu').append($folder);
        });
    });

    $('#addfolder').click(function() {
        $('#addfolder_dialog').dialog('open');
        $('#folder_add_name').val('');
    });

    $('#addfeedbtn').click(function() {
        $(this).hide();
        $('#addfeed_dialog_firstrun').show();
    });

    $('#addfeedfolder').click(function(event) {
        News.DropDownMenu.fade($(this).children('ul'));
        event.stopPropagation();
    });

    $('#settingsbtn').on('click keydown', function() {
        try {
            OC.appSettings({appid:'news', loadJS:true, cache:false});
        } catch(e) {
            alert(e);
        }
    });

    $('#addfolder_dialog,#addfeed_dialog,#changefolder_dialog').dialog({
        dialogClass:'dialog',
        minWidth: 600,
        autoOpen: false
    });

    $('#changefolder_dialog input[type=submit]').click(function(){
        News.Folder.changeName(this);
    });

    $('#folder_add_submit').click(function(){
        News.Folder.submit(this);
    });

    $('.dropdownBtn').click(function(){
        News.DropDownMenu.dropdown(this);
    });

    $('#feed_add_submit').click(function(){
        News.Feed.submit(this);
    });

    $('#view').click(function(){
        var data = {};
        var showAll;
        if($(this).hasClass('show_all')){
            data.showAll = false;
            $(this).addClass('show_unread').removeClass('show_all');
            $(this).attr('title', t('news', 'Show only unread'));
        } else {
            data.showAll = true;
            $(this).addClass('show_all').removeClass('show_unread');
            $(this).attr('title', t('news', 'Show everything'));
        }

        News.Objects.Menu.triggerHideRead();

        $.post(OC.filePath('news', 'ajax', 'usersettings.php'), data, function(jsondata){
            if(jsondata.status == 'success'){
                News.Objects.Menu.setShowAll(data.showAll);
            } else {
                OC.dialogs.alert(jsonData.data.message, t('news', 'Error'));
            }
        });
    });

    $(document).click(function(event) {
        $('#feedfoldermenu').hide();
    });

    $(document).keyup(function(e) {
        if ((e.keyCode || e.which) == 74 || (e.keyCode || e.which) == 39) { // 'j' key shortcut
            if(!$('.dialog').is(':visible')){
                News.Objects.Items.jumpToNext();
            }
        }
        if ((e.keyCode || e.which) == 75 || (e.keyCode || e.which) == 37) { // 'k' key shortcut
            if(!$('.dialog').is(':visible')){
                News.Objects.Items.jumpToPrevious();
            }
        }
    });

    $('.dialog input[type=text]').keyup(function(e){
        if((e.keyCode || e.which) == 13) { // 'enter' key shortcut
            $(this).parent().parent().find('input[type=submit]').trigger('click');
        }
    });

    $('#addfeed_dialog_firstrun input[type=text]').keyup(function(e){
        if((e.keyCode || e.which) == 13) { // 'enter' key shortcut
            $(this).siblings('input[type=submit]').trigger('click');
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

$(document).ready(function(){
    /**
     * Ensure each section is minimally the viewport height
     */
     $(".section-item").css("min-height", $(window).height());
         $(window).resize(function(){
             $(".section-item").css("min-height", $(window).height());
     });
     /**
      * Collapse navbar when selecting an option
      */
     $('.navbar-collapse .nav a').on('click', function(){
        $(".navbar-collapse").collapse('hide'); //bootstrap 3.x by Richard
      });
      /**
       * Animate anchor links
       */
      $('a[href^="#"]').on('click',function (e) {
  	    e.preventDefault();

  	    var target = this.hash;
  	    var $target = $(target);

  	    $('html, body').stop().animate({
  	        'scrollTop': $target.offset().top
  	    }, 900, 'swing', function () {
  	        window.location.hash = target;
  	    });
  	});
    /**
     * Open all external links in new window
     */
    $('a').not('[href*="mailto:"]').each(function () {
  		var isInternalLink = new RegExp('/' + window.location.host + '/');
  		if ( ! isInternalLink.test(this.href) ) {
  			$(this).attr('target', '_blank');
  		}
  	});
 });
<commit_msg>remove viewport section adjustment<commit_after>'use strict';

$(document).ready(function(){
    // /**
    //  * Ensure each section is minimally the viewport height
    //  */
    //  $(".section-item").css("min-height", $(window).height());
    //      $(window).resize(function(){
    //          $(".section-item").css("min-height", $(window).height());
    //  });
     /**
      * Collapse navbar when selecting an option
      */
     $('.navbar-collapse .nav a').on('click', function(){
        $(".navbar-collapse").collapse('hide'); //bootstrap 3.x by Richard
      });
      /**
       * Animate anchor links
       */
      $('a[href^="#"]').on('click',function (e) {
  	    e.preventDefault();

  	    var target = this.hash;
  	    var $target = $(target);

  	    $('html, body').stop().animate({
  	        'scrollTop': $target.offset().top
  	    }, 900, 'swing', function () {
  	        window.location.hash = target;
  	    });
  	});
    /**
     * Open all external links in new window
     */
    $('a').not('[href*="mailto:"]').each(function () {
  		var isInternalLink = new RegExp('/' + window.location.host + '/');
  		if ( ! isInternalLink.test(this.href) ) {
  			$(this).attr('target', '_blank');
  		}
  	});
 });
<|endoftext|>