<commit_before>(function () {

    var app = angular.module('myApp', ['firebase', 'ngRoute']);
    var myDataRef = new Firebase('https://burning-heat-392.firebaseio.com');
    var authData = myDataRef.getAuth();

    app.config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);

            $routeProvider.
              when('/', {
                  templateUrl: 'app/index.html',
                  controller: 'MainController'
              }).
              when('/cars', {
                  templateUrl: 'app/partials/car-info.html',
                  controller: 'MainController'
              }).
              when('/register', {
                  templateUrl: 'app/partials/register.html',
                  controller: 'MainController'
              }).
              when('/addcar', {
                  templateUrl: 'app/partials/add-car.html',
                  controller: 'MainController'
              }).
              when('/editcar/:id', {
                  templateUrl: 'app/partials/editcar.html',
                  controller: 'editCarController'
              }).
              when('/login', {
                  templateUrl: 'app/partials/login.html',
                  controller: 'MainController'
              }).
              when('/addrepair/:id', {
                  templateUrl: 'app/partials/add-repair.html',
                  controller: 'MainController'
              }).
              otherwise({
                  redirectTo: 'app/index.html'
              });
        }]);

    app.controller("MainController", ["$scope", "$firebase", "$location", "$routeParams", function($scope, $firebase, $location, $routeParams) {
        //var sync = $firebase(myDataRef);

        $scope.addCar = function(year, make, model) {
            console.log('authData before getAuth: ' + authData);
            var authData = myDataRef.getAuth();
            var currentUser = myDataRef.child('users').child(authData.uid);
            var vehicleRef = myDataRef.child('vehicles').push();
            var vehicleRefID = vehicleRef.name();
            //var vehicleRef = myDataRef.child('users').child(authData.uid).child('vehicles');
            //var sync = $firebase(vehicleRef);

            console.log("current user: " + currentUser);
            console.log("vehiclerefid: " + vehicleRefID);
            var picture = "app/img/default-vehicle.png";

            vehicleRef.set({year: year, make: make, model: model, picture: picture});
            currentUser.child("vehicles").child(vehicleRefID).set(true);
            /*vehicleRef.push({
                year: $scope.year,
                make: $scope.make,
                model: $scope.model,
                picture: $scope.picture
            });*/

            console.log("End of addCar function reached");
            $location.path('/cars');

        };

        $scope.editCar = function(year, make, model) {
            console.log("start editcar function");
            $scope.vehicle = $scope.carlist[$routeParams.id];
            console.log($scope.vehicle);
            $scope.$save();
            $location.path('/cars');
        }

        $scope.addRepair = function(carID) {
            console.log("Starting addRepair");
            var authData = myDataRef.getAuth();
            //console.log($scope.$index);
            //console.log(carID);
            /*$scope.repair = $scope.vehicle[$routeParams.id];
            console.log("scope.repair: " + $scope.repair);
            */
            console.log("scope.id: " + $scope.$id);
            console.log("scope.id without $ on id:" + $scope.id);
            myDataRef.child('users').child(authData.uid).child('vehicles').child(carID).child('repairs').push({
                work: $scope.work,
                cost: $scope.cost,
                mileage: $scope.mileage
            });
            console.log("End of addRepair function");
            $location.path('/cars');
        };

        $scope.removeCar = function() {
            console.log("Starting removeCar");
            var authData = myDataRef.getAuth();
        };

        $scope.register = function() {
            console.log("Register function entered");
            console.log("user: " + $scope.emailRegister + " / pw: " + $scope.passwordRegister);

            myDataRef.createUser({
                email    : $scope.emailRegister,
                password : $scope.passwordRegister
            }, function(error) {
                if (error === null) {
                    console.log("user created successfully");
                    myDataRef.authWithPassword({
                        email   : $scope.emailRegister,
                        password: $scope.passwordRegister
                    }, function ( error, authData) {
                        console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                        myDataRef.child('users').child(authData.uid).set(authData);
                        $location.path('/');
                    })
                } else {
                    console.log("error creating user:", error);
                }
            });
        };

        $scope.login = function () {
            myDataRef.authWithPassword({
                email    : $scope.emailLogin,
                password : $scope.passwordLogin
            }, function (error, authData) {
                if (error === null) {
                    console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                    $location.path('/cars');
                } else {
                    alert("Error authenticating: ", error);
                }
            });
        };

        $('.bt-social').on('click', function(e) {

            var $currentButton = $(this);
            var provider = $currentButton.data("provider");
            e.preventDefault();
            console.log("bt social clicked with provider " + provider);

            thirdPartyLogin(provider);
        });

        function thirdPartyLogin(provider) {
            console.log("third party login entered");
            myDataRef.authWithOAuthPopup(provider, function (error, authData) {
                if (error === null) {
                    console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                    $location.path('/cars');
                } else {
                    alert("Error authenticating: ", error);
                }
            });
        };

        $scope.logout = function() {
            myDataRef.unauth();
            $scope.authData = "";
            $('.login-state').html("Not logged in");
            alert("You are logged out");
			console.log("User logged out");
            $location.path('/');
        };

        myDataRef.onAuth(function(authData) {
            if (authData) {
                $('.login-state').html("Logged In");
                $scope.authData = authData;
                var vehicleRef = myDataRef.child('users').child(authData.uid).child('vehicles');
                //var vehicleRef = myDataRef.child('users').child(authData.uid).child('vehicles');
                var sync = $firebase(vehicleRef);
                carlist = sync.$asArray();

                carlist.$loaded().then(function() {
                    console.log("list has " + carlist.length + " items");
                    console.log(carlist);
                });

                $scope.carlist = carlist;
                console.log("cars assigned, carlist scope = " + $scope.carlist);
            } else {
                $('.loginState').html("Not Logged In");
            }
        });

    }]);

    app.controller("editCarController", ["$scope", "$firebase", "$location", "$routeParams", function($scope, $firebase, $location, $routeParams) {
        console.log("starting edit controller");
        var authData = myDataRef.getAuth();
        var ref = new Firebase(myDataRef + '/users/' + authData.uid + '/vehicles/');
        var sync = $firebase(ref);
        var carlist = sync.$asArray();
        console.log(carlist);
        console.log(carlist[$routeParams.id]);
        $scope.vehicle = carlist.$getRecord($routeParams.id);
        console.log($scope.vehicle);
    }]);

    function handleFileSelect(evt) {
        var f = evt.target.files[0];
        var reader = new FileReader();
        console.log("entered file select");
        reader.onload = (function(theFile) {
            return function(e) {
                var filePayload = e.target.result;
                // Generate a location that can't be guessed using the file's contents and a random number
                var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
                var f = new Firebase(myDataRef + '/pano/' + hash + '/filePayload');
                console.log(f);
               // spinner.spin(document.getElementById('spin'));
               // Set the file payload to Firebase and register an onComplete handler to stop the spinner and show the preview
               f.set(filePayload, function() {
                 // spinner.stop();
                            //document.getElementById("pano").src = e.target.result;
                 //$('#file-upload').hide();
                 // Update the location bar so the URL can be shared with others
                 window.location.hash = hash;
               });
             };
            })(f);
            reader.readAsDataURL(f);
        }
    /*$(function() {
        // $('#spin').append(spinner);
        console.log("entered function");
        var myDataRef = new Firebase('https://burning-heat-392.firebaseio.com');
        var idx = window.location.href.indexOf('#');
        var hash = (idx > 0) ? window.location.href.slice(idx + 1) : '';
        if (hash === '') {
            // No hash found, so render the file upload button.
            $('#file-upload').show();
            //document.getElementById("file-upload").addEventListener('change', handleFileSelect, false);
        } else {
            // A hash was passed in, so let's retrieve and render it.
            // spinner.spin(document.getElementById('spin'));
            var f = new Firebase(myDataRef + '/pano/' + hash + '/filePayload');
            console.log(f);
        f.once('value', function(snap) {
            var payload = snap.val();
            if (payload != null) {
            document.getElementById("pano").src = payload;
            } else {
            $('#body').append("Not found");
            }
            //spinner.stop();
        });
      }
    }); */
}())
<commit_msg>started on pulling vehicle data callback<commit_after>(function () {

    var app = angular.module('myApp', ['firebase', 'ngRoute']);
    var myDataRef = new Firebase('https://burning-heat-392.firebaseio.com');
    var authData = myDataRef.getAuth();

    app.config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);

            $routeProvider.
              when('/', {
                  templateUrl: 'app/index.html',
                  controller: 'MainController'
              }).
              when('/cars', {
                  templateUrl: 'app/partials/car-info.html',
                  controller: 'MainController'
              }).
              when('/register', {
                  templateUrl: 'app/partials/register.html',
                  controller: 'MainController'
              }).
              when('/addcar', {
                  templateUrl: 'app/partials/add-car.html',
                  controller: 'MainController'
              }).
              when('/editcar/:id', {
                  templateUrl: 'app/partials/editcar.html',
                  controller: 'editCarController'
              }).
              when('/login', {
                  templateUrl: 'app/partials/login.html',
                  controller: 'MainController'
              }).
              when('/addrepair/:id', {
                  templateUrl: 'app/partials/add-repair.html',
                  controller: 'MainController'
              }).
              otherwise({
                  redirectTo: 'app/index.html'
              });
        }]);

    app.controller("MainController", ["$scope", "$firebase", "$location", "$routeParams", function($scope, $firebase, $location, $routeParams) {
        //var sync = $firebase(myDataRef);

        $scope.addCar = function(year, make, model) {
            console.log('authData before getAuth: ' + authData);
            var authData = myDataRef.getAuth();
            var currentUser = myDataRef.child('users').child(authData.uid);
            var vehicleRef = myDataRef.child('vehicles').push();
            var vehicleRefID = vehicleRef.name();
            //var vehicleRef = myDataRef.child('users').child(authData.uid).child('vehicles');
            //var sync = $firebase(vehicleRef);

            console.log("current user: " + currentUser);
            console.log("vehiclerefid: " + vehicleRefID);
            var picture = "app/img/default-vehicle.png";

            vehicleRef.set({year: year, make: make, model: model, picture: picture, user: authData.uid});
            currentUser.child("vehicles").child(vehicleRefID).set(true);
            /*vehicleRef.push({
                year: $scope.year,
                make: $scope.make,
                model: $scope.model,
                picture: $scope.picture
            });*/

            console.log("End of addCar function reached");
            $location.path('/cars');

        };

        $scope.editCar = function(year, make, model) {
            console.log("start editcar function");
            $scope.vehicle = $scope.carlist[$routeParams.id];
            console.log($scope.vehicle);
            $scope.$save();
            $location.path('/cars');
        }

        $scope.addRepair = function(carID) {
            console.log("Starting addRepair");
            var authData = myDataRef.getAuth();
            //console.log($scope.$index);
            //console.log(carID);
            /*$scope.repair = $scope.vehicle[$routeParams.id];
            console.log("scope.repair: " + $scope.repair);
            */
            console.log("scope.id: " + $scope.$id);
            console.log("scope.id without $ on id:" + $scope.id);
            myDataRef.child('users').child(authData.uid).child('vehicles').child(carID).child('repairs').push({
                work: $scope.work,
                cost: $scope.cost,
                mileage: $scope.mileage
            });
            console.log("End of addRepair function");
            $location.path('/cars');
        };

        $scope.removeCar = function() {
            console.log("Starting removeCar");
            var authData = myDataRef.getAuth();
        };

        $scope.register = function() {
            console.log("Register function entered");
            console.log("user: " + $scope.emailRegister + " / pw: " + $scope.passwordRegister);

            myDataRef.createUser({
                email    : $scope.emailRegister,
                password : $scope.passwordRegister
            }, function(error) {
                if (error === null) {
                    console.log("user created successfully");
                    myDataRef.authWithPassword({
                        email   : $scope.emailRegister,
                        password: $scope.passwordRegister
                    }, function ( error, authData) {
                        console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                        myDataRef.child('users').child(authData.uid).set(authData);
                        $location.path('/');
                    })
                } else {
                    console.log("error creating user:", error);
                }
            });
        };

        $scope.login = function () {
            myDataRef.authWithPassword({
                email    : $scope.emailLogin,
                password : $scope.passwordLogin
            }, function (error, authData) {
                if (error === null) {
                    console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                    $location.path('/cars');
                } else {
                    alert("Error authenticating: ", error);
                }
            });
        };

        $('.bt-social').on('click', function(e) {

            var $currentButton = $(this);
            var provider = $currentButton.data("provider");
            e.preventDefault();
            console.log("bt social clicked with provider " + provider);

            thirdPartyLogin(provider);
        });

        function thirdPartyLogin(provider) {
            console.log("third party login entered");
            myDataRef.authWithOAuthPopup(provider, function (error, authData) {
                if (error === null) {
                    console.log("user id: " + authData.uid + ", Provider: " + authData.provider);
                    $location.path('/cars');
                } else {
                    alert("Error authenticating: ", error);
                }
            });
        };

        $scope.logout = function() {
            myDataRef.unauth();
            $scope.authData = "";
            $('.login-state').html("Not logged in");
            alert("You are logged out");
			console.log("User logged out");
            $location.path('/');
        };

        myDataRef.onAuth(function(authData) {
            if (authData) {
                $('.login-state').html("Logged In");
                $scope.authData = authData;
                //var vehicleRef = myDataRef.child('users').child(authData.uid).child('vehicles');
                var vehicleRef = myDataRef.child('vehicles').child(authData.uid);
                var userRef = myDataRef.child('users').child(authData.uid);
                var userVehicleRef = userRef.child(authData.uid).child('vehicles');
                var carlist = {};

                userVehicleRef.on("value", function(dataSnapshot) {
                    console.log('entered vehicleref once function');
                    carlist = dataSnapshot.$asArray();
                });

                /*
                var sync = $firebase(vehicleRef);
                carlist = sync.$asArray();

                carlist.$loaded().then(function() {
                    console.log("list has " + carlist.length + " items");
                    console.log(carlist);
                });
                */
                $scope.carlist = carlist;

                console.log("cars assigned, carlist scope = " + $scope.carlist);
            } else {
                $('.loginState').html("Not Logged In");
            }
        });

    }]);

    app.controller("editCarController", ["$scope", "$firebase", "$location", "$routeParams", function($scope, $firebase, $location, $routeParams) {
        console.log("starting edit controller");
        var authData = myDataRef.getAuth();
        var ref = new Firebase(myDataRef + '/users/' + authData.uid + '/vehicles/');
        var sync = $firebase(ref);
        var carlist = sync.$asArray();
        console.log(carlist);
        console.log(carlist[$routeParams.id]);
        $scope.vehicle = carlist.$getRecord($routeParams.id);
        console.log($scope.vehicle);
    }]);

    function handleFileSelect(evt) {
        var f = evt.target.files[0];
        var reader = new FileReader();
        console.log("entered file select");
        reader.onload = (function(theFile) {
            return function(e) {
                var filePayload = e.target.result;
                // Generate a location that can't be guessed using the file's contents and a random number
                var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
                var f = new Firebase(myDataRef + '/pano/' + hash + '/filePayload');
                console.log(f);
               // spinner.spin(document.getElementById('spin'));
               // Set the file payload to Firebase and register an onComplete handler to stop the spinner and show the preview
               f.set(filePayload, function() {
                 // spinner.stop();
                            //document.getElementById("pano").src = e.target.result;
                 //$('#file-upload').hide();
                 // Update the location bar so the URL can be shared with others
                 window.location.hash = hash;
               });
             };
            })(f);
            reader.readAsDataURL(f);
        }
    /*$(function() {
        // $('#spin').append(spinner);
        console.log("entered function");
        var myDataRef = new Firebase('https://burning-heat-392.firebaseio.com');
        var idx = window.location.href.indexOf('#');
        var hash = (idx > 0) ? window.location.href.slice(idx + 1) : '';
        if (hash === '') {
            // No hash found, so render the file upload button.
            $('#file-upload').show();
            //document.getElementById("file-upload").addEventListener('change', handleFileSelect, false);
        } else {
            // A hash was passed in, so let's retrieve and render it.
            // spinner.spin(document.getElementById('spin'));
            var f = new Firebase(myDataRef + '/pano/' + hash + '/filePayload');
            console.log(f);
        f.once('value', function(snap) {
            var payload = snap.val();
            if (payload != null) {
            document.getElementById("pano").src = payload;
            } else {
            $('#body').append("Not found");
            }
            //spinner.stop();
        });
      }
    }); */
}())
<|endoftext|>


<commit_before>var jsontr = require('./json-transform.js');

var items = require('./pages.json');
var transform = {
  nid: {
    newName: 'id',
    props: {value:String}
  },
  uuid: {
    props: {value:String}
  },
  title: {
    props: {value: String}
  },
  body: {
    props: {value: String}
  },
  field_parent_page: {
    newName: "parentPage",
    props: {target_id:{newName:'id',type:Number},target_uuid:{newName:'uuid',type:String}}
  },
  field_path: {
    newName: "path",
    props: {value: String}
  },
  field_sidebar: {
    newName: "sidebar",
    props: {target_uuid: {newName:'uuid',type:String}}
  },
  field_subnav: {
    newName: "subnav",
    props: {target_uuid: {newName:'uuid',type:String}}
  },
  field_serve_via_iframe: {
    newName: "iframe",
    props: {value:Boolean}
  },
  field_book_tour: {
    newName: 'bookTour',
    props: {value:String}
  },
  field_category_id: {
    newName: "categoryId",
    props: {value:String}
  },
  field_end_date: {
    newName: "endDate",
    props: {value:String}
  },
  field_start_date: {
    newName: "startDate",
    props: {value:String}
  },
  field_exhibition_css: {
    newName: "exhibition_css",
    props: {value:String}
  },
  field_further_location_informati: {
    newName: "locationInfo",
    props: {value:String}
  },
  field_image: {
    newName: "image",
    props: {alt:String, width:Number, height:Number, url:String}
  },
  field_libcal_id: {
    newName: "libcalId",
    props: {value:String}
  },
  field_library: {
    newName: "library",
    props: {target_id:{newName:"id",type:Number}, target_uuid:{newName:"uuid",type:String}}
  },
  field_press_kit: {
    newName: "pressKit",
    props: {uri:String}
  },
  field_redirects_from_: {
    newName: "redirectsFrom",
    props: {uri:String}
  },
  field_subtitle: {
    newName: "subTitle",
    props: {value:String}
  },
  field_url_slug: {
    newName: "urlSlug",
    props: {value:String}
  }
};

console.log( JSON.stringify( jsontr.transform(items,transform) ) );
<commit_msg>fix for major exhibits pull<commit_after>var jsontr = require('./json-transform.js');

var items = require('./exhibit-pages.json');
var transform = {
  nid: {
    newName: 'id',
    props: {value:String}
  },
  uuid: {
    props: {value:String}
  },
  title: {
    props: {value: String}
  },
  body: {
    props: {value: String}
  },
  field_parent_page: {
    newName: "parentPage",
    props: {target_id:{newName:'id',type:Number},target_uuid:{newName:'uuid',type:String}}
  },
  field_path: {
    newName: "path",
    props: {value: String}
  },
  field_sidebar: {
    newName: "sidebar",
    props: {target_uuid: {newName:'uuid',type:String}}
  },
  field_subnav: {
    newName: "subnav",
    props: {target_uuid: {newName:'uuid',type:String}}
  },
  field_serve_via_iframe: {
    newName: "iframe",
    props: {value:Boolean}
  },
  field_book_tour: {
    newName: 'bookTour',
    props: {value:String}
  },
  field_category_id: {
    newName: "categoryId",
    props: {value:String}
  },
  field_end_date: {
    newName: "endDate",
    props: {value:String}
  },
  field_start_date: {
    newName: "startDate",
    props: {value:String}
  },
  field_exhibition_css: {
    newName: "exhibition_css",
    props: {value:String}
  },
  field_further_location_informati: {
    newName: "locationInfo",
    props: {value:String}
  },
  field_image: {
    newName: "image",
    props: {alt:String, width:Number, height:Number, url:String}
  },
  field_libcal_id: {
    newName: "libcalId",
    props: {value:String}
  },
  field_library: {
    newName: "library",
    props: {target_id:{newName:"id",type:Number}, target_uuid:{newName:"uuid",type:String}}
  },
  field_press_kit: {
    newName: "pressKit",
    props: {uri:String}
  },
  field_redirects_from_: {
    newName: "redirectsFrom",
    props: {uri:String}
  },
  field_subtitle: {
    newName: "subTitle",
    props: {value:String}
  },
  field_url_slug: {
    newName: "urlSlug",
    props: {value:String}
  }
};

console.log( JSON.stringify( jsontr.transform(items,transform) ) );
<|endoftext|>


<commit_before>import {COLORS} from "./colors";
import {AnimationOne} from "./animation-one";
import {AnimationTwo} from "./animation-two";
import {AnimationThree} from "./animation-three";
import {AnimationFour} from "./animation-four";
import {AnimationFive} from "./animation-five";
import {AnimationSix} from "./animation-six";

const $window = $(window);
const $document = $(document);
let windowHeight = $window.height();
let windowWidth = $window.width();
const $containers = $('.container');
let scrollTo = {scrollTo: $window.scrollTop()};

//scroll tween
const tween = new TWEEN.Tween( scrollTo )
        .to( { scrollTo: 0 }, 1000 )
        .easing( TWEEN.Easing.Quartic.InOut )
        .onUpdate( function () {

          $window.scrollTop(this.scrollTo);

        } ).onStart(function() {

          this.scrollTo = $window.scrollTop();

        });

const random = new Random(Random.engines.mt19937().autoSeed());

const canvasAnimations = [
  new AnimationOne,
  new AnimationTwo,
  new AnimationThree,
  new AnimationFour,
  new AnimationFive,
  new AnimationSix
];

function generateRect(containerIndex){
  let $rect = $('

');
  let size = random.integer(50, 150);
  let x = random.integer(-windowWidth, windowWidth);
  let y = random.integer(-windowHeight, windowHeight);
  let pixelToTravelVertical = random.integer(-200, 200);
  let pixelToTravelHorizontal = random.integer(-200, 200);

  $rect.addClass('center rect');
  $rect.data('pixels-to-travel-vertical', pixelToTravelVertical);
  $rect.data('pixels-to-travel-horizontal', pixelToTravelHorizontal);

  containerIndex

  $rect.css({
    width: size,
    height: size,
    top:y,
    left: x,
    background: `hsl(${COLORS[containerIndex].h},${COLORS[containerIndex].s + 20}%,${COLORS[containerIndex].l + 10}%)`,
    opacity: 0.5
  });

  return $rect;

}

$('.next').on('click', function(){
  let $this = $(this);

  tween.stop();

  tween.to( { scrollTo: $this.parent().next().offset().top });
  tween.start();

});

$('.prev').on('click', function(){
  let $this = $(this);

  tween.stop();

  tween.to( { scrollTo: $this.parent().prev().offset().top });
  tween.start();

});

function init(){

  //add COLORS
  COLORS.forEach(function(item, index){

    $($containers[index]).css('background', COLORS[index].toString());

  });

  $containers.each(function(index, item){

    let $container = $(item);
    let $canvas = $container.children('.canvas');

    $container.children('.prev, .next').css({
      background: `hsl(${COLORS[index].h},${COLORS[index].s + 20}%,${COLORS[index].l + 15}%)`
    });

    $canvas.css({
      border: `hsl(${COLORS[index].h},${COLORS[index].s + 20}%,${COLORS[index].l + 10}%) solid 10px`,
      background: `hsl(${COLORS[index].h},${COLORS[index].s - 5}%,${COLORS[index].l - 15}%)`
    });

    for (let i = 0; i < 10; i++) {
      $container.append(generateRect(index));
    };

  });

}

$('.canvas').on('click', function(){

  let $this = $(this);
  tween.stop();

  tween.to( { scrollTo: $this.parent().offset().top });
  tween.start();

});

function updateParallax(){

  let scrollPosition = $window.scrollTop();

  $containers.each(function(index, item){

    let $container = $(item);
    let offset = $container.offset();
    let $rects;

    let height = $container.height();
    let percentageinViewPort = Math.max(0, Math.min(100, ((offset.top + height) - scrollPosition) / (windowHeight + height) * 100));

    let halfPercentage = percentageinViewPort - 50;
    let per = (halfPercentage / 50) * 100;

    let $prev = $container.children('.prev');
    let $next = $container.children('.next');

    $prev.css('transform', `translate(-50%, ${-(per / 100) * 50 }px) rotate(-90deg)`);
    $next.css('transform', `translate(-50%, ${-(per / 100) * 50 }px) rotate(-90deg)`);

    if(scrollPosition + windowHeight > offset.top &&  offset.top + $container.height() > scrollPosition){
      canvasAnimations[index].onScreen = true;
      canvasAnimations[index].scrollPosition = per;
      $rects = $container.children('.rect');

      let $canvas = $container.children('.canvas');

      $canvas.css('transform', `translate(0, ${(per / 100) * 400}px)`);

      $rects.each(function(index, item){

        let $item = $(item);
        $item.css('transform', `translate(${(per / 100) * parseInt($item.data('pixels-to-travel-horizontal')) }px, ${(per / 100) * parseInt($item.data('pixels-to-travel-vertical')) }px)`);

      });

    } else {
      canvasAnimations[index].onScreen = false;

    }

  });

}

$window.on('mousewheel', function(){
  tween.stop();
});

$window.on('resize scroll load', updateParallax);

function update(){

  for (let i = 0; i < canvasAnimations.length; i++) {
    if(canvasAnimations[i].onScreen){
      canvasAnimations[i].update();
      canvasAnimations[i].draw();
    }
  };

  TWEEN.update();

  requestAnimationFrame(update);
}

requestAnimationFrame(update);

init();
<commit_msg>Performance optimization. Only paints on canvas if is on screen<commit_after>import {COLORS} from "./colors";
import {AnimationOne} from "./animation-one";
import {AnimationTwo} from "./animation-two";
import {AnimationThree} from "./animation-three";
import {AnimationFour} from "./animation-four";
import {AnimationFive} from "./animation-five";
import {AnimationSix} from "./animation-six";

const $window = $(window);
const $document = $(document);
let windowHeight = $window.height();
let windowWidth = $window.width();
const $containers = $('.container');
let scrollTo = {scrollTo: $window.scrollTop()};

//scroll tween
const tween = new TWEEN.Tween( scrollTo )
        .to( { scrollTo: 0 }, 1000 )
        .easing( TWEEN.Easing.Quartic.InOut )
        .onUpdate( function () {

          $window.scrollTop(this.scrollTo);

        } ).onStart(function() {

          this.scrollTo = $window.scrollTop();

        });

const random = new Random(Random.engines.mt19937().autoSeed());

const canvasAnimations = [
  new AnimationOne,
  new AnimationTwo,
  new AnimationThree,
  new AnimationFour,
  new AnimationFive,
  new AnimationSix
];

function generateRect(containerIndex){
  let $rect = $('

');
  let size = random.integer(50, 150);
  let x = random.integer(-windowWidth, windowWidth);
  let y = random.integer(-windowHeight, windowHeight);
  let pixelToTravelVertical = random.integer(-200, 200);
  let pixelToTravelHorizontal = random.integer(-200, 200);

  $rect.addClass('center rect');
  $rect.data('pixels-to-travel-vertical', pixelToTravelVertical);
  $rect.data('pixels-to-travel-horizontal', pixelToTravelHorizontal);

  containerIndex

  $rect.css({
    width: size,
    height: size,
    top:y,
    left: x,
    background: `hsl(${COLORS[containerIndex].h},${COLORS[containerIndex].s + 20}%,${COLORS[containerIndex].l + 10}%)`,
    opacity: 0.5
  });

  return $rect;

}

$('.next').on('click', function(){
  let $this = $(this);

  tween.stop();

  tween.to( { scrollTo: $this.parent().next().offset().top });
  tween.start();

});

$('.prev').on('click', function(){
  let $this = $(this);

  tween.stop();

  tween.to( { scrollTo: $this.parent().prev().offset().top });
  tween.start();

});

function init(){

  //add COLORS
  COLORS.forEach(function(item, index){

    $($containers[index]).css('background', COLORS[index].toString());

  });

  $containers.each(function(index, item){

    let $container = $(item);
    let $canvas = $container.children('.canvas');

    $container.children('.prev, .next').css({
      background: `hsl(${COLORS[index].h},${COLORS[index].s + 20}%,${COLORS[index].l + 15}%)`
    });

    $canvas.css({
      border: `hsl(${COLORS[index].h},${COLORS[index].s + 20}%,${COLORS[index].l + 10}%) solid 10px`,
      background: `hsl(${COLORS[index].h},${COLORS[index].s - 5}%,${COLORS[index].l - 15}%)`
    });

    for (let i = 0; i < 10; i++) {
      $container.append(generateRect(index));
    };

  });

}

$('.canvas').on('click', function(){

  let $this = $(this);
  tween.stop();

  tween.to( { scrollTo: $this.parent().offset().top });
  tween.start();

});

function updateParallax(){

  let scrollPosition = $window.scrollTop();

  $containers.each(function(index, item){

    let $container = $(item);
    let offset = $container.offset();
    let $rects;
    let $canvas = $container.children('.canvas');
    let height = $container.height();
    let percentageinViewPort = Math.max(0, Math.min(100, ((offset.top + height) - scrollPosition) / (windowHeight + height) * 100));

    let halfPercentage = percentageinViewPort - 50;
    let per = (halfPercentage / 50) * 100;

    let $prev = $container.children('.prev');
    let $next = $container.children('.next');

    $prev.css('transform', `translate(-50%, ${-(per / 100) * 50 }px) rotate(-90deg)`);
    $next.css('transform', `translate(-50%, ${-(per / 100) * 50 }px) rotate(-90deg)`);

    if(scrollPosition + windowHeight > offset.top &&  offset.top + $container.height() > scrollPosition){

      $rects = $container.children('.rect');

      $canvas.css('transform', `translate(0, ${(per / 100) * 400}px)`);

      $rects.each(function(index, item){

        let $item = $(item);
        $item.css('transform', `translate(${(per / 100) * parseInt($item.data('pixels-to-travel-horizontal')) }px, ${(per / 100) * parseInt($item.data('pixels-to-travel-vertical')) }px)`);

      });

    }

    if(scrollPosition + windowHeight > $canvas.offset().top &&  $canvas.offset().top + $canvas.height() > scrollPosition){
      canvasAnimations[index].onScreen = true;
      canvasAnimations[index].scrollPosition = per;
    } else {
      canvasAnimations[index].onScreen = false;
    }

  });

}

$window.on('mousewheel', function(){
  tween.stop();
});

$window.on('resize scroll load', updateParallax);

function update(){

  for (let i = 0; i < canvasAnimations.length; i++) {
    if(canvasAnimations[i].onScreen){
      canvasAnimations[i].update();
      canvasAnimations[i].draw();
    }
  };

  TWEEN.update();

  requestAnimationFrame(update);
}

requestAnimationFrame(update);

init();
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode("crystal", function(config) {
    function wordRegExp(words, end) {
      return new RegExp((end ? "" : "^") + "(?:" + words.join("|") + ")" + (end ? "$" : "\\b"));
    }

    function chain(tokenize, stream, state) {
      state.tokenize.push(tokenize);
      return tokenize(stream, state);
    }

    var operators = /^(?:[-+/%|&^]|\*\*?|[<>]{2})/;
    var conditionalOperators = /^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/;
    var indexingOperators = /^(?:\[\][?=]?)/;
    var anotherOperators = /^(?:\.(?:\.{2})?|->|[?:])/;
    var idents = /^[a-z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/;
    var types = /^[A-Z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/;
    var keywords = wordRegExp([
      "abstract", "alias", "as", "asm", "begin", "break", "case", "class", "def", "do",
      "else", "elsif", "end", "ensure", "enum", "extend", "for", "fun", "if",
      "include", "instance_sizeof", "lib", "macro", "module", "next", "of", "out", "pointerof",
      "private", "protected", "rescue", "return", "require", "select", "sizeof", "struct",
      "super", "then", "type", "typeof", "uninitialized", "union", "unless", "until", "when", "while", "with",
      "yield", "__DIR__", "__END_LINE__", "__FILE__", "__LINE__"
    ]);
    var atomWords = wordRegExp(["true", "false", "nil", "self"]);
    var indentKeywordsArray = [
      "def", "fun", "macro",
      "class", "module", "struct", "lib", "enum", "union",
      "do", "for"
    ];
    var indentKeywords = wordRegExp(indentKeywordsArray);
    var indentExpressionKeywordsArray = ["if", "unless", "case", "while", "until", "begin", "then"];
    var indentExpressionKeywords = wordRegExp(indentExpressionKeywordsArray);
    var dedentKeywordsArray = ["end", "else", "elsif", "rescue", "ensure"];
    var dedentKeywords = wordRegExp(dedentKeywordsArray);
    var dedentPunctualsArray = ["\\)", "\\}", "\\]"];
    var dedentPunctuals = new RegExp("^(?:" + dedentPunctualsArray.join("|") + ")$");
    var nextTokenizer = {
      "def": tokenFollowIdent, "fun": tokenFollowIdent, "macro": tokenMacroDef,
      "class": tokenFollowType, "module": tokenFollowType, "struct": tokenFollowType,
      "lib": tokenFollowType, "enum": tokenFollowType, "union": tokenFollowType
    };
    var matching = {"[": "]", "{": "}", "(": ")", "<": ">"};

    function tokenBase(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      // Macros
      if (state.lastToken != "\\" && stream.match("{%", false)) {
        return chain(tokenMacro("%", "%"), stream, state);
      }

      if (state.lastToken != "\\" && stream.match("{{", false)) {
        return chain(tokenMacro("{", "}"), stream, state);
      }

      // Comments
      if (stream.peek() == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Variables and keywords
      var matched;
      if (stream.match(idents)) {
        stream.eat(/[?!]/);

        matched = stream.current();
        if (stream.eat(":")) {
          return "atom";
        } else if (state.lastToken == ".") {
          return "property";
        } else if (keywords.test(matched)) {
          if (indentKeywords.test(matched)) {
            if (!(matched == "fun" && state.blocks.indexOf("lib") >= 0) && !(matched == "def" && state.lastToken == "abstract")) {
              state.blocks.push(matched);
              state.currentIndent += 1;
            }
          } else if ((state.lastStyle == "operator" || !state.lastStyle) && indentExpressionKeywords.test(matched)) {
            state.blocks.push(matched);
            state.currentIndent += 1;
          } else if (matched == "end") {
            state.blocks.pop();
            state.currentIndent -= 1;
          }

          if (nextTokenizer.hasOwnProperty(matched)) {
            state.tokenize.push(nextTokenizer[matched]);
          }

          return "keyword";
        } else if (atomWords.test(matched)) {
          return "atom";
        }

        return "variable";
      }

      // Class variables and instance variables
      // or attributes
      if (stream.eat("@")) {
        if (stream.peek() == "[") {
          return chain(tokenNest("[", "]", "meta"), stream, state);
        }

        stream.eat("@");
        stream.match(idents) || stream.match(types);
        return "variable-2";
      }

      // Constants and types
      if (stream.match(types)) {
        return "tag";
      }

      // Symbols or ':' operator
      if (stream.eat(":")) {
        if (stream.eat("\"")) {
          return chain(tokenQuote("\"", "atom", false), stream, state);
        } else if (stream.match(idents) || stream.match(types) ||
                   stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators)) {
          return "atom";
        }
        stream.eat(":");
        return "operator";
      }

      // Strings
      if (stream.eat("\"")) {
        return chain(tokenQuote("\"", "string", true), stream, state);
      }

      // Strings or regexps or macro variables or '%' operator
      if (stream.peek() == "%") {
        var style = "string";
        var embed = true;
        var delim;

        if (stream.match("%r")) {
          // Regexps
          style = "string-2";
          delim = stream.next();
        } else if (stream.match("%w")) {
          embed = false;
          delim = stream.next();
        } else if (stream.match("%q")) {
          embed = false;
          delim = stream.next();
        } else {
          if(delim = stream.match(/^%([^\w\s=])/)) {
            delim = delim[1];
          } else if (stream.match(/^%[a-zA-Z0-9_\u009F-\uFFFF]*/)) {
            // Macro variables
            return "meta";
          } else {
            // '%' operator
            return "operator";
          }
        }

        if (matching.hasOwnProperty(delim)) {
          delim = matching[delim];
        }
        return chain(tokenQuote(delim, style, embed), stream, state);
      }

      // Here Docs
      if (matched = stream.match(/^<<-('?)([A-Z]\w*)\1/)) {
        return chain(tokenHereDoc(matched[2], !matched[1]), stream, state)
      }

      // Characters
      if (stream.eat("'")) {
        stream.match(/^(?:[^']|\\(?:[befnrtv0'"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]{1,6}\})))/);
        stream.eat("'");
        return "atom";
      }

      // Numbers
      if (stream.eat("0")) {
        if (stream.eat("x")) {
          stream.match(/^[0-9a-fA-F]+/);
        } else if (stream.eat("o")) {
          stream.match(/^[0-7]+/);
        } else if (stream.eat("b")) {
          stream.match(/^[01]+/);
        }
        return "number";
      }

      if (stream.eat(/^\d/)) {
        stream.match(/^\d*(?:\.\d+)?(?:[eE][+-]?\d+)?/);
        return "number";
      }

      // Operators
      if (stream.match(operators)) {
        stream.eat("="); // Operators can follow assign symbol.
        return "operator";
      }

      if (stream.match(conditionalOperators) || stream.match(anotherOperators)) {
        return "operator";
      }

      // Parens and braces
      if (matched = stream.match(/[({[]/, false)) {
        matched = matched[0];
        return chain(tokenNest(matched, matching[matched], null), stream, state);
      }

      // Escapes
      if (stream.eat("\\")) {
        stream.next();
        return "meta";
      }

      stream.next();
      return null;
    }

    function tokenNest(begin, end, style, started) {
      return function (stream, state) {
        if (!started && stream.match(begin)) {
          state.tokenize[state.tokenize.length - 1] = tokenNest(begin, end, style, true);
          state.currentIndent += 1;
          return style;
        }

        var nextStyle = tokenBase(stream, state);
        if (stream.current() === end) {
          state.tokenize.pop();
          state.currentIndent -= 1;
          nextStyle = style;
        }

        return nextStyle;
      };
    }

    function tokenMacro(begin, end, started) {
      return function (stream, state) {
        if (!started && stream.match("{" + begin)) {
          state.currentIndent += 1;
          state.tokenize[state.tokenize.length - 1] = tokenMacro(begin, end, true);
          return "meta";
        }

        if (stream.match(end + "}")) {
          state.currentIndent -= 1;
          state.tokenize.pop();
          return "meta";
        }

        return tokenBase(stream, state);
      };
    }

    function tokenMacroDef(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      var matched;
      if (matched = stream.match(idents)) {
        if (matched == "def") {
          return "keyword";
        }
        stream.eat(/[?!]/);
      }

      state.tokenize.pop();
      return "def";
    }

    function tokenFollowIdent(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      if (stream.match(idents)) {
        stream.eat(/[!?]/);
      } else {
        stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators);
      }
      state.tokenize.pop();
      return "def";
    }

    function tokenFollowType(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      stream.match(types);
      state.tokenize.pop();
      return "def";
    }

    function tokenQuote(end, style, embed) {
      return function (stream, state) {
        var escaped = false;

        while (stream.peek()) {
          if (!escaped) {
            if (stream.match("{%", false)) {
              state.tokenize.push(tokenMacro("%", "%"));
              return style;
            }

            if (stream.match("{{", false)) {
              state.tokenize.push(tokenMacro("{", "}"));
              return style;
            }

            if (embed && stream.match("#{", false)) {
              state.tokenize.push(tokenNest("#{", "}", "meta"));
              return style;
            }

            var ch = stream.next();

            if (ch == end) {
              state.tokenize.pop();
              return style;
            }

            escaped = embed && ch == "\\";
          } else {
            stream.next();
            escaped = false;
          }
        }

        return style;
      };
    }

    function tokenHereDoc(phrase, embed) {
      return function (stream, state) {
        if (stream.sol()) {
          stream.eatSpace()
          if (stream.match(phrase)) {
            state.tokenize.pop();
            return "string";
          }
        }

        var escaped = false;
        while (stream.peek()) {
          if (!escaped) {
            if (stream.match("{%", false)) {
              state.tokenize.push(tokenMacro("%", "%"));
              return "string";
            }

            if (stream.match("{{", false)) {
              state.tokenize.push(tokenMacro("{", "}"));
              return "string";
            }

            if (embed && stream.match("#{", false)) {
              state.tokenize.push(tokenNest("#{", "}", "meta"));
              return "string";
            }

            escaped = embed && stream.next() == "\\";
          } else {
            stream.next();
            escaped = false;
          }
        }

        return "string";
      }
    }

    return {
      startState: function () {
        return {
          tokenize: [tokenBase],
          currentIndent: 0,
          lastToken: null,
          lastStyle: null,
          blocks: []
        };
      },

      token: function (stream, state) {
        var style = state.tokenize[state.tokenize.length - 1](stream, state);
        var token = stream.current();

        if (style && style != "comment") {
          state.lastToken = token;
          state.lastStyle = style;
        }

        return style;
      },

      indent: function (state, textAfter) {
        textAfter = textAfter.replace(/^\s*(?:\{%)?\s*|\s*(?:%\})?\s*$/g, "");

        if (dedentKeywords.test(textAfter) || dedentPunctuals.test(textAfter)) {
          return config.indentUnit * (state.currentIndent - 1);
        }

        return config.indentUnit * state.currentIndent;
      },

      fold: "indent",
      electricInput: wordRegExp(dedentPunctualsArray.concat(dedentKeywordsArray), true),
      lineComment: '#'
    };
  });

  CodeMirror.defineMIME("text/x-crystal", "crystal");
});
<commit_msg>[crystal mode] Allow underscore separators in numbers<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode("crystal", function(config) {
    function wordRegExp(words, end) {
      return new RegExp((end ? "" : "^") + "(?:" + words.join("|") + ")" + (end ? "$" : "\\b"));
    }

    function chain(tokenize, stream, state) {
      state.tokenize.push(tokenize);
      return tokenize(stream, state);
    }

    var operators = /^(?:[-+/%|&^]|\*\*?|[<>]{2})/;
    var conditionalOperators = /^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/;
    var indexingOperators = /^(?:\[\][?=]?)/;
    var anotherOperators = /^(?:\.(?:\.{2})?|->|[?:])/;
    var idents = /^[a-z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/;
    var types = /^[A-Z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/;
    var keywords = wordRegExp([
      "abstract", "alias", "as", "asm", "begin", "break", "case", "class", "def", "do",
      "else", "elsif", "end", "ensure", "enum", "extend", "for", "fun", "if",
      "include", "instance_sizeof", "lib", "macro", "module", "next", "of", "out", "pointerof",
      "private", "protected", "rescue", "return", "require", "select", "sizeof", "struct",
      "super", "then", "type", "typeof", "uninitialized", "union", "unless", "until", "when", "while", "with",
      "yield", "__DIR__", "__END_LINE__", "__FILE__", "__LINE__"
    ]);
    var atomWords = wordRegExp(["true", "false", "nil", "self"]);
    var indentKeywordsArray = [
      "def", "fun", "macro",
      "class", "module", "struct", "lib", "enum", "union",
      "do", "for"
    ];
    var indentKeywords = wordRegExp(indentKeywordsArray);
    var indentExpressionKeywordsArray = ["if", "unless", "case", "while", "until", "begin", "then"];
    var indentExpressionKeywords = wordRegExp(indentExpressionKeywordsArray);
    var dedentKeywordsArray = ["end", "else", "elsif", "rescue", "ensure"];
    var dedentKeywords = wordRegExp(dedentKeywordsArray);
    var dedentPunctualsArray = ["\\)", "\\}", "\\]"];
    var dedentPunctuals = new RegExp("^(?:" + dedentPunctualsArray.join("|") + ")$");
    var nextTokenizer = {
      "def": tokenFollowIdent, "fun": tokenFollowIdent, "macro": tokenMacroDef,
      "class": tokenFollowType, "module": tokenFollowType, "struct": tokenFollowType,
      "lib": tokenFollowType, "enum": tokenFollowType, "union": tokenFollowType
    };
    var matching = {"[": "]", "{": "}", "(": ")", "<": ">"};

    function tokenBase(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      // Macros
      if (state.lastToken != "\\" && stream.match("{%", false)) {
        return chain(tokenMacro("%", "%"), stream, state);
      }

      if (state.lastToken != "\\" && stream.match("{{", false)) {
        return chain(tokenMacro("{", "}"), stream, state);
      }

      // Comments
      if (stream.peek() == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Variables and keywords
      var matched;
      if (stream.match(idents)) {
        stream.eat(/[?!]/);

        matched = stream.current();
        if (stream.eat(":")) {
          return "atom";
        } else if (state.lastToken == ".") {
          return "property";
        } else if (keywords.test(matched)) {
          if (indentKeywords.test(matched)) {
            if (!(matched == "fun" && state.blocks.indexOf("lib") >= 0) && !(matched == "def" && state.lastToken == "abstract")) {
              state.blocks.push(matched);
              state.currentIndent += 1;
            }
          } else if ((state.lastStyle == "operator" || !state.lastStyle) && indentExpressionKeywords.test(matched)) {
            state.blocks.push(matched);
            state.currentIndent += 1;
          } else if (matched == "end") {
            state.blocks.pop();
            state.currentIndent -= 1;
          }

          if (nextTokenizer.hasOwnProperty(matched)) {
            state.tokenize.push(nextTokenizer[matched]);
          }

          return "keyword";
        } else if (atomWords.test(matched)) {
          return "atom";
        }

        return "variable";
      }

      // Class variables and instance variables
      // or attributes
      if (stream.eat("@")) {
        if (stream.peek() == "[") {
          return chain(tokenNest("[", "]", "meta"), stream, state);
        }

        stream.eat("@");
        stream.match(idents) || stream.match(types);
        return "variable-2";
      }

      // Constants and types
      if (stream.match(types)) {
        return "tag";
      }

      // Symbols or ':' operator
      if (stream.eat(":")) {
        if (stream.eat("\"")) {
          return chain(tokenQuote("\"", "atom", false), stream, state);
        } else if (stream.match(idents) || stream.match(types) ||
                   stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators)) {
          return "atom";
        }
        stream.eat(":");
        return "operator";
      }

      // Strings
      if (stream.eat("\"")) {
        return chain(tokenQuote("\"", "string", true), stream, state);
      }

      // Strings or regexps or macro variables or '%' operator
      if (stream.peek() == "%") {
        var style = "string";
        var embed = true;
        var delim;

        if (stream.match("%r")) {
          // Regexps
          style = "string-2";
          delim = stream.next();
        } else if (stream.match("%w")) {
          embed = false;
          delim = stream.next();
        } else if (stream.match("%q")) {
          embed = false;
          delim = stream.next();
        } else {
          if(delim = stream.match(/^%([^\w\s=])/)) {
            delim = delim[1];
          } else if (stream.match(/^%[a-zA-Z0-9_\u009F-\uFFFF]*/)) {
            // Macro variables
            return "meta";
          } else {
            // '%' operator
            return "operator";
          }
        }

        if (matching.hasOwnProperty(delim)) {
          delim = matching[delim];
        }
        return chain(tokenQuote(delim, style, embed), stream, state);
      }

      // Here Docs
      if (matched = stream.match(/^<<-('?)([A-Z]\w*)\1/)) {
        return chain(tokenHereDoc(matched[2], !matched[1]), stream, state)
      }

      // Characters
      if (stream.eat("'")) {
        stream.match(/^(?:[^']|\\(?:[befnrtv0'"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]{1,6}\})))/);
        stream.eat("'");
        return "atom";
      }

      // Numbers
      if (stream.eat("0")) {
        if (stream.eat("x")) {
          stream.match(/^[0-9a-fA-F_]+/);
        } else if (stream.eat("o")) {
          stream.match(/^[0-7_]+/);
        } else if (stream.eat("b")) {
          stream.match(/^[01_]+/);
        }
        return "number";
      }

      if (stream.eat(/^\d/)) {
        stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+-]?\d+)?/);
        return "number";
      }

      // Operators
      if (stream.match(operators)) {
        stream.eat("="); // Operators can follow assign symbol.
        return "operator";
      }

      if (stream.match(conditionalOperators) || stream.match(anotherOperators)) {
        return "operator";
      }

      // Parens and braces
      if (matched = stream.match(/[({[]/, false)) {
        matched = matched[0];
        return chain(tokenNest(matched, matching[matched], null), stream, state);
      }

      // Escapes
      if (stream.eat("\\")) {
        stream.next();
        return "meta";
      }

      stream.next();
      return null;
    }

    function tokenNest(begin, end, style, started) {
      return function (stream, state) {
        if (!started && stream.match(begin)) {
          state.tokenize[state.tokenize.length - 1] = tokenNest(begin, end, style, true);
          state.currentIndent += 1;
          return style;
        }

        var nextStyle = tokenBase(stream, state);
        if (stream.current() === end) {
          state.tokenize.pop();
          state.currentIndent -= 1;
          nextStyle = style;
        }

        return nextStyle;
      };
    }

    function tokenMacro(begin, end, started) {
      return function (stream, state) {
        if (!started && stream.match("{" + begin)) {
          state.currentIndent += 1;
          state.tokenize[state.tokenize.length - 1] = tokenMacro(begin, end, true);
          return "meta";
        }

        if (stream.match(end + "}")) {
          state.currentIndent -= 1;
          state.tokenize.pop();
          return "meta";
        }

        return tokenBase(stream, state);
      };
    }

    function tokenMacroDef(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      var matched;
      if (matched = stream.match(idents)) {
        if (matched == "def") {
          return "keyword";
        }
        stream.eat(/[?!]/);
      }

      state.tokenize.pop();
      return "def";
    }

    function tokenFollowIdent(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      if (stream.match(idents)) {
        stream.eat(/[!?]/);
      } else {
        stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators);
      }
      state.tokenize.pop();
      return "def";
    }

    function tokenFollowType(stream, state) {
      if (stream.eatSpace()) {
        return null;
      }

      stream.match(types);
      state.tokenize.pop();
      return "def";
    }

    function tokenQuote(end, style, embed) {
      return function (stream, state) {
        var escaped = false;

        while (stream.peek()) {
          if (!escaped) {
            if (stream.match("{%", false)) {
              state.tokenize.push(tokenMacro("%", "%"));
              return style;
            }

            if (stream.match("{{", false)) {
              state.tokenize.push(tokenMacro("{", "}"));
              return style;
            }

            if (embed && stream.match("#{", false)) {
              state.tokenize.push(tokenNest("#{", "}", "meta"));
              return style;
            }

            var ch = stream.next();

            if (ch == end) {
              state.tokenize.pop();
              return style;
            }

            escaped = embed && ch == "\\";
          } else {
            stream.next();
            escaped = false;
          }
        }

        return style;
      };
    }

    function tokenHereDoc(phrase, embed) {
      return function (stream, state) {
        if (stream.sol()) {
          stream.eatSpace()
          if (stream.match(phrase)) {
            state.tokenize.pop();
            return "string";
          }
        }

        var escaped = false;
        while (stream.peek()) {
          if (!escaped) {
            if (stream.match("{%", false)) {
              state.tokenize.push(tokenMacro("%", "%"));
              return "string";
            }

            if (stream.match("{{", false)) {
              state.tokenize.push(tokenMacro("{", "}"));
              return "string";
            }

            if (embed && stream.match("#{", false)) {
              state.tokenize.push(tokenNest("#{", "}", "meta"));
              return "string";
            }

            escaped = embed && stream.next() == "\\";
          } else {
            stream.next();
            escaped = false;
          }
        }

        return "string";
      }
    }

    return {
      startState: function () {
        return {
          tokenize: [tokenBase],
          currentIndent: 0,
          lastToken: null,
          lastStyle: null,
          blocks: []
        };
      },

      token: function (stream, state) {
        var style = state.tokenize[state.tokenize.length - 1](stream, state);
        var token = stream.current();

        if (style && style != "comment") {
          state.lastToken = token;
          state.lastStyle = style;
        }

        return style;
      },

      indent: function (state, textAfter) {
        textAfter = textAfter.replace(/^\s*(?:\{%)?\s*|\s*(?:%\})?\s*$/g, "");

        if (dedentKeywords.test(textAfter) || dedentPunctuals.test(textAfter)) {
          return config.indentUnit * (state.currentIndent - 1);
        }

        return config.indentUnit * state.currentIndent;
      },

      fold: "indent",
      electricInput: wordRegExp(dedentPunctualsArray.concat(dedentKeywordsArray), true),
      lineComment: '#'
    };
  });

  CodeMirror.defineMIME("text/x-crystal", "crystal");
});
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var body = $("body");

  function init() {
    loginInfo = $("#loginInfo");
    user = loginInfo.user.value;
    pass = loginInfo.pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      loginInfo.user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    body.empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    var canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
    }).focus();

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillRect(enemies[i], enemies[i+1], 30, 50);
    }

    //draw player
    context.fillStyle = userData[2];
    context.fillRect(userData[0], userData[1], 30, 50);

    //draw enemy names
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
    }

    //draw player name
    context.fillStyle = userData[2];
    context.font = "15px Arial";
    context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

    setTimeout(gameLoop, frameLength);
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>Now gracefully handles window resizing<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var body = $("body");

  function init() {
    loginInfo = $("#loginInfo");
    user = loginInfo.user.value;
    pass = loginInfo.pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      loginInfo.user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    body.empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    var canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
    }).focus();

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillRect(enemies[i], enemies[i+1], 30, 50);
    }

    //draw player
    context.fillStyle = userData[2];
    context.fillRect(userData[0], userData[1], 30, 50);

    //draw enemy names
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
    }

    //draw player name
    context.fillStyle = userData[2];
    context.font = "15px Arial";
    context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

    setTimeout(gameLoop, frameLength);
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  $(window).resize(function() {
    windowWidth = $(window).innerWidth();
    windowHeight = $(window).innerHeight();

    canvasElement.attr({
      width: windowWidth,
      height: windowHeight
    });
  });

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var body = $("body");

  function init() {

    user = ($('#user').value);
    pass = ($('#pass').value);
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      loginInfo.user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    body.empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    var canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
    }).focus();

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillRect(enemies[i], enemies[i+1], 30, 50);
    }

    //draw player
    context.fillStyle = userData[2];
    context.fillRect(userData[0], userData[1], 30, 50);

    //draw enemy names
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
    }

    //draw player name
    context.fillStyle = userData[2];
    context.font = "15px Arial";
    context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

    setTimeout(gameLoop, frameLength);
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  $(window).resize(function() {
    windowWidth = $(window).innerWidth();
    windowHeight = $(window).innerHeight();

    canvasElement.attr({
      width: windowWidth,
      height: windowHeight
    });
  });

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>Doubt this'll work but meh<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var body = $("body");

  function init() {

    user = $('#user');
    pass = $('#pass').val();
    if (user.value.indexOf(",") >= 0 || user.value.indexOf(":") >= 0){
      user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    body.empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    var canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth,
      height: windowHeight,
      tabIndex: 0,
    }).focus();

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);

    //draw enemies
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillRect(enemies[i], enemies[i+1], 30, 50);
    }

    //draw player
    context.fillStyle = userData[2];
    context.fillRect(userData[0], userData[1], 30, 50);

    //draw enemy names
    for (i = 0; i < enemies.length; i += 4){
      context.fillStyle = enemies[i+2];
      context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
    }

    //draw player name
    context.fillStyle = userData[2];
    context.font = "15px Arial";
    context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

    setTimeout(gameLoop, frameLength);
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  $(window).resize(function() {
    windowWidth = $(window).innerWidth();
    windowHeight = $(window).innerHeight();

    canvasElement.attr({
      width: windowWidth,
      height: windowHeight
    });
  });

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';

togglbutton.render('.chr-EditorsWorkItemEditor-linkSpan:not(.toggl)', {observe: true}, function (elem) {
  var project, link, div, existingContainer,
    description = $('.smb-TextInput-renderedText').textContent,
    title = $('.chr-QuickDetailFormattedId'),
    project = $('.chr-EditorsWorkItemEditor-linkSpan').textContent;
  existingContainer = $('.togglContainer')

  //if page is not refreshed by F5/CTRL + F5 we need to remove existing timer container.
  if(existingContainer) {
    existingContainer.remove();
  }

  link = togglbutton.createTimerLink({
    className: 'rallydev',
    description: description,
    projectName: project
  });

  div = document.createElement("div");
  div.classList.add("timer__container", "togglContainer");
  div.appendChild(link);
  title.appendChild(div);
});
<commit_msg>Fix rallydev linting errors and bugs<commit_after>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';

togglbutton.render('.chr-QuickDetailQuickDetailEditor', {observe: true}, function (elem) {
  var link, div,
    descriptionElem = $('.chr-QuickDetailAttributeEditorWrapper--name .smb-TextInput-renderedText', elem),
    titleElem = $('.chr-QuickDetailFormattedId', elem),
    projectElem = $('.chr-EditorsWorkItemEditor-linkSpan', elem),
    existingContainer = $('.togglContainer');

  //if page is not refreshed by F5/CTRL + F5 we need to remove existing timer container.
  if (existingContainer) {
    existingContainer.remove();
  }

  link = togglbutton.createTimerLink({
    className: 'rallydev',
    description: descriptionElem ? descriptionElem.textContent : '',
    projectName: projectElem ? projectElem.textContent : ''
  });

  div = document.createElement("div");
  div.classList.add("timer__container", "togglContainer");
  div.appendChild(link);
  titleElem.appendChild(div);
}, '.chr-QuickDetailGridView, .chr-QuickDetailAttributeEditorWrapper--name .smb-TextInput, .smb-TextInput-renderedText, .chr-EditorsWorkItemEditor-linkSpan');
<|endoftext|>


<commit_before>const NEIGHBOUR_DISTANCE = 1;
var selectedGem = null;

function swapClassNames(leftElement, rightElement) {
    var thisClassName = $(leftElement).attr("class");
    $(leftElement).attr("class", $(rightElement).attr("class"));
    $(rightElement).attr("class", thisClassName);
}

function deselectGem(gem) {
    $(gem).removeClass("selected");
    selectedGem = null;
}

function isSelected(gem) {
    return selectedGem === gem;
}

function someGemIsSelected() {
    return selectedGem !== null;
}

function swapGemWithSelected(gem) {
    swapClassNames(gem, selectedGem);
    deselectGem(gem);
}

function selectGem(gem) {
    $(gem).addClass("selected");
    selectedGem = gem;
}

function getGemCoordinates(gem) {
    return {
        col: ($(gem).offset().left - 11) / 34,
        row: ($(gem).offset().top - 11) / 34
    };
}

function columnDistance(coordinates, otherCoordinates) {
    return Math.abs(coordinates.col - otherCoordinates.col);
}

function rowDistance(coordinates, otherCoordinates) {
    return Math.abs(coordinates.row - otherCoordinates.row);
}

function getDistance(gem, otherGem) {
    var coordinates = getGemCoordinates(gem);
    var otherCoordinates = getGemCoordinates(otherGem);
    return columnDistance(coordinates, otherCoordinates) + rowDistance(coordinates, otherCoordinates);
}

function areNeighbours(gem, otherGem) {
    return getDistance(gem, otherGem) === NEIGHBOUR_DISTANCE;
}

function putGemIntoTableByCoordinates(table, row, col, gem) {
    table[row] = table[row] || [];
    table[row][col] = gem;
}

function putGemIntoTable(table, gem) {
    var coordinates = getGemCoordinates(gem);

    $(gem).attr("coordinates", JSON.stringify(coordinates));
    putGemIntoTableByCoordinates(table, coordinates.row, coordinates.col, gem);
}
function getGemsCoordinateLookupTable() {
    var table = [];

    $(".gem").each(function () {
        putGemIntoTable(table, $(this));
    });
    return table;
}

function getGem(lookupTable, row, col) {
    var lookupRow = lookupTable[row];

    if (!lookupRow) {
        return $(null);
    }

    return $(lookupRow[col]);
}

function getGemsWithPattern(lookupTable, row, col, rowOffsets, colOffsets) {
    var gems = [];

    for (var index = 0; index < rowOffsets.length; index++) {
        gems.push(getGem(lookupTable, row + rowOffsets[index], col + colOffsets[index]));
    }

    return gems;
}

function thereIsNoGem(gem) {
    return !gem.attr("class");
}

function isDestroyedGem(gem) {
    return gem.hasClass("gem-destroyed");
}

function allGemsHaveSameClass(gems, name) {
    var firstGem = gems[0];

    if (thereIsNoGem(firstGem) || isDestroyedGem(firstGem)) {
        return false;
    }

    for (var index = 1; index < gems.length; index++) {
        if (firstGem.attr("class") !== gems[index].attr("class")) {
            return false;
        }
    }

    return true;
}

function destroyGem(gem) {
    gem.addClass("gem-destroyed");
}

function destroyGems(gems) {
    for (var index = 0; index < gems.length; index++) {
        destroyGem(gems[index]);
    }
}

function getGemsToBeDestroyedWithPattern(lookupTable, rowOffsets, colOffsets, name) {
    var gemsToBeDestroyed = [];

    for (var row = 0; row < lookupTable.length; row++) {
        for (var col = 0; col < lookupTable[row].length; col++) {
            var gems = getGemsWithPattern(lookupTable, row, col, rowOffsets, colOffsets);

            if (allGemsHaveSameClass(gems, name)) {
                gemsToBeDestroyed.push(gems);
            }
        }
    }

    return gemsToBeDestroyed;
}

function generateRandomColor() {
    var randomValue = Math.random();

    if (randomValue < 0.25) return "red";
    if (randomValue < 0.50) return "green";
    if (randomValue < 0.75) return "yellow";
    return "blue";
}

var $gems = $(".gem");

function enableGravity() {
    var lookupTable = getGemsCoordinateLookupTable();

    setInterval(function () {
        $gems.each(function () {
            var $gem = $(this);
            var coordinates = getGemCoordinates($gem);
            var $downGem = getGem(lookupTable, coordinates.row + 1, coordinates.col);

            if (isDestroyedGem($downGem) && !isDestroyedGem($gem)) {
                swapClassNames($gem, $downGem);
            }
        });

        foundGemsAndDestroy();
    }, 50);
}

function cancelPlayerTurn(clickedGem, selectedGemBeforeSwap) {
    swapClassNames(clickedGem, selectedGemBeforeSwap);
}

function foundGemsAndDestroy() {
    var lookupTable = getGemsCoordinateLookupTable();

    var gemsToBeDestroyedByCol = getGemsToBeDestroyedWithPattern(lookupTable, [0, 1, 2], [0, 0, 0], "3 in column");
    var gemsToBeDestroyedByRow = getGemsToBeDestroyedWithPattern(lookupTable, [0, 0, 0], [0, 1, 2], "3 in row");

    var foundGems = gemsToBeDestroyedByCol.concat(gemsToBeDestroyedByRow);

    for (var index = 0; index < foundGems.length; index++) {
        destroyGems(foundGems[index]);
    }
    return foundGems;
}

$gems.click(function () {
    var clickedGem = this;

    if (isSelected(clickedGem)) {
        deselectGem(clickedGem);
    } else {
        if (someGemIsSelected()) {
            if (areNeighbours(clickedGem, selectedGem)) {
                var selectedGemBeforeSwap = selectedGem;

                swapGemWithSelected(clickedGem);

                var foundGems = foundGemsAndDestroy();

                if (foundGems.length === 0) {
                    cancelPlayerTurn(clickedGem, selectedGemBeforeSwap);
                }

            } else {
                deselectGem(selectedGem);
            }

        } else {
            selectGem(clickedGem);
        }
    }
});
<commit_msg>Disallow swap turn with destroyed gem.<commit_after>const NEIGHBOUR_DISTANCE = 1;
var selectedGem = null;

function swapClassNames(leftElement, rightElement) {
    var thisClassName = $(leftElement).attr("class");
    $(leftElement).attr("class", $(rightElement).attr("class"));
    $(rightElement).attr("class", thisClassName);
}

function deselectGem(gem) {
    $(gem).removeClass("selected");
    selectedGem = null;
}

function isSelected(gem) {
    return selectedGem === gem;
}

function someGemIsSelected() {
    return selectedGem !== null;
}

function swapGemWithSelected(gem) {
    swapClassNames(gem, selectedGem);
    deselectGem(gem);
}

function selectGem(gem) {
    $(gem).addClass("selected");
    selectedGem = gem;
}

function getGemCoordinates(gem) {
    return {
        col: ($(gem).offset().left - 11) / 34,
        row: ($(gem).offset().top - 11) / 34
    };
}

function columnDistance(coordinates, otherCoordinates) {
    return Math.abs(coordinates.col - otherCoordinates.col);
}

function rowDistance(coordinates, otherCoordinates) {
    return Math.abs(coordinates.row - otherCoordinates.row);
}

function getDistance(gem, otherGem) {
    var coordinates = getGemCoordinates(gem);
    var otherCoordinates = getGemCoordinates(otherGem);
    return columnDistance(coordinates, otherCoordinates) + rowDistance(coordinates, otherCoordinates);
}

function areNeighbours(gem, otherGem) {
    return getDistance(gem, otherGem) === NEIGHBOUR_DISTANCE;
}

function putGemIntoTableByCoordinates(table, row, col, gem) {
    table[row] = table[row] || [];
    table[row][col] = gem;
}

function putGemIntoTable(table, gem) {
    var coordinates = getGemCoordinates(gem);

    $(gem).attr("coordinates", JSON.stringify(coordinates));
    putGemIntoTableByCoordinates(table, coordinates.row, coordinates.col, gem);
}
function getGemsCoordinateLookupTable() {
    var table = [];

    $(".gem").each(function () {
        putGemIntoTable(table, $(this));
    });
    return table;
}

function getGem(lookupTable, row, col) {
    var lookupRow = lookupTable[row];

    if (!lookupRow) {
        return $(null);
    }

    return $(lookupRow[col]);
}

function getGemsWithPattern(lookupTable, row, col, rowOffsets, colOffsets) {
    var gems = [];

    for (var index = 0; index < rowOffsets.length; index++) {
        gems.push(getGem(lookupTable, row + rowOffsets[index], col + colOffsets[index]));
    }

    return gems;
}

function thereIsNoGem(gem) {
    return !gem.attr("class");
}

function isDestroyedGem(gem) {
    return $(gem).hasClass("gem-destroyed");
}

function allGemsHaveSameClass(gems, name) {
    var firstGem = gems[0];

    if (thereIsNoGem(firstGem) || isDestroyedGem(firstGem)) {
        return false;
    }

    for (var index = 1; index < gems.length; index++) {
        if (firstGem.attr("class") !== gems[index].attr("class")) {
            return false;
        }
    }

    return true;
}

function destroyGem(gem) {
    gem.addClass("gem-destroyed");
}

function destroyGems(gems) {
    for (var index = 0; index < gems.length; index++) {
        destroyGem(gems[index]);
    }
}

function getGemsToBeDestroyedWithPattern(lookupTable, rowOffsets, colOffsets, name) {
    var gemsToBeDestroyed = [];

    for (var row = 0; row < lookupTable.length; row++) {
        for (var col = 0; col < lookupTable[row].length; col++) {
            var gems = getGemsWithPattern(lookupTable, row, col, rowOffsets, colOffsets);

            if (allGemsHaveSameClass(gems, name)) {
                gemsToBeDestroyed.push(gems);
            }
        }
    }

    return gemsToBeDestroyed;
}

function generateRandomColor() {
    var randomValue = Math.random();

    if (randomValue < 0.25) return "red";
    if (randomValue < 0.50) return "green";
    if (randomValue < 0.75) return "yellow";
    return "blue";
}

var $gems = $(".gem");

function enableGravity() {
    var lookupTable = getGemsCoordinateLookupTable();

    setInterval(function () {
        $gems.each(function () {
            var $gem = $(this);
            var coordinates = getGemCoordinates($gem);
            var $downGem = getGem(lookupTable, coordinates.row + 1, coordinates.col);

            if (isDestroyedGem($downGem) && !isDestroyedGem($gem)) {
                swapClassNames($gem, $downGem);
            }
        });

        foundGemsAndDestroy();
    }, 50);
}

function cancelPlayerTurn(clickedGem, selectedGemBeforeSwap) {
    swapClassNames(clickedGem, selectedGemBeforeSwap);
}

function foundGemsAndDestroy() {
    var lookupTable = getGemsCoordinateLookupTable();

    var gemsToBeDestroyedByCol = getGemsToBeDestroyedWithPattern(lookupTable, [0, 1, 2], [0, 0, 0], "3 in column");
    var gemsToBeDestroyedByRow = getGemsToBeDestroyedWithPattern(lookupTable, [0, 0, 0], [0, 1, 2], "3 in row");

    var foundGems = gemsToBeDestroyedByCol.concat(gemsToBeDestroyedByRow);

    for (var index = 0; index < foundGems.length; index++) {
        destroyGems(foundGems[index]);
    }
    return foundGems;
}

function tryToMakePlayerTurn(clickedGem) {
    var selectedGemBeforeSwap = selectedGem;

    swapGemWithSelected(clickedGem);

    var foundGems = foundGemsAndDestroy();

    if (foundGems.length === 0) {
        cancelPlayerTurn(clickedGem, selectedGemBeforeSwap);
    }
}

$gems.click(function () {
    var clickedGem = this;

    if (isSelected(clickedGem)) {
        deselectGem(clickedGem);
    } else {
        if (someGemIsSelected()) {
            if (areNeighbours(clickedGem, selectedGem) && !isDestroyedGem(selectedGem) && !isDestroyedGem(clickedGem)) {
                tryToMakePlayerTurn(clickedGem);
            } else {
                deselectGem(selectedGem);
            }

        } else {
            selectGem(clickedGem);
        }
    }
});
<|endoftext|>