<commit_before>$(document).ready(function(){
	$(".newgame").click(newGame);
	$("#home").click(paginaInicial);
});

function paginaInicial(){
    $("#menu").show();
    $("#botoes").empty();
}

function newGame(){
    game = new BatalhaNaval();
    game.startGame();
    adicionaBotoes();
}

function adicionaBotoes(){
	l = 7;
	c =7;
	$("#menu").hide();
	$("#botoes").empty();
	$("#botoes").append("
");
	for(i = 0; i <= l; i++){
		var linha = $("
");
		for(j=0; j <= c; j++){
			if(i == 0 && j!=0){
				var th = $(""+j+"	");
				linha.append(th);
			}
			else{
				if(j==0){
					if(i!=0){
						var th = $(""+i+"	");
						linha.append(th);
					}
					else{
						var th = $("");
						linha.append(th);
					}
				}
				else{
					var coluna = $(""+i+""+j+"	");
					linha.append(coluna);
				}
			}
		}
		$("#tabela").append(linha);
	}
	$(".botao").click(verificaGuess);
}

function verificaGuess(){
	flag = game.checkGuess($(this).html());
	if(flag){
		$(this).css("background-color","yellow");
	}
	if(game.endGame()){
	    alert("Você ganhou");
	    paginaInicial();
	}
	$(this).removeClass("botao");
	$(this).addClass("botao_pressed");
}
<commit_msg>script.js - movendo codigo principal para o final<commit_after>function paginaInicial(){
    $("#menu").show();
    $("#botoes").empty();
}

function newGame(){
    game = new BatalhaNaval();
    game.startGame();
    adicionaBotoes();
}

function adicionaBotoes(){
	l = 7;
	c =7;
	$("#menu").hide();
	$("#botoes").empty();
	$("#botoes").append("
");
	for(i = 0; i <= l; i++){
		var linha = $("
");
		for(j=0; j <= c; j++){
			if(i == 0 && j!=0){
				var th = $(""+j+"	");
				linha.append(th);
			}
			else{
				if(j==0){
					if(i!=0){
						var th = $(""+i+"	");
						linha.append(th);
					}
					else{
						var th = $("");
						linha.append(th);
					}
				}
				else{
					var coluna = $(""+i+""+j+"	");
					linha.append(coluna);
				}
			}
		}
		$("#tabela").append(linha);
	}
	$(".botao").click(verificaGuess);
}

function verificaGuess(){
	flag = game.checkGuess($(this).html());
	if(flag){
		$(this).css("background-color","yellow");
	}
	if(game.endGame()){
	    alert("Você ganhou");
	    paginaInicial();
	}
	$(this).removeClass("botao");
	$(this).addClass("botao_pressed");
}

$(document).ready(function(){
	$(".newgame").click(newGame);
	$("#home").click(paginaInicial);
});
<|endoftext|>


<commit_before>var cur = 0,
    container = document.querySelector('.slider-inner'),
    slide = document.getElementsByClassName('slide'),
    controls = document.getElementsByClassName('controls'),
    prevBtn = document.getElementsByClassName('controls-btn_prev'),
    nextBtn = document.getElementsByClassName('controls-btn_next'),
    slideWidth = slide[cur].offsetWidth;
var numOfSlides = slide.length;
var right = 1;
var left = -1;

[].slice.call(slide).map(function(e, i) { e.style.left = slideWidth * i + 'px' });

function changeSlide(direction) {
    cur += direction;
    container.style.transition = 'transform .5s ease';
    if (cur < 0) {
        resetTransition();
        cur = numOfSlides - 1;
    }
    if (cur === numOfSlides) {
        resetTransition();
        cur = 0;
    }

    function resetTransition() {
        container.style.transition = 'none';
    }

    container.style.setProperty('transform', 'translateX(' + (-slideWidth * cur) + 'px');
};

controls[0].addEventListener('click', function(e) {
    e.target === prevBtn[0] && changeSlide(left);
    e.target === nextBtn[0] && changeSlide(right);

});<commit_msg>.style properties are now in same fashioned way<commit_after>var cur = 0,
    container = document.querySelector('.slider-inner'),
    slide = document.getElementsByClassName('slide'),
    controls = document.getElementsByClassName('controls'),
    prevBtn = document.getElementsByClassName('controls-btn_prev'),
    nextBtn = document.getElementsByClassName('controls-btn_next'),
    slideWidth = slide[cur].offsetWidth;
var numOfSlides = slide.length;
var right = 1;
var left = -1;

[].slice.call(slide).map(function(element, index) {
    element.style.left = slideWidth * index + 'px'
});

function changeSlide(direction) {
    cur += direction;
    container.style.transition = 'transform .5s ease';

    if (cur < 0) {
        resetTransition();
        cur = numOfSlides - 1;
    }

    if (cur === numOfSlides) {
        resetTransition();
        cur = 0;
    }

    function resetTransition() {
        container.style.transition = 'none';
    }

    container.style.transform = 'translateX(' + (-slideWidth * cur) + 'px';
};

controls[0].addEventListener('click', function(e) {
    e.target === prevBtn[0] && changeSlide(left);
    e.target === nextBtn[0] && changeSlide(right);

});<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k<tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                        remove = 0;
                        break;
                    }
                }

                if(remove ==1 ){
                    removelist.push(i);
                }
            }
            for(var i= 0; i< removelist.length; i++){
                roomlist.splice(removelist[i], 1);
            }
        }

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

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

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

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

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //create a branch point
           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               //add a branch point half way through
               if( i >= Math.floor(walkArray.length/2) && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;
                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#FFFFFF";
                c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                c.stroke();
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30 + 6, branchpoint.y*30 + 6, 18, 18);
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k<tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    removelist.push(i);
                }
            }
            for(var i= 0; i< removelist.length; i++){
                roomlist.splice(removelist[i], 1);
            }
        }

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

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

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

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

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //create a branch point
           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               //add a branch point half way through
               if( i >= Math.floor(walkArray.length/2) && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;
                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#FFFFFF";
                c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                c.stroke();
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30 + 6, branchpoint.y*30 + 6, 18, 18);
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>const {webFrame} = require('electron');
const configFile = require('electron-json-config');//*

//Default Configs
var config = {
    "inputFilePath":"",
    "outputFilePath":"",
    "curZoom":"1",
    "language":"java",
    "buildFilePath":"",
    "projectFolders":[]
}

var curZoom = 1,
    changeZoomBy = 0.2;

var ioPanelIsVisible = false;
var mainMenuIsVisible = false;
var isCtrl = false;

function initialise() {
    loadDefaultValues();
    initialiseSidebar();

    //Set default state of IO Panel
    showIOPanel(ioPanelIsVisible);

    //Style: IO-Content
    var ta = document.getElementsByClassName('IO-Content');
    for(var i=0;i<2;i++) {
        var el = ta[i];
        el.style.color = 'white';
        el.style.backgroundColor = 'rgb(39, 40, 34)';
    }
    //Display Element Name on hover(hover and hold)
        var timer;
        $('*').hover(function(){
            $(this).data('hover',1); //store in that element that the mouse is over it
        },
        function(){
            $(this).data('hover',0); //store in that element that the mouse is no longer over it
        });
        $('#sidebar-MainMenu').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-MainMenu') ))
                    showElementName(e, 'Main Menu');
            }, 1000)
        }, function(){
        });
        $('#sidebar-CurrentFolder').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-CurrentFolder') ))
                    showElementName(e, 'Current Folder');
            }, 1000)
        }, function(){
        });
        $('#sidebar-OpenFolders').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-OpenFolders') ))
                    showElementName(e, 'Open Projects');
            }, 1000)
        }, function(){
        });
        $('#Button-OpenFolder').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#Button-OpenFolder') ))
                    showElementName(e, 'Add New Project');
            }, 1000)
        }, function(){
        });
        $('#compileBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#compileBtn') ))
                    showElementName(e, 'Compile');
            }, 1000)
        }, function(){
        });
        $('#runBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#runBtn') ))
                    showElementName(e, 'Execute');
            }, 1000)
        }, function(){
        });
        $('#stopBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('stopBtn') ))
                    showElementName(e, 'Stop');
            }, 1000)
        }, function(){
        });

        $('body').on('mousemove', function(){
            hideElementName();
        });

    //Style Elements
    //Sidemenu Scrollbars
    $('.Sidemenu').on('mouseenter', function(){
        $('.Sidemenu::-webkit-scrollbar').fadeIn(200);
    });
    $('.Sidemenu').on('mouseleave', function(){
        $('.Sidemenu::-webkit-scrollbar').fadeOut(200);
    });

    //Get IO File Paths
    $("#input-InputPath").val(inputFile.path);
    $("#input-OutputPath").val(outputFile.path);

    //Update data if file exists
    if(fs.existsSync(inputFile.path))
        fileRead(inputFile, function(data){
            $("#inputTab").text(data);
        });

    //Set default zoom value
    webFrame.setZoomFactor(curZoom);

}
function isHovering(selector) {
    return $(selector).data('hover')?true:false; //check element for hover property
}
jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
};
function showElementName(e, name) {
    $('#elementName').html(name);
    $('#elementName').css('left', e.pageX+'px');
    $('#elementName').css('top', e.pageY+'px');
    $('#elementName').fadeIn(150);
}
function hideElementName() {
    $('#elementName').fadeOut(150);
}
$(document).ready(function(){
    //MOUSE EVENT LISTENERS:
    //MainMenu-Button
    $('#sidebar-MainMenu').on('click', function(){
        showMainMenu(!mainMenuIsVisible);
    });

    //KEYBOARD SHORTCUT LISTENRS:
    $('body').on('keyup', function(e){
        if(e.ctrlKey) isCtrl = false;
    });
    $('body').on('keydown', function(e){
        if(e.ctrlKey) isCtrl = true;
    });
    $('body').on('keydown', function(e){
        if(isCtrl) {
            switch(e.keyCode) {
                //CTRL + N: Create new file (temporary)
                case 78 : var wt = new WorkingTab(randomIndex++, 'New File-'+(randomIndex-1));
                          wt.exists = false;
                          addWorkingFile(wt);
                          selectWorkingFile(wt);
                          break;
                //CTRL + S: Save current file
                case 83 : curFile.data = getData();
                          saveFile(curFile);
                          break;
                //CTRL + W: Close current tab
                case 87 : closeWorkTab(curFile);
                          break;
                //CTRL + 1: Compile file
                case 49 : compile();
                          break;
                //CTRL + 2: Run file
                case 50 : run();
                          break;
                //CTRL + B: Toggle Sidemenu
                case 66 : if(sideMenuIsVisible)
                              showSideMenuContainer(false);
                          else
                              showSideMenuContainer(true);
                          break;
                //CTRL + I: Toggle I/O Panel
                case 73 : showIOPanel(!ioPanelIsVisible);
                          break;
                //CTRL + =: Zoom in
                case 187 : zoomIn();
                           break;
                //CTRL + -: Zoom out
                case 189: zoomOut();
                          break;
                default : break;
            }
        }
    });
    $(window).resize(function(){
        showSideMenuContainer(sideMenuIsVisible);
    });

});

function showIOPanel(state) {
    if(state)
        $('.IO').css("height", "200px");
    else
        $('.IO').css("height", "0px");
    ioPanelIsVisible = state;
}
function showMainMenu(state) {
    if(state)
        $('.MainMenu').fadeIn(150);
    else
        $('.MainMenu').fadeOut(150);
    mainMenuIsVisible = state;

}
function updateSessionData(notifyUpdate) {
    //*
    configFile.set('config', config);
    if(notifyUpdate)
        console.log('Settings updated successfully');
}
function getInputFilePath() {
    getFilePath(function(path) {
        $('#input-InputPath').val(path);
    });
}
function getOutputFilePath() {
    getFilePath(function(path) {
        $('#input-OutputPath').val(path);
    });
}
function getBuildFilePath() {
    getFilePath(function(path) {
        $('#input-BuildPath').val(path);
    });
}
function updateIOFilePath() {
    config.inputFilePath = inputFile.path = $('#input-InputPath').val();
    config.outputFilePath = outputFile.path = $('#input-OutputPath').val();
    config.buildFilePath = $('#input-BuildPath').val();
    loadBuildFile(config.buildFilePath);
    updateSessionData(true);
    alert('Path has been updated.');
}
function updateProjectFolderPath() {
    var size=projectFolderRecord.length;
    config.projectFolders = [];
    for(var i=0;i<size;i++)
        config.projectFolders.push(projectFolderRecord[i].path);
    updateSessionData(false);
}

function zoomIn() {
    curZoom = webFrame.getZoomFactor();
    curZoom += changeZoomBy;
    webFrame.setZoomFactor(curZoom);

    config.curZoom = curZoom;
    updateSessionData(false);
}
function zoomOut() {
    curZoom = webFrame.getZoomFactor();
    curZoom -= changeZoomBy;
    webFrame.setZoomFactor(curZoom);

    config.curZoom = curZoom;
    updateSessionData(false);
}
function loadDefaultValues() {
    //*
    if(configFile.has('config')) //When application loads for the first time
        config = configFile.get('config');
    else
        configFile.set('config', config);

    //IO File Path
    inputFile.path = config.inputFilePath;
    $('#input-InputPath').val(inputFile.path);

    outputFile.path = config.outputFilePath;
    $('#input-OutputPath').val(outputFile.path);

    //Zoom Level
    curZoom = config.curZoom;

    //Load Build File
    loadBuildFile(config.buildFilePath);
    $('#input-BuildPath').val(config.buildFilePath);

    //Load Language
    // setLanguage(config.language);

    //Project Folders
    var openProjects = config.projectFolders;
    var size = openProjects.length;
    for(var i=0;i<size;i++)
        if(fs.existsSync(openProjects[i]))
            addProjectFolder(new ProjectFolderTab(randomIndex++, openProjects[i]));
}

function loadJS(file) {
    var jsElm = document.createElement("script"); // DOM: Create the script element
    jsElm.type = "application/javascript";        // set the type attribute
    jsElm.src = file;                             // make the script element load file
    document.body.appendChild(jsElm);             // finally insert the element to the body element in order to load the script
}<commit_msg>Added stop button title on hover<commit_after>const {webFrame} = require('electron');
const configFile = require('electron-json-config');//*

//Default Configs
var config = {
    "inputFilePath":"",
    "outputFilePath":"",
    "curZoom":"1",
    "language":"java",
    "buildFilePath":"",
    "projectFolders":[]
}

var curZoom = 1,
    changeZoomBy = 0.2;

var ioPanelIsVisible = false;
var mainMenuIsVisible = false;
var isCtrl = false;

function initialise() {
    loadDefaultValues();
    initialiseSidebar();

    //Set default state of IO Panel
    showIOPanel(ioPanelIsVisible);

    //Style: IO-Content
    var ta = document.getElementsByClassName('IO-Content');
    for(var i=0;i<2;i++) {
        var el = ta[i];
        el.style.color = 'white';
        el.style.backgroundColor = 'rgb(39, 40, 34)';
    }
    //Display Element Name on hover(hover and hold)
        var timer;
        $('*').hover(function(){
            $(this).data('hover',1); //store in that element that the mouse is over it
        },
        function(){
            $(this).data('hover',0); //store in that element that the mouse is no longer over it
        });
        $('#sidebar-MainMenu').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-MainMenu') ))
                    showElementName(e, 'Main Menu');
            }, 1000)
        }, function(){
        });
        $('#sidebar-CurrentFolder').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-CurrentFolder') ))
                    showElementName(e, 'Current Folder');
            }, 1000)
        }, function(){
        });
        $('#sidebar-OpenFolders').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#sidebar-OpenFolders') ))
                    showElementName(e, 'Open Projects');
            }, 1000)
        }, function(){
        });
        $('#Button-OpenFolder').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#Button-OpenFolder') ))
                    showElementName(e, 'Add New Project');
            }, 1000)
        }, function(){
        });
        $('#compileBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#compileBtn') ))
                    showElementName(e, 'Compile');
            }, 1000)
        }, function(){
        });
        $('#runBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#runBtn') ))
                    showElementName(e, 'Execute');
            }, 1000)
        }, function(){
        });
        $('#stopBtn').hover(function(e) {
            if(timer) {
                clearTimeout(timer);
                timer = null
            }
            timer = setTimeout(function() {
                if(isHovering( $('#stopBtn') ))
                    showElementName(e, 'Stop');
            }, 1000)
        }, function(){
        });

        $('body').on('mousemove', function(){
            hideElementName();
        });

    //Style Elements
    //Sidemenu Scrollbars
    $('.Sidemenu').on('mouseenter', function(){
        $('.Sidemenu::-webkit-scrollbar').fadeIn(200);
    });
    $('.Sidemenu').on('mouseleave', function(){
        $('.Sidemenu::-webkit-scrollbar').fadeOut(200);
    });

    //Get IO File Paths
    $("#input-InputPath").val(inputFile.path);
    $("#input-OutputPath").val(outputFile.path);

    //Update data if file exists
    if(fs.existsSync(inputFile.path))
        fileRead(inputFile, function(data){
            $("#inputTab").text(data);
        });

    //Set default zoom value
    webFrame.setZoomFactor(curZoom);

}
function isHovering(selector) {
    return $(selector).data('hover')?true:false; //check element for hover property
}
jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
};
function showElementName(e, name) {
    $('#elementName').html(name);
    $('#elementName').css('left', e.pageX+'px');
    $('#elementName').css('top', e.pageY+'px');
    $('#elementName').fadeIn(150);
}
function hideElementName() {
    $('#elementName').fadeOut(150);
}
$(document).ready(function(){
    //MOUSE EVENT LISTENERS:
    //MainMenu-Button
    $('#sidebar-MainMenu').on('click', function(){
        showMainMenu(!mainMenuIsVisible);
    });

    //KEYBOARD SHORTCUT LISTENRS:
    $('body').on('keyup', function(e){
        if(e.ctrlKey) isCtrl = false;
    });
    $('body').on('keydown', function(e){
        if(e.ctrlKey) isCtrl = true;
    });
    $('body').on('keydown', function(e){
        if(isCtrl) {
            switch(e.keyCode) {
                //CTRL + N: Create new file (temporary)
                case 78 : var wt = new WorkingTab(randomIndex++, 'New File-'+(randomIndex-1));
                          wt.exists = false;
                          addWorkingFile(wt);
                          selectWorkingFile(wt);
                          break;
                //CTRL + S: Save current file
                case 83 : curFile.data = getData();
                          saveFile(curFile);
                          break;
                //CTRL + W: Close current tab
                case 87 : closeWorkTab(curFile);
                          break;
                //CTRL + 1: Compile file
                case 49 : compile();
                          break;
                //CTRL + 2: Run file
                case 50 : run();
                          break;
                //CTRL + B: Toggle Sidemenu
                case 66 : if(sideMenuIsVisible)
                              showSideMenuContainer(false);
                          else
                              showSideMenuContainer(true);
                          break;
                //CTRL + I: Toggle I/O Panel
                case 73 : showIOPanel(!ioPanelIsVisible);
                          break;
                //CTRL + =: Zoom in
                case 187 : zoomIn();
                           break;
                //CTRL + -: Zoom out
                case 189: zoomOut();
                          break;
                default : break;
            }
        }
    });
    $(window).resize(function(){
        showSideMenuContainer(sideMenuIsVisible);
    });

});

function showIOPanel(state) {
    if(state)
        $('.IO').css("height", "200px");
    else
        $('.IO').css("height", "0px");
    ioPanelIsVisible = state;
}
function showMainMenu(state) {
    if(state)
        $('.MainMenu').fadeIn(150);
    else
        $('.MainMenu').fadeOut(150);
    mainMenuIsVisible = state;

}
function updateSessionData(notifyUpdate) {
    //*
    configFile.set('config', config);
    if(notifyUpdate)
        console.log('Settings updated successfully');
}
function getInputFilePath() {
    getFilePath(function(path) {
        $('#input-InputPath').val(path);
    });
}
function getOutputFilePath() {
    getFilePath(function(path) {
        $('#input-OutputPath').val(path);
    });
}
function getBuildFilePath() {
    getFilePath(function(path) {
        $('#input-BuildPath').val(path);
    });
}
function updateIOFilePath() {
    config.inputFilePath = inputFile.path = $('#input-InputPath').val();
    config.outputFilePath = outputFile.path = $('#input-OutputPath').val();
    config.buildFilePath = $('#input-BuildPath').val();
    loadBuildFile(config.buildFilePath);
    updateSessionData(true);
    alert('Path has been updated.');
}
function updateProjectFolderPath() {
    var size=projectFolderRecord.length;
    config.projectFolders = [];
    for(var i=0;i<size;i++)
        config.projectFolders.push(projectFolderRecord[i].path);
    updateSessionData(false);
}

function zoomIn() {
    curZoom = webFrame.getZoomFactor();
    curZoom += changeZoomBy;
    webFrame.setZoomFactor(curZoom);

    config.curZoom = curZoom;
    updateSessionData(false);
}
function zoomOut() {
    curZoom = webFrame.getZoomFactor();
    curZoom -= changeZoomBy;
    webFrame.setZoomFactor(curZoom);

    config.curZoom = curZoom;
    updateSessionData(false);
}
function loadDefaultValues() {
    //*
    if(configFile.has('config')) //When application loads for the first time
        config = configFile.get('config');
    else
        configFile.set('config', config);

    //IO File Path
    inputFile.path = config.inputFilePath;
    $('#input-InputPath').val(inputFile.path);

    outputFile.path = config.outputFilePath;
    $('#input-OutputPath').val(outputFile.path);

    //Zoom Level
    curZoom = config.curZoom;

    //Load Build File
    loadBuildFile(config.buildFilePath);
    $('#input-BuildPath').val(config.buildFilePath);

    //Load Language
    // setLanguage(config.language);

    //Project Folders
    var openProjects = config.projectFolders;
    var size = openProjects.length;
    for(var i=0;i<size;i++)
        if(fs.existsSync(openProjects[i]))
            addProjectFolder(new ProjectFolderTab(randomIndex++, openProjects[i]));
}

function loadJS(file) {
    var jsElm = document.createElement("script"); // DOM: Create the script element
    jsElm.type = "application/javascript";        // set the type attribute
    jsElm.src = file;                             // make the script element load file
    document.body.appendChild(jsElm);             // finally insert the element to the body element in order to load the script
}<|endoftext|>


<commit_before>var userInputTitle = $('.input-title');
var userInputBody = $('.input-body');
var searchValue = $('.search-input');
var allIdeas = [];

function Idea (title, body, quality){
  this.title = title;
  this.body = body;
  this.quality = quality;
  this.id = Date.now();
}

function deleteIdeas() {
  $('.delete').on('click', function(){
    $(this).parent().remove();
  });
}

Idea.prototype.storeIdea = function () {
  localStorage.setItem('ideas', JSON.stringify(allIdeas));
}

function returnIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}
//
// function getIdeasFromStorageAndAppendThem() {
//   var ideas = returnIdeas();
//   for (var idea of ideas) {
//     createOutput(idea.title, idea.body);
//   }
//   deleteIdeas()
// }

function getIdeasFromStorageAndAppendThem() {
  var ideas = returnIdeas();
  for (var i = 0; i < ideas.length; i++) {
    var idea = ideas[i]
    createOutput(idea.title, idea.body);
  }
}
// Block.prototype.moveRight = function () {
//   this.x = this.x + 1;
//   return this;

function createOutput(title, body) {
  $('.all-ideas').prepend(
    `

${title}

      <button class="idea-button delete" type="button"></button>

${body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: swill

`
  );
};

$('.save-button').on('click', function(event) {
  event.preventDefault();
  var title = userInputTitle.val();
  var body = userInputBody.val();
  var buildNewIdea = new Idea(title, body);
  var userIdeas = createOutput(title, body);
  allIdeas.push(buildNewIdea);
  buildNewIdea.storeIdea();
  deleteIdeas()
});

getIdeasFromStorageAndAppendThem()
// $('.search-input').on('keyup', function() {
//   var searchedValue = $('.layout-section-user-output').has('.user-idea-title').val(searchValue.val());
//   // allIdeas.title = searchedValue;
// });
<commit_msg>refactor/clean up logic works<commit_after>'use strict'

const userInputTitle = $('.input-title');
const userInputBody = $('.input-body');
const searchValue = $('.search-input');

function checkIdeas() {
  let currentIdeas = localStorage.getItem("ideas");
  if (currentIdeas === null || currentIdeas === undefined) {
    localStorage.setItem("ideas", JSON.stringify([]))
  }
}
// class Idea {
//   constructor(title, body, quality) {
//     this.title = title;
//     this.body = body;
//     this.quality = quality;
//     this.id = Date.now();
//   }
//
//   storeIdea() {
//     localStorage.setItem('ideas', JSON.stringify(allIdeas));
//   }
// }

function Idea (title, body, quality){
  this.title = title;
  this.body = body;
  this.quality = quality;
  this.id = Date.now();
}

Idea.prototype.storeIdea = function (idea) {
  let newIdeas = JSON.parse(localStorage.getItem("ideas"))
  newIdeas.push(idea)
  localStorage.setItem("ideas", JSON.stringify(newIdeas))
}

const deleteIdeaFromStorage = function(ideaId) {
  let currentIdeas = JSON.parse(localStorage.getItem('ideas'))
  currentIdeas.forEach((idea, index) => {
    if (idea.id === ideaId) {
      currentIdeas.splice(index, 1)
      localStorage.setItem('ideas', JSON.stringify(currentIdeas))
    }
  })
}

function getAndParseIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}

function deleteIdeasFromDom() {
  $('.delete').on('click', function(){
    let $idea = $(this).parent()
    deleteIdeaFromStorage($idea.data("id"))
    $idea.remove();
  });
}

// getAndParseIdeas()
//if the id of the deleted item matches
//an id of any idea object then delete the
//id from local storage.

function getIdeasFromStorageAndAppendThem() {
  let ideas = getAndParseIdeas();
  if (typeof ideas[0] !== "object") {
    console.log("NOTHINGGG");
  } else {
    for (let i = 0; i < ideas.length; i++) {
      let idea = ideas[i]
      createOutput(idea.title, idea.body, idea.id);
    }
    deleteIdeasFromDom()
  }
}

//
// function getIdeasFromStorageAndAppendThem() {
//   var ideas = returnIdeas();
//   for (var idea of ideas) {
//     createOutput(idea.title, idea.body);
//   }
//   deleteIdeas()
// }

function createOutput(title, body, ideaId) {
  $('.all-ideas').prepend(
    `

${title}

      <button class="idea-button delete" type="button"></button>

${body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: swill

`
  );
};

$('.save-button').on('click', function(event) {
  event.preventDefault();
  const title = userInputTitle.val();
  const body = userInputBody.val();
  const newIdea = new Idea(title, body);
  createOutput(title, body, newIdea.id);
  newIdea.storeIdea(newIdea);
  deleteIdeasFromDom();
});

checkIdeas();
getIdeasFromStorageAndAppendThem()

// $('.search-input').on('keyup', function() {
//   var searchedValue = $('.layout-section-user-output').has('.user-idea-title').val(searchValue.val());
//   // allIdeas.title = searchedValue;
// });
<|endoftext|>


<commit_before>(function() {

	// load the available notes and tags.
	loadNotes();
	loadTags();

	function loadNotes() {
		$.ajax({
			url: 'load-note.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result === 'success') {
				$('#note-list').append(data);
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {
		$.ajax({
			url: 'load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				$('#add-note-tags').append(data);
				toastr.info('Loading success');
			}
		})
		.fail(function(error) {
			console.log(result);
		});
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};;

	// Hide the form to create new note until clicked
	$('#new-note-section').hide();
	$('#new-tag-section').hide();

	$('#new-note-button').on('click', function(){
		$('#new-note-section').toggle();
	});

	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	});

	$('#show-all-notes-button').on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {
		// add the note
		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});

		$.ajax({
			url: 'add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: tagArray,
				noteTitle: noteTitle
			}
		})
		.done(function(data, result) {
			console.log(data);
			var tags = '';

			$.each(tagArray, function(index, value) {
				tags += '' + value + '';
			});

			$('#note-list').append('
Note ID: ' + data + '
' + noteText + '
' + tags + '
');

			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

		toastr.success('Note has been added successfully!');
		console.log('Note added.');
	});

	$('#add-tag-button').on('click', function() {
		// TODO: implement this in the PHP file add-new-tag.php, and also actually create the database table - new table or column?
		var newTag = $('#add-tag-text').val();

		$.ajax({
			url: 'add-new-tag.php',
			method: 'POST',
			data: {
				newTag: newTag
			}
		})
		.done(function(data, result) {
			console.log(data);
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

		toastr.success('Tag has been added successfully!');
		console.log('Tag added.');
	});

	$('#note-list').on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

})();<commit_msg>Changes references to the files moved into includes folder. Remove debugging console.log functions. Added some validation to the noteText ID. Tags are now added when adding the note, rather than having to add the tags then add them to the note. Add the note with all of the tags to the list. Tags are appended to the DOM after the add-tag button is clicked. Remove note funcitonality is added and works to remove the item from both the DB and the DOM. Edit note skeleton code is added.<commit_after>(function() {

	// load the available notes and tags.
	var tagsToAdd = [];
	loadNotes();
	loadTags();

	function loadNotes() {

		$.ajax({
			url: 'includes/load-note.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result === 'success') {
				$('#note-list').append(data);
			}
		})
		.fail(function(error) {
			console.log('It failed: ', error);
		});
	}

	function loadTags() {

		$.ajax({
			url: 'includes/load-tags.php',
			method: 'POST'
		})
		.done(function(data, result) {
			if(result == 'success') {
				$('#add-note-tags').append(data);
				toastr.info('Loading success');
			}
		})
		.fail(function(error) {
			console.log(error);
		});
	}

	toastr.options = {
		"timeOut": "2000",
		"preventDuplicates": false,
		"closeButton": true
	};;

	// Hide the form to create new note until clicked
	$('#new-note-section').hide();
	$('.note-text-validation').hide();

	$('#new-note-button').on('click', function(){
		$('#new-note-section').toggle();
	});

	$('#show-new-tag-button').on('click', function() {
		$('#new-tag-section').toggle();
	});

	$('#show-all-notes-button').on('click', function() {
		$('.note').show();
	});

	$('#add-note-button').on('click', function() {

		var noteText = $('#add-note-text').val();
		var noteTitle = $('#add-note-title').val();
		var tagArray = [];

		if(noteText.trim() === '') {
			$('.note-text-validation').show();
			return;
		}

		$('input:checkbox[name=new-tag]:checked').each(function() {
			tagArray.push($(this).val());
		});
		var allTags = tagArray.concat(tagsToAdd);

		$.ajax({
			url: 'includes/add-new-note.php',
			method: 'POST',
			data: {
				noteText: noteText,
				noteTags: allTags,
				noteTitle: noteTitle
			}
		})
		.done(function(data, result) {
			var tags = '';

			$.each(allTags, function(index, value) {
				tags += '' + value + '';
			});

			$('#note-list').append('
Note ID: ' + data + '
' + noteTitle + '

' + noteText + '
' + tags + '

');

			// Reset and confirmation.
			$('#add-note-title').val('');
			$('#add-note-text').val('');
			$('input:checkbox[name=new-tag]').removeAttr('checked');
			tagsToAdd = [];
			toastr.success('Note has been added successfully!');
			$('#new-note-section').hide();
		})
		.fail(function(error) {
			console.log('There was a failure: ', error);
		});

	});

	$('#show-new-tag-button').on('click', function() {

		var newTag = $('#add-new-tag-text').val();

		if(newTag.trim() !== '') {
			tagsToAdd.push(newTag);
			$('#add-note-tags').append('
' + newTag + '
');
			$('#add-new-tag-text').val('');
		}

	});

	$('#note-list').on('click', '.note-tags', function() {

		var tag = $(this).data('tag');
		var notes = $('.note');
		var hide = [];
		$('.note').show();

		$.each(notes, function(index, value) {
			$value = $(value);

			var tags = $value.children('.note-tags');
			var tagData = [];

			$.each(tags, function(i, childTag) {
				$this = $(childTag);
				var data = $this.data('tag');
				tagData.push(data);
			});

			if(tagData.indexOf(tag) === -1) {
				hide.push(value);
			}
		});

		$.each(hide, function(index, value) {
			$(value).hide();
		});

		toastr.info('Now only showing notes with the tag "' + tag + '"');
	});

	$('#note-list').on('click', '.remove-note', function() {
		$this = $(this);
		var deleteId = $this.closest('.note').data('id');

 		$.ajax({
			method: 'POST',
			url: 'includes/delete-note.php',
			data: {
				deleteNote: deleteId
			}
		})
		.done(function(data, result) {
			$this.closest('.note').remove();
			toastr.success('Note has been deleted!');
		})
		.fail(function(error) {
			console.log('An error has occurred: ', error);
		});

	});

	$('#note-list').on('click', '.edit-note', function() {
		// edit the note in the database.
		// also edit the note which is in the DOM
		// would probably be best to have this done in a modal.
		// TODO : above - skeleton code is below.
		$this = $(this);
		var newText = '';
		var noteId = $this.closest('.note').data('id');

		$.ajax({
			method: 'POST',
			url: 'includes/',
			data: {
				noteText: newText,
				noteId: noteId
			}
		})
		.done(function(data, result) {
			console.log(data, result)
			// update the DOM here.

			toastr.success('Note successfully updated!');
		})
		.fail(function() {
			console.log('An error has occurred: ', error);
		});

	});

	$('#add-note-text').on('keyup', function() {
		$('.note-text-validation').hide();
	});

	$('#refresh-button').on('click', function() {
		window.location.reload();
	});

})();<|endoftext|>


<commit_before>var DOMAIN                  = "DOMAIN_PLACEHOLDER",
    HTTPS_PORT              = "HTTPS_PORT_PLACEHOLDER",
    HTTP_PORT               = "HTTP_PORT_PLACEHOLDER",
    SECURE                  = (document.location.protocol == "https:") ? "s" : "",
    CROSSHAIR_HALF_SIZE     = 8,
    WIDTH                   = 2000,
    HEIGHT                  = 3000,
    MOUSEMOVE_DELAY         = 16,  // minimum time (in ms) between two mousemove events; 16ms ~= 60Hz
    MAX_NICKNAME_LENGTH     = 20,
    MAX_CHAT_MESSAGE_LENGTH = 256,
    ZOOM_MIN                = 0.5,
    ZOOM_MAX                = 10,
    ZOOM_FACTOR             = 1.1,
    this_script             = document.documentElement.lastChild,
    users                   = new Object(),
    mask_lines              = new Array(),
    lines_to_draw           = new Array(),
    my_last_x               = null,
    my_last_y               = null,
    my_use_pen              = 1,
    my_mouse_is_down        = null,
    chat_was_visible        = null,
    max_size                = 0,
    incoming_blobs          = [],
    zoom                    = 1.0,
    is_decoding             = false,
    mask_dirty              = false,
    chat_div, myPicker, nickname_span, canvas, messages_div, mySocket,
    mask_canvas, ctx, mask_ctx, biggest_node, last_time, loading_box,
    progress_bar, warning_box, frame_div, frame, error_message_div, zoom_slider

function distance(x1, y1, x2, y2){
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
}

function logn(i, base){
    return Math.log(i) / Math.log(base)
}

function time_since_last_time(){
    var now, duration
    if (typeof(last_time) == "undefined"){
        last_time = (new Date()).getTime()
        return 0
    }
    now = (new Date()).getTime()
    duration = now - last_time
    if (duration >= MOUSEMOVE_DELAY){  // if duration is too short, act like if we were never called
        last_time = now
    }
    return duration
}

function remove_all_users(){
    for (var user_id in users) {
        // use hasOwnProperty to filter out keys from the Object.prototype
        if (users.hasOwnProperty(user_id)) {
            users[user_id].destroy()
            delete users[user_id]
        }
    }
}

function destroy(){
    mySocket.close()
    remove_all_users()
    unwrap_document_from_iframe()
    delete window.webinvader_pad
}
this.destroy = destroy

var requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame

function render_loop(){
    requestAnimFrame(render_loop)
    for (var user_id in users) {
        // use hasOwnProperty to filter out keys from the Object.prototype
        if (users.hasOwnProperty(user_id)) {
            users[user_id].reposition_label()
        }
    }
    while(lines_to_draw.length > 0){
        draw_line.apply(this, lines_to_draw.shift())
    }
    // anti-lag mask canvas
    if (mask_dirty){
        mask_ctx.clearRect(0, 0, mask_canvas.width, mask_canvas.height)
        for (var i=0; i < mask_lines.length; i++){
            draw_line.apply(this, mask_lines[i])
        }
        mask_dirty = false
    }
}
render_loop()

//function init(){

    wrap_document_in_iframe()

    create_toolbar()
    create_chat_window()
    create_loading_box()
    create_warning_box()
    set_loading_on()
    create_socket()
    create_canvas()

//}
<commit_msg>remove unused variables<commit_after>var DOMAIN                  = "DOMAIN_PLACEHOLDER",
    HTTPS_PORT              = "HTTPS_PORT_PLACEHOLDER",
    HTTP_PORT               = "HTTP_PORT_PLACEHOLDER",
    SECURE                  = (document.location.protocol == "https:") ? "s" : "",
    CROSSHAIR_HALF_SIZE     = 8,
    WIDTH                   = 2000,
    HEIGHT                  = 3000,
    MOUSEMOVE_DELAY         = 16,  // minimum time (in ms) between two mousemove events; 16ms ~= 60Hz
    MAX_NICKNAME_LENGTH     = 20,
    MAX_CHAT_MESSAGE_LENGTH = 256,
    ZOOM_MIN                = 0.5,
    ZOOM_MAX                = 10,
    ZOOM_FACTOR             = 1.1,
    users                   = new Object(),
    mask_lines              = new Array(),
    lines_to_draw           = new Array(),
    my_last_x               = null,
    my_last_y               = null,
    my_use_pen              = 1,
    my_mouse_is_down        = null,
    chat_was_visible        = null,
    zoom                    = 1.0,
    mask_dirty              = false,
    chat_div, myPicker, nickname_span, canvas, messages_div, mySocket,
    mask_canvas, ctx, mask_ctx, last_time, loading_box,
    progress_bar, warning_box, frame_div, frame, error_message_div, zoom_slider

function distance(x1, y1, x2, y2){
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
}

function logn(i, base){
    return Math.log(i) / Math.log(base)
}

function time_since_last_time(){
    var now, duration
    if (typeof(last_time) == "undefined"){
        last_time = (new Date()).getTime()
        return 0
    }
    now = (new Date()).getTime()
    duration = now - last_time
    if (duration >= MOUSEMOVE_DELAY){  // if duration is too short, act like if we were never called
        last_time = now
    }
    return duration
}

function remove_all_users(){
    for (var user_id in users) {
        // use hasOwnProperty to filter out keys from the Object.prototype
        if (users.hasOwnProperty(user_id)) {
            users[user_id].destroy()
            delete users[user_id]
        }
    }
}

function destroy(){
    mySocket.close()
    remove_all_users()
    unwrap_document_from_iframe()
    delete window.webinvader_pad
}
this.destroy = destroy

var requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame

function render_loop(){
    requestAnimFrame(render_loop)
    for (var user_id in users) {
        // use hasOwnProperty to filter out keys from the Object.prototype
        if (users.hasOwnProperty(user_id)) {
            users[user_id].reposition_label()
        }
    }
    while(lines_to_draw.length > 0){
        draw_line.apply(this, lines_to_draw.shift())
    }
    // anti-lag mask canvas
    if (mask_dirty){
        mask_ctx.clearRect(0, 0, mask_canvas.width, mask_canvas.height)
        for (var i=0; i < mask_lines.length; i++){
            draw_line.apply(this, mask_lines[i])
        }
        mask_dirty = false
    }
}
render_loop()

//function init(){

    wrap_document_in_iframe()

    create_toolbar()
    create_chat_window()
    create_loading_box()
    create_warning_box()
    set_loading_on()
    create_socket()
    create_canvas()

//}
<|endoftext|>


<commit_before>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				console.log("YAAASSS!!!!\n");
				console.log(results.size);
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<commit_msg>print results list from find()<commit_after>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				console.log("YAAASSS!!!!\n");
				console.log(results);
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<|endoftext|>


<commit_before>$(document).ready(function()
{
	console.log("js working");

	$('#test').click(function(){
		console.log("test working");
		Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		var Classroom = Parse.Object.extend("Classroom");
		var room = new Classroom();
		console.log("Classroom declared");

		var Post = Parse.Object.Classroom.extend("Post");
		var post = new Post();
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);
		console.log("Post declared");

		room.save(null, {
	  		success: function(Classroom) {
	    		// Execute any logic that should take place after the object is saved.
	    		alert('New object created with objectId: ' + room.id);
	  		},
	  		error: function(Classroom, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  			//console.log("Nope.");
	  		}
		});

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		alert('New object created with objectId: ' + post.id);
	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  			//console.log("Nope.");
	  		}
		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		alert("yay! it worked");
		});
	});
});

<commit_msg>Revert<commit_after>$(document).ready(function()
{
	console.log("js working");

	$('#test').click(function(){
		console.log("test working");
		Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		var Classroom = Parse.Object.extend("Classroom");
		var room = new Classroom();
		console.log("Classroom declared");

		// var Post = Parse.Object.Classroom.extend("Post");
		// var post = new Post();
		// post.set("upvotes", 0);
		// post.set("downvotes", 0);
		// post.set("answered", false);
		// console.log("Post declared");

		room.save(null, {
	  		success: function(Classroom) {
	    		// Execute any logic that should take place after the object is saved.
	    		alert('New object created with objectId: ' + room.id);
	  		},
	  		error: function(Classroom, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  			//console.log("Nope.");
	  		}
		});

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		alert('New object created with objectId: ' + post.id);
	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  			//console.log("Nope.");
	  		}
		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		alert("yay! it worked");
		});
	});
});

<|endoftext|>


<commit_before>var liveRetrieveInterval = 5000; //milliseconds
var recentTemps = new Array();

function loadSettings() {
    //do ajax to load settings into form
    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            loadSettings:1
        },
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            $('#minTemp').val(response.minTemp);
            $('#maxTemp').val(response.maxTemp);
            $('#minutesBetweenNotifications').val(response.minutesBetweenNotifications);
            $('#alertEmails').val(response.alertEmails);
        }
    }); //ajax call
}

function loadLiveTemp() {
     $.ajax({
        url: '/',
        type: 'POST',
        data: {
            getLiveTemp:1
        },
	beforeSend:function(){
		//$('#lastTempVal').html('--.--');
	},
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            console.log(response);
            $('#lastTempVal').html(response.temperature);
            $('#lastTempTime').html(response.minutesSince);

	recentTemps.push(response);
	recentTemps.slice(Math.max(recentTemps.length - 50, 1));
console.log(recentTemps);

  $( "#lastTempVal" ).animate({
    opacity: 0.7
  }, 100, function() {
    $( "#lastTempVal" ).animate({
    opacity: 1
  }, 100, function() {
    // Animation complete.
  });
  });
	}

    }); //ajax call
}

function loadLastTemp() {
    //do ajax to load settings into form
    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            loadLastTemp:1
        },
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            console.log(response);
            $('#lastTempVal').html(response.temperature);
            $('#lastTempTime').html(response.minutesSince);
        }
    }); //ajax call
}

$(document).ready(function(){
    console.log('document is ready');
    $(document).on('click','#loadSettingsButton',loadSettings);
    $(document).on('click','#loadLastTempButton',loadLastTemp);

    loadLiveTemp();
    loadSettings();

clearInterval(interval);
var interval = setInterval(function() {
  // method to be executed;
console.log('interval met');
loadLiveTemp();
}, liveRetrieveInterval );

});
<commit_msg>updated js slice<commit_after>var liveRetrieveInterval = 5000; //milliseconds
var recentTemps = new Array();

function loadSettings() {
    //do ajax to load settings into form
    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            loadSettings:1
        },
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            $('#minTemp').val(response.minTemp);
            $('#maxTemp').val(response.maxTemp);
            $('#minutesBetweenNotifications').val(response.minutesBetweenNotifications);
            $('#alertEmails').val(response.alertEmails);
        }
    }); //ajax call
}

function loadLiveTemp() {
     $.ajax({
        url: '/',
        type: 'POST',
        data: {
            getLiveTemp:1
        },
	beforeSend:function(){
		//$('#lastTempVal').html('--.--');
	},
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            console.log(response);
            $('#lastTempVal').html(response.temperature);
            $('#lastTempTime').html(response.minutesSince);

	recentTemps.push(response);
	recentTemps = recentTemps.slice(Math.max(recentTemps.length - 50, 1));
console.log(recentTemps);

  $( "#lastTempVal" ).animate({
    opacity: 0.7
  }, 100, function() {
    $( "#lastTempVal" ).animate({
    opacity: 1
  }, 100, function() {
    // Animation complete.
  });
  });
	}

    }); //ajax call
}

function loadLastTemp() {
    //do ajax to load settings into form
    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            loadLastTemp:1
        },
        success:function(result)
        {
            var response = jQuery.parseJSON(result);
            console.log(response);
            $('#lastTempVal').html(response.temperature);
            $('#lastTempTime').html(response.minutesSince);
        }
    }); //ajax call
}

$(document).ready(function(){
    console.log('document is ready');
    $(document).on('click','#loadSettingsButton',loadSettings);
    $(document).on('click','#loadLastTempButton',loadLastTemp);

    loadLiveTemp();
    loadSettings();

clearInterval(interval);
var interval = setInterval(function() {
  // method to be executed;
console.log('interval met');
loadLiveTemp();
}, liveRetrieveInterval );

});
<|endoftext|>


<commit_before>// Declare global variables
var mainTimer = document.getElementById('startTimer');
var timerState = document.getElementById('displayTimer');
var currentTimer = document.getElementById('displayTimer').innerHTML;
var count = parseInt(document.getElementById('displayTimer').innerHTML);
var breakCount
var alertSound = document.getElementById('alertsound');

// alertSound.play();

// Event handler for user clicks on main timer
mainTimer.addEventListener('click', activateTimer);

function activateTimer() {
    if (timerState.style.zIndex == '-1') {
        timerState.style.zIndex = '1';
    } else {
        timerState.style.zIndex = '-1';
    }

}

var startTimer = setInterval(function() {
    if (timerState.style.zIndex == '1' || count === 0) {
        clearInterval(startTimer);
    } else {
        count--;
    }
}, 1000);
<commit_msg>add logic for timer adjustments<commit_after>// Declare global variables
var mainTimer = document.getElementById('startTimer');
var timerState = document.getElementById('displayTimer');
var breakState = document.getElementById('displayBreak');
var count = parseInt(document.getElementById('displayTimer').innerHTML);
var breakCount = parseInt(document.getElementById('displayBreak').innerHTML)
var alertSound = document.getElementById('alertsound');
var timerAdd = document.getElementById('timerAdd');
var timerSubtract = document.getElementById('timerSubtract');
var breakAdd = document.getElementById('breakAdd');
var breakSubtract = document.getElementById('breakSubtract');

// alertSound.play();

// Event handler for user clicks on main timer
mainTimer.addEventListener('click', activateTimer);

function activateTimer(event) {
    if (timerState.style.zIndex == '-1') {
        timerState.style.zIndex = '1';
        breakState.style.zIndex = '1';
    } else {
        timerState.style.zIndex = '-1';
        breakState.style.zIndex = '-1';
    }
    event.preventDefault();
}

timerAdd.addEventListener('click', function(event) {
        count += 1;
        timerState.innerHTML = count;
    event.preventDefault();
});

timerSubtract.addEventListener('click', function(event) {
    if(count > 0) {
        count -= 1;
        timerState.innerHTML = count;
    }
    event.preventDefault();
});

breakAdd.addEventListener('click', function(event) {
    breakCount += 1;
    breakState.innerHTML = breakCount;
event.preventDefault();
});

breakSubtract.addEventListener('click', function(event) {
if(breakCount > 0) {
    breakCount -= 1;
    breakState.innerHTML = breakCount;
}
event.preventDefault();
});<|endoftext|>


<commit_before>//set up global variables
var keys = document.getElementsByClassName("key");
var display = document.getElementById("display_result_inline");
var keyCode = 0;
var key = '';
var firstNum = 0;
var secondNum = 0;
var operator = '';

for (var i = 0; i < keys.length; i++) {
	keys[i].addEventListener("click", function() {
		//when a button is clicked, activate shadow effect
		var elem = this;
		removeBoxShadow(elem);
		setTimeout(function(){ setBoxShadow(elem); }, 200);

		//set keyCode to visible contents of the button to directly
		//get either the ASCII code of number or the operator clicked
		keyCode = this.innerHTML.charCodeAt(0);
		mainEvent(false);
	});
}

function removeBoxShadow(div){
	div.style.boxShadow = "none";
}

function setBoxShadow(div) {
	div.style.boxShadow = "2px 2px 5px 2px orange";
}

function isNumber() {
	return ['', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].findIndex(function(arg) { return arg == key; }) > 0;
}

function isOperator() {
	return ['', '+', '-', '*', '/'].findIndex(function(arg) { return arg == key; }) > 0;
}

//Returns the result of the computation based on the three global variables
function getResult() {
	switch (operator) {
	case '+':
		return firstNum + secondNum;
		break;
	case '-':
		return firstNum - secondNum;
		break;
	case '*':
		return firstNum * secondNum;
		break;
	case '/':
		return firstNum / secondNum;
		break;
	}
}

//Every keypress will fire mainEvent with keyPressed defaulting to true
document.addEventListener("keypress", mainEvent);

function mainEvent(keyPressed = true) {
	//If the function is called from the document's event listener, keyCode will be set to the window event's key code
	if (keyPressed)
		keyCode = (window.event.keyCode || window.event.which);

	//key is derived from the key keycode. toUpperCase is called to turn 'e' to 'E' and 'u' to 'U'
	key = String.fromCharCode(keyCode).toUpperCase();

	if (isNumber()) { //if key holds a numeric value...
		if (firstNum == 0) {
			//if firstNum doesn't have a value yet, set it
			firstNum = parseInt(key);
			display.innerHTML = firstNum;
		} else if (operator == '' && secondNum == 0) {
			//If firstNum has a value and operator doesn't and secondNum doesn't,
			//the user is adding a digit to firstNum
			firstNum *= 10;
			firstNum += parseInt(key);
			display.innerHTML = firstNum;
		} else if (operator != '' && secondNum == 0) {
			//If firstNum and operator have values but secondNum doesn't, set secondNum
			secondNum = parseInt(key);
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		} else if (firstNum != 0 && operator != '' && secondNum != 0) {
			//If all three have values, user is adding a digit to secondNum
			secondNum *= 10;
			secondNum += parseInt(key);
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		}
	} else if (isOperator()) { //if key holds an operator...
		operator = key;
		if (firstNum != 0 && secondNum == 0) //firstNum has value and secondNum doesn't so set the operator
			display.innerHTML = firstNum + " " + operator;
		else if (firstNum != 0 && operator != '' && secondNum != 0) //all three have value, switch operator and get new value
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
	} else if (key == 'E') { //reset output
		firstNum = 0;
		secondNum = 0;
		operator = '';
		display.innerHTML = "Result";
	} else if (key == 'U') { //user is trying to undo
		if (firstNum != 0 && operator != '' && secondNum != 0) { //if all three have values...
			secondNum = Math.floor(secondNum / 10); //remove digit from secondNum
			if (secondNum == 0) //if secondNum was 1 digit, it's now 0. remove it from output
				display.innerHTML = firstNum + " " + operator;
			else //otherwise, get new result
				display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		} else if (firstNum != 0 && operator != '') { //if firstNum and operator have values...
			//reset operator and remove it from output
			operator = '';
			display.innerHTML = firstNum;
		} else { //if operator and secondNum both don't have values...
			firstNum = Math.floor(firstNum/10); //remove digit from firstNum
			if (firstNum == 0) //if it was 1 digit, it's now 0. remove it from output
				display.innerHTML = "Result";
			else //otherwise, display firstNum
				display.innerHTML = firstNum;
		}
	}
}
<commit_msg>Update script.js<commit_after>//set up global variables
var keys = document.getElementsByClassName("key");
var display = document.getElementById("display_result_inline");
var keyCode = 0;
var key = '';
var firstNum = 0;
var secondNum = 0;
var operator = '';

for (var i = 0; i < keys.length; i++) {
	keys[i].addEventListener("click", function() {
		//when a button is clicked, activate shadow effect
		var elem = this;
		removeBoxShadow(elem);
		setTimeout(function(){ setBoxShadow(elem); }, 200);

		//set keyCode to visible contents of the button to directly
		//get either the ASCII code of number or the operator clicked
		keyCode = this.innerHTML.charCodeAt(0);
		mainEvent(false);
	});
}

function removeBoxShadow(div){
	div.style.boxShadow = "none";
}

function setBoxShadow(div) {
	div.style.boxShadow = "2px 2px 5px 2px orange";
}

function isNumber() {
	return ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].findIndex(function(arg) { return arg == key; }) != -1;
}

function isOperator() {
	return ['+', '-', '*', '/'].findIndex(function(arg) { return arg == key; }) != -1;
}

//Returns the result of the computation based on the three global variables
function getResult() {
	switch (operator) {
	case '+':
		return firstNum + secondNum;
		break;
	case '-':
		return firstNum - secondNum;
		break;
	case '*':
		return firstNum * secondNum;
		break;
	case '/':
		return firstNum / secondNum;
		break;
	}
}

//Every keypress will fire mainEvent with keyPressed defaulting to true
document.addEventListener("keypress", mainEvent);

function mainEvent(keyPressed = true) {
	//If the function is called from the document's event listener, keyCode will be set to the window event's key code
	if (keyPressed)
		keyCode = (window.event.keyCode || window.event.which);

	//key is derived from the key keycode. toUpperCase is called to turn 'e' to 'E' and 'u' to 'U'
	key = String.fromCharCode(keyCode).toUpperCase();

	if (isNumber()) { //if key holds a numeric value...
		if (firstNum == 0) {
			//if firstNum doesn't have a value yet, set it
			firstNum = parseInt(key);
			display.innerHTML = firstNum;
		} else if (operator == '' && secondNum == 0) {
			//If firstNum has a value and operator doesn't and secondNum doesn't,
			//the user is adding a digit to firstNum
			firstNum *= 10;
			firstNum += parseInt(key);
			display.innerHTML = firstNum;
		} else if (operator != '' && secondNum == 0) {
			//If firstNum and operator have values but secondNum doesn't, set secondNum
			secondNum = parseInt(key);
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		} else if (firstNum != 0 && operator != '' && secondNum != 0) {
			//If all three have values, user is adding a digit to secondNum
			secondNum *= 10;
			secondNum += parseInt(key);
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		}
	} else if (isOperator()) { //if key holds an operator...
		operator = key;
		if (firstNum != 0 && secondNum == 0) //firstNum has value and secondNum doesn't so set the operator
			display.innerHTML = firstNum + " " + operator;
		else if (firstNum != 0 && operator != '' && secondNum != 0) //all three have value, switch operator and get new value
			display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
	} else if (key == 'E') { //reset output
		firstNum = 0;
		secondNum = 0;
		operator = '';
		display.innerHTML = "Result";
	} else if (key == 'U') { //user is trying to undo
		if (firstNum != 0 && operator != '' && secondNum != 0) { //if all three have values...
			secondNum = Math.floor(secondNum / 10); //remove digit from secondNum
			if (secondNum == 0) //if secondNum was 1 digit, it's now 0. remove it from output
				display.innerHTML = firstNum + " " + operator;
			else //otherwise, get new result
				display.innerHTML = firstNum + " " + operator + " " + secondNum + " = " + getResult();
		} else if (firstNum != 0 && operator != '') { //if firstNum and operator have values...
			//reset operator and remove it from output
			operator = '';
			display.innerHTML = firstNum;
		} else { //if operator and secondNum both don't have values...
			firstNum = Math.floor(firstNum/10); //remove digit from firstNum
			if (firstNum == 0) //if it was 1 digit, it's now 0. remove it from output
				display.innerHTML = "Result";
			else //otherwise, display firstNum
				display.innerHTML = firstNum;
		}
	}
}
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

        //create an empty map
        var map = new Array(canvas.width);
        for(var i = 0; i < canvas.width; i++) {
            map[i] = new Array(canvas.height);
        }

        //function for finding if one point is a wall
        function iswall(i,j){
            if(i >= canvas.width || i < 0 || j >= canvas.height || j < 0){
                return 1;
            }else{
                return map[i][j];
            }
        }

       //functions for finding how many neighbors are walls
        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(iswall(i1,j1) == 1){
                neighbors++;
            }
            if(iswall(i,j1) == 1){
                neighbors++;
            }
            if(iswall(i2,j1) == 1){
                neighbors++;
            }
            if(iswall(i1,j) == 1){
                neighbors++;
            }
            if(iswall(i2,j) == 1){
                neighbors++;
            }
            if(iswall(i1,j2) == 1){
                neighbors++;
            }
            if(iswall(i,j2) == 1){
                neighbors++;
            }
            if(iswall(i2,j2) == 1){
                neighbors++;
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            document.getElementById("iter").innerHTML = it;
            if(it == 1){
                //fill the values
                for(var i = 0; i < canvas.width; i++) {
                    for(var j = 0; j < canvas.height; j++) {
                        if(Math.random() < .40){
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i < canvas.width; i++) {
                    for(var j = 0; j < canvas.height; j++){
                        var nc = ncount(i,j);
                        if(it<=4){
                            if(nc >= 5 || nc <=2){
                                map[i][j] = 1;
                            }else{
                                map[i][j] = 0;
                            }
                        }else{
                            if(nc >=5){
                                map[i][j] = 1;
                            }else{
                                map[i][j] = 0;
                            }
                        }
                    }
                }
            }

            //paint the map
            for(var i = 0; i < canvas.width; i++) {
                for(var j = 0; j< canvas.height; j++){
                    if(map[i][j] == 1){
                        c.fillStyle = "#000000";
                        c.fillRect(i, j, 1, 1);
                    }else {
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i, j, 1, 1);
                    }
                }
            }
            it++;
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

        //create an empty map
        var map = new Array(canvas.width);
        for(var i = 0; i < canvas.width; i++) {
            map[i] = new Array(canvas.height);
        }

        //function for finding if one point is a wall
        function iswall(i,j) {
            if(i >= canvas.width || i < 0 || j >= canvas.height || j < 0) {
                return 1;
            }else{
                return map[i][j];
            }
        }

       //functions for finding how many neighbors are walls
        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(iswall(i1,j1) == 1) {
                neighbors++;
            }
            if(iswall(i,j1) == 1) {
                neighbors++;
            }
            if(iswall(i2,j1) == 1) {
                neighbors++;
            }
            if(iswall(i1,j) == 1) {
                neighbors++;
            }
            if(iswall(i2,j) == 1) {
                neighbors++;
            }
            if(iswall(i1,j2) == 1) {
                neighbors++;
            }
            if(iswall(i,j2) == 1) {
                neighbors++;
            }
            if(iswall(i2,j2) == 1) {
                neighbors++;
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            document.getElementById("iter").innerHTML = it;
            if(it == 1) {
                //fill the values
                for(var i = 0; i < canvas.width; i++) {
                    for(var j = 0; j < canvas.height; j++) {
                        if(Math.random() < .40) {
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i < canvas.width; i++) {
                    for(var j = 0; j < canvas.height; j++) {
                        var nc = ncount(i,j);
                        if(it <= 4) {
                            if(nc >= 5 || nc <= 2) {
                                map[i][j] = 1;
                            }else{
                                map[i][j] = 0;
                            }
                        }else{
                            if(nc >= 4) {
                                map[i][j] = 1;
                            }else{
                                map[i][j] = 0;
                            }
                        }
                    }
                }
            }

            //paint the map
            for(var i = 0; i < canvas.width; i++) {
                for(var j = 0; j < canvas.height; j++) {
                    if(map[i][j] == 1) {
                        c.fillStyle = "#000000";
                        c.fillRect(i, j, 1, 1);
                    }else {
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i, j, 1, 1);
                    }
                }
            }
            it++;
        }
    }
})(window, document, undefined);
<|endoftext|>