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

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

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

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

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

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

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

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

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

            return shuffle(walkSteps);
        }

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

            return [randw, randh];
        }

        function paint(){
            reset();

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

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

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

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

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

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

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

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

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

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

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

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

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

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

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

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

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

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

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

            return shuffle(walkSteps);
        }

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

            return [randw, randh];
        }

        function paint(){
            reset();

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

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

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

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

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

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

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

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

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

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

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


<commit_before>/**
 * ownCloud - recorder
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Shawn <syu702@aucklanduni.ac.nz>
 * @copyright Shawn 2016
 */

(function ($, OC) {

    $(document).ready(function () {
        $('#hello').click(function () {
            alert('Hello from your script file');
        });

        $('#echo').click(function () {
            var url = OC.generateUrl('/apps/recorder/echo');
            var data = {
                echo: $('#echo-content').val()
            };

            $.post(url, data).success(function (response) {
                $('#echo-result').text(response.echo);
            });

        });

            function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
            }

            var mediaConstraints = {
                audio: true
            };

            $('#start-recording').click(function() {
                this.disabled = true;
                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
            });

            $('#stop-recording').click(function() {
                this.disabled = true;
                mediaRecorder.stop();
                mediaRecorder.stream.stop();

                $('#pause-recording').disabled = true;
                $('#start-recording').disabled = false;
            });

            $('#pause-recording').click(function() {
                this.disabled = true;
                mediaRecorder.pause();

                $('#resume-recording').disabled = false;
            });

            $('#resume-recording').click(function() {
                this.disabled = true;
                mediaRecorder.resume();

                $('#pause-recording').disabled = false;
            });

            $('#save-recording').click(function() {
                this.disabled = true;
                mediaRecorder.save();
            });

            var mediaRecorder;

            function onMediaSuccess(stream) {
                var audio = document.createElement('audio');

                audio = mergeProps(audio, {
                    controls: true,
                    muted: true,
                    src: URL.createObjectURL(stream)
                });
                audio.play();

                audiosContainer.appendChild(audio);
                audiosContainer.appendChild(document.createElement('hr'));

                mediaRecorder = new MediaStreamRecorder(stream);
                mediaRecorder.stream = stream;
                mediaRecorder.mimeType = document.getElementById('audio-mimeType').value;
                mediaRecorder.audioChannels = !!document.getElementById('left-channel').checked ? 1 : 2;
                mediaRecorder.ondataavailable = function(blob) {
                    var a = document.createElement('a');
                    a.target = '_blank';
                    a.innerHTML = 'Open Recorded Audio No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);

                    a.href = URL.createObjectURL(blob);

                    audiosContainer.appendChild(a);
                    audiosContainer.appendChild(document.createElement('hr'));
                };

                var timeInterval = $('#time-interval').value;
                if (timeInterval) timeInterval = parseInt(timeInterval);
                else timeInterval = 5 * 1000;

                // get blob after specific time interval
                mediaRecorder.start(timeInterval);

                $('#stop-recording').disabled = false;
                $('#pause-recording').disabled = false;
                $('#save-recording').disabled = false;
            }

            function onMediaError(e) {
                console.error('media error', e);
            }

            var audiosContainer = document.getElementById('audios-container');
            var index = 1;

            // below function via: http://goo.gl/B3ae8c
            function bytesToSize(bytes) {
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes === 0) return '0 Bytes';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            }

            // below function via: http://goo.gl/6QNDcI
            function getTimeLength(milliseconds) {
                var data = new Date(milliseconds);
                return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
            }

            window.onbeforeunload = function() {
                $('#start-recording').disabled = false;
            };
    });

})(jQuery, OC);
<commit_msg>no message<commit_after>/**
 * ownCloud - recorder
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Shawn <syu702@aucklanduni.ac.nz>
 * @copyright Shawn 2016
 */

(function ($, OC) {

    $(document).ready(function () {
        $('#hello').click(function () {
            alert('Hello from your script file');
        });

        $('#echo').click(function () {
            var url = OC.generateUrl('/apps/recorder/echo');
            var data = {
                echo: $('#echo-content').val()
            };

            $.post(url, data).success(function (response) {
                $('#echo-result').text(response.echo);
            });

        });

            function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
            }

            var mediaConstraints = {
                audio: true
            };

            $('#start-recording').click(function() {
                this.disabled = true;
                $('#pause-recording').disabled = false;
                $('#stop-recording').disabled = false;

                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
            });

            $('#stop-recording').click(function() {
                this.disabled = true;
                mediaRecorder.stop();
                mediaRecorder.stream.stop();

                $('#pause-recording').disabled = true;
                $('#start-recording').disabled = false;
            });

            $('#pause-recording').click(function() {
                this.disabled = true;
                mediaRecorder.pause();

                $('#resume-recording').disabled = false;
            });

            $('#resume-recording').click(function() {
                this.disabled = true;
                mediaRecorder.resume();

                $('#pause-recording').disabled = false;
            });

            $('#save-recording').click(function() {
                this.disabled = true;
                mediaRecorder.save();
            });

            var mediaRecorder;

            function onMediaSuccess(stream) {
                var audio = document.createElement('audio');

                audio = mergeProps(audio, {
                    controls: true,
                    muted: true,
                    src: URL.createObjectURL(stream)
                });
                audio.play();

                audiosContainer.appendChild(audio);
                audiosContainer.appendChild(document.create('hr'));

                mediaRecorder = new MediaStreamRecorder(stream);
                mediaRecorder.stream = stream;
                mediaRecorder.mimeType = $('audio-mimeType').value;
                mediaRecorder.audioChannels = !! $('left-channel').checked ? 1 : 2;
                mediaRecorder.ondataavailable = function(blob) {
                    var a = document.create('a');
                    a.target = '_blank';
                    a.innerHTML = 'Open Recorded Audio No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);

                    a.href = URL.createObjectURL(blob);

                    audiosContainer.appendChild(a);
                    audiosContainer.appendChild(document.create('hr'));
                };

                var timeInterval = $('#time-interval').value;
                if (timeInterval) timeInterval = parseInt(timeInterval);
                else timeInterval = 5 * 1000;

                // get blob after specific time interval
                mediaRecorder.start(timeInterval);

                $('#stop-recording').disabled = false;
                $('#pause-recording').disabled = false;
                $('#save-recording').disabled = false;
            }

            function onMediaError(e) {
                console.error('media error', e);
            }

            var audiosContainer = $('audios-container');
            var index = 1;

            // below function via: http://goo.gl/B3ae8c
            function bytesToSize(bytes) {
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes === 0) return '0 Bytes';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            }

            // below function via: http://goo.gl/6QNDcI
            function getTimeLength(milliseconds) {
                var data = new Date(milliseconds);
                return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
            }

            window.onbeforeunload = function() {
                $('#start-recording').disabled = false;
            };
    });

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


<commit_before>/* Author:

*/

<commit_msg>Testing pre-commit gook<commit_after>/* Author:

*/
debugger;

<|endoftext|>


<commit_before>$(document).ready(function() {
  // variables
  var searchInput = $('#search-input'),
      urlResult = $('#url-result'),
      cursor = $('#cursor'),
      previewSearchLink = $('.preview-search-link');

  // display the current location for the shareable url
  urlResult.attr("value", window.location);
  // keep the shareable text selected
  urlResult.mouseup(function() {
    this.select()
  });
  // select the shareable url when they focus on it
  urlResult.focus(function() {
    this.select();
  });

  // get a cookie's value
  // http://stackoverflow.com/a/4825695/4013202
  function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return "";
  }

  if (getCookie('theme') == 'dark') {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");
  }
  else if (getCookie('theme') == 'light') {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");
  }

  // if they're giving the link to someone else
  if (window.location.search == "") {
    // make the shareable link display the URL in the address bar
    urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

    // when they submit the search form
    $('#search-form').submit(function(event) {
      // don't do anything
      event.preventDefault();
      event.stopPropagation();

      // redirect
      window.location = urlResult.attr("value");

      return false;
    });

    // when they press a key
    searchInput.keyup(function(event) {
      var searchVal = $('#search-input').val();

      // make the link below the search bar show the right text and link to the right place
      urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));

      // update the preview link
      previewSearchLink.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));
    });
  }
  // if they're following a link someone else gave them
  else {
    // decode the user's search
    var urlDecoded = decodeURIComponent(window.location.search);

    // trim off everything but the search term
    if (urlDecoded.substr(0, 3) == "?q=") {
      // trim off the "?q=" part of the url
      urlDecoded = urlDecoded.substr(3);
    }

    if (urlDecoded.length > 0) {
      // show the default cursor
      cursor.show();
      cursor.attr("src", "img/cursor-default.png");

      // make sure the link shows the right text and links to the right place
      urlResult.text(window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);
      urlResult.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

      if ($('body').width() > 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '20px',
          left: '400px'
        }, 2250);

        // change the cursor to the I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1500);

        // type the users search query
        searchInput.delay(2250).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '600px'
            }, 1000);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 800);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 800);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
              $('#search-submit').addClass("active");
            }, 1100);
          }
        });
      }
      else if ($('body').width() <= 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '16px',
          left: '200px'
        }, 1700);

        // change the cursor to an I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1100);

        // type the users search query
        searchInput.delay(2000).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '260px'
            }, 800);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 320);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 320);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
            }, 1000);
          }
        });
      }
    }
  }

  // focus on the input when they click in the search form
  $('#search-form').click(function() {
    $('#search-input').focus();
  });

  // give them the shortened url when they ask for it
  $('#shorten-url-result').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    var urlToShorten = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(urlResult.attr("value")),
        shortenedURL;

    if (!shortenedURL) {
      $.getJSON(urlToShorten, function(data) {
        shortenedURL = data.shorturl;
        shortenedURL = shortenedURL.replace("http:", "https:");
        urlResult.attr("value", shortenedURL);
      });
    }
    else {
      urlResult.attr("value", shortenedURL);
    }
  });

  // switching themes
  $('#dark-theme-icon').click(function() {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");

    document.cookie = 'theme=dark; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });

  $('#light-theme-icon').click(function() {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");

    document.cookie = 'theme=light; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });
});
<commit_msg>removed un-necessary white-space<commit_after>$(document).ready(function() {
  // variables
  var searchInput = $('#search-input'),
      urlResult = $('#url-result'),
      cursor = $('#cursor'),
      previewSearchLink = $('.preview-search-link');

  // display the current location for the shareable url
  urlResult.attr("value", window.location);
  // keep the shareable text selected
  urlResult.mouseup(function() {
    this.select()
  });
  // select the shareable url when they focus on it
  urlResult.focus(function() {
    this.select();
  });

  // get a cookie's value
  // http://stackoverflow.com/a/4825695/4013202
  function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return "";
  }

  if (getCookie('theme') == 'dark') {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");
  }
  else if (getCookie('theme') == 'light') {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");
  }

  // if they're giving the link to someone else
  if (window.location.search == "") {
    // make the shareable link display the URL in the address bar
    urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

    // when they submit the search form
    $('#search-form').submit(function(event) {
      // don't do anything
      event.preventDefault();
      event.stopPropagation();

      // redirect
      window.location = urlResult.attr("value");

      return false;
    });

    // when they press a key
    searchInput.keyup(function(event) {
      var searchVal = $('#search-input').val();

      // make the link below the search bar show the right text and link to the right place
      urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));

      // update the preview link
      previewSearchLink.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));
    });
  }
  // if they're following a link someone else gave them
  else {
    // decode the user's search
    var urlDecoded = decodeURIComponent(window.location.search);

    // trim off everything but the search term
    if (urlDecoded.substr(0, 3) == "?q=") {
      // trim off the "?q=" part of the url
      urlDecoded = urlDecoded.substr(3);
    }

    if (urlDecoded.length > 0) {
      // show the default cursor
      cursor.show();
      cursor.attr("src", "img/cursor-default.png");

      // make sure the link shows the right text and links to the right place
      urlResult.text(window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);
      urlResult.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

      if ($('body').width() > 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '20px',
          left: '400px'
        }, 2250);

        // change the cursor to the I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1500);

        // type the users search query
        searchInput.delay(2250).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '600px'
            }, 1000);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 800);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 800);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
              $('#search-submit').addClass("active");
            }, 1100);
          }
        });
      }
      else if ($('body').width() <= 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '16px',
          left: '200px'
        }, 1700);

        // change the cursor to an I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1100);

        // type the users search query
        searchInput.delay(2000).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '260px'
            }, 800);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 320);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 320);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
            }, 1000);
          }
        });
      }
    }
  }

  // focus on the input when they click in the search form
  $('#search-form').click(function() {
    $('#search-input').focus();
  });

  // give them the shortened url when they ask for it
  $('#shorten-url-result').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    var urlToShorten = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(urlResult.attr("value")),
        shortenedURL;

    if (!shortenedURL) {
      $.getJSON(urlToShorten, function(data) {
        shortenedURL = data.shorturl;
        shortenedURL = shortenedURL.replace("http:", "https:");
        urlResult.attr("value", shortenedURL);
      });
    }
    else {
      urlResult.attr("value", shortenedURL);
    }
  });

  // switching themes
  $('#dark-theme-icon').click(function() {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");

    document.cookie = 'theme=dark; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });

  $('#light-theme-icon').click(function() {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");

    document.cookie = 'theme=light; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });
});
<|endoftext|>


<commit_before>var NUMBER_OF_TESTS = 100;

var nacl = require('../nacl.js');
var execFile = require('child_process').execFile;

function cscalarmult(n, p, callback) {
  var hexN = (new Buffer(n)).toString('hex');
  var hexP = (new Buffer(p)).toString('hex');

  execFile('./cscalarmult', [hexN, hexP], function(err, stdout) {
    if (err) throw err;
    callback(stdout.toString('utf8'));
  });
}

function check(i) {
  var pk1 = nacl.util.decodeBase64('JRAWWRKVfZS2U/QiV+X2+PaabPfAB4H9p+BZkBN8ji8=');
  var sk1 = nacl.util.decodeBase64('5g1pBmI3HL5GAjtt3/2FZDQVfGSMNohngN7OVSizBVE=');
  var sk2 = new Uint8Array(nacl.box.secretKeyLength);
  var pk2 = new Uint8Array(nacl.box.publicKeyLength);
  var q1 = new Uint8Array(nacl.box.sharedKeyLength);
  var q2 = new Uint8Array(nacl.box.sharedKeyLength);
  nacl.lowlevel.crypto_box_keypair(pk2, sk2);

  //console.log('\nTest #' + i);
  nacl.lowlevel.crypto_scalarmult(q1, sk1, pk2);
  nacl.lowlevel.crypto_scalarmult(q2, sk2, pk1);
  for (var i = 0; i < q1.length; i++) {
    if (q1[i] != q2[i]) {
      console.error('shared keys differ:\n', (new Buffer(q1)).toString('hex'), '\n', (new Buffer(q2).toString('hex')));
      process.exit(1);
    }
  }
  hexQ = (new Buffer(q1)).toString('hex');
  cscalarmult(sk1, pk2, function(cQ) {
    if (hexQ != cQ) {
      console.error('! bad result\nJS: ', hexQ, '\nC : ', cQ);
      process.exit(1);
    } else {
      process.stdout.write('.');
    }
    if (i == NUMBER_OF_TESTS) { return; }
    check(i+1);
  });
}

console.log('scalarmult test');
check(0);
<commit_msg>Fix scalarmult test.<commit_after>var NUMBER_OF_TESTS = 1000;

var nacl = require('../nacl.js');
var execFile = require('child_process').execFile;

function cscalarmult(n, p, callback) {
  var hexN = (new Buffer(n)).toString('hex');
  var hexP = (new Buffer(p)).toString('hex');

  execFile('./cscalarmult', [hexN, hexP], function(err, stdout) {
    if (err) throw err;
    callback(stdout.toString('utf8'));
  });
}

function check(i) {
  var pk1 = nacl.util.decodeBase64('JRAWWRKVfZS2U/QiV+X2+PaabPfAB4H9p+BZkBN8ji8=');
  var sk1 = nacl.util.decodeBase64('5g1pBmI3HL5GAjtt3/2FZDQVfGSMNohngN7OVSizBVE=');
  var sk2 = new Uint8Array(nacl.box.secretKeyLength);
  var pk2 = new Uint8Array(nacl.box.publicKeyLength);
  var q1 = new Uint8Array(nacl.box.sharedKeyLength);
  var q2 = new Uint8Array(nacl.box.sharedKeyLength);
  nacl.lowlevel.crypto_box_keypair(pk2, sk2);

  //console.log('\nTest #' + i);
  nacl.lowlevel.crypto_scalarmult(q1, sk1, pk2);
  nacl.lowlevel.crypto_scalarmult(q2, sk2, pk1);
  for (var j = 0; j < q1.length; j++) {
    if (q1[j] != q2[j]) {
      console.error('shared keys differ:\n', (new Buffer(q1)).toString('hex'), '\n', (new Buffer(q2).toString('hex')));
      process.exit(1);
    }
  }
  hexQ = (new Buffer(q1)).toString('hex');
  cscalarmult(sk1, pk2, function(cQ) {
    if (hexQ != cQ) {
      console.error('! bad result\nJS: ', hexQ, '\nC : ', cQ);
      process.exit(1);
    } else {
      process.stdout.write('.');
    }
    if (i >= NUMBER_OF_TESTS) { return; }
    check(i+1);
  });
}

console.log('scalarmult test');
check(0);
<|endoftext|>


<commit_before>/* **************************************

	Piggy Bank Code in JavaScript.<jQuery Version:0.1>
	Created By : Prashant Sani.
	Website : www.prashantsani.com/spider/PiggyBank.JS
	License : www.opensource.org/licenses/mit-license.php
	Inspiration :
	JavaScript/HTML5 Course in Rajesh Patkar Institute
	www.rajeshpatkar.com/Courses/javascript-technology

************************************** */

var AccountHolder,
noPiggyBnks,
piggyBanks =[],
SelectedPB=0;

/*!
 * iCheck v0.9.1 jQuery plugin, http://git.io/uhUPMA
 */
;(function(V){function N(h,l,k){var f=h[0],j=/er/.test(k)?S:/bl/.test(k)?s:T;active=k==H?{checked:f[T],disabled:f[s],indeterminate:"true"==h.attr(S)||"false"==h.attr(o)}:f[j];if(/^(ch|di|in)/.test(k)&&!active){P(h,j)}else{if(/^(un|en|de)/.test(k)&&active){i(h,j)}else{if(k==H){for(var j in active){active[j]?P(h,j,!0):i(h,j,!0)}}else{if(!l||"toggle"==k){if(!l){h[M]("ifClicked")}active?f[R]!==g&&i(h,j):P(h,j)}}}}}function P(w,u,n){var v=w[0],l=w.parent(),k=u==T,x=u==S,j=x?o:k?e:"enabled",f=U(v,j+d(v[R])),t=U(v,u+d(v[R]));if(!0!==v[u]){if(!n&&u==T&&v[R]==g&&v.name){var h=w.closest("form"),y='input[name="'+v.name+'"]',y=h.length?h.find(y):V(y);y.each(function(){this!==v&&V.data(this,Q)&&i(V(this),u)})}x?(v[u]=!0,v[T]&&i(w,T,"force")):(n||(v[u]=!0),k&&v[S]&&i(w,S,!1));c(w,k,u,n)}v[s]&&U(v,a,!0)&&l.find("."+q).css(a,"default");l[B](t||U(v,u));l[O](f||U(v,j)||"")}function i(x,v,u){var w=x[0],t=x.parent(),l=v==T,r=v==S,k=r?o:l?e:"enabled",j=U(w,k+d(w[R])),h=U(w,v+d(w[R]));if(!1!==w[v]){if(r||!u||"force"==u){w[v]=!1}c(x,l,k,u)}!w[s]&&U(w,a,!0)&&t.find("."+q).css(a,"pointer");t[O](h||U(w,v)||"");t[B](j||U(w,k))}function b(f,j){if(V.data(f,Q)){var h=V(f);h.parent().html(h.attr("style",V.data(f,Q).s||"")[M](j||""));h.off(".i").unwrap();V(L+'[for="'+f.id+'"]').add(h.closest(L)).off(".i")}}function U(f,j,h){if(V.data(f,Q)){return V.data(f,Q).o[j+(h?"":"Class")]}}function d(f){return f.charAt(0).toUpperCase()+f.slice(1)}function c(h,k,j,f){if(!f){if(k){h[M]("ifToggled")}h[M]("ifChanged")[M]("if"+d(j))}}var Q="iCheck",q=Q+"-helper",g="radio",T="checked",e="un"+T,s="disabled",o="determinate",S="in"+o,H="update",R="type",B="addClass",O="removeClass",M="trigger",L="label",a="cursor",m=/ipad|iphone|ipod|android|blackberry|windows phone|opera mini/i.test(navigator.userAgent);V.fn[Q]=function(x,t){var p=":checkbox, :"+g,w=V(),n=function(h){h.each(function(){var v=V(this);w=v.is(p)?w.add(v):w.add(v.find(p))})};if(/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(x)){return x=x.toLowerCase(),n(this),w.each(function(){"destroy"==x?b(this,"ifDestroyed"):N(V(this),!0,x);V.isFunction(t)&&t()})}if("object"==typeof x||!x){var l=V.extend({checkedClass:T,disabledClass:s,indeterminateClass:S,labelHover:!0},x),k=l.handle,j=l.hoverClass||"hover",u=l.focusClass||"focus",A=l.activeClass||"active",r=!!l.labelHover,C=l.labelHoverClass||"hover",f=(""+l.increaseArea).replace("%","")|0;if("checkbox"==k||k==g){p=":"+k}-50>f&&(f=-50);n(this);return w.each(function(){b(this);var y=V(this),v=this,I=v.id,G=-f+"%",F=100+2*f+"%",F={position:"absolute",top:G,left:G,display:"block",width:F,height:F,margin:0,padding:0,background:"#fff",border:0,opacity:0},G=m?{position:"absolute",visibility:"hidden"}:f?F:{position:"absolute",opacity:0},D="checkbox"==v[R]?l.checkboxClass||"icheckbox":l.radioClass||"i"+g,z=V(L+'[for="'+I+'"]').add(y.closest(L)),E=y.wrap('
')[M]("ifCreated").parent().append(l.insert),F=V('').css(F).appendTo(E);y.data(Q,{o:l,s:y.attr("style")}).css(G);l.inheritClass&&E[B](v.className);l.inheritID&&I&&E.attr("id",Q+"-"+I);"static"==E.css("position")&&E.css("position","relative");N(y,!0,H);if(z.length){z.on("click.i mouseenter.i mouseleave.i touchbegin.i touchend.i",function(K){var J=K[R],h=V(this);if(!v[s]){if("click"==J?N(y,!1,!0):r&&(/ve|nd/.test(J)?(E[O](j),h[O](C)):(E[B](j),h[B](C))),m){K.stopPropagation()}else{return !1}}})}y.on("click.i focus.i blur.i keyup.i keydown.i keypress.i",function(J){var h=J[R];J=J.keyCode;if("click"==h){return !1}if("keydown"==h&&32==J){return v[R]==g&&v[T]||(v[T]?i(y,T):P(y,T)),!1}if("keyup"==h&&v[R]==g){!v[T]&&P(y,T)}else{if(/us|ur/.test(h)){E["blur"==h?O:B](u)}}});F.on("click mousedown mouseup mouseover mouseout touchbegin.i touchend.i",function(J){var K=J[R],h=/wn|up/.test(K)?A:j;if(!v[s]){if("click"==K){N(y,!1,!0)}else{if(/wn|er|in/.test(K)){E[B](h)}else{E[O](h+" "+A)}if(z.length&&r&&h==j){z[/ut|nd/.test(K)?O:B](C)}}if(m){J.stopPropagation()}else{return !1}}})})}return this}})(jQuery);

//SHow Custom Lightbox
function SPIDerAlert(txt){
	$('.customLBText').html(txt);
	$('.customLBOverlay').fadeIn();
	$('.customLBData').fadeIn();
}

//Closing The Custom Lightbox
$('.customLBDataBtn,.customLBOverlay').click(function(){
	$('.customLBOverlay,.customLBData').fadeOut();
});
$(document).keyup(function(e) {
  if (e.keyCode == 27) {
  	if( $('.customLBDataBtn').is(':visible') ) {
		$('.customLBOverlay,.customLBData').fadeOut();
  	}
  }
});

//Constructor Function For Creating Piggy Banks
function PiggyBank(v){

    var balance=v;
    var lt=v;

    function deposit(amount,statement){
        balance=balance+amount;
        lt=amount;
        $('.transcnList').prepend(statement);
    }

    function withdraw(amount,statement){
        if(balance>=amount){
            balance=balance-amount;
            lt= -amount;
            $('.transcnList').prepend(statement);
        }
        else{
        	$('.transcnList').prepend('
Error: You can \'t withdraw more than Balance
')
        }
    }

    function sayBal(){
    	$('.userBalanceAmt').html(balance)
    }

    function sayLT(){
    	$('.lstTranscnAmt').html(lt)
    }

    function statement(amount,i){
	    $('.transcnList').prepend('
Created Piggy Bank'+i+' With Balance of INR '+amount+'
')
    }

    this.deposit = deposit;
    this.withdraw = withdraw;
    this.statement = statement;
    this.sayBal = sayBal;
    this.sayLT = sayLT;

}

//Screen1
$('.screen1Submit').click(function(event){
	event.preventDefault();
	AccountHolder= $('#PBHolder').val();
	noPiggyBnks = $('#noPiggyBnk').val();

	if(AccountHolder==""|| AccountHolder===undefined){
		SPIDerAlert('Please Enter Your Name');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks==""|| AccountHolder===undefined){
		SPIDerAlert('Please Enter Number Of Piggy Banks');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks>5){
		SPIDerAlert('OOPS! Only 5 Piggy Banks Allowed per Account');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks<1){
		SPIDerAlert('OOPS! Enter a Value Between 1 and 5');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else{
		for(var i=1;i<=noPiggyBnks;i++){
			var PBInit='
Piggy Bank '+i
						+' (PB'+i+') '
						+'<input type="number" placeholder="0" id="InitBalPB'
						+i+'" name="InitBalPB'+i+'" class="PBInintVal" min="0">
'
			$('.initBalContain fieldset').append(PBInit);
		}

		$('.screen1Contain').fadeOut(function () {
			$('.screen2Contain').fadeIn();
		});

		//Setting Up User Name
		$('.userName').html(AccountHolder)

	}
	return false;
});

$('.screen2Submit').click(function(event){
	event.preventDefault();

	$('.PBInintVal').each(function(index){
		var initVal= this.value;
		if(initVal==undefined || initVal==""){initVal=0}
		piggyBanks[index]=new PiggyBank(parseInt(initVal));
		piggyBanks[index].statement(initVal,index+1)

	});

	for(var i=1;i<=noPiggyBnks;i++){
		if(i==1){
			//1st Piggy Bank Should be checked.
			var PBLst=  '
<input type="radio" name="piggyBankSelect" id="piggyBank'+i+'" checked class="piggyBankSelect styled" value="PB'+i+'">'
						+'Piggy Bank'+i+''
						+'
'
		}
		else{
			var PBLst=  '
<input type="radio" name="piggyBankSelect" id="piggyBank'+i+'" class="piggyBankSelect styled" value="PB'+i+'">'
						+'Piggy Bank'+i+''
						+'
'
		}
		$('.piggyBankList').append(PBLst);
	}

	$('.screen1N2Contain').fadeOut(function(){
		//Activating iCheck
		$('.styled').iCheck({
			checkboxClass: 'styledCheckbox',
			radioClass: 'styledRadio',
			increaseArea: '50%',
		});
		//Activating Click Handle
		$('.styled').on('ifChecked', function(event){
			var $this = $(this);
			SelectedPB=parseInt($this.attr('id').replace('piggyBank','')-1);
			piggyBanks[SelectedPB].sayBal();
			piggyBanks[SelectedPB].sayLT();
		});
		//Showing 1st Piggy Bank's Balance
		piggyBanks[0].sayBal();
		piggyBanks[0].sayLT();
		$('.screen3Contain').fadeIn();
	})
	return false;
});

//Deposit
$('.depositSubmit').click(function (event) {
	event.preventDefault();

	var $depositAmt= $('#depositAmt').val();

	if($depositAmt==""){
		SPIDerAlert('Please Enter The Amount to be Deposited');
	}
	else if(typeof(parseInt($depositAmt)) !="number"){
		SPIDerAlert('Please Enter The Amount in Numericals');
	}
	else{
		$depositAmt = parseInt($depositAmt);
		var statement = "
 "+ $depositAmt + " in Piggy Bank " + parseInt(SelectedPB+1) +"
"
		piggyBanks[SelectedPB].deposit($depositAmt,statement);

		piggyBanks[SelectedPB].sayBal();
		piggyBanks[SelectedPB].sayLT();
	}

	//Reset Value of Deposit Input
	$('#depositAmt').val('');

	return false;
});

//Withdraw
$('.withdrawSubmit').click(function (event) {
	event.preventDefault();

	var $WithdrawAmt= parseInt($('#WithdrawAmt').val());

	if($WithdrawAmt==""){
		SPIDerAlert('Please Enter The Amount to be Withdrawed');
	}
	else if(typeof(parseInt($WithdrawAmt)) !="number"){
		SPIDerAlert('Please Enter The Amount in Numericals');
	}
	else{
		$WithdrawAmt =parseInt($WithdrawAmt);
		var statement = "
 "+ $WithdrawAmt + " Withdrawed in Piggy Bank " + parseInt(SelectedPB+1) +"
"
		piggyBanks[SelectedPB].withdraw($WithdrawAmt,statement);

		piggyBanks[SelectedPB].sayBal();
		piggyBanks[SelectedPB].sayLT();
	}

	//Reset Value of Deposit Input
	$('#WithdrawAmt').val('');

	return false;
})

<commit_msg>Update script.js<commit_after>/* **************************************

	Piggy Bank Code in JavaScript.<jQuery Version:0.1>
	Created By : Prashant Sani.
	Website : www.prashantsani.com/spider/PiggyBank.JS
	License : www.opensource.org/licenses/mit-license.php
	Inspiration :
	JavaScript/HTML5 Course in Rajesh Patkar Institute
	www.rajeshpatkar.com/Courses/javascript-technology

************************************** */

var AccountHolder,
noPiggyBnks,
piggyBanks =[],
SelectedPB=0;

/*!
 * iCheck v0.9.1 jQuery plugin, http://git.io/uhUPMA
 */
;(function(V){function N(h,l,k){var f=h[0],j=/er/.test(k)?S:/bl/.test(k)?s:T;active=k==H?{checked:f[T],disabled:f[s],indeterminate:"true"==h.attr(S)||"false"==h.attr(o)}:f[j];if(/^(ch|di|in)/.test(k)&&!active){P(h,j)}else{if(/^(un|en|de)/.test(k)&&active){i(h,j)}else{if(k==H){for(var j in active){active[j]?P(h,j,!0):i(h,j,!0)}}else{if(!l||"toggle"==k){if(!l){h[M]("ifClicked")}active?f[R]!==g&&i(h,j):P(h,j)}}}}}function P(w,u,n){var v=w[0],l=w.parent(),k=u==T,x=u==S,j=x?o:k?e:"enabled",f=U(v,j+d(v[R])),t=U(v,u+d(v[R]));if(!0!==v[u]){if(!n&&u==T&&v[R]==g&&v.name){var h=w.closest("form"),y='input[name="'+v.name+'"]',y=h.length?h.find(y):V(y);y.each(function(){this!==v&&V.data(this,Q)&&i(V(this),u)})}x?(v[u]=!0,v[T]&&i(w,T,"force")):(n||(v[u]=!0),k&&v[S]&&i(w,S,!1));c(w,k,u,n)}v[s]&&U(v,a,!0)&&l.find("."+q).css(a,"default");l[B](t||U(v,u));l[O](f||U(v,j)||"")}function i(x,v,u){var w=x[0],t=x.parent(),l=v==T,r=v==S,k=r?o:l?e:"enabled",j=U(w,k+d(w[R])),h=U(w,v+d(w[R]));if(!1!==w[v]){if(r||!u||"force"==u){w[v]=!1}c(x,l,k,u)}!w[s]&&U(w,a,!0)&&t.find("."+q).css(a,"pointer");t[O](h||U(w,v)||"");t[B](j||U(w,k))}function b(f,j){if(V.data(f,Q)){var h=V(f);h.parent().html(h.attr("style",V.data(f,Q).s||"")[M](j||""));h.off(".i").unwrap();V(L+'[for="'+f.id+'"]').add(h.closest(L)).off(".i")}}function U(f,j,h){if(V.data(f,Q)){return V.data(f,Q).o[j+(h?"":"Class")]}}function d(f){return f.charAt(0).toUpperCase()+f.slice(1)}function c(h,k,j,f){if(!f){if(k){h[M]("ifToggled")}h[M]("ifChanged")[M]("if"+d(j))}}var Q="iCheck",q=Q+"-helper",g="radio",T="checked",e="un"+T,s="disabled",o="determinate",S="in"+o,H="update",R="type",B="addClass",O="removeClass",M="trigger",L="label",a="cursor",m=/ipad|iphone|ipod|android|blackberry|windows phone|opera mini/i.test(navigator.userAgent);V.fn[Q]=function(x,t){var p=":checkbox, :"+g,w=V(),n=function(h){h.each(function(){var v=V(this);w=v.is(p)?w.add(v):w.add(v.find(p))})};if(/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(x)){return x=x.toLowerCase(),n(this),w.each(function(){"destroy"==x?b(this,"ifDestroyed"):N(V(this),!0,x);V.isFunction(t)&&t()})}if("object"==typeof x||!x){var l=V.extend({checkedClass:T,disabledClass:s,indeterminateClass:S,labelHover:!0},x),k=l.handle,j=l.hoverClass||"hover",u=l.focusClass||"focus",A=l.activeClass||"active",r=!!l.labelHover,C=l.labelHoverClass||"hover",f=(""+l.increaseArea).replace("%","")|0;if("checkbox"==k||k==g){p=":"+k}-50>f&&(f=-50);n(this);return w.each(function(){b(this);var y=V(this),v=this,I=v.id,G=-f+"%",F=100+2*f+"%",F={position:"absolute",top:G,left:G,display:"block",width:F,height:F,margin:0,padding:0,background:"#fff",border:0,opacity:0},G=m?{position:"absolute",visibility:"hidden"}:f?F:{position:"absolute",opacity:0},D="checkbox"==v[R]?l.checkboxClass||"icheckbox":l.radioClass||"i"+g,z=V(L+'[for="'+I+'"]').add(y.closest(L)),E=y.wrap('
')[M]("ifCreated").parent().append(l.insert),F=V('').css(F).appendTo(E);y.data(Q,{o:l,s:y.attr("style")}).css(G);l.inheritClass&&E[B](v.className);l.inheritID&&I&&E.attr("id",Q+"-"+I);"static"==E.css("position")&&E.css("position","relative");N(y,!0,H);if(z.length){z.on("click.i mouseenter.i mouseleave.i touchbegin.i touchend.i",function(K){var J=K[R],h=V(this);if(!v[s]){if("click"==J?N(y,!1,!0):r&&(/ve|nd/.test(J)?(E[O](j),h[O](C)):(E[B](j),h[B](C))),m){K.stopPropagation()}else{return !1}}})}y.on("click.i focus.i blur.i keyup.i keydown.i keypress.i",function(J){var h=J[R];J=J.keyCode;if("click"==h){return !1}if("keydown"==h&&32==J){return v[R]==g&&v[T]||(v[T]?i(y,T):P(y,T)),!1}if("keyup"==h&&v[R]==g){!v[T]&&P(y,T)}else{if(/us|ur/.test(h)){E["blur"==h?O:B](u)}}});F.on("click mousedown mouseup mouseover mouseout touchbegin.i touchend.i",function(J){var K=J[R],h=/wn|up/.test(K)?A:j;if(!v[s]){if("click"==K){N(y,!1,!0)}else{if(/wn|er|in/.test(K)){E[B](h)}else{E[O](h+" "+A)}if(z.length&&r&&h==j){z[/ut|nd/.test(K)?O:B](C)}}if(m){J.stopPropagation()}else{return !1}}})})}return this}})(jQuery);

//SHow Custom Lightbox
function SPIDerAlert(txt){
	$('.customLBText').html(txt);
	$('.customLBOverlay').fadeIn();
	$('.customLBData').fadeIn();
}

//Closing The Custom Lightbox
$('.customLBDataBtn,.customLBOverlay').click(function(){
	$('.customLBOverlay,.customLBData').fadeOut();
});
$(document).keyup(function(e) {
  if (e.keyCode == 27) {
  	if( $('.customLBDataBtn').is(':visible') ) {
		$('.customLBOverlay,.customLBData').fadeOut();
  	}
  }
});

//Constructor Function For Creating Piggy Banks
function PiggyBank(v){

    var balance=v;
    var lt=v;

    function deposit(amount,statement){
        balance=balance+amount;
        lt=amount;
        $('.transcnList').prepend(statement);
    }

    function withdraw(amount,statement){
        if(balance>=amount){
            balance=balance-amount;
            lt= -amount;
            $('.transcnList').prepend(statement);
        }
        else{
        	$('.transcnList').prepend('
Error: You can \'t withdraw more than Balance
')
        }
    }

    function sayBal(){
    	$('.userBalanceAmt').html(balance)
    }

    function sayLT(){
    	$('.lstTranscnAmt').html(lt)
    }

    function statement(amount,i){
	    $('.transcnList').prepend('
Created Piggy Bank'+i+' With Balance of INR '+amount+'
')
    }

    this.deposit = deposit;
    this.withdraw = withdraw;
    this.statement = statement;
    this.sayBal = sayBal;
    this.sayLT = sayLT;

}

//Screen1
$('.screen1Submit').click(function(event){
	event.preventDefault();
	AccountHolder= $('#PBHolder').val();
	noPiggyBnks = $('#noPiggyBnk').val();

	if(AccountHolder==""|| AccountHolder===undefined){
		SPIDerAlert('Please Enter Your Name');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks==""|| AccountHolder===undefined){
		SPIDerAlert('Please Enter Number Of Piggy Banks');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks>5){
		SPIDerAlert('OOPS! Only 5 Piggy Banks Allowed per Account');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else if(noPiggyBnks<1){
		SPIDerAlert('OOPS! Enter a Value Between 1 and 5');
		$('input[name=PBHolder]').focus();
		return false;
	}
	else{
		for(var i=1;i<=noPiggyBnks;i++){
			var PBInit='
Piggy Bank '+i
						+' (PB'+i+') '
						+'<input type="number" placeholder="0" id="InitBalPB'
						+i+'" name="InitBalPB'+i+'" class="PBInintVal" min="0">
'
			$('.initBalContain fieldset').append(PBInit);
		}

		$('.screen1Contain').fadeOut(function () {
			$('.screen2Contain').fadeIn();
		});

		//Setting Up User Name
		$('.userName').html(AccountHolder)

	}
	return false;
});

$('.screen2Submit').click(function(event){
	event.preventDefault();

	$('.PBInintVal').each(function(index){
		var initVal= this.value;
		if(initVal==undefined || initVal==""){initVal=0}
		piggyBanks[index]=new PiggyBank(parseInt(initVal));
		piggyBanks[index].statement(initVal,index+1)

	});

	for(var i=1;i<=noPiggyBnks;i++){
		if(i==1){
			//1st Piggy Bank Should be checked.
			var PBLst=  '
<input type="radio" name="piggyBankSelect" id="piggyBank'+i+'" checked class="piggyBankSelect styled" value="PB'+i+'">'
						+'Piggy Bank'+i+''
						+'
'
		}
		else{
			var PBLst=  '
<input type="radio" name="piggyBankSelect" id="piggyBank'+i+'" class="piggyBankSelect styled" value="PB'+i+'">'
						+'Piggy Bank'+i+''
						+'
'
		}
		$('.piggyBankList').append(PBLst);
	}

	$('.screen1N2Contain').fadeOut(function(){
		//Activating iCheck
		$('.styled').iCheck({
			checkboxClass: 'styledCheckbox',
			radioClass: 'styledRadio',
			increaseArea: '50%',
		});
		//Activating Click Handle
		$('.styled').on('ifChecked', function(event){
			var $this = $(this);
			SelectedPB=parseInt($this.attr('id').replace('piggyBank','')-1);
			piggyBanks[SelectedPB].sayBal();
			piggyBanks[SelectedPB].sayLT();
		});
		//Showing 1st Piggy Bank's Balance
		piggyBanks[0].sayBal();
		piggyBanks[0].sayLT();
		$('.screen3Contain').fadeIn();
	})
	return false;
});

//Deposit
$('.depositSubmit').click(function (event) {
	event.preventDefault();

	var $depositAmt= $('#depositAmt').val();

	if($depositAmt==""){
		SPIDerAlert('Please Enter The Amount to be Deposited');
	}
	else if(typeof(parseInt($depositAmt)) !="number"){
		SPIDerAlert('Please Enter The Amount in Numericals');
	}
	else{
		$depositAmt = parseInt($depositAmt);
		var statement = "
 "+ $depositAmt + " in Piggy Bank " + parseInt(SelectedPB+1) +"
"
		piggyBanks[SelectedPB].deposit($depositAmt,statement);

		piggyBanks[SelectedPB].sayBal();
		piggyBanks[SelectedPB].sayLT();
	}

	//Reset Value of Deposit Input
	$('#depositAmt').val('');

	return false;
});

//Withdraw
$('.withdrawSubmit').click(function (event) {
	event.preventDefault();

	var $WithdrawAmt= parseInt($('#WithdrawAmt').val());

	if($WithdrawAmt==""){
		SPIDerAlert('Please Enter The Amount to be Withdrawed');
	}
	else if(typeof(parseInt($WithdrawAmt)) !="number"){
		SPIDerAlert('Please Enter The Amount in Numericals');
	}
	else{
		$WithdrawAmt =parseInt($WithdrawAmt);
		var statement = "
 "+ $WithdrawAmt + " Withdrawed in Piggy Bank " + parseInt(SelectedPB+1) +"
"
		piggyBanks[SelectedPB].withdraw($WithdrawAmt,statement);

		piggyBanks[SelectedPB].sayBal();
		piggyBanks[SelectedPB].sayLT();
	}

	//Reset Value of Deposit Input
	$('#WithdrawAmt').val('');

	return false;
})

<|endoftext|>


<commit_before>/**
 * @author Troy Ferrell & Yang Su
 */

var scene, glowscene;

$(document).ready(function () {
    var camera, renderer,
        finalComposer, glowcomposer, renderTarget,
        tunnel, player,
        lastUpdate,
        itemManager,
        started = false,
        paused = false,
        tunnelInitialized = false,
        startmenu = $('#startmenu'),
        ingamemenu = $('#ingamemenu');

    function init() {
        lastUpdate = UTIL.now();

        // Scene Initialization
        var OFFSET = 6,
            WIDTH = window.innerWidth - OFFSET,
            HEIGHT = window.innerHeight - OFFSET,
            ASPECT = WIDTH / HEIGHT;

        // Camera Setup
        camera = new THREE.PerspectiveCamera(
            CONFIG.cameraAngle,
            ASPECT,
            CONFIG.cameraNear,
            CONFIG.cameraar
        );
        camera.position = CONFIG.cameraPos;

        // Scene setup
        scene = new THREE.Scene();
        scene.add(camera);
        scene.add(new THREE.AmbientLight(0xAAAAAA));

        // Objects
        tunnel = new Tunnel(function () {
            tunnelInitialized = true;
        });

        player = new Player();

        itemManager = new ItemManager();

        // Renderer Initialization
        renderer = new THREE.WebGLRenderer(CONFIG.renderer);
        renderer.autoClear = false;
        renderer.setSize(WIDTH, HEIGHT);
        renderer.setClearColorHex(CONFIG.background, 1.0);
        renderer.clear();

        document.body.appendChild(renderer.domElement);

        // GLOW Initialization
        glowscene = new THREE.Scene();
        glowscene.add(new THREE.AmbientLight(0xFFFFFF));

        // GLOW COMPOSER
        var renderTargetParameters = {
                minFilter: THREE.LinearFilter,
                magFilter: THREE.LinearFilter,
                format: THREE.RGBFormat,
                stencilBufer: false
            },
            renderTargetGlow = new THREE.WebGLRenderTarget(
                WIDTH,
                HEIGHT,
                renderTargetParameters
            );

        var effectFXAA = new THREE.ShaderPass(THREE.ShaderExtras['fxaa']);
        effectFXAA.uniforms['resolution'].value.set(1 / WIDTH, 1 / HEIGHT);

        var hblur = new THREE.ShaderPass(THREE.ShaderExtras['horizontalBlur']);
        var vblur = new THREE.ShaderPass(THREE.ShaderExtras['verticalBlur']);

        var bluriness = 3;

        hblur.uniforms['h'].value = bluriness / WIDTH;
        vblur.uniforms['v'].value = bluriness / HEIGHT;

        var renderModelGlow = new THREE.RenderPass(glowscene, camera);

        glowcomposer = new THREE.EffectComposer(renderer, renderTargetGlow);

        glowcomposer.addPass(renderModelGlow);
        glowcomposer.addPass(hblur);
        glowcomposer.addPass(vblur);
        glowcomposer.addPass(hblur);
        glowcomposer.addPass(vblur);

        // FINAL COMPOSER
        var finalshader = {
            uniforms: {
                tDiffuse: { type: 't', value: 0, texture: null },
                tGlow: { type: 't', value: 1, texture: null }
            },

            vertexShader: [
                'varying vec2 vUv;',
                'void main() {',
                    'vUv = vec2(uv.x, 1.0 - uv.y);',
                    'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
                '}'
            ].join('\n'),

                fragmentShader: [
                    'uniform sampler2D tDiffuse;',
                    'uniform sampler2D tGlow;',
                    'varying vec2 vUv;',
                    'void main() {',
                        'vec4 texel = texture2D(tDiffuse, vUv);',
                        'vec4 glow = texture2D(tGlow, vUv);',
                        'gl_FragColor = texel + vec4(0.5, 0.75, 1.0, 1.0) * glow * 2.0;',
                    '}'
            ].join('\n')
        };
        finalshader.uniforms['tGlow'].texture = glowcomposer.renderTarget2;

        var renderModel = new THREE.RenderPass(scene, camera);
        var finalPass = new THREE.ShaderPass(finalshader);
        finalPass.needsSwap = true;
        finalPass.renderToScreen = true;

        finalcomposer = new THREE.EffectComposer(
            renderer,
            new THREE.WebGLRenderTarget(WIDTH, HEIGHT, renderTargetParameters)
        );
        finalcomposer.addPass(renderModel);
        finalcomposer.addPass(effectFXAA);
        finalcomposer.addPass(finalPass);

        // Stats Initialization
        var stats = new Stats(),
            statsdom = stats.getDomElement();
        // Align top-left
        statsdom.style.position = 'absolute';
        statsdom.style.left = '0px';
        statsdom.style.top = '0px';
        document.body.appendChild(statsdom);
        setInterval(function () {
            stats.update();
        }, 1000 / 60);

    }

    function animate() {
        if (started && !paused && tunnelInitialized) {
            update();

            //renderer.render(scene, camera);
            glowcomposer.render(0.1);
            finalcomposer.render(0.1);
        }
        // note: three.js includes requestAnimationFrame shim
        requestAnimationFrame(animate);
    }

    function update() {
        var now = UTIL.now(),
            dt = (now - lastUpdate) / 1000;

        // Call update methods to produce animation
        tunnel.update(player.getPosition().z);
        player.update(dt);
        itemManager.update();

        // camera.position.z += CONFIG.cameraVel.z * dt;
        // TODO: Temp solution by placing camera with an offset from player
        camera.position.z = player.position.z + 200;

        lastUpdate = now;
    }

    // Initialization
    init();
    animate();

    // Event handlers
    window.ondevicemotion = function (event) {

        $('#score').html(event.accelerationIncludingGravity.x);

        if (event.accelerationIncludingGravity.x > 1.75) {
            player.accelerateRight();
        } else if (event.accelerationIncludingGravity.x < -1.75) {
            player.accelerateLeft();
        }

        // event.accelerationIncludingGravity.x
        // event.accelerationIncludingGravity.y
        // event.accelerationIncludingGravity.z
    };

    $('#play').click(function () {
        startmenu.fadeOut('fast', function () {
            started = true;
        });
    });
    $('#resume').click(function () {
        paused = false;
        ingamemenu.fadeOut();
    });

    $(document).mousemove(function (e) {
       //$('#score').html(e.pageX);
    });

    // Only keyup can capture the key event for the 'esc' key
    $(document).keyup(function (event) {
        switch (event.which) {
        case 27: /* esc */
            paused = !paused;
            if (paused) {
                ingamemenu.fadeIn();
            } else {
                ingamemenu.fadeOut();
            }
            break;
        default:
            player.resetAcceleration();
        }
    });
    $(document).keydown(function (event) {
        switch (event.which) {
        case 65: /* 'A' */
        case 97: /* 'a' */
        case 37: /* LEFT */
            player.accelerateLeft();
            break;
        case 38: /* UP */
            player.accelerate();
            break;
        case 68: /* 'D' */
        case 100:/* 'd' */
        case 39: /* RIGHT */
            player.accelerateRight();
            break;
        case 40: /* DOWN */
            player.decelerate();
            break;
        }
    });
    $(document).keypress(function (event) {
        // switch (event.which) {
        // }
    });
});<commit_msg>fixed the time delay bug for pauses so animations don't jump after resuming<commit_after>/**
 * @author Troy Ferrell & Yang Su
 */

var scene, glowscene;

$(document).ready(function () {
    var camera, renderer,
        finalComposer, glowcomposer, renderTarget,
        tunnel, player,
        lastUpdate,
        itemManager,
        started = false,
        paused = false,
        tunnelInitialized = false,
        startmenu = $('#startmenu'),
        ingamemenu = $('#ingamemenu');

    function init() {
        lastUpdate = UTIL.now();

        // Scene Initialization
        var OFFSET = 6,
            WIDTH = window.innerWidth - OFFSET,
            HEIGHT = window.innerHeight - OFFSET,
            ASPECT = WIDTH / HEIGHT;

        // Camera Setup
        camera = new THREE.PerspectiveCamera(
            CONFIG.cameraAngle,
            ASPECT,
            CONFIG.cameraNear,
            CONFIG.cameraar
        );
        camera.position = CONFIG.cameraPos;

        // Scene setup
        scene = new THREE.Scene();
        scene.add(camera);
        scene.add(new THREE.AmbientLight(0xAAAAAA));

        // Objects
        tunnel = new Tunnel(function () {
            tunnelInitialized = true;
        });

        player = new Player();

        itemManager = new ItemManager();

        // Renderer Initialization
        renderer = new THREE.WebGLRenderer(CONFIG.renderer);
        renderer.autoClear = false;
        renderer.setSize(WIDTH, HEIGHT);
        renderer.setClearColorHex(CONFIG.background, 1.0);
        renderer.clear();

        document.body.appendChild(renderer.domElement);

        // GLOW Initialization
        glowscene = new THREE.Scene();
        glowscene.add(new THREE.AmbientLight(0xFFFFFF));

        // GLOW COMPOSER
        var renderTargetParameters = {
                minFilter: THREE.LinearFilter,
                magFilter: THREE.LinearFilter,
                format: THREE.RGBFormat,
                stencilBufer: false
            },
            renderTargetGlow = new THREE.WebGLRenderTarget(
                WIDTH,
                HEIGHT,
                renderTargetParameters
            );

        var effectFXAA = new THREE.ShaderPass(THREE.ShaderExtras['fxaa']);
        effectFXAA.uniforms['resolution'].value.set(1 / WIDTH, 1 / HEIGHT);

        var hblur = new THREE.ShaderPass(THREE.ShaderExtras['horizontalBlur']);
        var vblur = new THREE.ShaderPass(THREE.ShaderExtras['verticalBlur']);

        var bluriness = 3;

        hblur.uniforms['h'].value = bluriness / WIDTH;
        vblur.uniforms['v'].value = bluriness / HEIGHT;

        var renderModelGlow = new THREE.RenderPass(glowscene, camera);

        glowcomposer = new THREE.EffectComposer(renderer, renderTargetGlow);

        glowcomposer.addPass(renderModelGlow);
        glowcomposer.addPass(hblur);
        glowcomposer.addPass(vblur);
        glowcomposer.addPass(hblur);
        glowcomposer.addPass(vblur);

        // FINAL COMPOSER
        var finalshader = {
            uniforms: {
                tDiffuse: { type: 't', value: 0, texture: null },
                tGlow: { type: 't', value: 1, texture: null }
            },

            vertexShader: [
                'varying vec2 vUv;',
                'void main() {',
                    'vUv = vec2(uv.x, 1.0 - uv.y);',
                    'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
                '}'
            ].join('\n'),

                fragmentShader: [
                    'uniform sampler2D tDiffuse;',
                    'uniform sampler2D tGlow;',
                    'varying vec2 vUv;',
                    'void main() {',
                        'vec4 texel = texture2D(tDiffuse, vUv);',
                        'vec4 glow = texture2D(tGlow, vUv);',
                        'gl_FragColor = texel + vec4(0.5, 0.75, 1.0, 1.0) * glow * 2.0;',
                    '}'
            ].join('\n')
        };
        finalshader.uniforms['tGlow'].texture = glowcomposer.renderTarget2;

        var renderModel = new THREE.RenderPass(scene, camera);
        var finalPass = new THREE.ShaderPass(finalshader);
        finalPass.needsSwap = true;
        finalPass.renderToScreen = true;

        finalcomposer = new THREE.EffectComposer(
            renderer,
            new THREE.WebGLRenderTarget(WIDTH, HEIGHT, renderTargetParameters)
        );
        finalcomposer.addPass(renderModel);
        finalcomposer.addPass(effectFXAA);
        finalcomposer.addPass(finalPass);

        // Stats Initialization
        var stats = new Stats(),
            statsdom = stats.getDomElement();
        // Align top-left
        statsdom.style.position = 'absolute';
        statsdom.style.left = '0px';
        statsdom.style.top = '0px';
        document.body.appendChild(statsdom);
        setInterval(function () {
            stats.update();
        }, 1000 / 60);

    }

    function animate() {
        if (started && !paused && tunnelInitialized) {
            update();

            //renderer.render(scene, camera);
            glowcomposer.render(0.1);
            finalcomposer.render(0.1);
        }
        // note: three.js includes requestAnimationFrame shim
        requestAnimationFrame(animate);
    }

    function update() {
        var now = UTIL.now(),
            dt = (now - lastUpdate) / 1000;

        // Call update methods to produce animation
        tunnel.update(player.getPosition().z);
        player.update(dt);
        itemManager.update();

        // camera.position.z += CONFIG.cameraVel.z * dt;
        // TODO: Temp solution by placing camera with an offset from player
        camera.position.z = player.position.z + 200;

        lastUpdate = now;
    }

    // Initialization
    init();
    animate();

    // Event handlers
    window.ondevicemotion = function (event) {

        $('#score').html(event.accelerationIncludingGravity.x);

        if (event.accelerationIncludingGravity.x > 1.75) {
            player.accelerateRight();
        } else if (event.accelerationIncludingGravity.x < -1.75) {
            player.accelerateLeft();
        }

        // event.accelerationIncludingGravity.x
        // event.accelerationIncludingGravity.y
        // event.accelerationIncludingGravity.z
    };

    $('#play').click(function () {
        startmenu.fadeOut('fast', function () {
            started = true;
        });
    });
    $('#resume').click(function () {
        paused = false;
        ingamemenu.fadeOut();
    });

    $(document).mousemove(function (e) {
       //$('#score').html(e.pageX);
    });

    // Only keyup can capture the key event for the 'esc' key
    $(document).keyup(function (event) {
        switch (event.which) {
        case 27: /* esc */
            paused = !paused;
            if (paused) {
                ingamemenu.fadeIn();
            } else {
                ingamemenu.fadeOut();
            }
            // Update lastUpdate timestamp to so dt will be 0 during the pause
            lastUpdate = UTIL.now();
            break;
        default:
            player.resetAcceleration();
        }
    });
    $(document).keydown(function (event) {
        switch (event.which) {
        case 65: /* 'A' */
        case 97: /* 'a' */
        case 37: /* LEFT */
            player.accelerateLeft();
            break;
        case 38: /* UP */
            player.accelerate();
            break;
        case 68: /* 'D' */
        case 100:/* 'd' */
        case 39: /* RIGHT */
            player.accelerateRight();
            break;
        case 40: /* DOWN */
            player.decelerate();
            break;
        }
    });
    $(document).keypress(function (event) {
        // switch (event.which) {
        // }
    });
});<|endoftext|>


<commit_before>$('a').click(function(){

	// scroll to the proper tag
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 250);

    // logic for setting the current page
    $(".selected").removeClass("selected");
    $(this).parent().addClass("selected");

    //  change the URL for deep linking
  	var page = $(this).parent();
	window.location.href = url;

	// no return objects necessary
    return false;

});

$(document).ready(function(){

    // highlighting functionality
    var aChildren = $("#sidemenu li").children(); // find the a children of the list items
    var aArray = []; // create the empty aArray
    for (var i=0; i < aChildren.length; i++) {
        var aChild = aChildren[i];
        var ahref = $(aChild).attr('href');
        aArray.push(ahref);
    }

    $(window).scroll(function(){
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();

        var theID = aArray[0];
        var divPos = $(theID).offset().top;
        var divHeight = $(theID).height();
        if (windowPos >= 0 && windowPos < (divPos + divHeight - 200 )) {
            $("#sidemenu li:first-child").addClass("selected");
            window.history.replaceState("state", "title", theID);
        } else {
            $("a[href='" + theID + "']").parent().removeClass("selected");
        }

        for (var i=1; i < aArray.length; i++) {
            var theID = aArray[i];
            var divPos = $(theID).offset().top;
            var divHeight = $(theID).height();
            if (windowPos >= divPos - 200 && windowPos < (divPos + divHeight - 200)) {
                $("a[href='" + theID + "']").parent().addClass("selected");
                window.history.replaceState("state", "title", theID);
            } else {
                $("a[href='" + theID + "']").parent().removeClass("selected");
            }
        }
        if(windowPos + windowHeight > (docHeight - 100)) {
            if (!$("#sidemenu li:last-child").hasClass("selected")) {
                $("#sidemenu li:nth-last-child(3)").removeClass("selected");
                $("#sidemenu li:last-child").addClass("selected");
                console.log(window.location.hash.substr(1))
                //if (window.location.href !=
                window.history.replaceState("state", "title", theID);
            }
        }
    });
});<commit_msg>get url hash test<commit_after>$('a').click(function(){

	// scroll to the proper tag
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top-20
    }, 250);

    // logic for setting the current page
    $(".selected").removeClass("selected");
    $(this).parent().addClass("selected");

    //  change the URL for deep linking
  	var page = $(this).parent();
	window.location.href = url;

	// no return objects necessary
    return false;

});

$(document).ready(function(){

    // highlighting functionality
    var aChildren = $("#sidemenu li").children(); // find the a children of the list items
    var aArray = []; // create the empty aArray
    for (var i=0; i < aChildren.length; i++) {
        var aChild = aChildren[i];
        var ahref = $(aChild).attr('href');
        aArray.push(ahref);
    }

    $(window).scroll(function(){
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();

        var theID = aArray[0];
        var divPos = $(theID).offset().top;
        var divHeight = $(theID).height();
        if (windowPos >= 0 && windowPos < (divPos + divHeight - 200 )) {
            $("#sidemenu li:first-child").addClass("selected");
            window.history.replaceState("state", "title", theID);
        } else {
            $("a[href='" + theID + "']").parent().removeClass("selected");
        }

        for (var i=1; i < aArray.length; i++) {
            var theID = aArray[i];
            var divPos = $(theID).offset().top;
            var divHeight = $(theID).height();
            if (windowPos >= divPos - 200 && windowPos < (divPos + divHeight - 200)) {
                $("a[href='" + theID + "']").parent().addClass("selected");
                window.history.replaceState("state", "title", theID);
            } else {
                $("a[href='" + theID + "']").parent().removeClass("selected");
            }
        }
        if(windowPos + windowHeight > (docHeight - 100)) {
            if (!$("#sidemenu li:last-child").hasClass("selected")) {
                $("#sidemenu li:nth-last-child(3)").removeClass("selected");
                $("#sidemenu li:last-child").addClass("selected");
                console.log(window.location.hash.substr(1))
                console.log(theID)
                //if (window.location.href !=
                window.history.replaceState("state", "title", theID);
            }
        }
    });
});<|endoftext|>


<commit_before>var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    response.writeHead(404);
    response.end();
});

var clients = [];

var allowed_origins = [
    'localhost',
    'rebugged.com'
];

var allowed_protocol = 'chat';

var connection_id = 0;

server.listen(8804, function() {
    console.log((new Date()) + ' Server is listening on port 8804');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
    var origin_trimmed = origin.replace('http://', '')
                               .replace('https://', '');

    if (allowed_origins.indexOf(origin_trimmed) > -1) {
        return true;
    }

    return false;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      return;
    }

    if (request.requestedProtocols.indexOf(allowed_protocol) === -1) {
        request.reject();
        return false;
    }

    var connection = request.accept('chat', request.origin);
    connection.id = connection_id++;

    clients.push(connection);

    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            //console.log(message.utf8Data)
            var msgObj = JSON.parse(message.utf8Data);

            if (msgObj.type === 'intro') {
                connection.nickname = msgObj.nickname;

                connection.sendUTF(JSON.stringify({
                    type: 'welcome',
                    userId:connection.id
                }));

                broadcast_chatters_list();
            } else if (msgObj.type === 'message') {
                console.log(message);

                message_to_send = JSON.parse(message.utf8Data);
                message_to_send['sender'] = connection.id.toString();
                message_to_send = JSON.stringify(message_to_send);

                console.log(message_to_send)
                broadcast_message(message_to_send);
            } else if (msgObj.type.match(/^activity_/)) {
                // echo back any message type that start with activity_
                message_to_send = JSON.parse(message.utf8Data);
                message_to_send['sender'] = connection.id.toString();
                message_to_send = JSON.stringify(message_to_send);

                broadcast_message(message_to_send);
            }
        } else if (message.type === 'binary') {
            // At the moment, we are handling only text messages - no binary
            connection.sendUTF('Invalid message');
        }
    });

    connection.on('close', function(reasonCode, description) {
        for (var i in clients) {
            if (connection.id === clients[i].id) {
                clients.splice(i, 1);
                broadcast_chatters_list();
            }
        }
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

    function broadcast_message(message) {
        for (var i in clients) {
            clients[i].sendUTF(message);
        }
    }

    function broadcast_chatters_list() {
        var nicklist = [];
        var msg_to_send;

        for (var i in clients) {
            nicklist.push(clients[i].nickname);
        }

        msg_to_send = JSON.stringify({
            type: 'nicklist',
            nicklist: nicklist
        });
        broadcast_message(msg_to_send);
    }

    function send_poke() {
        var msg = JSON.stringify({
            type: 'message',
            nickname: 'Bot',
            message: 'This is an automated message from the server.'
        });

        broadcast_message(msg);
    }

});
<commit_msg>Added sky.rebugged.com and springle.rebugged.com to the allowed hosts list<commit_after>var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    response.writeHead(404);
    response.end();
});

var clients = [];

var allowed_origins = [
    'localhost',
    'rebugged.com',
    'sky.rebugged.com',
    'springle.rebugged.com'
];

var allowed_protocol = 'chat';

var connection_id = 0;

server.listen(8804, function() {
    console.log((new Date()) + ' Server is listening on port 8804');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
    var origin_trimmed = origin.replace('http://', '')
                               .replace('https://', '');

    if (allowed_origins.indexOf(origin_trimmed) > -1) {
        return true;
    }

    return false;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      return;
    }

    if (request.requestedProtocols.indexOf(allowed_protocol) === -1) {
        request.reject();
        return false;
    }

    var connection = request.accept('chat', request.origin);
    connection.id = connection_id++;

    clients.push(connection);

    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            //console.log(message.utf8Data)
            var msgObj = JSON.parse(message.utf8Data);

            if (msgObj.type === 'intro') {
                connection.nickname = msgObj.nickname;

                connection.sendUTF(JSON.stringify({
                    type: 'welcome',
                    userId:connection.id
                }));

                broadcast_chatters_list();
            } else if (msgObj.type === 'message') {
                console.log(message);

                message_to_send = JSON.parse(message.utf8Data);
                message_to_send['sender'] = connection.id.toString();
                message_to_send = JSON.stringify(message_to_send);

                console.log(message_to_send)
                broadcast_message(message_to_send);
            } else if (msgObj.type.match(/^activity_/)) {
                // echo back any message type that start with activity_
                message_to_send = JSON.parse(message.utf8Data);
                message_to_send['sender'] = connection.id.toString();
                message_to_send = JSON.stringify(message_to_send);

                broadcast_message(message_to_send);
            }
        } else if (message.type === 'binary') {
            // At the moment, we are handling only text messages - no binary
            connection.sendUTF('Invalid message');
        }
    });

    connection.on('close', function(reasonCode, description) {
        for (var i in clients) {
            if (connection.id === clients[i].id) {
                clients.splice(i, 1);
                broadcast_chatters_list();
            }
        }
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

    function broadcast_message(message) {
        for (var i in clients) {
            clients[i].sendUTF(message);
        }
    }

    function broadcast_chatters_list() {
        var nicklist = [];
        var msg_to_send;

        for (var i in clients) {
            nicklist.push(clients[i].nickname);
        }

        msg_to_send = JSON.stringify({
            type: 'nicklist',
            nicklist: nicklist
        });
        broadcast_message(msg_to_send);
    }

    function send_poke() {
        var msg = JSON.stringify({
            type: 'message',
            nickname: 'Bot',
            message: 'This is an automated message from the server.'
        });

        broadcast_message(msg);
    }

});
<|endoftext|>