<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 ){
                    roomlist[i].removed = 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,
              removed: 0
            };
            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;

           //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

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

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   } else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i + 1][] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //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++){
               if(roomlist[i].removed == 0){
                   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();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //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);

        }
    }
})(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 ){
                    roomlist[i].removed = 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,
              removed: 0
            };
            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;

           //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

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

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i + 1][] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //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++){
               if(roomlist[i].removed == 0){
                   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();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //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);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>import React from 'react';
import Title from 'react-title-component';
import { injectIntl } from 'react-intl';
import { Grid, Row, Col } from 'react-flexbox-grid/lib';
import TopicSearchContainer from './search/TopicSearchContainer';
import TopicListContainer from './list/TopicListContainer';

const localMessages = {
  homeTitle: { id: 'home.title', defaultMessage: 'Home' },
};

const HomeContainer = (props) => {
  const { formatMessage } = props.intl;
  const title = formatMessage(localMessages.homeTitle);
  const titleHandler = parentTitle => `${title} | ${parentTitle}`;
  return (

      <Title render={titleHandler} />

          <Grid>
            <Row>
              <Col lg={8} />
              <Col lg={4}>
                <TopicSearchContainer />
              </Col>
            </Row>
          </Grid>

      <Grid>
        <TopicListContainer />
      </Grid>

  );
};

HomeContainer.propTypes = {
  // from context
  intl: React.PropTypes.object.isRequired,
};

export default
  injectIntl(
    HomeContainer
  );
<commit_msg>specifically redirect from /home to public home if user isn't logged in<commit_after>import React from 'react';
import Title from 'react-title-component';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { Grid, Row, Col } from 'react-flexbox-grid/lib';
import TopicSearchContainer from './search/TopicSearchContainer';
import TopicListContainer from './list/TopicListContainer';

const localMessages = {
  homeTitle: { id: 'home.title', defaultMessage: 'Home' },
};

class HomeContainer extends React.Component {

  componentWillReceiveProps(nextProps) {
    // make sure logout on home goes to public home
    const { redirectToPublicHome } = this.props;
    if (nextProps.isLoggedIn === false) {
      redirectToPublicHome();
    }
  }

  render() {
    const { formatMessage } = this.props.intl;
    const title = formatMessage(localMessages.homeTitle);
    const titleHandler = parentTitle => `${title} | ${parentTitle}`;
    return (

        <Title render={titleHandler} />

            <Grid>
              <Row>
                <Col lg={8} />
                <Col lg={4}>
                  <TopicSearchContainer />
                </Col>
              </Row>
            </Grid>

        <Grid>
          <TopicListContainer />
        </Grid>

    );
  }

}

HomeContainer.propTypes = {
  // from state
  isLoggedIn: React.PropTypes.bool.isRequired,
  // from dispatch
  redirectToPublicHome: React.PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  userTopicPermission: state.topics.selected.info.user_permission,
  isLoggedIn: state.user.isLoggedIn,
});

const mapDispatchToProps = dispatch => ({
  redirectToPublicHome: () => {
    dispatch(push('/topics/public/home'));
  },
});

HomeContainer.propTypes = {
  // from context
  intl: React.PropTypes.object.isRequired,
};

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      HomeContainer
    )
  );
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import React, { PropTypes } from 'react';

import styles from './CBGSlice.css';

const CBGSlice = (props) => {
  const { datum, radius, xScale, yPositions } = props;
  const { isFocused, focusSlice, unfocusSlice } = props;

  function renderLine(category, y1Accessor, y2Accessor) {
    const focus = focusSlice.bind(null, datum);
    const unfocus = unfocusSlice.bind(null);
    if (yPositions[y1Accessor] && yPositions[y2Accessor]) {
      return (
        <line
          className={isFocused ? styles[`${category}Focused`] : styles[category]}
          key={`${category}-${datum.id}`}
          onMouseOver={focus}
          onMouseOut={unfocus}
          x1={xScale(datum.msX)}
          x2={xScale(datum.msX)}
          y1={yPositions[y1Accessor]}
          y2={yPositions[y2Accessor]}
        />
      );
    }
    return null;
  }

  return (
    <g id="cbgSlice">
      {[
        renderLine('rangeSlice', 'min', 'max'),
        renderLine('outerSlice', 'tenthQuantile', 'ninetiethQuantile'),
        renderLine('quartileSlice', 'firstQuartile', 'thirdQuartile'),
        <circle
          className={styles.cbgMedian}
          key={`individualMedian-${datum.id}`}
          cx={xScale(datum.msX)}
          cy={yPositions.median}
          r={radius}
        />,
      ]}
    </g>
  );
};

CBGSlice.defaultProps = {
  radius: 7,
};

CBGSlice.propTypes = {
  datum: PropTypes.object.isRequired,
  focusSlice: PropTypes.func.isRequired,
  isFocused: PropTypes.bool.isRequired,
  radius: PropTypes.number.isRequired,
  unfocusSlice: PropTypes.func.isRequired,
  xScale: PropTypes.func.isRequired,
  yPositions: PropTypes.object.isRequired,
};

export default CBGSlice;
<commit_msg>CBGSlice w/o the median circles<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2016, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import React, { PropTypes } from 'react';

import styles from './CBGSlice.css';

const CBGSlice = (props) => {
  const { datum, xScale, yPositions } = props;
  const { isFocused, focusSlice, unfocusSlice } = props;

  function renderLine(category, y1Accessor, y2Accessor) {
    const focus = focusSlice.bind(null, datum);
    const unfocus = unfocusSlice.bind(null);
    if (yPositions[y1Accessor] && yPositions[y2Accessor]) {
      return (
        <line
          className={isFocused ? styles[`${category}Focused`] : styles[category]}
          key={`${category}-${datum.id}`}
          onMouseOver={focus}
          onMouseOut={unfocus}
          x1={xScale(datum.msX)}
          x2={xScale(datum.msX)}
          y1={yPositions[y1Accessor]}
          y2={yPositions[y2Accessor]}
        />
      );
    }
    return null;
  }

  return (
    <g id="cbgSlice">
      {[
        renderLine('rangeSlice', 'min', 'max'),
        renderLine('outerSlice', 'tenthQuantile', 'ninetiethQuantile'),
        renderLine('quartileSlice', 'firstQuartile', 'thirdQuartile'),
      ]}
    </g>
  );
};

CBGSlice.propTypes = {
  datum: PropTypes.object.isRequired,
  focusSlice: PropTypes.func.isRequired,
  isFocused: PropTypes.bool.isRequired,
  radius: PropTypes.number.isRequired,
  unfocusSlice: PropTypes.func.isRequired,
  xScale: PropTypes.func.isRequired,
  yPositions: PropTypes.object.isRequired,
};

export default CBGSlice;
<|endoftext|>


<commit_before>/*
Copyright 2019 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React, {useState} from "react";
import PropTypes from "prop-types";
import classNames from 'classnames';

import {_t, _td} from '../../../languageHandler';
import {useFeatureEnabled, useSettingValue} from "../../../hooks/useSettings";
import AccessibleButton from "../elements/AccessibleButton";
import Tooltip from "../elements/Tooltip";

export const E2E_STATE = {
    VERIFIED: "verified",
    WARNING: "warning",
    UNKNOWN: "unknown",
    NORMAL: "normal",
};

const crossSigningUserTitles = {
    [E2E_STATE.WARNING]: _td("This user has not verified all of their sessions."),
    [E2E_STATE.NORMAL]: _td("You have not verified this user."),
    [E2E_STATE.VERIFIED]: _td("You have verified this user. This user has verified all of their sessions."),
};
const crossSigningRoomTitles = {
    [E2E_STATE.WARNING]: _td("Someone is using an unknown session"),
    [E2E_STATE.NORMAL]: _td("This room is end-to-end encrypted"),
    [E2E_STATE.VERIFIED]: _td("Everyone in this room is verified"),
};

const legacyUserTitles = {
    [E2E_STATE.WARNING]: _td("Some sessions for this user are not trusted"),
    [E2E_STATE.VERIFIED]: _td("All sessions for this user are trusted"),
};
const legacyRoomTitles = {
    [E2E_STATE.WARNING]: _td("Some sessions in this encrypted room are not trusted"),
    [E2E_STATE.VERIFIED]: _td("All sessions in this encrypted room are trusted"),
};

const E2EIcon = ({isUser, status, className, size, onClick, hideTooltip}) => {
    const [hover, setHover] = useState(false);

    const classes = classNames({
        mx_E2EIcon: true,
        mx_E2EIcon_warning: status === E2E_STATE.WARNING,
        mx_E2EIcon_normal: status === E2E_STATE.NORMAL,
        mx_E2EIcon_verified: status === E2E_STATE.VERIFIED,
    }, className);

    let e2eTitle;
    const crossSigning = useSettingValue("feature_cross_signing");
    if (crossSigning && isUser) {
        e2eTitle = crossSigningUserTitles[status];
    } else if (crossSigning && !isUser) {
        e2eTitle = crossSigningRoomTitles[status];
    } else if (!crossSigning && isUser) {
        e2eTitle = legacyUserTitles[status];
    } else if (!crossSigning && !isUser) {
        e2eTitle = legacyRoomTitles[status];
    }

    let style;
    if (size) {
        style = {width: `${size}px`, height: `${size}px`};
    }

    const onMouseOver = () => setHover(true);
    const onMouseOut = () => setHover(false);

    let tip;
    if (hover && !hideTooltip) {
        tip = <Tooltip label={e2eTitle ? _t(e2eTitle) : ""} />;
    }

    if (onClick) {
        return (
            <AccessibleButton
                onClick={onClick}
                onMouseOver={onMouseOver}
                onMouseOut={onMouseOut}
                className={classes}
                style={style}
            >
                { tip }
            </AccessibleButton>
        );
    }

    return

        { tip }

;
};

E2EIcon.propTypes = {
    isUser: PropTypes.bool,
    status: PropTypes.oneOf(Object.values(E2E_STATE)),
    className: PropTypes.string,
    size: PropTypes.number,
    onClick: PropTypes.func,
};

export default E2EIcon;
<commit_msg>Appease the linter<commit_after>/*
Copyright 2019 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React, {useState} from "react";
import PropTypes from "prop-types";
import classNames from 'classnames';

import {_t, _td} from '../../../languageHandler';
import {useSettingValue} from "../../../hooks/useSettings";
import AccessibleButton from "../elements/AccessibleButton";
import Tooltip from "../elements/Tooltip";

export const E2E_STATE = {
    VERIFIED: "verified",
    WARNING: "warning",
    UNKNOWN: "unknown",
    NORMAL: "normal",
};

const crossSigningUserTitles = {
    [E2E_STATE.WARNING]: _td("This user has not verified all of their sessions."),
    [E2E_STATE.NORMAL]: _td("You have not verified this user."),
    [E2E_STATE.VERIFIED]: _td("You have verified this user. This user has verified all of their sessions."),
};
const crossSigningRoomTitles = {
    [E2E_STATE.WARNING]: _td("Someone is using an unknown session"),
    [E2E_STATE.NORMAL]: _td("This room is end-to-end encrypted"),
    [E2E_STATE.VERIFIED]: _td("Everyone in this room is verified"),
};

const legacyUserTitles = {
    [E2E_STATE.WARNING]: _td("Some sessions for this user are not trusted"),
    [E2E_STATE.VERIFIED]: _td("All sessions for this user are trusted"),
};
const legacyRoomTitles = {
    [E2E_STATE.WARNING]: _td("Some sessions in this encrypted room are not trusted"),
    [E2E_STATE.VERIFIED]: _td("All sessions in this encrypted room are trusted"),
};

const E2EIcon = ({isUser, status, className, size, onClick, hideTooltip}) => {
    const [hover, setHover] = useState(false);

    const classes = classNames({
        mx_E2EIcon: true,
        mx_E2EIcon_warning: status === E2E_STATE.WARNING,
        mx_E2EIcon_normal: status === E2E_STATE.NORMAL,
        mx_E2EIcon_verified: status === E2E_STATE.VERIFIED,
    }, className);

    let e2eTitle;
    const crossSigning = useSettingValue("feature_cross_signing");
    if (crossSigning && isUser) {
        e2eTitle = crossSigningUserTitles[status];
    } else if (crossSigning && !isUser) {
        e2eTitle = crossSigningRoomTitles[status];
    } else if (!crossSigning && isUser) {
        e2eTitle = legacyUserTitles[status];
    } else if (!crossSigning && !isUser) {
        e2eTitle = legacyRoomTitles[status];
    }

    let style;
    if (size) {
        style = {width: `${size}px`, height: `${size}px`};
    }

    const onMouseOver = () => setHover(true);
    const onMouseOut = () => setHover(false);

    let tip;
    if (hover && !hideTooltip) {
        tip = <Tooltip label={e2eTitle ? _t(e2eTitle) : ""} />;
    }

    if (onClick) {
        return (
            <AccessibleButton
                onClick={onClick}
                onMouseOver={onMouseOver}
                onMouseOut={onMouseOut}
                className={classes}
                style={style}
            >
                { tip }
            </AccessibleButton>
        );
    }

    return

        { tip }

;
};

E2EIcon.propTypes = {
    isUser: PropTypes.bool,
    status: PropTypes.oneOf(Object.values(E2E_STATE)),
    className: PropTypes.string,
    size: PropTypes.number,
    onClick: PropTypes.func,
};

export default E2EIcon;
<|endoftext|>


<commit_before>/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
(function( w ){
  // rel=preload support test
  if( !w.loadCSS ){
    return;
  }
  var rp = loadCSS.relpreload = {};
  rp.support = function(){
    try {
      return w.document.createElement( "link" ).relList.supports( "preload" );
    } catch (e) {
      return false;
    }
  };

  // loop preload links and fetch using loadCSS
  rp.poly = function(){
    var links = w.document.getElementsByTagName( "link" );
    for( var i = 0; i < links.length; i++ ){
      var link = links[ i ];
      if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ){
        w.loadCSS( link.href, link, link.getAttribute( "media" ) );
        link.rel = null;
      }
    }
  };

  // if link[rel=preload] is not supported, we must fetch the CSS manually using loadCSS
  if( !rp.support() ){
    rp.poly();
    var run = w.setInterval( rp.poly, 300 );
    if( w.addEventListener ){
      w.addEventListener( "load", function(){
        rp.poly();
        w.clearInterval( run );
      } );
    }
    if( w.attachEvent ){
      w.attachEvent( "onload", function(){
        w.clearInterval( run );
      } )
    }
  }
}( this ));
<commit_msg>fixes #221<commit_after>/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
(function( w ){
  // rel=preload support test
  if( !w.loadCSS ){
    return;
  }
  var rp = loadCSS.relpreload = {};
  rp.support = function(){
    try {
      return w.document.createElement( "link" ).relList.supports( "preload" );
    } catch (e) {
      return false;
    }
  };

  // loop preload links and fetch using loadCSS
  rp.poly = function(){
    var links = w.document.getElementsByTagName( "link" );
    for( var i = 0; i < links.length; i++ ){
      var link = links[ i ];
      if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ){
        w.loadCSS( link.href, link, link.getAttribute( "media" ) );
        link.rel = null;
      }
    }
  };

  // if link[rel=preload] is not supported, we must fetch the CSS manually using loadCSS
  if( !rp.support() ){
    rp.poly();
    var run = w.setInterval( rp.poly, 300 );
    if( w.addEventListener ){
      w.addEventListener( "load", function(){
        rp.poly();
        w.clearInterval( run );
      } );
    }
    if( w.attachEvent ){
      w.attachEvent( "onload", function(){
        w.clearInterval( run );
      } );
    }
  }
}( this ));
<|endoftext|>


<commit_before>/**
 * Editor.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
define([
  'chai',
  'spies',
  'chaidom',
  'jquery',
  'summernote/base/core/agent',
  'summernote/base/core/dom',
  'summernote/base/core/range',
  'summernote/base/Context'
], function (chai, spies, chaidom, $, agent, dom, range, Context) {
  'use strict';
  var expect = chai.expect;
  chai.use(spies);
  chai.use(chaidom);

  // [workaround]
  //  - Firefox need setTimeout for applying contents
  //  - IE8-11 can't create range in headless mode
  if (!(agent.isWebkit || agent.isEdge)) {
    return;
  }

  var expectContents = function (context, markup) {
    expect(context.layoutInfo.editable.html()).to.equalsIgnoreCase(markup);
  };

  var expectToHaveBeenCalled = function (context, customEvent, handler) {
    var $note = context.layoutInfo.note;
    var spy = chai.spy();
    $note.on(customEvent, spy);
    handler();
    expect(spy).to.have.been.called();
  };

  describe('Editor', function () {
    var editor, context;

    beforeEach(function () {
      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
      context = new Context($('

hello

'), options);
      editor = context.modules.editor;
    });

    describe('initialize', function () {
      it('should bind custom events', function () {
        [
          'keydown', 'keyup', 'blur', 'mousedown', 'mouseup',
          'scroll', 'focusin', 'focusout'
        ].forEach(function (eventName) {
          expectToHaveBeenCalled(context, 'summernote.' + eventName, function () {
            context.layoutInfo.editable.trigger(eventName);
          });
        });

        expectToHaveBeenCalled(context, 'summernote.change', function () {
          editor.insertText('hello');
        });
      });
    });

    if (agent.isWebkit) {
      describe('undo and redo', function () {
        it('should control history', function () {
          editor.insertText(' world');
          expectContents(context, '
hello world
');

          editor.undo();
          expectContents(context, '
hello
');

          editor.redo();
          expectContents(context, '
hello world
');
        });
      });
    }

    describe('tab', function () {
      it('should insert tab', function () {
        editor.tab();
        expectContents(context, '
hello
');
      });
    });

    describe('insertParagraph', function () {
      it('should insert paragraph', function () {
        editor.insertParagraph();
        expectContents(context, '
hello

');

        editor.insertParagraph();
        expectContents(context, '
hello

');
      });
    });

    if (agent.isWebkit) {
      /* jshint ignore:start */
      describe('insertImage', function () {
        it('should insert image', function () {
          var source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAF0lEQVQYGWP8////fwYsgAmLGFiIHhIAT+oECGHuN2UAAAAASUVORK5CYII=';
          return editor.insertImage(source, 'image').then(function () {
            expectContents(context, '
hello
');
          });
        });
      });
      /* jshint ignore:end */
    }

    describe('insertOrderedList and insertUnorderedList', function () {
      it('should toggle paragraph to list', function () {
        editor.insertOrderedList();
        expectContents(context, '

hello

');

        editor.insertUnorderedList();
        expectContents(context, '

hello

');

        editor.insertUnorderedList();
        expectContents(context, '
hello
');
      });
    });

    describe('indent and outdent', function () {
      // [workaround] style is different by browser
      if (agent.isPhantom) {
        it('should indent and outdent paragraph', function () {
          editor.indent();
          expectContents(context, '
hello
');

          editor.outdent();
          expectContents(context, '
hello
');
        });
      }

      it('should indent and outdent list', function () {
        editor.insertOrderedList();
        expectContents(context, '

hello

');

        editor.indent();
        expectContents(context, '

hello

');

        editor.outdent();
        expectContents(context, '

hello

');
      });
    });

    describe('insertNode', function () {
      it('should insert node', function () {
        editor.insertNode($(' world')[0]);
        expectContents(context, '
hello world
');
      });
    });

    describe('insertText', function () {
      it('should insert text', function () {
        editor.insertText(' world');
        expectContents(context, '
hello world
');
      });
    });

    describe('pasteHTML', function () {
      it('should paste html', function () {
        editor.pasteHTML(' world');
        expectContents(context, '
hello world
');
      });

      it('should not call change change event more than once per paste event', function () {
        var generateLargeHtml = function () {
          var html = '
';
          for (var i = 0; i < 1000; i++) {
            html += '
HTML element #' + i + '
';
          }
          html += '
';
          return html;
        };
        var $note = context.layoutInfo.note;
        var spy = chai.spy();
        $note.on('summernote.change', spy);
        var html = generateLargeHtml();
        editor.pasteHTML(html);
        expect(spy).to.have.been.called.once;
      });
    });

    describe('insertHorizontalRule', function () {
      it('should insert horizontal rule', function () {
        editor.insertHorizontalRule();
        expectContents(context, '
hello

');
      });
    });

    describe('insertTable', function () {
      it('should insert table', function () {
        var markup = [
          '
hello
',
          '

',
          '

',
          '

',
          '

',
          '

'
        ].join('');
        editor.insertTable('2x2');
        expectContents(context, markup);
      });
    });

    describe('empty', function () {
      it('should make contents empty', function () {
        editor.empty();
        expect(editor.isEmpty()).to.be.true;
      });
    });

    describe('createLink', function () {
      it('should create normal link', function () {
        var text = 'hello';

        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        range.create(textNode, startIndex, textNode, endIndex).normalize().select();

        // check creation normal link
        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote'
        });

        expectContents(context, '
hellosummernote
');
      });

      it('should create a link with range', function () {
        var text = 'hello';
        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        var rng = range.create(textNode, startIndex, textNode, endIndex);

        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote',
          range: rng
        });

        expectContents(context, '
summernote
');
      });

      it('should create a link with isNewWindow', function () {
        var text = 'hello';
        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        var rng = range.create(textNode, startIndex, textNode, endIndex);

        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote',
          range: rng,
          isNewWindow: true
        });

        expectContents(context, '
summernote
');
      });

      it('should modify a link', function () {
        context.invoke('code', '
hello world
');

        var editable = context.layoutInfo.editable;
        var anchorNode = editable.find('a')[0];
        var rng = range.createFromNode(anchorNode);

        editor.createLink({
          url: 'http://wow.summernote.org',
          text: 'summernote wow',
          range: rng
        });

        expectContents(context, '
summernote wow
');
      });
    });
  });
});
<commit_msg>add test unit for formatBlock<commit_after>/**
 * Editor.spec.js
 * (c) 2015~ Summernote Team
 * summernote may be freely distributed under the MIT license./
 */
define([
  'chai',
  'spies',
  'chaidom',
  'jquery',
  'summernote/base/core/agent',
  'summernote/base/core/dom',
  'summernote/base/core/range',
  'summernote/base/Context'
], function (chai, spies, chaidom, $, agent, dom, range, Context) {
  'use strict';
  var expect = chai.expect;
  chai.use(spies);
  chai.use(chaidom);

  // [workaround]
  //  - Firefox need setTimeout for applying contents
  //  - IE8-11 can't create range in headless mode
  if (!(agent.isWebkit || agent.isEdge)) {
    return;
  }

  var expectContents = function (context, markup) {
    expect(context.layoutInfo.editable.html()).to.equalsIgnoreCase(markup);
  };

  var expectToHaveBeenCalled = function (context, customEvent, handler) {
    var $note = context.layoutInfo.note;
    var spy = chai.spy();
    $note.on(customEvent, spy);
    handler();
    expect(spy).to.have.been.called();
  };

  describe('Editor', function () {
    var editor, context;

    beforeEach(function () {
      var options = $.extend({}, $.summernote.options);
      options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
      context = new Context($('

hello

'), options);
      editor = context.modules.editor;
    });

    describe('initialize', function () {
      it('should bind custom events', function () {
        [
          'keydown', 'keyup', 'blur', 'mousedown', 'mouseup',
          'scroll', 'focusin', 'focusout'
        ].forEach(function (eventName) {
          expectToHaveBeenCalled(context, 'summernote.' + eventName, function () {
            context.layoutInfo.editable.trigger(eventName);
          });
        });

        expectToHaveBeenCalled(context, 'summernote.change', function () {
          editor.insertText('hello');
        });
      });
    });

    if (agent.isWebkit) {
      describe('undo and redo', function () {
        it('should control history', function () {
          editor.insertText(' world');
          expectContents(context, '
hello world
');

          editor.undo();
          expectContents(context, '
hello
');

          editor.redo();
          expectContents(context, '
hello world
');
        });
      });
    }

    describe('tab', function () {
      it('should insert tab', function () {
        editor.tab();
        expectContents(context, '
hello
');
      });
    });

    describe('insertParagraph', function () {
      it('should insert paragraph', function () {
        editor.insertParagraph();
        expectContents(context, '
hello

');

        editor.insertParagraph();
        expectContents(context, '
hello

');
      });
    });

    if (agent.isWebkit) {
      /* jshint ignore:start */
      describe('insertImage', function () {
        it('should insert image', function () {
          var source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAF0lEQVQYGWP8////fwYsgAmLGFiIHhIAT+oECGHuN2UAAAAASUVORK5CYII=';
          return editor.insertImage(source, 'image').then(function () {
            expectContents(context, '
hello
');
          });
        });
      });
      /* jshint ignore:end */
    }

    describe('insertOrderedList and insertUnorderedList', function () {
      it('should toggle paragraph to list', function () {
        editor.insertOrderedList();
        expectContents(context, '

hello

');

        editor.insertUnorderedList();
        expectContents(context, '

hello

');

        editor.insertUnorderedList();
        expectContents(context, '
hello
');
      });
    });

    describe('indent and outdent', function () {
      // [workaround] style is different by browser
      if (agent.isPhantom) {
        it('should indent and outdent paragraph', function () {
          editor.indent();
          expectContents(context, '
hello
');

          editor.outdent();
          expectContents(context, '
hello
');
        });
      }

      it('should indent and outdent list', function () {
        editor.insertOrderedList();
        expectContents(context, '

hello

');

        editor.indent();
        expectContents(context, '

hello

');

        editor.outdent();
        expectContents(context, '

hello

');
      });
    });

    describe('insertNode', function () {
      it('should insert node', function () {
        editor.insertNode($(' world')[0]);
        expectContents(context, '
hello world
');
      });
    });

    describe('insertText', function () {
      it('should insert text', function () {
        editor.insertText(' world');
        expectContents(context, '
hello world
');
      });
    });

    describe('pasteHTML', function () {
      it('should paste html', function () {
        editor.pasteHTML(' world');
        expectContents(context, '
hello world
');
      });

      it('should not call change change event more than once per paste event', function () {
        var generateLargeHtml = function () {
          var html = '
';
          for (var i = 0; i < 1000; i++) {
            html += '
HTML element #' + i + '
';
          }
          html += '
';
          return html;
        };
        var $note = context.layoutInfo.note;
        var spy = chai.spy();
        $note.on('summernote.change', spy);
        var html = generateLargeHtml();
        editor.pasteHTML(html);
        expect(spy).to.have.been.called.once;
      });
    });

    describe('insertHorizontalRule', function () {
      it('should insert horizontal rule', function () {
        editor.insertHorizontalRule();
        expectContents(context, '
hello

');
      });
    });

    describe('insertTable', function () {
      it('should insert table', function () {
        var markup = [
          '
hello
',
          '

',
          '

',
          '

',
          '

',
          '

'
        ].join('');
        editor.insertTable('2x2');
        expectContents(context, markup);
      });
    });

    describe('empty', function () {
      it('should make contents empty', function () {
        editor.empty();
        expect(editor.isEmpty()).to.be.true;
      });
    });

    describe('formatBlock', function () {
      it('should apply formatBlock', function () {
        context.layoutInfo.editable.appendTo('body');
        editor.formatBlock('blockquote');

        // start
hello
 =>
hello

        expectContents(context, '
hello
');
      });

      it('should apply custom className in formatBlock', function () {
        context.layoutInfo.editable.appendTo('body');
        var $target = $('
');
        editor.formatBlock('blockquote', $target);

        // start
hello
 =>
hello

        expectContents(context, '
hello
');
      });
    });

    describe('createLink', function () {
      it('should create normal link', function () {
        var text = 'hello';

        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        range.create(textNode, startIndex, textNode, endIndex).normalize().select();

        // check creation normal link
        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote'
        });

        expectContents(context, '
hellosummernote
');
      });

      it('should create a link with range', function () {
        var text = 'hello';
        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        var rng = range.create(textNode, startIndex, textNode, endIndex);

        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote',
          range: rng
        });

        expectContents(context, '
summernote
');
      });

      it('should create a link with isNewWindow', function () {
        var text = 'hello';
        var editable = context.layoutInfo.editable;
        var pNode = editable.find('p')[0];
        var textNode = pNode.childNodes[0];
        var startIndex = textNode.wholeText.indexOf(text);
        var endIndex = startIndex + text.length;

        var rng = range.create(textNode, startIndex, textNode, endIndex);

        editor.createLink({
          url: 'http://summernote.org',
          text: 'summernote',
          range: rng,
          isNewWindow: true
        });

        expectContents(context, '
summernote
');
      });

      it('should modify a link', function () {
        context.invoke('code', '
hello world
');

        var editable = context.layoutInfo.editable;
        var anchorNode = editable.find('a')[0];
        var rng = range.createFromNode(anchorNode);

        editor.createLink({
          url: 'http://wow.summernote.org',
          text: 'summernote wow',
          range: rng
        });

        expectContents(context, '
summernote wow
');
      });
    });
  });
});
<|endoftext|>


<commit_before>// event listener to respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document.getElementById('loadQuote').addEventListener("click", printQuote, false);

<commit_msg>Project complete<commit_after>'use strict';

// Object array holding the quotes
let quotes = [
  {
    id: 1,
    quote: 'Don\'t cry because it\'s over, smile because it happened.',
    source: 'Dr. Seuss',
    citation: 'Citation Example 1',
    year: 1995,
    category: ['Example1 Tag 1', 'Example2 Tag 2']
  }, {
    id: 2,
    quote: 'You can do anything but not everything',
    source: 'David Allen',
    citation: 'Making It All Work',
    year: 2009,
    category: ['life', 'self growth']
  }, {
    id: 3,
    quote: 'You can observe a lot just by watching.',
    source: 'Yogi Berra',
    citation: '',
    category: ['managment', 'planning', 'truism']
  }, {
    id: 4,
    quote: 'A house divided against itself cannot stand.',
    source: 'Abraham Lincoln',
    citation: '',
    category: ['wisdom']
  }, {
    id: 5,
    quote: 'Difficulties increase the nearer we get to the goal.',
    source: 'Johann Wolfgang von Goethe',
    citation: '',
    category: ['future', 'goals']
  }, {
    id: 6,
    quote: 'Fate is in your hands and no one elses',
    source: 'Byron Pulsifer',
    citation: '',
    category: ['fate', 'wisdom']
  }, {
    id: 7,
    quote: 'Be the chief but never the lord.',
    source: 'Lao Tzu',
    citation: '',
    category: ['leadership']
  }, {
    id: 8,
    quote: 'Nothing happens unless first we dream.',
    source: 'Carl Sandburg',
    citation: '',
    category: ['dreams']
  }, {
    id: 9,
    quote: 'Well begun is half done.',
    source: 'Aristotle',
    citation: '',
    category: ['wisdom', 'greek', 'intelligence']
  }
];

// array of already displayed quotes
let consumedQuotes = [];

// saved interval so it can be manualy canceled
let intervalID;

/*  function that resets the quote rotation on button click -
    the function is triggered if all quotes were shown or button was clicked
*/
const resetQuoteRotation = (event) => {
  if (event) {
    if (event.id) {
      printQuote(event); // event here is the last quote shown in last rotation
    } else { // event = button click
      printQuote();
      clearInterval(intervalID);
      intervalID = setInterval(printQuote, 10000);
    }
  } else {
    printQuote();
  }
};

/**
 * [startQuoteRotation initial quote rotation start]
 * @return {[void]}
 */
const startQuoteRotation = () => {
  printQuote();
  intervalID = setInterval(printQuote, 10000);
};

/**
 * [calculateRandomBodyColor description]
 * @return {[string]} [string representing HEX color - #cc12aa]
 */
const calculateRandomBodyColor = () => {
  return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
};

/**
 * [changeBodyColor changes the body color]
 * @param  {[string]} bodyColor [which color to display]
 * @return {[void]}           []
 */
const changeBodyColor = (bodyColor) => {
  document.body.style.background = bodyColor;
};

/**
 * [getRandomQuote description]
 * @return {[Object]} [Object of Quotes]
 */
const getRandomQuote = () => {
  return quotes[Math.floor(Math.random() * quotes.length) + 0];
};

/**
 * [quoteAlreadyShown checks if the newly fetched quote was already displayed]
 * @param  {[number]} quoteId [quote.id - id value of the quote to be checked]
 * @return {[boolean]}         [returns true: if incoming quotes has already been show / false: if the quote wasn't shown before]
 */
const quoteAlreadyShown = (quoteId) => {
  for (let i = 0; i < consumedQuotes.length; i++) {
    if (consumedQuotes[i].id === quoteId) {
      return true;
    }
  }
  return false;
};

/**
 * [checkIfAllQuotesWereUsed checks if all of the quotes were uses - displayed]
 * @return {[boolean]} []
 */
const checkIfAllQuotesWereUsed = () => {
  if (consumedQuotes.length === quotes.length) {
    return true;
  } else {
    return false;
  }
};

/**
 * [printQuote gets a random quote from the Object[] and checks if all quotes were used
 * checks the current quote if it was shown before
 * appends the quote object to the DOM]
 * @param  {[Object]} lastQuote [if the rotation has been through 1 time then this is set to the last quote that was displayed]
 * @return {[void]}
 */
const printQuote = (lastQuote) => {
  let quote = getRandomQuote();
  // console.log(quote);

  if (lastQuote) {
    while (lastQuote.id === quote.id) {
      quote = getRandomQuote();
    }
  }

  if (checkIfAllQuotesWereUsed()) {
    lastQuote = consumedQuotes.pop();
    consumedQuotes = [];
    resetQuoteRotation(lastQuote);
  } else {

    while (quoteAlreadyShown(quote.id)) {
      quote = getRandomQuote();
    }

    consumedQuotes.push(quote);
    console.log('Displayed quotes: ', consumedQuotes);

    changeBodyColor(calculateRandomBodyColor());

    let quoteMarkup = `<p class="quote">${quote.quote}</p><p class="source">${quote.source}`;

    if (quote.citation !== undefined) {
      quoteMarkup += `<span class="citation">${quote.citation}</span>`;
    } else if (quote.year !== undefined) {
      quoteMarkup += `<span class="year">${quote.year}</span>`;
    }

    quoteMarkup += '
';

    if(quote.category !== 0 ) {
      quoteMarkup += '

category:
';
      for(let i = 0; i < quote.category.length; i++){
        quoteMarkup += `<p class="tag-item">${quote.category[i]}</p>`;
      }
      quoteMarkup += '
';
    }

    document.getElementById('quote-box').innerHTML = quoteMarkup;
  }
};

/**
 * main logic start - set interval to automatically display quotes
 */
startQuoteRotation();

// event listener to respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document.getElementById('loadQuote').addEventListener('click', resetQuoteRotation, false);
<|endoftext|>


<commit_before>/**
* File script.js
*
* All scripts for the site
*
* @author Florian Keller
*/

$(window).load(function() {										// warte darauf, dass der Inhalt geladen wurde
	$.ajaxSetup({ cache: false });

	$('#searchform .submitForm').on('click', function() {
		$('#searchform').submit();
	});

	$('#results .close').on('click', function() {
		$('#results').slideUp();
	});

	$('#searchform input').on('keyup', function() {
		if ($('#searchform input').val() === "") {
			$('#results').slideUp();
		}
		console.log($('#searchform input').val());
	});

	$(document).on('submit', '#searchform', function(event) {
		event.preventDefault();
		searchData();
	});

	$(document).on('submit', '#newdataform', function(event) {
		event.preventDefault();
		var formEmail = $('#formemail').val();
		if (formEmail.substring(formEmail.length-20,
								formEmail.length) !== "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			$('#formemail').popover('show');
		} else {
			$('#formemail').popover('hide');
			sendEntries('#newdataform');
		}
	});

	$(document).on('change', 'select', function() {
		if ($(this).find('option:selected').val() === "neuestadt") {								// wenn eine neue Stadt eingetragen werden soll
			var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
			if (userInput !== "" && userInput !== null) {
				var JSONdata = {};
				JSONdata['id'] = generateID();
				JSONdata['user'] = "lkf4vyxn9";
				JSONdata['name_short'] = formatValue(userInput);
				JSONdata['name_long'] = userInput;
				JSONdata['lat'] = 5.333;
				JSONdata['lng'] = 1.222;
				JSONdata['country'] = "";
				JSONdata['website'] = "";
				JSONdata['comment'] = "";
				var request = $.ajax({
					type: 'POST',
					dataType: 'json',
					url: 'php/functions.php',
					data: JSON.stringify({
						"type": "city",
						"data": JSONdata
					}),
					contentType: "application/json"
				});

				request.done(function(data) {
					//console.log(data);
					$.each($('select'), function(id, obj) {
						$('<option/>', {
							text: JSONdata['name_long'],
							name: JSONdata['name_short'],
							value: JSONdata['id'],
							selected: true
						}).appendTo(obj);
					});
				});

				request.fail(function(jqXHR, textStatus) {
					console.log("Request failed: " + textStatus);
					console.log("Received: " + JSON.stringify(jqXHR));
				});
			}
		}
	});

	$('table').on('click', '.wetterbild', function() {
		var img = $(this).attr('src');
		var text = $(this).attr('alt');
		$('#zoom')
			.find('#zoomtitle').html(text)
			.end().find('#zoombody').html('')
			.end().modal('show');
	});

	$('table').on('click', '.editlink', function() {
		$(this).parent().parent().find('.editable').hide();
		$(this).parent().parent().find('.edit').show();
	});

	$('table').on('click', '.savelink', function() {
		var tr = $(this).parent().parent();
		tr.find('.editable.date').text(formatDate(tr.find('input[type=date]').val()));
		tr.find('.editable.temp').html(tr.find('input[type=number]').val() + " °C");
		tr.find('.editable.city').text(tr.find('select option:selected').text());
		tr.find('.editable.comment').text(tr.find('input[type=text]').val());
		tr.find('.edit').hide();
		tr.find('.editable').show();
	});

	$('table').on('click', '.removelink', function(e) {
		e.preventDefault();
		//var el = $(this).parent();
		var id = $(this).parent().parent().attr('data-id');
		var title = $(this).attr('data-title');
		var msg = $(this).attr('data-message');
		var type = $(this).attr('data-type');
		$('#frm_submit').attr('remove-id', id);
		if (msg === "" && type === 'remove') {
			title = "Löschen?";
			msg = "Diesen Eintrag wirklich löschen?";
		}

		$('#formConfirm')
			.find('#frm_body').html(msg)
			.end().find('#frm_submit').html("Ja")
			.end().find('#frm_cancel').html("Nein")
			.end().find('#frm_title').html(title)
			.end().modal('show');

		//$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
	});

	$('#formConfirm').on('click', '#frm_submit', function(e) {
		//console.log('remove-id: ' + $(this).attr('remove-id'));
		var tr = $('table').find('[data-id="' + $(this).attr('remove-id') + '"]');
		//console.log(tr);
		var entryID = $(tr).attr('data-id');
		//console.log(entryID);
		var request = $.ajax({
			url: 'php/functions.php',
			type: 'GET',
			dataType: 'json',
			data: {
				action: "removeentry",
				entry: entryID
			}
		});

		request.done(function() {
			tr.remove();
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});

	});

	var today = new Date();									// neues Datum erzeugen
	var dateString = today.getFullYear() + '-'
		+ ('0' + (today.getMonth()+1)).slice(-2) + '-'
		+ ('0' + today.getDate()).slice(-2);
	$('#formdate').val(dateString);							// formdate auf das heutige Datum setzen

	$('#status').text("Daten werden geladen...");

	var request1 = $.ajax({
		url: 'php/functions.php',
		type: 'GET',
		dataType: 'json',
		data: {
			action: "getdata"
		}
	});

	request1.done(function(data) {
		$('#status').hide();
		$('#datawrap').show();
		$.each(data, function(i, item) {
			var entry = data[i];
			addEntry(entry.id, entry.date, entry.temp, entry.city, entry.image, entry.comment);
		});
	});

	request1.fail(function(jqXHR, textStatus) {
		$('#status').text("Request failed: " + textStatus);
		console.log("Received: " + JSON.stringify(jqXHR));
	});

	var citiesJSON = {};
	var request2 = $.ajax({
		url: 'php/functions.php',
		type: 'GET',
		dataType: 'json',
		data: {
			action: "getcities"
		}
	});

	request2.done(function(data) {
		$('select').each(function() {
			addCities($(this), data);
		});
	});

	request2.fail(function(jqXHR, textStatus) {
		console.log("Request failed: " + textStatus);
		console.log("Received: " + JSON.stringify(jqXHR));
	});

	function addEntry(id, date, temp, city, image, comment) {
		var tr = $('
' +
			'<form class="form-horizontal" role="form" action="" method="post" class="editform">' +
			'' + formatDate(date) + '	' +
			'<input type="date" class="form-control" value="' + date + '" />	' +
			'' + temp + '° C	' +
			'<input type="number" class="form-control" value="' + temp + '" min="-72" max="100" /> °C	' +
			'' + city + '	' +
			'' +
				'<select class="form-control">' +
				'</select>' +
			'	' +
			'	' +
			'<button type="button" class="btn btn-primary"></button>	' +
			'' + comment + '	' +
			'<input type="text" class="form-control" value="' + comment + '" />	' +
			'' +
				'<button type="button" class="btn btn-primary btn-xs editlink"></button>' +
				'<button type="button" class="btn btn-danger btn-xs removelink" data-type="remove"></button>' +
			'	' +
			'' +
				'<button type="button" class="btn btn-success btn-xs savelink"></button>' +
				'<button type="button" class="btn btn-danger btn-xs removelink" data-type="remove"></button>' +
			'	' +
			'</form>' +
			'
').appendTo($('table tbody'));
		//console.log("id: " + id);
		addCities(tr.find('select'), citiesJSON);
	}

	function addCities(select, data) {
		//console.log(select);
		$('<option/>', {
			text: "Stadt",
			value: "",
			disabled: true
		}).appendTo(select);

		$.each(data, function(id, obj) {
			$('<option/>', {
				text: obj.name_long,
				name: obj.name_short,
				value: obj.id
			}).appendTo(select);
		});

		/*$(select).sort(function(a, b) {
			a = a.name;
			b = b.name;

			return a-b;
		});*/

		$('<option/>', {
			text: "Neue Stadt...",
			value: "neuestadt"
		}).appendTo(select);
	}

	function searchData() {
		var keyword = $('#searchform .searchbox').val();
		var request = $.ajax({
			url: 'php/functions.php',
			type: 'GET',
			dataType: 'json',
			data: {
				action: "searchcity",
				key: keyword
			}
		});

		request.done(function(data) {
			if (data.status === "success") {
				data = data.results;
				$('#results .panel-body').html("Suchergebnisse: ");
				$.each(data, function(id, obj) {
					$('#results .panel-body').append(obj.name_long + " ");
				});
				//console.log(data);
			} else {
				$('#results .panel-body').html(data.message);
			}
			$('#results').slideDown();
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});
	}

	function sendImage(form) {

	}

	function sendEntries(form) {
		var JSONdata = {};
		JSONdata['id'] = generateID();
		JSONdata['user'] = "lkf4vyxn9";
		JSONdata['image'] = "mitte20141001.jpg";
		$(form + ' *').filter(':input').each(function(i, obj) {
			JSONdata[$(obj).attr('name')] = $(obj).val();
			delete JSONdata['undefined'];
		});
		//console.log(JSONdata);
		var formId = $('table tr').length;
		var request = $.ajax({
			type: 'POST',
			dataType: 'json',
			url: 'php/functions.php',
			data: JSON.stringify({
				"type": "entries",
				"data": JSONdata
			}),
			contentType: "application/json"
		});

		request.done(function() {
			addEntry(JSONdata['id'], JSONdata['date'], JSONdata['temp'], $(form + ' option:selected').text(), JSONdata['image'], JSONdata['comment']);
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});
	}

	/**
	* Function formatValue
	*
	* Returns a String with umlauts replaced to ae, oe, etc.
	*
	* @param String str The string with umlauts
	* @return The replaced string without umlauts
	*/

	function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
		return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
	}

	/**
	* Function formatDate
	*
	* Returns a date String in the dd.mm.yyyy format
	*
	* @param String date The date in the format yyyy-mm-dd
	* @return The replaced date string
	*/

	function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
		return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
	}

	function generateID() {
		return Math.random().toString(36).substr(2, 9);
	}

	var mapOptions = {
		center: {
			lat: 52.5167,
			lng: 13.3833
		},
		zoom: 13,
		disableDefaultUI: true,
		draggable: false,
		scrollwheel: false,
		disableDoubleClickZoom: true
	};
	var map = new google.maps.Map(document.getElementById('map'), mapOptions);
	$('#map').fadeIn();
});
<commit_msg>Search on keypress<commit_after>/**
* File script.js
*
* All scripts for the site
*
* @author Florian Keller
*/

$(window).load(function() {										// warte darauf, dass der Inhalt geladen wurde
	$.ajaxSetup({ cache: false });

	$('#searchform .submitForm').on('click', function() {
		$('#searchform').submit();
	});

	$('#results .close').on('click', function() {
		$('#results').slideUp();
	});

	$('#searchform input').on('keyup', function() {
		if ($('#searchform input').val() === "") {
			$('#results').slideUp();
		} else {
			$('#searchform').submit();
		}
	});

	$(document).on('submit', '#searchform', function(event) {
		event.preventDefault();
		searchData();
	});

	$(document).on('submit', '#newdataform', function(event) {
		event.preventDefault();
		var formEmail = $('#formemail').val();
		if (formEmail.substring(formEmail.length-20,
								formEmail.length) !== "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			$('#formemail').popover('show');
		} else {
			$('#formemail').popover('hide');
			sendEntries('#newdataform');
		}
	});

	$(document).on('change', 'select', function() {
		if ($(this).find('option:selected').val() === "neuestadt") {								// wenn eine neue Stadt eingetragen werden soll
			var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
			if (userInput !== "" && userInput !== null) {
				var JSONdata = {};
				JSONdata['id'] = generateID();
				JSONdata['user'] = "lkf4vyxn9";
				JSONdata['name_short'] = formatValue(userInput);
				JSONdata['name_long'] = userInput;
				JSONdata['lat'] = 5.333;
				JSONdata['lng'] = 1.222;
				JSONdata['country'] = "";
				JSONdata['website'] = "";
				JSONdata['comment'] = "";
				var request = $.ajax({
					type: 'POST',
					dataType: 'json',
					url: 'php/functions.php',
					data: JSON.stringify({
						"type": "city",
						"data": JSONdata
					}),
					contentType: "application/json"
				});

				request.done(function(data) {
					//console.log(data);
					$.each($('select'), function(id, obj) {
						$('<option/>', {
							text: JSONdata['name_long'],
							name: JSONdata['name_short'],
							value: JSONdata['id'],
							selected: true
						}).appendTo(obj);
					});
				});

				request.fail(function(jqXHR, textStatus) {
					console.log("Request failed: " + textStatus);
					console.log("Received: " + JSON.stringify(jqXHR));
				});
			}
		}
	});

	$('table').on('click', '.wetterbild', function() {
		var img = $(this).attr('src');
		var text = $(this).attr('alt');
		$('#zoom')
			.find('#zoomtitle').html(text)
			.end().find('#zoombody').html('')
			.end().modal('show');
	});

	$('table').on('click', '.editlink', function() {
		$(this).parent().parent().find('.editable').hide();
		$(this).parent().parent().find('.edit').show();
	});

	$('table').on('click', '.savelink', function() {
		var tr = $(this).parent().parent();
		tr.find('.editable.date').text(formatDate(tr.find('input[type=date]').val()));
		tr.find('.editable.temp').html(tr.find('input[type=number]').val() + " °C");
		tr.find('.editable.city').text(tr.find('select option:selected').text());
		tr.find('.editable.comment').text(tr.find('input[type=text]').val());
		tr.find('.edit').hide();
		tr.find('.editable').show();
	});

	$('table').on('click', '.removelink', function(e) {
		e.preventDefault();
		//var el = $(this).parent();
		var id = $(this).parent().parent().attr('data-id');
		var title = $(this).attr('data-title');
		var msg = $(this).attr('data-message');
		var type = $(this).attr('data-type');
		$('#frm_submit').attr('remove-id', id);
		if (msg === "" && type === 'remove') {
			title = "Löschen?";
			msg = "Diesen Eintrag wirklich löschen?";
		}

		$('#formConfirm')
			.find('#frm_body').html(msg)
			.end().find('#frm_submit').html("Ja")
			.end().find('#frm_cancel').html("Nein")
			.end().find('#frm_title').html(title)
			.end().modal('show');

		//$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
	});

	$('#formConfirm').on('click', '#frm_submit', function(e) {
		//console.log('remove-id: ' + $(this).attr('remove-id'));
		var tr = $('table').find('[data-id="' + $(this).attr('remove-id') + '"]');
		//console.log(tr);
		var entryID = $(tr).attr('data-id');
		//console.log(entryID);
		var request = $.ajax({
			url: 'php/functions.php',
			type: 'GET',
			dataType: 'json',
			data: {
				action: "removeentry",
				entry: entryID
			}
		});

		request.done(function() {
			tr.remove();
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});

	});

	var today = new Date();									// neues Datum erzeugen
	var dateString = today.getFullYear() + '-'
		+ ('0' + (today.getMonth()+1)).slice(-2) + '-'
		+ ('0' + today.getDate()).slice(-2);
	$('#formdate').val(dateString);							// formdate auf das heutige Datum setzen

	$('#status').text("Daten werden geladen...");

	var request1 = $.ajax({
		url: 'php/functions.php',
		type: 'GET',
		dataType: 'json',
		data: {
			action: "getdata"
		}
	});

	request1.done(function(data) {
		$('#status').hide();
		$('#datawrap').show();
		$.each(data, function(i, item) {
			var entry = data[i];
			addEntry(entry.id, entry.date, entry.temp, entry.city, entry.image, entry.comment);
		});
	});

	request1.fail(function(jqXHR, textStatus) {
		$('#status').text("Request failed: " + textStatus);
		console.log("Received: " + JSON.stringify(jqXHR));
	});

	var citiesJSON = {};
	var request2 = $.ajax({
		url: 'php/functions.php',
		type: 'GET',
		dataType: 'json',
		data: {
			action: "getcities"
		}
	});

	request2.done(function(data) {
		$('select').each(function() {
			addCities($(this), data);
		});
	});

	request2.fail(function(jqXHR, textStatus) {
		console.log("Request failed: " + textStatus);
		console.log("Received: " + JSON.stringify(jqXHR));
	});

	function addEntry(id, date, temp, city, image, comment) {
		var tr = $('
' +
			'<form class="form-horizontal" role="form" action="" method="post" class="editform">' +
			'' + formatDate(date) + '	' +
			'<input type="date" class="form-control" value="' + date + '" />	' +
			'' + temp + '° C	' +
			'<input type="number" class="form-control" value="' + temp + '" min="-72" max="100" /> °C	' +
			'' + city + '	' +
			'' +
				'<select class="form-control">' +
				'</select>' +
			'	' +
			'	' +
			'<button type="button" class="btn btn-primary"></button>	' +
			'' + comment + '	' +
			'<input type="text" class="form-control" value="' + comment + '" />	' +
			'' +
				'<button type="button" class="btn btn-primary btn-xs editlink"></button>' +
				'<button type="button" class="btn btn-danger btn-xs removelink" data-type="remove"></button>' +
			'	' +
			'' +
				'<button type="button" class="btn btn-success btn-xs savelink"></button>' +
				'<button type="button" class="btn btn-danger btn-xs removelink" data-type="remove"></button>' +
			'	' +
			'</form>' +
			'
').appendTo($('table tbody'));
		//console.log("id: " + id);
		addCities(tr.find('select'), citiesJSON);
	}

	function addCities(select, data) {
		//console.log(select);
		$('<option/>', {
			text: "Stadt",
			value: "",
			disabled: true
		}).appendTo(select);

		$.each(data, function(id, obj) {
			$('<option/>', {
				text: obj.name_long,
				name: obj.name_short,
				value: obj.id
			}).appendTo(select);
		});

		/*$(select).sort(function(a, b) {
			a = a.name;
			b = b.name;

			return a-b;
		});*/

		$('<option/>', {
			text: "Neue Stadt...",
			value: "neuestadt"
		}).appendTo(select);
	}

	function searchData() {
		var keyword = $('#searchform .searchbox').val();
		var request = $.ajax({
			url: 'php/functions.php',
			type: 'GET',
			dataType: 'json',
			data: {
				action: "searchcity",
				key: keyword
			}
		});

		request.done(function(data) {
			if (data.status === "success") {
				data = data.results;
				$('#results .panel-body').html("Suchergebnisse: ");
				$.each(data, function(id, obj) {
					$('#results .panel-body').append(obj.name_long + " ");
				});
				//console.log(data);
			} else {
				$('#results .panel-body').html(data.message);
			}
			$('#results').slideDown();
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});
	}

	function sendImage(form) {

	}

	function sendEntries(form) {
		var JSONdata = {};
		JSONdata['id'] = generateID();
		JSONdata['user'] = "lkf4vyxn9";
		JSONdata['image'] = "mitte20141001.jpg";
		$(form + ' *').filter(':input').each(function(i, obj) {
			JSONdata[$(obj).attr('name')] = $(obj).val();
			delete JSONdata['undefined'];
		});
		//console.log(JSONdata);
		var formId = $('table tr').length;
		var request = $.ajax({
			type: 'POST',
			dataType: 'json',
			url: 'php/functions.php',
			data: JSON.stringify({
				"type": "entries",
				"data": JSONdata
			}),
			contentType: "application/json"
		});

		request.done(function() {
			addEntry(JSONdata['id'], JSONdata['date'], JSONdata['temp'], $(form + ' option:selected').text(), JSONdata['image'], JSONdata['comment']);
		});

		request.fail(function(jqXHR, textStatus) {
			console.log("Request failed: " + textStatus);
			console.log("Received: " + JSON.stringify(jqXHR));
		});
	}

	/**
	* Function formatValue
	*
	* Returns a String with umlauts replaced to ae, oe, etc.
	*
	* @param String str The string with umlauts
	* @return The replaced string without umlauts
	*/

	function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
		return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
	}

	/**
	* Function formatDate
	*
	* Returns a date String in the dd.mm.yyyy format
	*
	* @param String date The date in the format yyyy-mm-dd
	* @return The replaced date string
	*/

	function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
		return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
	}

	function generateID() {
		return Math.random().toString(36).substr(2, 9);
	}

	var mapOptions = {
		center: {
			lat: 52.5167,
			lng: 13.3833
		},
		zoom: 13,
		disableDefaultUI: true,
		draggable: false,
		scrollwheel: false,
		disableDoubleClickZoom: true
	};
	var map = new google.maps.Map(document.getElementById('map'), mapOptions);
	$('#map').fadeIn();
});
<|endoftext|>