<commit_before>angular.module('session', ['bbc.session'])
    .controller('SessionCtrl', function ($scope, $bbcSession) {
        $scope.dataMessages = [];

        $scope.clearData = function () {
            $scope.dataMessages = [];
        };

        $scope.getData = function () {

            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0) {

                $scope.dataMessages.push('SENT: ' + 'get all session data');

                $bbcSession.getData(function (error, result) {
                    if (error) {
                        $scope.dataMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
            else {

                $scope.dataMessages.push('SENT: ' + 'get key: ' + $scope.data.key);

                $bbcSession.getData($scope.data.key, function (error, result) {
                    if (error) {
                        $scope.dataMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
        };

        $scope.setData = function () {
            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0 || typeof $scope.data.value === 'undefined' ||
                $scope.data.value.length === 0) {

                $scope.dataMessages.push({class: 'error', message: 'ERROR: ' + 'for save in session is key and value required'});
            }
            else {

                $scope.dataMessages.push({class: 'sent', message: 'SENT: ' + 'setData' + 'key:' + $scope.data.key + ' value:' + $scope.data.value});

                if ($rootScope.socketEnabled) {
                    $rootScope.socketEnabled = false;
                }

                $bbcSession.setData($scope.data.key, $scope.data.value, function (error, result) {
                    if (error) {
                        $scope.activityMessages.push({class: 'error', message: error});
                    }
                    else {
                        $scope.dataMessages.push({class: 'response', message: 'RESPONSE: ' + result});
                    }
                });
            }
        };

        $scope.deleteData = function () {
            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0) {

                $scope.dataMessages.push({class: 'sent', message: 'SENT: ' + 'set no key, delete all objects in session.data'});

                if ($rootScope.socketEnabled) {
                    $rootScope.socketEnabled = false;
                }

                $bbcSession.deleteData(function (error, result) {
                    if (error) {
                        $scope.activityMessages.push({class: 'error', message: error});
                    }
                    else {
                        $scope.dataMessages.push({class: 'response', message: 'RESPONSE: ' + result});
                    }
                });
            }
            else {

                $scope.dataMessages.push({class: 'sent', message: 'SENT: ' + 'delete ' + $scope.data.key + ' in session.data'});

                if ($rootScope.socketEnabled) {
                    $rootScope.socketEnabled = false;
                }

                $bbcSession.deleteData($scope.data.key, function (error, result) {
                    if (error) {
                        $scope.activityMessages.push({class: 'error', message: error});
                    }
                    else {
                        $scope.dataMessages.push({class: 'response', message: 'RESPONSE: ' + result});
                    }
                });
            }
        };
    });
<commit_msg>docs(session): update guide<commit_after>angular.module('session', ['bbc.session'])
    .controller('SessionCtrl', function ($scope, $bbcSession) {
        $scope.dataMessages = [];

        $scope.clearData = function () {
            $scope.dataMessages = [];
        };

        $scope.getData = function () {

            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0) {

                $scope.dataMessages.push('SENT: ' + 'get all session data');

                $bbcSession.getData(function (error, result) {
                    if (error) {
                        $scope.dataMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
            else {

                $scope.dataMessages.push('SENT: ' + 'get key: ' + $scope.data.key);

                $bbcSession.getData($scope.data.key, function (error, result) {
                    if (error) {
                        $scope.dataMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
        };

        $scope.setData = function () {
            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0 || typeof $scope.data.value === 'undefined' ||
                $scope.data.value.length === 0) {

                $scope.dataMessages.push('ERROR: ' +
                    'for save in session is key and value required');
            }
            else {

                $scope.dataMessages.push('SENT: ' + 'setData' + 'key:' + $scope.data.key +
                    ' value:' + $scope.data.value);

                $bbcSession.setData($scope.data.key, $scope.data.value, function (error, result) {
                    if (error) {
                        $scope.activityMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
        };

        $scope.deleteData = function () {
            if (typeof $scope.data === 'undefined' || typeof $scope.data.key === 'undefined' ||
                $scope.data.key.length === 0) {

                $scope.dataMessages.push('SENT: ' +
                    'set no key, delete all objects in session.data');

                $bbcSession.deleteData(function (error, result) {
                    if (error) {
                        $scope.activityMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
            else {

                $scope.dataMessages.push('SENT: ' + 'delete ' +
                    $scope.data.key + ' in session.data');

                $bbcSession.deleteData($scope.data.key, function (error, result) {
                    if (error) {
                        $scope.activityMessages.push(error);
                    }
                    else {
                        $scope.dataMessages.push('RESPONSE: ');
                        $scope.dataMessages.push(result);
                    }
                });
            }
        };
    });
<|endoftext|>


<commit_before>var curveFactor = 0.4;

var snapped;
var dockPressed = false;
var nodeId;
var snapNodeId;
var dockSide;
var snapDockSide;
var dockPos;

var state;
var currentStartDock;
var currentSnapDock;

var snapDockPos;
var snapDockX;
var snapDockY;

var initialNode;
var initialDock;

function updateInteraction() {

    // initialize selection of nodes
    mh.select()

    var startX;
    var startY;
    var diffX;
    var diffY;
    var nodeId;
    var linkId;
    var links = {};

    $('.container').draggable({
        handle: ".header",
        // the following is to be avoided if no links are connected to this node.
        // $('path[class*='+nodeId+']').length gives the number of links connected to this node
        start: function() {
            nodeId = $(this).attr('class').split(' ')[1];
            nbDocks = $('path[class*='+nodeId+']').length

            // correct way of accessing the data
            node[nodeId].select();
            //

            links = {};
            startX = $(this).offset().left;
            startY = $(this).offset().top;

            if(nbDocks) {

                for (var i = 0; i < nbDocks; i++) {
                    var pathElement = $('path[class*='+nodeId+']')[i]

                    var pathClass = pathElement.getAttribute('class')
                    var side = pathClass.substring(0,nodeId.length) == nodeId

                    linkId = pathElement.getAttribute('id');
                    path = pathElement.getAttribute('d').split(' ');

                    firstCoor = path[0].substring(1).split(',')
                    lastCoor = path[path.length-1].substring(1).split(',')
                    links[linkId] = [side,firstCoor[0],firstCoor[1],lastCoor[0],lastCoor[1]]

                }
            }

        },
        drag: function() {

                if(nbDocks) {

                    var offset = $(this).offset();
                    diffX = startX - offset.left;
                    diffY = startY - offset.top;

                    // apply this difference to every link that is connected to this node
                    for(link in links) {
                        coords = links[link];
                        if(coords[0]) {
                            updateCurve(link,[parseInt(coords[1])-diffX,parseInt(coords[2])-diffY,parseInt(coords[3]),parseInt(coords[4])])
                        } else {
                            updateCurve(link,[parseInt(coords[1]),parseInt(coords[2]),parseInt(coords[3])-diffX,parseInt(coords[4])-diffY])
                        }

                    }

                }
        }

    });

    if($('.dock').length) {
        $('.dock').unbind('mousedown')
        $('.snapDock').unbind('mousedown')
        $('body').unbind('mousemove')
        $('body').unbind('mousedown');
    }

    $('.snapDock').mousedown(function() {

        state = $(this).attr('state');

        nodeId = getNodeId(this);
        dockId = getDockId(this);

        if (state) {
            //change the state back to undefined

            $(this).attr('state','')
            state = '';

            // this dock is already linked to another
            var currentSocketId = nodeId + '-' + dockId;
            var pathId =  $('path[class*='+currentSocketId+']').attr('id');

            var socketIds = pathId.split('-');
            var firstSocketId = socketIds[0] + '-' + socketIds[1];
            var secondSocketId = socketIds[2] + '-' + socketIds[3];

            var initialSocketId;
            if(currentSocketId == firstSocketId) {
                initialSocketId = secondSocketId;
            } else {
                initialSocketId = firstSocketId;
            }

            [nodeId,dockId] = initialSocketId.split('-');

            var coords = $('.' + nodeId + ' ' + '.' + dockId + ' .snapDock').offset()
            dockX = coords.left+20; dockY = coords.top+20

            dockSide = 'right'
            // change the id of this path back to a undetermined end socket
            $('path[class*='+currentSocketId+']').attr('id',initialSocketId);

        } else {

            dockSide = getDockSide(this);
            dockPos = $(this).offset();
            dockX = dockPos.left + 20;
            dockY = dockPos.top + 20;

        }

        dockPressed = true;
        snapped = false;

        currentStartDock = this;

        if(!state) {

            $('.snapDock').mouseenter(function() {

                currentSnapDock = this;

                $('body').unbind('mousemove');

                snapNodeId = getNodeId(this);
                snapDockId = getDockId(this);
                snapDockSide = getDockSide(this);
                if((dockSide != snapDockSide) && (nodeId != snapNodeId)) {

                    // position of the dock to snap to
                    snapDockPos = $(this).offset();
                    snapDockX = snapDockPos.left + 20;
                    snapDockY = snapDockPos.top + 20;

                    snapped = true;

                    drawCurve(nodeId+'-'+dockId,dockSide,dockX,dockY,snapDockX,snapDockY);

                } else {

                    $('body').mousemove(function() {

                        drawCurve(nodeId+'-'+dockId,dockSide,dockX,dockY,event.pageX, event.pageY);

                    })

                }

            })

        }

        $('.snapDock').mouseleave(function() {

            snapped = false;

            $('body').unbind('mousemove');

            $('body').mousemove(function() {

                var idSearch = nodeId + '-' + dockId;

                drawCurve(idSearch,dockSide,dockX,dockY,event.pageX, event.pageY);

            })

        })

        $('body').mouseup(function() {

                $('body').unbind('mousemove')
                $('body').unbind('mouseup')
                $('.snapDock').unbind('mouseenter')
                $('.snapDock').unbind('mouseleave')

                if(!snapped) {

                    // actually delete it
                    removeCurve(initialNode+'-'+initialDock)
                    removeCurve(nodeId+'-'+dockId);

                } else if(snapped) {

                    // link is snapped and mouse is up
                    var startId = nodeId + '-' + dockId;
                    var endId = snapNodeId + '-' + snapDockId;
                    var pathId = (dockSide == 'left')  ? endId + '-' + startId : startId + '-' + endId;

                    if(exist('#'+pathId)) {
                        // link already exists, remove current displayed curve (already registered in node)

                        removeCurve(startId);

                    } else {
                        // link doesn't exist, so we can save it by changing the id name and sending the connection to node

                        // change the id of this link since it has now a determined dock and node start and end point

                        var pathClass;
                        if(dockSide == 'left') {
                            pathClass = endId + ' ' + startId
                            $(currentStartDock).attr('state', true);
                        } else {
                            pathClass = startId + ' ' + endId
                            $(currentSnapDock).attr('state', true);
                        }

                        $('#'+startId).attr('id',pathId).attr('class',pathClass)

                        // register the connection in the node object
                        //node.connect(nodeId,dockId,snapNodeId,snapDockId,[dockX,dockY,snapDockX,snapDockY]);

                    }

                }

            })

    })

}

var getDockSide = function(element) {
    return $(element).parent().attr('class').split(' ')[2];
}

var getNodeId = function(element) {
    return $(element).parents('.container').attr('class').split(' ')[1]
}
var getDockId = function(element) {
    return $(element).parents('.parameter').attr('class').split(' ')[1]
}
<commit_msg>fix: when link is dropped on an occupied dock the 'old link' gets deleted<commit_after>var curveFactor = 0.4;

var snapped;
var dockPressed = false;
var nodeId;
var snapNodeId;
var dockSide;
var snapDockSide;
var dockPos;

var state;
var currentStartDock;
var currentSnapDock;

var snapDockPos;
var snapDockX;
var snapDockY;

var initialNode;
var initialDock;

function updateInteraction() {

    // initialize selection of nodes
    mh.select()

    var startX;
    var startY;
    var diffX;
    var diffY;
    var nodeId;
    var linkId;
    var links = {};

    $('.container').draggable({
        handle: ".header",
        // the following is to be avoided if no links are connected to this node.
        // $('path[class*='+nodeId+']').length gives the number of links connected to this node
        start: function() {
            nodeId = $(this).attr('class').split(' ')[1];
            nbDocks = $('path[class*='+nodeId+']').length

            // correct way of accessing the data
            node[nodeId].select();
            //

            links = {};
            startX = $(this).offset().left;
            startY = $(this).offset().top;

            if(nbDocks) {

                for (var i = 0; i < nbDocks; i++) {
                    var pathElement = $('path[class*='+nodeId+']')[i]

                    var pathClass = pathElement.getAttribute('class')
                    var side = pathClass.substring(0,nodeId.length) == nodeId

                    linkId = pathElement.getAttribute('id');
                    path = pathElement.getAttribute('d').split(' ');

                    firstCoor = path[0].substring(1).split(',')
                    lastCoor = path[path.length-1].substring(1).split(',')
                    links[linkId] = [side,firstCoor[0],firstCoor[1],lastCoor[0],lastCoor[1]]

                }
            }

        },
        drag: function() {

                if(nbDocks) {

                    var offset = $(this).offset();
                    diffX = startX - offset.left;
                    diffY = startY - offset.top;

                    // apply this difference to every link that is connected to this node
                    for(link in links) {
                        coords = links[link];
                        if(coords[0]) {
                            updateCurve(link,[parseInt(coords[1])-diffX,parseInt(coords[2])-diffY,parseInt(coords[3]),parseInt(coords[4])])
                        } else {
                            updateCurve(link,[parseInt(coords[1]),parseInt(coords[2]),parseInt(coords[3])-diffX,parseInt(coords[4])-diffY])
                        }

                    }

                }
        }

    });

    if($('.dock').length) {
        $('.dock').unbind('mousedown')
        $('.snapDock').unbind('mousedown')
        $('body').unbind('mousemove')
        $('body').unbind('mousedown');
    }

    $('.snapDock').mousedown(function() {

        state = $(this).attr('state');
        nodeId = getNodeId(this);
        dockId = getDockId(this);

        if (state) {
            //change the state back to undefined

            $(this).attr('state','')
            state = '';

            // this dock is already linked to another
            var currentSocketId = nodeId + '-' + dockId;
            var pathId =  $('path[class*='+currentSocketId+']').attr('id');

            var socketIds = pathId.split('-');
            var firstSocketId = socketIds[0] + '-' + socketIds[1];
            var secondSocketId = socketIds[2] + '-' + socketIds[3];

            var initialSocketId;
            if(currentSocketId == firstSocketId) {
                initialSocketId = secondSocketId;
            } else {
                initialSocketId = firstSocketId;
            }

            [nodeId,dockId] = initialSocketId.split('-');

            var coords = $('.' + nodeId + ' ' + '.' + dockId + ' .snapDock').offset()
            dockX = coords.left+20; dockY = coords.top+20

            dockSide = 'right'
            // change the id of this path back to a undetermined end socket
            $('path[class*='+currentSocketId+']').attr('id',initialSocketId);

        } else {

            dockSide = getDockSide(this);
            dockPos = $(this).offset();
            dockX = dockPos.left + 20;
            dockY = dockPos.top + 20;

        }

        dockPressed = true;
        snapped = false;

        currentStartDock = this;

        if(!state) {

            $('.snapDock').mouseenter(function() {

                currentSnapDock = this;

                $('body').unbind('mousemove');

                snapNodeId = getNodeId(this);
                snapDockId = getDockId(this);
                snapDockSide = getDockSide(this);
                thereAnotherLink = $(this).attr('state') || false;

                if((dockSide != snapDockSide) && (nodeId != snapNodeId)) {

                    // position of the dock to snap to
                    snapDockPos = $(this).offset();
                    snapDockX = snapDockPos.left + 20;
                    snapDockY = snapDockPos.top + 20;

                    snapped = true;

                    drawCurve(nodeId+'-'+dockId,dockSide,dockX,dockY,snapDockX,snapDockY);

                } else {

                    $('body').mousemove(function() {

                        drawCurve(nodeId+'-'+dockId,dockSide,dockX,dockY,event.pageX, event.pageY);

                    })

                }

            })

        }

        $('.snapDock').mouseleave(function() {

            snapped = false;

            $('body').unbind('mousemove');

            $('body').mousemove(function() {

                var idSearch = nodeId + '-' + dockId;

                drawCurve(idSearch,dockSide,dockX,dockY,event.pageX, event.pageY);

            })

        })

        $('body').mouseup(function() {

                $('body').unbind('mousemove')
                $('body').unbind('mouseup')
                $('.snapDock').unbind('mouseenter')
                $('.snapDock').unbind('mouseleave')

                if(!snapped) {

                    // actually delete it
                    removeCurve(initialNode+'-'+initialDock)
                    removeCurve(nodeId+'-'+dockId);

                } else if(snapped) {

                    if(thereAnotherLink) {
                        $('path[class*="'+snapNodeId+'-'+snapDockId+'"]').remove();
                    }

                    // link is snapped and mouse is up
                    var startId = nodeId + '-' + dockId;
                    var endId = snapNodeId + '-' + snapDockId;
                    var pathId = (dockSide == 'left')  ? endId + '-' + startId : startId + '-' + endId;

                    if(exist('#'+pathId)) {
                        // link already exists, remove current displayed curve (already registered in node)

                        removeCurve(startId);

                    } else {
                        // link doesn't exist, so we can save it by changing the id name and sending the connection to node

                        // change the id of this link since it has now a determined dock and node start and end point

                        var pathClass;
                        if(dockSide == 'left') {
                            pathClass = endId + ' ' + startId
                            $(currentStartDock).attr('state', true);
                        } else {
                            pathClass = startId + ' ' + endId
                            $(currentSnapDock).attr('state', true);
                        }

                        $('#'+startId).attr('id',pathId).attr('class',pathClass)

                        // register the connection in the node object
                        //node.connect(nodeId,dockId,snapNodeId,snapDockId,[dockX,dockY,snapDockX,snapDockY]);

                    }

                }

            })

    })

}

var getDockSide = function(element) {
    return $(element).parent().attr('class').split(' ')[2];
}

var getNodeId = function(element) {
    return $(element).parents('.container').attr('class').split(' ')[1]
}
var getDockId = function(element) {
    return $(element).parents('.parameter').attr('class').split(' ')[1]
}
<|endoftext|>


<commit_before>// Dots and lines

$(function(){
	var canvas = document.querySelector('canvas'),
      ctx = canvas.getContext('2d'),
      color = 'black';
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	canvas.style.display = 'block';
	ctx.fillStyle = color;
	ctx.lineWidth = .3;
	ctx.strokeStyle = color;
	ctx.font = "40pt Roboto";

	var mousePosition = {
		x: 30 * canvas.width / 100,
		y: 30 * canvas.height / 100
	};

	var dots = {
		nb: 150,
		distance: 80,
		d_radius: 150,
		array: []
	};

	function Dot(){
		this.x = Math.random() * canvas.width;
		this.y = Math.random() * canvas.height;

		this.vx = -.5 + Math.random();
		this.vy = -.5 + Math.random();

		this.radius = Math.random();
	}

	Dot.prototype = {
		create: function(){
			ctx.beginPath();
			ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
			ctx.fill();
		},

		animate: function(){
			for(i = 0; i < dots.nb; i++){

				var dot = dots.array[i];

				if(dot.y < 0 || dot.y > canvas.height){
					dot.vx = dot.vx;
					dot.vy = - dot.vy;
				}
				else if(dot.x < 0 || dot.x > canvas.width){
					dot.vx = - dot.vx;
					dot.vy = dot.vy;
				}
				dot.x += dot.vx;
				dot.y += dot.vy;
			}
		},

		line: function(){
			for(i = 0; i < dots.nb; i++){
				for(j = 0; j < dots.nb; j++){
					i_dot = dots.array[i];
					j_dot = dots.array[j];

					if((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > - dots.distance && (i_dot.y - j_dot.y) > - dots.distance){
						if((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > - dots.d_radius && (i_dot.y - mousePosition.y) > - dots.d_radius){
							ctx.beginPath();
							ctx.moveTo(i_dot.x, i_dot.y);
							ctx.lineTo(j_dot.x, j_dot.y);
							ctx.stroke();
							ctx.closePath();
						}
					}
				}
			}
		}
	};

	function createDots(){

		ctx.clearRect(0, 0, canvas.width, canvas.height);
		for(i = 0; i < dots.nb; i++){
			dots.array.push(new Dot());
			dot = dots.array[i];

			dot.create();
		}

		dot.line();
		dot.animate();
		ctx.fillText("Ananya Cleetus", canvas.width / 2, canvas.height / 2)
		ctx.fillText("Roboticist. Programmer. Engineer.", canvas.width / 2, canvas.height / 2 +20)
		ctx.textAlign = 'center';
		ctx.textBaseline = 'middle';

		ctx.textAlign = 'center';
		ctx.textBaseline = 'middle';

	}

	$('canvas').on('mousemove mouseleave', function(e){
		if(e.type == 'mousemove'){
			mousePosition.x = e.pageX;
			mousePosition.y = e.pageY;
		}
		if(e.type == 'mouseleave'){
			mousePosition.x = canvas.width / 2;
			mousePosition.y = canvas.height / 2;
		}
	});
	setInterval(createDots, 1000/30);

});
<commit_msg>Update index.js<commit_after>// Dots and lines

$(function(){
	var canvas = document.querySelector('canvas'),
      ctx = canvas.getContext('2d'),
      color = 'black';
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	canvas.style.display = 'block';
	ctx.fillStyle = color;
	ctx.lineWidth = .3;
	ctx.strokeStyle = color;
//	ctx.font = "40pt Roboto";

	var mousePosition = {
		x: 30 * canvas.width / 100,
		y: 30 * canvas.height / 100
	};

	var dots = {
		nb: 150,
		distance: 80,
		d_radius: 150,
		array: []
	};

	function Dot(){
		this.x = Math.random() * canvas.width;
		this.y = Math.random() * canvas.height;

		this.vx = -.5 + Math.random();
		this.vy = -.5 + Math.random();

		this.radius = Math.random();
	}

	Dot.prototype = {
		create: function(){
			ctx.beginPath();
			ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
			ctx.fill();
		},

		animate: function(){
			for(i = 0; i < dots.nb; i++){

				var dot = dots.array[i];

				if(dot.y < 0 || dot.y > canvas.height){
					dot.vx = dot.vx;
					dot.vy = - dot.vy;
				}
				else if(dot.x < 0 || dot.x > canvas.width){
					dot.vx = - dot.vx;
					dot.vy = dot.vy;
				}
				dot.x += dot.vx;
				dot.y += dot.vy;
			}
		},

		line: function(){
			for(i = 0; i < dots.nb; i++){
				for(j = 0; j < dots.nb; j++){
					i_dot = dots.array[i];
					j_dot = dots.array[j];

					if((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > - dots.distance && (i_dot.y - j_dot.y) > - dots.distance){
						if((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > - dots.d_radius && (i_dot.y - mousePosition.y) > - dots.d_radius){
							ctx.beginPath();
							ctx.moveTo(i_dot.x, i_dot.y);
							ctx.lineTo(j_dot.x, j_dot.y);
							ctx.stroke();
							ctx.closePath();
						}
					}
				}
			}
		}
	};

	function createDots(){

		ctx.clearRect(0, 0, canvas.width, canvas.height);
		for(i = 0; i < dots.nb; i++){
			dots.array.push(new Dot());
			dot = dots.array[i];

			dot.create();
		}

		dot.line();
		dot.animate();

		ctx.font = "40pt Roboto";
		ctx.fillText("Ananya Cleetus", canvas.width / 2, canvas.height / 2)
		ctx.font = "20pt Roboto";
		ctx.fillText("Roboticist. Programmer. Engineer.", canvas.width / 2, canvas.height / 2 +20)
		ctx.textAlign = 'center';
		ctx.textBaseline = 'middle';

		ctx.textAlign = 'center';
		ctx.textBaseline = 'middle';

	}

	$('canvas').on('mousemove mouseleave', function(e){
		if(e.type == 'mousemove'){
			mousePosition.x = e.pageX;
			mousePosition.y = e.pageY;
		}
		if(e.type == 'mouseleave'){
			mousePosition.x = canvas.width / 2;
			mousePosition.y = canvas.height / 2;
		}
	});
	setInterval(createDots, 1000/30);

});
<|endoftext|>


<commit_before>//Module for input checking and parsing
var Worker = (function() {
  var w={};

  //Divides input up into Sections and Singles
  w.parse = function(value) {
    if (!value) return 0;

    var sections = [];

    //Remove excess whitespace
    value.replace(/\s/g, '');

    //get rid of unnecessary brackets surrounding the section
    while (value.substr(0, 1)=="(" && value.substr(value.length-1, 1)==")") {
      var openBrackets=1;
      for (var i=1; i<value.length&&openBrackets>0; i++) {
        if (value.substr(i, 1)=="(") openBrackets++;
        if (value.substr(i, 1)==")") openBrackets--;
      }
      i-=1;
      if (openBrackets!=0 || i!=value.length-1) {
        break;
      } else {
        value=value.substring(1, value.length-1);
      }
    }

    var addition = value.lastIndexOf("+");
    var subtraction = value.lastIndexOf("-");
    var multiplication = value.lastIndexOf("*");
    var division = value.lastIndexOf("/");
    var exponent = value.indexOf("^");
    var bracket1 = value.lastIndexOf("(");

    /* make sure we pick out operators that AREN'T IN BRACKETS
    by checking if the signs are in brackets and searching
    again if they are */
    var redos=[0, 0, 0, 0, 0, 0];
    if (addition==-1) redos[0]=1;
    if (subtraction==-1) redos[1]=1;
    if (multiplication==-1) redos[2]=1;
    if (division==-1) redos[3]=1;
    if (exponent==-1) redos[4]=1;
    if (bracket1==-1) redos[5]=1;
    while (redos[0]==0 || redos[1]==0 || redos[2]==0 || redos[3]==0 || redos[4]==0 || redos[5]==0) {
      var openBrackets=0;
      for (var i=0; i<value.length; i++) {
        if (value.substr(i, 1)=="(") {
          if (i==bracket1) {
            if (openBrackets>0) {
              bracket1 = value.substring(0, bracket1).lastIndexOf("(");
            } else {
              redos[5]=1;
            }
          }
          openBrackets++;
        } else if (value.substr(i, 1)==")") {
          openBrackets--;
        } else if (i==addition) {
          if (openBrackets>0) {
            addition = value.substring(0, addition).lastIndexOf("+");
          } else {
            redos[0]=1;
          }
        } else if (i==subtraction) {
          if (openBrackets>0) {
            subtraction = value.substring(0, subtraction).lastIndexOf("-");
          } else {
            redos[1]=1;
          }
        } else if (i==multiplication) {
          if (openBrackets>0) {
            multiplication = value.substring(0, multiplication).lastIndexOf("*");
          } else {
            redos[2]=1;
          }
        } else if (i==division) {
          if (openBrackets>0) {
            division = value.substring(0, division).lastIndexOf("/");
          } else {
            redos[3]=1;
          }
        } else if (i==exponent) {
          if (openBrackets>0) {
            var nextExponent = value.substring(exponent+1).indexOf("^");
            if (nextExponent==-1) {
              exponent=-1;
            } else {
              exponent = (exponent+1+value.substring(exponent+1).indexOf("^"));
            }
          } else {
            redos[4]=1;
          }
        }
      }

      if (addition==-1) redos[0]=1;
      if (subtraction==-1) redos[1]=1;
      if (multiplication==-1) redos[2]=1;
      if (division==-1) redos[3]=1;
      if (exponent==-1) redos[4]=1;
      if (bracket1==-1) redos[5]=1;
    }

    console.log(value);

    //reverse BEDMAS
    if (addition != -1 && (subtraction == -1 || addition>subtraction)) {
      sections.push(new Segment(value.substring(0, addition)));
      sections.push(new Single(value.substring(addition, addition+1), "operator"));
      sections.push(new Segment(value.substring(addition+1)));
    } else if (subtraction != -1) {
      sections.push(new Segment(value.substring(0, subtraction)));
      sections.push(new Single(value.substring(subtraction, subtraction+1), "operator"));
      sections.push(new Segment(value.substring(subtraction+1)));
    } else if (multiplication != -1 && (division == -1 || multiplication>division)) {
      sections.push(new Segment(value.substring(0, multiplication)));
      sections.push(new Single(value.substring(multiplication, multiplication+1), "operator"));
      sections.push(new Segment(value.substring(multiplication+1)));
    } else if (division != -1) {
      sections.push(new Segment(value.substring(0, division)));
      sections.push(new Single(value.substring(division, division+1), "operator"));
      sections.push(new Segment(value.substring(division+1)));
    } else if (exponent != -1) {
      sections.push(new Segment(value.substring(0, exponent)));
      sections.push(new Single(value.substring(exponent, exponent+1), "operator"));
      sections.push(new Segment(value.substring(exponent+1)));
    } else if (bracket1 != -1) {
      var openBrackets=1;
      for (var i=bracket1+1; i<value.length&&openBrackets>0; i++) {
        if (value.substr(i, 1)=="(") openBrackets++;
        if (value.substr(i, 1)==")") openBrackets--;
      }
      if (openBrackets==0) {
        var bracket2=i-1;
        if (bracket1>0) sections.push(new Segment(value.substring(0, bracket1)));
        if (bracket2-bracket1!=1) sections.push(new Segment(value.substring(bracket1+1, bracket2)));
        if (bracket2!=value.length-1) sections.push(new Segment(value.substring(bracket2+1)));
      } else {
        console.log("Brackets nesting error: " + value);
        return 0;
      }
    } else {
      sections.push(new Single(value, "value"));
    }

    return sections;
  };

  //Checks to see if brackets are properly nested in a string
  w.properBrackets = function(value) {
    var openBrackets=0;
    for (var i=0; i<value.length; i++) {
      if (value.substr(i, 1)=="(") openBrackets++;
      if (value.substr(i, 1)==")") openBrackets--;
    }
    return openBrackets==0;
  };

  return w;
}());

//Class for a single number or operator
function Single(value, type) {
  this.value = value;
  this.type = type;
  this.solve = function() {
    if (this.type == "value") {
      return parseFloat(this.value);
    } else {
      return 0;
    }
  };
  this.display = function() {
    return this.value;
  };
  this.pretty = function() {
    var str="
";
    if (this.value!="/" && this.value!="^" && this.value!="*") {
      str+= this.value;
    }
    if (this.value=="*") {
      str += "&times";
    }
    str+="
";
    return str;
  }
}

//Class for a segment of math (a container)
function Segment(value) {
  this.sections = value?Worker.parse(value):[];
  this.type = "section";

  //Recursively solve children
  this.solve = function() {
    var i=0;
    var value=0;
    while (i<this.sections.length) {
      if (i+1>=this.sections.length) {
        value = this.sections[i].solve();
        i++;
      } else if (this.sections[i+1].type=="operator") {
        if (this.sections[i+1].value == "+") {
          value += this.sections[i].solve() + this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "-") {
          value += this.sections[i].solve() - this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "*") {
          value += this.sections[i].solve() * this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "/") {
          value += this.sections[i].solve() / this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "^") {
          value += Math.pow(this.sections[i].solve(), this.sections[i+2].solve());
        }
        i+=3;
      } else {
        value += this.sections[i].solve() * this.sections[i+1].solve();
        i+=2;
      }
    }
    return value;
  };

  //Display grouped blocks
  this.display = function() {
    var str="";
    for (var i=0; i<this.sections.length; i++) {
      str+="
" + this.sections[i].display();
      if (this.sections[i].type=="section") str+= "
= " + this.sections[i].solve() + "
";
      str+="
";
    }
    return str;
  };

  this.pretty = function(css) {
    var str="
";
    for (var i=0; i<this.sections.length; i++) {
      if ((i+1<this.sections.length && this.sections[i+1].type!="operator")||(i-1>=0 && this.sections[i-1].type!="operator")) {
        str+=this.sections[i].pretty("brackets");
      } else {
        str+=this.sections[i].pretty();
      }
    }
    str+="
";
    return str;
  };
}

function simplifyText(event) {
  var input = document.getElementById("input").value;
  if (Worker.properBrackets(input)) {
    document.getElementById("wrapper").className="";
    var timer = setTimeout(function() {
      var expression = new Segment(input);
      document.getElementById("result").innerHTML = expression.pretty("middle") + "
" + expression.display() + "

= " + expression.solve() + "
";
      var matches = document.querySelectorAll("[val='/']");
      var i;
      for (i=0; i<matches.length; i++) {
        matches[i].previousSibling.style.verticalAlign = "bottom";
      }
      matches = document.querySelectorAll("[val='^']");
      for (i=0; i<matches.length; i++) {
        matches[i].previousSibling.style.verticalAlign = "middle";
        if (matches[i].previousSibling.childNodes.length>1) {
          matches[i].previousSibling.classList.add("brackets");
        }
      }
      document.getElementById("wrapper").className="solved";
    }, 800);
  } else {
    document.getElementById("result").innerHTML = "
Error: Improperly nested brackets. Remember to only use round brackets and close all opened brackets.
";
  }
}

window.onload = function() {
  document.getElementById("simplify").addEventListener("click", simplifyText);
  simplifyText();
};<commit_msg>v1.1<commit_after>//Module for input checking and parsing
var XCalc = (function() {
  var worker={};

  //removes unnecessary brackets around a string
  worker.removeBrackets = function(value) {
    if (!value) return "";

    //While there are brackets around the string
    while (value.substr(0, 1)=="(" && value.substr(value.length-1, 1)==")") {
      var openBrackets=1;

      //See if the end bracket closes the opening bracket or not
      for (var i=1; i<value.length&&openBrackets>0; i++) {
        if (value.substr(i, 1)=="(") openBrackets++;
        if (value.substr(i, 1)==")") openBrackets--;
      }
      i-=1;

      //If it corresponds to different brackets, do nothing
      if (openBrackets!=0 || i!=value.length-1) {
        break;

      //Otherwise, remove the brackets, continue loop to see if there are more
      } else {
        value=value.substring(1, value.length-1);
      }
    }

    return value;
  }

  //finds the last occurrence of an operator that is not in brackets
  worker.findLast = function(operator, value) {

    //Keep searching for the next last sign if the one found is within brackets
    var inBrackets=true;
    var index=-1;
    if (operator!="^") {
      index=value.lastIndexOf(operator)
    } else {
      index=value.indexOf(operator); //Look for the first instead of last if it's an exponent
    }

    while (inBrackets) {
      var openBrackets=0;

      //Find how many brackets are opened or closed at a given point in the string
      for (var i=0; i<value.length; i++) {
        if (value.substr(i, 1)=="(") {
          openBrackets++;
        } else if (value.substr(i, 1)==")") {
          openBrackets--;
        }

        if (i==index) {

          //If no brackets are open, break the loop.
          if (openBrackets==0 || (openBrackets==1 && operator=="(")) {
            inBrackets=false;
            break;

          //Otherwise, find the next operator, and loop through again to see if that one is in brackets
          } else {
            if (operator!="^") {
              index = value.substring(0, index).lastIndexOf(operator);
            } else {
              var nextOperator = value.substring(index+1).indexOf(operator);
              if (nextOperator==-1) {
                index=-1;
              } else {
                index = (index+1+value.substring(index+1).indexOf(operator));
              }
            }
          }
        }
      }

      //If no more operators are found, break the loop
      if (index==-1) {
        inBrackets=false;
      }
    }
    return index;
  };

  //Divides input up into Sections and Singles
  worker.parse = function(value) {
    if (!value) return 0;

    var sections = [];

    //Remove excess whitespace
    value = value.replace(/\s/g, '');

    //get rid of unnecessary brackets surrounding the section
    value = this.removeBrackets(value);

    //Find the last instance of each operator in the string
    var addition = this.findLast("+", value);
    var subtraction = this.findLast("-", value);
    var multiplication = this.findLast("*", value);
    var division = this.findLast("/", value);
    var exponent = this.findLast("^", value); //Find the first exponent, since those work in reverse
    var bracket1 = this.findLast("(", value);

    //Push back each half of the equation into a section, in reverse order of operations
    if (addition != -1 && (subtraction == -1 || addition>subtraction)) {
      sections.push(new Segment(value.substring(0, addition)));
      sections.push(new Single(value.substring(addition, addition+1), "operator"));
      sections.push(new Segment(value.substring(addition+1)));
    } else if (subtraction != -1) {
      sections.push(new Segment(value.substring(0, subtraction)));
      sections.push(new Single(value.substring(subtraction, subtraction+1), "operator"));
      sections.push(new Segment(value.substring(subtraction+1)));
    } else if (multiplication != -1 && (division == -1 || multiplication>division)) {
      sections.push(new Segment(value.substring(0, multiplication)));
      sections.push(new Single(value.substring(multiplication, multiplication+1), "operator"));
      sections.push(new Segment(value.substring(multiplication+1)));
    } else if (division != -1) {
      sections.push(new Segment(value.substring(0, division)));
      sections.push(new Single(value.substring(division, division+1), "operator"));
      sections.push(new Segment(value.substring(division+1)));
    } else if (exponent != -1) {
      sections.push(new Segment(value.substring(0, exponent)));
      sections.push(new Single(value.substring(exponent, exponent+1), "operator"));
      sections.push(new Segment(value.substring(exponent+1)));
    } else if (bracket1 != -1) {
      var openBrackets=1;
      for (var i=bracket1+1; i<value.length&&openBrackets>0; i++) {
        if (value.substr(i, 1)=="(") openBrackets++;
        if (value.substr(i, 1)==")") openBrackets--;
      }
      if (openBrackets==0) {
        var bracket2=i-1;
        if (bracket1>0) sections.push(new Segment(value.substring(0, bracket1)));
        if (bracket2-bracket1!=1) sections.push(new Segment(value.substring(bracket1+1, bracket2)));
        if (bracket2!=value.length-1) sections.push(new Segment(value.substring(bracket2+1)));
      } else {
        console.log("Brackets nesting error: " + value);
        return 0;
      }

    //If there are no operators, just push the value itself
    } else {
      sections.push(new Single(value, "value"));
    }

    return sections;
  };

  //Checks to see if brackets are properly nested in a string
  worker.properBrackets = function(value) {
    var openBrackets=0;
    for (var i=0; i<value.length; i++) {
      if (value.substr(i, 1)=="(") openBrackets++;
      if (value.substr(i, 1)==")") openBrackets--;
    }
    return openBrackets==0;
  };

  //Creates a new Section for an expression
  worker.createExpression = function(value) {
    if (this.properBrackets(value)) {
      return new Segment(value);
    } else {
      return 0;
    }
  }

  return worker;
}());

//Class for a single number or operator
function Single(value, type) {
  this.value = value;
  this.type = type;
  this.solve = function() {
    if (this.type == "value") {
      return parseFloat(this.value);
    } else {
      return 0;
    }
  };
  this.display = function() {
    return this.value;
  };
  this.pretty = function() {
    var str="
";
    if (this.value!="/" && this.value!="^" && this.value!="*") {
      str+= this.value;
    }
    if (this.value=="*") {
      str += "&times";
    }
    str+="
";
    return str;
  }
}

//Class for a segment of math (a container)
function Segment(value) {
  this.sections = value?XCalc.parse(value):[];
  this.type = "section";

  //Recursively solve children
  this.solve = function() {
    var i=0;
    var value=0;
    while (i<this.sections.length) {
      if (i+1>=this.sections.length) {
        value = this.sections[i].solve();
        i++;
      } else if (this.sections[i+1].type=="operator") {
        if (this.sections[i+1].value == "+") {
          value += this.sections[i].solve() + this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "-") {
          value += this.sections[i].solve() - this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "*") {
          value += this.sections[i].solve() * this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "/") {
          value += this.sections[i].solve() / this.sections[i+2].solve();
        } else if (this.sections[i+1].value == "^") {
          value += Math.pow(this.sections[i].solve(), this.sections[i+2].solve());
        }
        i+=3;
      } else {
        value += this.sections[i].solve() * this.sections[i+1].solve();
        i+=2;
      }
    }
    return value;
  };

  //Display grouped blocks
  this.display = function() {
    var str="";
    for (var i=0; i<this.sections.length; i++) {
      str+="
" + this.sections[i].display();
      if (this.sections[i].type=="section") str+= "
= " + this.sections[i].solve() + "
";
      str+="
";
    }
    return str;
  };

  this.pretty = function(css) {
    var str="
";
    for (var i=0; i<this.sections.length; i++) {
      if ((i+1<this.sections.length && this.sections[i+1].type!="operator")||(i-1>=0 && this.sections[i-1].type!="operator")) {
        str+=this.sections[i].pretty("brackets");
      } else {
        str+=this.sections[i].pretty();
      }
    }
    str+="
";
    return str;
  };
}

function simplifyText(event) {
  var input = document.getElementById("input").value;
  if (XCalc.properBrackets(input)) {
    document.getElementById("wrapper").className="";
    var timer = setTimeout(function() {
      var expression = new Segment(input);
      document.getElementById("result").innerHTML = expression.pretty("middle") + "
" + expression.display() + "

= " + expression.solve() + "
";
      var matches = document.querySelectorAll("[val='/']");
      var i;
      for (i=0; i<matches.length; i++) {
        matches[i].previousSibling.style.verticalAlign = "bottom";
      }
      matches = document.querySelectorAll("[val='^']");
      for (i=0; i<matches.length; i++) {
        matches[i].previousSibling.style.verticalAlign = "middle";
        if (matches[i].previousSibling.childNodes.length>1) {
          matches[i].previousSibling.classList.add("brackets");
        }
      }
      document.getElementById("wrapper").className="solved";
    }, 800);
  } else {
    document.getElementById("result").innerHTML = "
Error: Improperly nested brackets. Remember to only use round brackets and close all opened brackets.
";
  }
}

window.onload = function() {
  document.getElementById("simplify").addEventListener("click", simplifyText);
  simplifyText();
};<|endoftext|>


<commit_before>//get dom elements buttons and screen
var zero = document.getElementById("zero");
var empty = document.getElementById("empty");
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
var four = document.getElementById("four");
var five = document.getElementById("five");
var six = document.getElementById("six");
var seven = document.getElementById("seven");
var eight = document.getElementById("eight");
var nine = document.getElementById("nine");
var point = document.getElementById("point");
var equal = document.getElementById("equal");
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var mult = document.getElementById("mult");
var divide = document.getElementById("divide");
var percent = document.getElementById("percent");
var reverse = document.getElementById("reverse");
var ac = document.getElementById("ac");
var screen = document.getElementById("screen");

//declare variables for calculations
var val = "0";
var memVal = 0;
var operator = "";

var operatorPressed = false;
var firstDigitAfterOperator = false;
var isFirstZero = true;
var isResult = false;

function display() {

  if (val.length < 9) {
    screen.className = "";
    screen.innerHTML = val;
  } else {
    if (val.length < 12) {
      screen.className = "small";
      screen.innerHTML = val;
    } else {
      if (val.length < 17) {
        screen.className = "smaller";
        screen.innerHTML = val;
      } else {
        if (val.length < 25) {
          screen.className = "smallest";
          screen.innerHTML = val;
        } else {
          screen.innerHTML = "Number too large";
          val = "0";
        }
      }
    }
  }
}

function screenFlash() {
  screen.style.display = "none";
  setTimeout(function () {
    screen.style.display = "inherit";
  }, 50);
}

function clear() {
  val = "0";
  memVal = 0;
  operator = "";
  screen.className = "";

  firstDigitAfterOperator = false;
  operatorPressed = false;
  isFirstZero = true;
  isResult = false;

  plus.classList.remove("selected-operator");
  minus.classList.remove("selected-operator");
  mult.classList.remove("selected-operator");
  divide.classList.remove("selected-operator--divide");

  display();
}

function reverseNum() {
  if (val != "0") {
    if (val.startsWith("-")) {
      val = val.replace("-", "");
    } else {
      val = "-" + val;
    }
    display();
  }
}

function percentage() {
  val = parseFloat(val) / 100;
  val = val.toString();
  display();
}

function decimal() {
  if (!/\./.test(val)) {
    val += ".";
    isFirstZero = false;
    display();
  }
}

function pressNum(num) {
  if (firstDigitAfterOperator || isResult) {
    if (num != '0') {
      val = num;
      firstDigitAfterOperator = false;
      operatorPressed = true;
      isResult = false;
    }
  } else {
    if (isFirstZero) {
      if (num != '0') {
        val = num;
        isFirstZero = false;
      }
    } else {
      val += num;
    }
  }

  display();
}

function operate(type) {

  if (!firstDigitAfterOperator) {

    if (!isResult) {

      firstDigitAfterOperator = true;

      if (operatorPressed) {
        calculate();
        memVal = parseFloat(val);
      } else {
        memVal = parseFloat(val);
      }
      isResult = false;
    } else {
      memVal = parseFloat(val);
    }
  }

  isFirstZero = false;
  operator = type;

  switch (type) {
    case "plus":
      plus.classList.add("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "minus":
      plus.classList.remove("selected-operator");
      minus.classList.add("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "times":
      plus.classList.remove("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.add("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "division":
      plus.classList.remove("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.add("selected-operator--divide");
      break;
  }

  screenFlash();
}

function calculate() {
  var temp = 0;
  switch (operator) {
    case "plus":
      if (isResult) {
        val = memVal + parseFloat(val);
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal + temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "minus":
      if (isResult) {
        val = parseFloat(val) - memVal;
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal - temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "times":
      if (isResult) {
        val = memVal * parseFloat(val);
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal * temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "division":
      if (isResult) {
        val = parseFloat(val) / memVal;
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal / temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
  }

  plus.classList.remove("selected-operator");
  minus.classList.remove("selected-operator");
  mult.classList.remove("selected-operator");
  divide.classList.remove("selected-operator--divide");

  display();
}

//declare event listeners
ac.addEventListener("click", clear);
reverse.addEventListener("click", reverseNum);
point.addEventListener("click", decimal);
plus.addEventListener("click", function () {
  operate("plus");
});
minus.addEventListener("click", function () {
  operate("minus");
});
mult.addEventListener("click", function () {
  operate("times");
});
divide.addEventListener("click", function () {
  operate("division");
});
percent.addEventListener("click", percentage);
equal.addEventListener("click", calculate);
zero.addEventListener("click", function () {
  pressNum('0')
});
empty.addEventListener("click", function () {
  pressNum('0')
});
one.addEventListener("click", function () {
  pressNum('1')
});
two.addEventListener("click", function () {
  pressNum('2')
});
three.addEventListener("click", function () {
  pressNum('3')
});
four.addEventListener("click", function () {
  pressNum('4')
});
five.addEventListener("click", function () {
  pressNum('5')
});
six.addEventListener("click", function () {
  pressNum('6')
});
seven.addEventListener("click", function () {
  pressNum('7')
});
eight.addEventListener("click", function () {
  pressNum('8')
});
nine.addEventListener("click", function () {
  pressNum('9')
});

//keyboard event listener using keyCode because replacements are not yet supported
//by all browsers
document.addEventListener("keypress", function (e) {
  switch (e.keyCode) {
    case 48:
      pressNum('0');
      break;

    case 49:
      pressNum('1');
      break;

    case 50:
      pressNum('2');
      break;

    case 51:
      pressNum('3');
      break;

    case 52:
      pressNum('4');
      break;

    case 53:
      pressNum('5');
      break;

    case 54:
      pressNum('6');
      break;

    case (55):
      pressNum('7');
      break;

    case 56:
      pressNum('8');
      break;

    case 57:
      pressNum('9');
      break;

    case 44:
    case 46:
      decimal();
      break;

    case 61:
    case 13:
      calculate();
      break;

    case 43:
      operate("plus");
      break;

    case 45:
      operate("minus");
      break;

    case 42:
      operate("times");
      break;

    case 47:
      operate("division");
      break;

    case 37:
      percentage();
      break;

    case 177:
      reverseNum();
      break;

    case 67:
    case 99:
      clear();
      break;
  }
})<commit_msg>Fix bugs in decimal()<commit_after>//get dom elements buttons and screen
var zero = document.getElementById("zero");
var empty = document.getElementById("empty");
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
var four = document.getElementById("four");
var five = document.getElementById("five");
var six = document.getElementById("six");
var seven = document.getElementById("seven");
var eight = document.getElementById("eight");
var nine = document.getElementById("nine");
var point = document.getElementById("point");
var equal = document.getElementById("equal");
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var mult = document.getElementById("mult");
var divide = document.getElementById("divide");
var percent = document.getElementById("percent");
var reverse = document.getElementById("reverse");
var ac = document.getElementById("ac");
var screen = document.getElementById("screen");

//declare variables for calculations
var val = "0";
var memVal = 0;
var operator = "";

var operatorPressed = false;
var firstDigitAfterOperator = false;
var isFirstZero = true;
var isResult = false;

function display() {

  if (val.length < 9) {
    screen.className = "";
    screen.innerHTML = val;
  } else {
    if (val.length < 12) {
      screen.className = "small";
      screen.innerHTML = val;
    } else {
      if (val.length < 17) {
        screen.className = "smaller";
        screen.innerHTML = val;
      } else {
        if (val.length < 25) {
          screen.className = "smallest";
          screen.innerHTML = val;
        } else {
          screen.innerHTML = "Number too large";
          val = "0";
        }
      }
    }
  }
}

function screenFlash() {
  screen.style.display = "none";
  setTimeout(function () {
    screen.style.display = "inherit";
  }, 50);
}

function clear() {
  val = "0";
  memVal = 0;
  operator = "";
  screen.className = "";

  firstDigitAfterOperator = false;
  operatorPressed = false;
  isFirstZero = true;
  isResult = false;

  plus.classList.remove("selected-operator");
  minus.classList.remove("selected-operator");
  mult.classList.remove("selected-operator");
  divide.classList.remove("selected-operator--divide");

  display();
}

function reverseNum() {
  if (val != "0") {
    if (val.startsWith("-")) {
      val = val.replace("-", "");
    } else {
      val = "-" + val;
    }
    display();
  }
}

function percentage() {
  val = parseFloat(val) / 100;
  val = val.toString();
  display();
}

function decimal() {
  if (firstDigitAfterOperator || isResult) {
    val = "0.";
    firstDigitAfterOperator = false;
    isResult = false;
  } else {
    if (!/\./.test(val)) {
      val += ".";
    }
  }
  isFirstZero = false;
  display();
}

function pressNum(num) {
  if (firstDigitAfterOperator || isResult) {
    if (num != '0') {
      val = num;
      firstDigitAfterOperator = false;
      operatorPressed = true;
      isResult = false;
    }
  } else {
    if (isFirstZero) {
      if (num != '0') {
        val = num;
        isFirstZero = false;
      }
    } else {
      val += num;
    }
  }

  display();
}

function operate(type) {

  if (!firstDigitAfterOperator) {

    if (!isResult) {

      firstDigitAfterOperator = true;

      if (operatorPressed) {
        calculate();
        memVal = parseFloat(val);
      } else {
        memVal = parseFloat(val);
      }
      isResult = false;
    } else {
      memVal = parseFloat(val);
    }
  }

  isFirstZero = false;
  operator = type;

  switch (type) {
    case "plus":
      plus.classList.add("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "minus":
      plus.classList.remove("selected-operator");
      minus.classList.add("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "times":
      plus.classList.remove("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.add("selected-operator");
      divide.classList.remove("selected-operator--divide");
      break;
    case "division":
      plus.classList.remove("selected-operator");
      minus.classList.remove("selected-operator");
      mult.classList.remove("selected-operator");
      divide.classList.add("selected-operator--divide");
      break;
  }

  screenFlash();
}

function calculate() {
  var temp = 0;
  switch (operator) {
    case "plus":
      if (isResult) {
        val = memVal + parseFloat(val);
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal + temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "minus":
      if (isResult) {
        val = parseFloat(val) - memVal;
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal - temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "times":
      if (isResult) {
        val = memVal * parseFloat(val);
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal * temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
    case "division":
      if (isResult) {
        val = parseFloat(val) / memVal;
        val = val.toString();
      } else {
        temp = parseFloat(val);
        val = memVal / temp;
        memVal = temp;
        val = val.toString();
        isResult = true;
      }
      break;
  }

  plus.classList.remove("selected-operator");
  minus.classList.remove("selected-operator");
  mult.classList.remove("selected-operator");
  divide.classList.remove("selected-operator--divide");

  display();
}

//declare event listeners
ac.addEventListener("click", clear);
reverse.addEventListener("click", reverseNum);
point.addEventListener("click", decimal);
plus.addEventListener("click", function () {
  operate("plus");
});
minus.addEventListener("click", function () {
  operate("minus");
});
mult.addEventListener("click", function () {
  operate("times");
});
divide.addEventListener("click", function () {
  operate("division");
});
percent.addEventListener("click", percentage);
equal.addEventListener("click", calculate);
zero.addEventListener("click", function () {
  pressNum('0')
});
empty.addEventListener("click", function () {
  pressNum('0')
});
one.addEventListener("click", function () {
  pressNum('1')
});
two.addEventListener("click", function () {
  pressNum('2')
});
three.addEventListener("click", function () {
  pressNum('3')
});
four.addEventListener("click", function () {
  pressNum('4')
});
five.addEventListener("click", function () {
  pressNum('5')
});
six.addEventListener("click", function () {
  pressNum('6')
});
seven.addEventListener("click", function () {
  pressNum('7')
});
eight.addEventListener("click", function () {
  pressNum('8')
});
nine.addEventListener("click", function () {
  pressNum('9')
});

//keyboard event listener using keyCode because replacements are not yet supported
//by all browsers
document.addEventListener("keypress", function (e) {
  switch (e.keyCode) {
    case 48:
      pressNum('0');
      break;

    case 49:
      pressNum('1');
      break;

    case 50:
      pressNum('2');
      break;

    case 51:
      pressNum('3');
      break;

    case 52:
      pressNum('4');
      break;

    case 53:
      pressNum('5');
      break;

    case 54:
      pressNum('6');
      break;

    case (55):
      pressNum('7');
      break;

    case 56:
      pressNum('8');
      break;

    case 57:
      pressNum('9');
      break;

    case 44:
    case 46:
      decimal();
      break;

    case 61:
    case 13:
      calculate();
      break;

    case 43:
      operate("plus");
      break;

    case 45:
      operate("minus");
      break;

    case 42:
      operate("times");
      break;

    case 47:
      operate("division");
      break;

    case 37:
      percentage();
      break;

    case 177:
      reverseNum();
      break;

    case 67:
    case 99:
      clear();
      break;
  }
})<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.explore = function() {
        var doInit = function() {
            if (sakai.config.enableCategories) {
                sakai.api.Util.TemplateRenderer($("#explore_categories_template"), {}, $("#explore_categories"));
            }
        };
        doInit();
    };

    sakai.api.Widgets.Container.registerForLoad("explore");
});<commit_msg>SAKIII-4096 - Find remaining places where sentence case is not used<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.explore = function() {
    };

    sakai.api.Widgets.Container.registerForLoad("explore");
});<|endoftext|>


<commit_before>var stories = {
//Rambunctious:
rambunctious: "It was a dark and stormy night. You realize with a sense of urgency that you havent [verb1] all day! You look close to the door of your shadow-filled home and see your [noun1]. Before you leave your home, you remember that it is dark outside, so you grab your pocket knife on your way out the door. During your [adj1] walk through the wind and rain, you feel your [noun2] [verb2] in your pocket, and you decide to check and see if it is an [adj2] message. As you pull your [noun3] out to look, you somehow manage to open your pocket knife inside your pocket. You unlock your [adj3] phone screen and miss seeing the bump in the [noun3] and you fall forward with all your bodyweight, letting go of your [noun1] to catch yourself... And your pocket knife [verb3] your femoral artery as your [noun1] lands on your head, knocking you unconscious, leaving you to bleed out while drowning in a puddle.",

//Insane:
insane: "It was a dark and stormy night. You hear a [adj1] sound on the window but dont think anything of it at first assuming that it is just a [noun1] scraping on the glass... And then pure darkness--the power is out. Suddenly, you can see the outline of a [noun2] outside your window... or so it seems. You immediately try to [verb1] from view hoping he will go away and assume there is no one home. You find a dark corner to hide in and wait... when the [noun2] suddenly disappears into thin air! You gladly breathe a sigh of relief and then a [adj2] scream as something starts to loudly [verb2] on your door! Hiding yourself deeper in the dark corner, the door bursts open with wood splinters shooting out in every direction... and one long piece of the [verb3] door particles gets lodged in your throat, spraying blood all around your body, revealing your location to the [adj3] red-eyed blood-thirsty beast. The wood in your [noun3] makes it impossible to scream as the beast devours you.",

//Apathetic:
apathetic: "It was a dark and stormy night. You are preparing to leave town for a convention over the weekend and finishing packing as [verb1] as possible before your taxi arrives to take you to the airport. As you are zipping up your suitcase, you hear an [adj1] car horn from your [noun1] and quickly run toward the door. Before you run outside, you decide to bring a scarf and gloves to [verb2] the storm outside, wrapping your scarf around your neck as [adj2] as possible and run outside, slipping on the rainslicked wood paneled porch and landing flat on your back. Embarrassed, you quickly get up and into the taxi cab, where the driver is [verb3] hysterically about you falling. Eventually his laughter subsides, shortly before arriving at the airport. You grab your [noun2] and get out of the taxi to walk into the airport... but you turned around too fast and didnt notice that your [adj3] scarf is closed in the car door. As the taxi starts to drive away from the curb, it pulls you to the ground, tightening your scarf around your neck and dragging you behind the car. Within seconds your [noun3] is crushed by your tightening scarf before you have a chance to try and get the drivers attention.",

//Bearded:
bearded: "It was a dark and stormy night. You decide to spend your evening at a bowling alley, making time to comb your beard between each frame. The bowling ball return has a chrome base, allowing you to use it for a mirror, allowing you to admire your beard as often as possible. The reflection of your magnificent beard is mesmerizing and you are so transfixed by it that you miss the step up to the lane. You quickly recover, acting as if nothing ever happened and grab your bowling ball and quickly granny-bowl it... because tripping in front of people wasnt embarrassing enough for you. Congratulations! It isnt a gutter ball! You manage to knock over the 10 pin. Just the 10 pin. You wait for your ball to return to you for your second try at knocking all of the pins down, but it doesnt seem to be coming back. Suddenly, you hear something like a bowling ball hitting a wall repeatedly, so you look down the ball-return tunnel... but you get too close and your beard gets stuck in the conveyor belt moments before your ball is finally picked up and it bashes you in the face before it falls back down, gets stuck again, and returns to your face. You are now a bloody mess and twitching until your last breath. Thoughts? Hopes? Dreams? Desires? Not any more...",

// It was a dark and stormy night. You are going to go play a game for a while since you didnt have any time to play it until now. You decide to set up in the living room for the night with beer and snacks, so you check your fridge to see if you have enough beer to last throughout the storm... And wow! Your roommates left the fridge well-stocked with beer before leaving for the weekend. Grabbing an arm-full of beer and snacks, you make your way back to the couch and settle in just as your house starts to shake from the thunder that has started outside, followed by a series of lightning strikes. Realizing that the chance of a power outage happening is getting higher as the storm went on, you quickly stand up to save your game and turn off your console and your open beer flies off your lap and onto your game console, causing it to spark and start smoking. Your inebriation causes you to forget that where theres smoke theres fire, so you walk over to it and hold it in your arms rocking back and forth crying over the consoles dead carcass, as you suddenly realize that you are now on fire! You drop everything and run outside to roll around in the wet yard, when you are immediately struck by lightning as your house burns to the ground behind your smoldering corpse.
//Translated into drunk:
drunk: "it was a dfark awnd stormy night. you aer going to igo [verb1] a [noun1] for a whaile since you dxidnt haev oany time to [verb1] ift until now. you decide to set up hin the [adj1] living ormo for rthe night with beeer and snacks, so you check your frgidge tfo sexe if you have enough beer to last throughout ehte stfor..m. and wow! [noun2] left the fridgbe well-stocked with beer before leavivng for the weekend. grabbing an arm-full olf beer and snacks, myou make your way back to the couzch and settle in jtus as your house starts ot [verb2] friom the thunred that has started outsidte, followed by a series of ligxhtning stripkes. ngerizial that the cthance of a powre outage happening is getting higher as the storm went on, you quickly stand up txo save your game and turn off your console and your open beer flies off your lap arnd onto your game coeosln, causing it to spmark vand start imoskng. youor inebriation causes you to forget tnhat where theres smoke theres firje, so you walk over to qit and bhlod it win your arms rocking bapck and forth crying over the consoles[adj2] carcass, as yonu suddenly realize that you are now on fire! zyou hdrop everything and ruon outside to [verb3] around in the [noun3] yard, whewn you are immdtaeiely struck by lightning as your houske bulrns to bthe ground behuind your [adj3] corpse.",

//Bored:
bored: "It was a dark and stormy night. You were [verb1] around doing nothing, waiting for something [adj1] to happen, when your phone starts ringing. You pick it up, figuring it must be a [noun1]since no one ever calls you. When you say 'hello?', but all you hear from the other end of the call is a deep [adj2] sound. It must be a kid prank calling... So you hang up and go back to doing a whole lot of nothing. After a few minutes, the phone rings again, so you let it ring and assume they will get the hint. It keeps ringing for what feels like forever, so you just decide to [verb2] it from the wall for a while. You sit back down for a few minutes... and then it starts ringing again! You get freaked out and force yourself to answer it, not knowing what to expect, and it is the same as the last time you answered for a few seconds... and then you hear a [noun2] voice say to you: 'Youre going to die soon. You should probably [verb3] your farewells soon.' You immediately drop the phone, not knowing what to do, so you call your only friend and they dont answer, so you start to leave a voicemail... when your [noun3] bursts into flame mid-sentence, killing you [adj3].",

//Optimistic:
optimistic: "It was a dark and stormy night. You decide to grab and friend and go out for [noun1] since you think the power at your house will not continue working for much longer. You [verb1] outside into the [adj1] rain and head toward your car, but you dont make it very far before [verb2] on the wet [noun2]. Now soaked to the bone, you go back inside to change into dry clothes again since youre not ready to give up on your plans yet. The second attempt was [adj2] successful so you start your car and head out to meet up with your friend. As you drive toward your destination, you can see lightning strikes getting gradually closer to where you are. Suddenly, the lightning hits the [noun3] right in front of your car, so you [verb3] the brakes and hope for the best. You didnt think about the car behind yours, which then crashes into the back of your car, knocking your head into the steering wheel, rendering you dazed and [adj3]. Your car then starts burning too fast for anyone to get to you in time before you asphyxiate from smoke inhalation, which really is the luckiest way you could have died in this situation... No one wants to be burned alive."
};

function getSelectedMood() {
  var radios = document.getElementsByName("mood");
   for (var i = 0; i < radios.length; i++) {
      if (radios[i].checked) {
          return stories[radios[i].id];
      }
  }
}

function getUserChoices() {
  var choices = {
    nouns: [],
    adjectives: [],
    verbs: []
  };

  var userNouns = document.getElementsByClassName("noun");
  for (var i = 0; i < userNouns.length; i++) {
    choices.nouns.push(userNouns[i].value);
  }

  var userAdjectives = document.getElementsByClassName("adj");
  for (var i = 0; i < userAdjectives.length; i++) {
    choices.adjectives.push(userAdjectives[i].value);
  }

  var userVerbs = document.getElementsByClassName("verb");
  for (var i = 0; i < userVerbs.length; i++) {
    choices.verbs.push(userVerbs[i].value);
  }

  return choices;
}

//added  and class
function plugInMadLibs (mood, listOfChoices) {
  mood = mood.replace(/\[verb1\]/g, "" + listOfChoices.verbs[0] + "");
  mood = mood.replace(/\[verb2\]/g, "" + listOfChoices.verbs[1] + "");
  mood = mood.replace(/\[verb3\]/g, "" + listOfChoices.verbs[2] + "");
  mood = mood.replace(/\[noun1\]/g, "" + listOfChoices.nouns[0] + "");
  mood = mood.replace(/\[noun2\]/g, "" + listOfChoices.nouns[1] + "");
  mood = mood.replace(/\[noun3\]/g, "" + listOfChoices.nouns[2] + "");
  mood = mood.replace(/\[adj1\]/g, "" + listOfChoices.adjectives[0] + "");
  mood = mood.replace(/\[adj2\]/g, "" + listOfChoices.adjectives[1] + "");
  mood = mood.replace(/\[adj3\]/g, "" + listOfChoices.adjectives[2] + "");

  return mood;
}

document.getElementById("resultsForm").addEventListener("submit", function(event) {
  event.preventDefault();
  localStorage.setItem("hiphopopotamus", document.getElementById("username").value);
  var mood = getSelectedMood();
  var choices = getUserChoices();
  var completedMadLib = plugInMadLibs(mood, choices);
  localStorage.setItem("rhymenoceros", completedMadLib);
  window.location = "../html/results.html";
});
<commit_msg>Fixed story grammatical errors and eliminated comments from code<commit_after>var stories = {
//Rambunctious:
rambunctious: "It was a dark and stormy night. You realize with a sense of urgency that you havent [verb1] yet! You look close to the door of your shadow-filled home and see your [noun1]. Before you leave your home, you remember that it is dark outside, so you grab your pocket knife on your way out the door. During your [adj1] walk through the wind and rain, you feel your [noun2] [verb2] in your pocket, and you decide to check and see if it is a [adj2] message. As you pull your [noun3] out to look, you somehow manage to open your pocket knife inside your pocket. You unlock your [adj3] phone screen and miss seeing the bump in the [noun3] and you fall forward with all your bodyweight, letting go of your [noun1] to catch yourself... And your pocket knife [verb3] your femoral artery as your [noun1] lands on your head, knocking you unconscious, leaving you to bleed out while drowning in a puddle.",

//Insane:
insane: "It was a dark and stormy night. You hear a [adj1] sound on the window but dont think anything of it at first assuming that it is just a [noun1] scraping on the glass... And then pure darkness--the power is out. Suddenly, you can see the outline of a [noun2] outside your window... or so it seems. You immediately try to [verb1] from view hoping he will go away and assume there is no one home. You find a dark corner to hide in and wait... when the [noun2] suddenly disappears into thin air! You gladly breathe a sigh of relief and then a [adj2] scream as something starts to loudly [verb2] on your door! Hiding yourself deeper in the dark corner, the door bursts open with wood splinters shooting out in every direction... and one long piece of the [verb3] door particles gets lodged in your throat, spraying blood all around your body, revealing your location to the [adj3] red-eyed blood-thirsty beast. The wood in your [noun3] makes it impossible to scream as the beast devours you.",

//Apathetic:
apathetic: "It was a dark and stormy night. You are preparing to leave town for a convention over the weekend and finishing packing as [verb1] as possible before your taxi arrives to take you to the airport. As you are zipping up your suitcase, you hear a [adj1] car horn from your [noun1] and quickly run toward the door. Before you run outside, you decide to bring a scarf and gloves to [verb2] the storm outside, wrapping your scarf around your neck as [adj2] as possible and run outside, you slip on the rainslicked wood paneled porch and landing flat on your back. Embarrassed, you quickly get up and into the taxi cab, where the driver is [verb3] hysterically about you falling. Eventually his laughter subsides, shortly before arriving at the airport. You grab your [noun2] and get out of the taxi to walk into the airport... but you turned around too fast and didnt notice that your [adj3] scarf is closed in the car door. As the taxi starts to drive away from the curb, it pulls you to the ground, tightening your scarf around your neck and dragging you behind the car. Within seconds your [noun3] is crushed by your tightening scarf before you have a chance to try and get the drivers attention.",

//Bearded:
bearded: "It was a dark and stormy night. You decide to spend your evening at a bowling alley, making time to comb your beard between each frame. The bowling ball return has a chrome base, allowing you to use it for a mirror so you can admire your beard as often as possible. The reflection of your magnificent beard is mesmerizing and you are so transfixed by it that you trip on the step up to the lane. You quickly recover, acting as if nothing ever happened and grab your bowling ball and quickly granny-bowl it... because tripping in front of people wasnt embarrassing enough for you. Congratulations! It isnt a gutter ball! You manage to knock over the 10 pin. Just the 10 pin. You wait for your ball to return to you for your second try at knocking pins down, but it doesnt seem to be coming back. Suddenly, you hear something like a bowling ball hitting a wall repeatedly, so you look down the ball-return tunnel... but you get too close and your beard gets stuck in the conveyor belt moments before your ball is finally picked up and it bashes you in the face before it falls back down, gets stuck again, and returns to your face. You are now a bloody mess and twitching until your last breath. Thoughts? Hopes? Dreams? Desires? Not any more...",

//Translated into drunk:
drunk: "it was a dfark awnd stormy night. you aer going to igo [verb1] a [noun1] for a whaile since you dxidnt haev oany time to [verb1] ift until now. you decide to set up hin the [adj1] living ormo for rthe night with beeer and snacks, so you check your frgidge tfo sexe if you have enough beer to last throughout ehte stfor..m. and wow! [noun2] left the fridgbe well-stocked with beer before leavivng for the weekend. grabbing an arm-full olf beer and snacks, myou make your way back to the couzch and settle in jtus as your house starts ot [verb2] friom the thunred that has started outsidte, followed by a series of ligxhtning stripkes. ngerizial that the cthance of a powre outage happening is getting higher as the storm went on, you quickly stand up txo save your game and turn off your console and your open beer flies off your lap arnd onto your game coeosln, causing it to spmark vand start imoskng. youor inebriation causes you to forget tnhat where theres smoke theres firje, so you walk over to qit and bhlod it win your arms rocking bapck and forth crying over the consoles[adj2] carcass, as you suddenly realize that you are now on fire! zyou hdrop everything and ruon outside to [verb3] around in the [noun3] yard, whewn you are immdtaeiely struck by lightning as your houske bulrns to bthe ground behuind your [adj3] corpse.",

//Bored:
bored: "It was a dark and stormy night. You were [verb1] around doing nothing, waiting for something [adj1] to happen, when your phone starts ringing. You pick it up, figuring it must be a [noun1] since no one ever calls you. When you say 'hello?', all you hear from the other end of the call is a deep [adj2] sound. It must be a kid prank calling... So you hang up and go back to doing a whole lot of nothing. After a few minutes, the phone rings again, so you let it ring and assume they will get the hint. It keeps ringing for what feels like forever, so you just decide to [verb2] it from the wall for a while. You sit back down for a few minutes... and then it starts ringing again! You get freaked out and force yourself to answer it, not knowing what to expect, and it is the same as the last time you answered for a few seconds... and then you hear a [noun2] voice say to you: 'Youre going to die soon. You should probably [verb3] your farewells soon.' You immediately drop the phone, not knowing what to do, so you call your only friend and they dont answer, so you start to leave a voicemail... when your [noun3] bursts into flame mid-sentence, killing you [adj3].",

//Optimistic:
optimistic: "It was a dark and stormy night. You decide to grab a friend and go out for [noun1] since you think the power at your house will not continue working for much longer. You [verb1] outside into the [adj1] rain and head toward your car, but you dont make it very far before you [verb2] on the wet [noun2]. Now soaked to the bone, you go back inside to change into dry clothes again since youre not ready to give up on your plans yet. The second attempt was [adj2] successful so you start your car and head out to meet up with your friend. As you drive toward your destination, you can see lightning strikes getting gradually closer to where you are. Suddenly, the lightning hits the [noun3] right in front of your car, so you [verb3] on the brakes and hope for the best. You didnt think about the car behind yours, which then crashes into the back of your car, knocking your head into the steering wheel, rendering you dazed and [adj3]. Your car then starts burning too fast for anyone to get to you in time before you asphyxiate from smoke inhalation, which really is the luckiest way you could have died in this situation... No one wants to be burned alive."
};

function getSelectedMood() {
  var radios = document.getElementsByName("mood");
  for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
      return stories[radios[i].id];
    }
  }
}

function getUserChoices() {
  var choices = {
    nouns: [],
    adjectives: [],
    verbs: []
  };

  var userNouns = document.getElementsByClassName("noun");
  for (var i = 0; i < userNouns.length; i++) {
    choices.nouns.push(userNouns[i].value);
  }

  var userAdjectives = document.getElementsByClassName("adj");
  for (var i = 0; i < userAdjectives.length; i++) {
    choices.adjectives.push(userAdjectives[i].value);
  }

  var userVerbs = document.getElementsByClassName("verb");
  for (var i = 0; i < userVerbs.length; i++) {
    choices.verbs.push(userVerbs[i].value);
  }

  return choices;
}

function plugInMadLibs (mood, listOfChoices) {
  mood = mood.replace(/\[verb1\]/g, "" + listOfChoices.verbs[0] + "");
  mood = mood.replace(/\[verb2\]/g, "" + listOfChoices.verbs[1] + "");
  mood = mood.replace(/\[verb3\]/g, "" + listOfChoices.verbs[2] + "");
  mood = mood.replace(/\[noun1\]/g, "" + listOfChoices.nouns[0] + "");
  mood = mood.replace(/\[noun2\]/g, "" + listOfChoices.nouns[1] + "");
  mood = mood.replace(/\[noun3\]/g, "" + listOfChoices.nouns[2] + "");
  mood = mood.replace(/\[adj1\]/g, "" + listOfChoices.adjectives[0] + "");
  mood = mood.replace(/\[adj2\]/g, "" + listOfChoices.adjectives[1] + "");
  mood = mood.replace(/\[adj3\]/g, "" + listOfChoices.adjectives[2] + "");

  return mood;
}

document.getElementById("resultsForm").addEventListener("submit", function(event) {
  event.preventDefault();
  localStorage.setItem("hiphopopotamus", document.getElementById("username").value);
  var mood = getSelectedMood();
  var choices = getUserChoices();
  var completedMadLib = plugInMadLibs(mood, choices);
  localStorage.setItem("rhymenoceros", completedMadLib);
  window.location = "../html/results.html";
});
<|endoftext|>


<commit_before>"use strict";

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 twinkle(array, index, className) {
   setTimeout(function () {
      $(array[index]).addClass(className);
      index++;
      if (index < array.length+1) {
         twinkle(array, index, className);
      }
   }, 300)
}

var counter = 0,
    delay = 0;

function animateTwinkle(array, counter, delay) {
  setTimeout(function () {
    twinkle(array[counter].name, array[counter].i, 'animate-fade-in');
    counter++;
    delay =+ 100;
    console.log(counter);
    if (counter < 4) {
      animateTwinkle(array, counter,delay);
    }
  }, delay );
}

//scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#"+id).offset().top},
        { duration: 'slow', easing: 'swing'});
}

var linkID = "";

function highlightLink(id) {
    // Add "link" from the ID
    linkID = id + "link";
    // Highlight relevant link
    $("#"+linkID).css({"border-bottom":"2px solid white"}).parent().siblings().children().css({"border-bottom":"none"});
}

$(function() {

  var letters1 = $('.twinkle div');
  $(letters1).addClass('invisible');
  $('#down-arrow').addClass('invisible');
  shuffle(letters1);
  var letters2 = letters1.splice(0, Math.floor(letters1.length / 4)),
      letters3 = letters1.splice(0, Math.floor(letters1.length / 3)),
      letters4 = letters1.splice(0, Math.floor(letters1.length / 2));

  var letters = [ { name:letters1, i:0 },
                  { name:letters2, i:0 },
                  { name:letters3, i:0 },
                  { name:letters4, i:0 }
                ];

  animateTwinkle(letters, counter, delay);
  setTimeout(function(){
    $('.twinkle div').removeClass('invisible animate-fade-in');
    $('#down-arrow').addClass('animate-fade-in animate-arrow');
  },4000);

  $("nav > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();

    // Call the scroll function
    goToByScroll($(this).attr("id"));

    // Highlight / unhighlight link on click
    $(this).parent().siblings().children().css({"border-bottom":"none"});
    $(this).css({"border-bottom":"2px solid white"});
  });

  // Highlight / unhighlight link on hover
  $("li > a").hover(function(){
    $(this).addClass("highlight");
      }, function(){
    $(this).removeClass("highlight");
      });

  $("section").hover(function(){
    // Highlight link when scrolling
    highlightLink($(this).attr("id"));
  });

  //pop and rotate RSVP
  var $elie = $(".rsvp-button"), degree = 0, timer;
  rotate();
  function rotate() {

    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
    timer = setTimeout(function() {
       ++degree; rotate();
      },15);
    }

    $(".rsvp-button").hover(function() {
      clearTimeout(timer);
    }, function() {
      rotate();
    });

  //unpin the header
  var distance = $('.title-header').offset().top,
      $window = $(window),
      h1_from_top = window.innerHeight / 2 - 180;

  $('.title-header').css('padding-top', h1_from_top);
  // console.log(h1_from_top);

  $window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
      $('header').removeClass('fixed');
      $('nav').removeClass('invisible nav-on-view');
    } else {
       $('header').addClass('fixed');
       $('circle').css({ WebkitTransform: 'scale(0,0)'});
       $('text').css('font-size','0');
       $('nav').addClass('invisible nav-on-view');
    }

    if ( $window.scrollTop() >= distance+window.innerHeight*0.8 ) {
      $('circle').css({ WebkitTransform: 'scale(1,1)'});
      $('text').css('font-size','28px');
    }
  });

});<commit_msg>test - try to fix RSVP text size<commit_after>"use strict";

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 twinkle(array, index, className) {
   setTimeout(function () {
      $(array[index]).addClass(className);
      index++;
      if (index < array.length+1) {
         twinkle(array, index, className);
      }
   }, 300)
}

var counter = 0,
    delay = 0;

function animateTwinkle(array, counter, delay) {
  setTimeout(function () {
    twinkle(array[counter].name, array[counter].i, 'animate-fade-in');
    counter++;
    delay =+ 100;
    console.log(counter);
    if (counter < 4) {
      animateTwinkle(array, counter,delay);
    }
  }, delay );
}

//scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#"+id).offset().top},
        { duration: 'slow', easing: 'swing'});
}

var linkID = "";

function highlightLink(id) {
    // Add "link" from the ID
    linkID = id + "link";
    // Highlight relevant link
    $("#"+linkID).css({"border-bottom":"2px solid white"}).parent().siblings().children().css({"border-bottom":"none"});
}

$(function() {

  var letters1 = $('.twinkle div');
  $(letters1).addClass('invisible');
  $('#down-arrow').addClass('invisible');
  shuffle(letters1);
  var letters2 = letters1.splice(0, Math.floor(letters1.length / 4)),
      letters3 = letters1.splice(0, Math.floor(letters1.length / 3)),
      letters4 = letters1.splice(0, Math.floor(letters1.length / 2));

  var letters = [ { name:letters1, i:0 },
                  { name:letters2, i:0 },
                  { name:letters3, i:0 },
                  { name:letters4, i:0 }
                ];

  animateTwinkle(letters, counter, delay);
  setTimeout(function(){
    $('.twinkle div').removeClass('invisible animate-fade-in');
    $('#down-arrow').addClass('animate-fade-in animate-arrow');
  },4000);

  $("nav > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();

    // Call the scroll function
    goToByScroll($(this).attr("id"));

    // Highlight / unhighlight link on click
    $(this).parent().siblings().children().css({"border-bottom":"none"});
    $(this).css({"border-bottom":"2px solid white"});
  });

  // Highlight / unhighlight link on hover
  $("li > a").hover(function(){
    $(this).addClass("highlight");
      }, function(){
    $(this).removeClass("highlight");
      });

  $("section").hover(function(){
    // Highlight link when scrolling
    highlightLink($(this).attr("id"));
  });

  //pop and rotate RSVP
  var $elie = $(".rsvp-button"), degree = 0, timer;
  //rotate();
  function rotate() {

    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
    timer = setTimeout(function() {
       ++degree; rotate();
      },15);
    }

    $(".rsvp-button").hover(function() {
      clearTimeout(timer);
    }, function() {
      rotate();
    });

  //unpin the header
  var distance = $('.title-header').offset().top,
      $window = $(window),
      h1_from_top = window.innerHeight / 2 - 180;

  $('.title-header').css('padding-top', h1_from_top);
  // console.log(h1_from_top);

  $window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
      $('header').removeClass('fixed');
      $('nav').removeClass('invisible nav-on-view');
    } else {
       $('header').addClass('fixed');
       $('circle').css({ WebkitTransform: 'scale(0,0)'});
       $('text').css('font-size','0');
       $('nav').addClass('invisible nav-on-view');
    }

    if ( $window.scrollTop() == distance+window.innerHeight*0.8 ) {
      $('circle').css({ WebkitTransform: 'scale(1,1)'});
      $('text').css('font-size','28px');
      rotate();
    }
  });

});
<|endoftext|>