<commit_before>'use strict';

/* Controllers */

angular.module('myApp.controllers', ['firebase.utils', 'simpleLogin'])
  .controller('LoungeCtrl', ['$scope', 'fbutil', 'user', 'FBURL', '$window', '$location', function($scope, fbutil, user, FBURL, $window, $location) {
    var profile = fbutil.syncObject(['users_login', user.uid]);
    profile.$bindTo($scope, 'profile');

    var onlineusers = fbutil.syncObject('presences');
    onlineusers.$bindTo($scope, 'onlineusers');

    var duels = fbutil.syncObject(['duels', user.uid]);
    duels.$bindTo($scope, 'duels');

    $scope.versus = {};

    profile.$loaded().then(function(snap) {
      var listRef = fbutil.ref('presences');
      console.log(snap);
      var userObj = {
        uid: user.uid,
        name: snap.name,
        avatar: snap.avatar,
        score: snap.score,
        status: '★ online'
      };
      var userRef = fbutil.ref('presences', user.uid);
      userRef.set(userObj);

      $scope.duel = function(uid) {
        console.log('duels');
        var roomid = user.uid + '::' + uid;
        var dueling = fbutil.syncObject(['duels', uid]);
        dueling.versus = userObj;
        dueling.roomid = roomid;
        dueling.$save();

        var check_accepted = fbutil.syncObject(['versus', roomid]);
        check_accepted.$watch(function() {
          if (check_accepted.start)
            $location.path('versus/'+roomid);
        })
      }

      $scope.accept_duel = function(roomid) {
        console.log('accept duels');
        var dueling = fbutil.ref('duels', user.uid);
        dueling.remove();
        //redirect to room id
        $location.path('versus/'+roomid);
      }

      var presenceRef = fbutil.ref('.info', 'connected');
      presenceRef.on('value', function(snap) {
        userRef.onDisconnect().remove();
      });

      var onIdle = function () {
        userRef.update({status: '☆ idle'});
      }
      var onAway = function () {
        userRef.update({status: '☄ away'});
      }
      var onBack = function () {
        userRef.update({status: '★ online'});
      }

      var idle = new $window.Idle({
        onHidden : onIdle,
        onVisible : onBack,
        onAway : onAway,
        onAwayBack : onBack,
        awayTimeout : 8000 //away with default value of the textbox
      });
    });
  }])

  .controller('GameoverCtrl', ['$scope', '$rootScope', '$location', function($scope, $rootScope, $location) {

  }])

  .controller('VersusOverCtrl', ['$scope', '$rootScope', '$location', 'fbutil', function($scope, $rootScope, $location, fbutil) {
    $scope.reset = function() {
      console.log('delete versus');
      var ref = fbutil.ref('versus', $rootScope.roomid);
      ref.remove();
    }
  }])

  .controller('GameCtrl', ['$scope','$rootScope', '$location', function($scope, $rootScope, $location) {
    $scope.p1 = [{
      id: 0,
      source: 1,
      val: 1
    },{
      id: 1,
      source: 1,
      val: 1
    }];
    $scope.p2 = [{
      id: 0,
      source: 2,
      val: 1
    },{
      id: 1,
      source: 2,
      val: 1
    }];
    $scope.turn = 1;
    $scope.getParent = function(target) {
      if (target.source == 1) {
        return $scope.p1;
      } else {
        return $scope.p2;
      }
    }
    $scope.checkSwapped = function(source, target, given) {
      var temp1, temp2; //check whether just swapped or not
      temp1 = $scope.getParent(target)[0].val;
      temp2 = $scope.getParent(target)[1].val;
      if (target.id == 0) {
        temp1 += given;
        temp2 -= given;
      } else {
        temp1 -= given;
        temp2 += given;
      }
      return ($scope.getParent(target)[0].val == temp2 && $scope.getParent(target)[1].val == temp1);
    }
    $scope.checkExceed = function(source, target, given) {
      var tmptarget = $.extend(true,{},target);
      tmptarget.val += given;
      return (tmptarget.val >= 5);
    }
    $scope.changeTurn = function() {
      if (parseInt($scope.turn) == 1) {
        $scope.turn = 2;
      } else {
        $scope.turn = 1;
      }
      //check winner
      if ($scope.p1[0].val == 0 && $scope.p1[1].val == 0) {
        $rootScope.winner = 2;
        $location.path('/game/over');
      } else if ($scope.p2[0].val == 0 && $scope.p2[1].val == 0) {
        $rootScope.winner = 1;
        $location.path('/game/over');
      }
    }
    $scope.validate = function(source, target) {
      if (source.val == 0) {
        // do nothing
      } else if (source.source != $scope.turn) {
        alert('Not your turn');
      } else if (source.source == target.source && source.id == target.id) {
        alert('You cannot drop here...');
      } else if (target.val == 0) {
        alert('You cannot drop to zero...');
      } else if (source.source != target.source) { //diffrent source
        target.val += source.val;
        if (target.val > 5) {
          target.val -= 5;
        } else if (target.val == 5) {
          target.val = 0;
        }
        $scope.changeTurn();
      } else { //same source
        var given, error = '', finish = false;
        while (!finish) {
          given = prompt('How many stick ['+ ((source.val == 1) ? 1 : ('1-'+source.val) ) +']\n'+error, 1);
          if (given == undefined) break;
          given = parseInt(given);
          if (given < 1 || given > source.val) {
            finish = false;
            error = 'stick number out of range';
          } else if ($scope.checkSwapped(source, target, given)) {
            finish = false;
            error = 'the hand is just swapped, try diffrent number';
          } else if ($scope.checkExceed(source, target, given)) {
            finish = false;
            error = 'the target hand is too much';
          } else {
            finish = true;
          }
        }
        if (given != undefined) {
          target.val += given;
          source.val -= given;
          $scope.changeTurn();
        }
      }
    }

    $scope.onDropCompleteP1_0=function(data,evt){
      $scope.validate(data, $scope.p1[0]);
    }
    $scope.onDropCompleteP1_1=function(data,evt){
      $scope.validate(data, $scope.p1[1]);
    }
    $scope.onDropCompleteP2_0=function(data,evt){
      $scope.validate(data, $scope.p2[0]);
    }
    $scope.onDropCompleteP2_1=function(data,evt){
      $scope.validate(data, $scope.p2[1]);
    }
  }])

  .controller('VersusCtrl', ['$scope','$rootScope', '$location', '$routeParams', 'fbutil', 'user', function($scope, $rootScope, $location, $routeParams, fbutil, user) {
    var roomid = String($routeParams.id);
    $rootScope.roomid = roomid;
    var roomsplit = roomid.split("::");

    if (roomsplit[0] == user.uid)
      $scope.statusPlayer = 1;
    else
      $scope.statusPlayer = 2;

    var player1 = fbutil.syncObject(['users_login', roomsplit[0]]);
    player1.$bindTo($scope, 'player1');

    var player2 = fbutil.syncObject(['users_login', roomsplit[1]]);
    player2.$bindTo($scope, 'player2');

    var p1 = [{
      id: 0,
      source: 1,
      val: 1
    },{
      id: 1,
      source: 1,
      val: 1
    }];

    var p2 = [{
      id: 0,
      source: 2,
      val: 1
    },{
      id: 1,
      source: 2,
      val: 1
    }];

    var turn = 1;
    var win = false;
    var winner = null;

    var current_game = fbutil.syncObject(['versus', roomid]);
    current_game.$loaded().then(function() {
      if (!current_game.start) {
        //init new game
        current_game.start = true;
        current_game.state = {p1: p1, p2: p2, turn: turn, win: win, winner: winner};
        current_game.$save();
        $scope.state = current_game.state;
      }
    });

    var state = fbutil.syncObject(['versus', roomid, 'state']);
    state.$bindTo($scope, 'state');

    state.$watch(function() {
      if (state.win) {
        $rootScope.winner = state.winner;
        $location.path('/versus/over');
      }
    });

    $scope.getParent = function(target) {
      if (target.source == 1) {
        return $scope.state.p1;
      } else {
        return $scope.state.p2;
      }
    }
    $scope.checkSwapped = function(source, target, given) {
      var temp1, temp2; //check whether just swapped or not
      temp1 = $scope.getParent(target)[0].val;
      temp2 = $scope.getParent(target)[1].val;
      if (target.id == 0) {
        temp1 += given;
        temp2 -= given;
      } else {
        temp1 -= given;
        temp2 += given;
      }
      return ($scope.getParent(target)[0].val == temp2 && $scope.getParent(target)[1].val == temp1);
    }
    $scope.checkExceed = function(source, target, given) {
      var tmptarget = $.extend(true,{},target);
      tmptarget.val += given;
      return (tmptarget.val >= 5);
    }
    $scope.changeTurn = function() {
      if (parseInt($scope.state.turn) == 1) {
        $scope.state.turn = 2;
      } else {
        $scope.state.turn = 1;
      }
      //check winner
      if ($scope.state.p1[0].val == 0 && $scope.state.p1[1].val == 0) {
        $scope.state.winner = $scope.player2.name;
        $scope.player2.score += 10;
        $scope.player1.score += 1;
        $scope.state.win = true;
        $location.path('/versus/over');
      } else if ($scope.state.p2[0].val == 0 && $scope.state.p2[1].val == 0) {
        $scope.state.winner = $scope.player1.name;
        $scope.player1.score += 10;
        $scope.player2.score += 1;
        $scope.state.win = true;
        $location.path('/versus/over');
      }
    }
    $scope.validate = function(source, target) {
      if (source.val == 0) {
        // do nothing
      } else if (source.source != $scope.statusPlayer) {
        alert("It's not your hand");
      } else if (source.source != $scope.state.turn) {
        alert("It's not your turn");
      } else if (source.source == target.source && source.id == target.id) {
        alert('You cannot drop here...');
      } else if (target.val == 0) {
        alert('You cannot drop to zero...');
      } else if (source.source != target.source) { //diffrent source
        target.val += source.val;
        if (target.val > 5) {
          target.val -= 5;
        } else if (target.val == 5) {
          target.val = 0;
        }
        $scope.changeTurn();
      } else { //same source
        var given, error = '', finish = false;
        while (!finish) {
          given = prompt('How many stick ['+ ((source.val == 1) ? 1 : ('1-'+source.val) ) +']\n'+error, 1);
          if (given == undefined) break;
          given = parseInt(given);
          if (given < 1 || given > source.val) {
            finish = false;
            error = 'stick number out of range';
          } else if ($scope.checkSwapped(source, target, given)) {
            finish = false;
            error = 'the hand is just swapped, try diffrent number';
          } else if ($scope.checkExceed(source, target, given)) {
            finish = false;
            error = 'the target hand is too much';
          } else {
            finish = true;
          }
        }
        if (given != undefined) {
          target.val += given;
          source.val -= given;
          $scope.changeTurn();
        }
      }
    }

    $scope.onDropCompleteP1_0=function(data,evt){
      $scope.validate(data, $scope.state.p1[0]);
    }
    $scope.onDropCompleteP1_1=function(data,evt){
      $scope.validate(data, $scope.state.p1[1]);
    }
    $scope.onDropCompleteP2_0=function(data,evt){
      $scope.validate(data, $scope.state.p2[0]);
    }
    $scope.onDropCompleteP2_1=function(data,evt){
      $scope.validate(data, $scope.state.p2[1]);
    }
  }])

  .controller('MenuCtrl', ['$scope', 'simpleLogin', '$location', 'createProfile', function($scope, simpleLogin, $location, createProfile) {

    $scope.login = function() {
      $scope.err = null;
      simpleLogin.login()
        .then(function( user ) {
          console.log(user);
          createProfile(user.uid, user.displayName, user.thirdPartyUserData.picture.data.url, 0).then(function() {
            $location.path('/lounge');
          });
        }, function(err) {
          $scope.err = errMessage(err);
        });
    };

    function errMessage(err) {
      return angular.isObject(err) && err.code? err.code : err + '';
    }
  }])

  .controller('AccountCtrl', ['$scope', 'simpleLogin', 'fbutil', 'user', '$location',
    function($scope, simpleLogin, fbutil, user, $location) {
      // create a 3-way binding with the user profile object in Firebase
      var profile = fbutil.syncObject(['users_login', user.uid]);
      profile.$bindTo($scope, 'profile');

      // expose logout function to scope
      $scope.logout = function() {
        profile.$destroy();
        simpleLogin.logout();
        $location.path('/menu');
      };

      $scope.clear = resetMessages;

      function resetMessages() {
        $scope.err = null;
        $scope.msg = null;
        $scope.emailerr = null;
        $scope.emailmsg = null;
      }
    }
  ]);<commit_msg>fixed bug share to zero in one's hand<commit_after>'use strict';

/* Controllers */

angular.module('myApp.controllers', ['firebase.utils', 'simpleLogin'])
  .controller('LoungeCtrl', ['$scope', 'fbutil', 'user', 'FBURL', '$window', '$location', function($scope, fbutil, user, FBURL, $window, $location) {
    var profile = fbutil.syncObject(['users_login', user.uid]);
    profile.$bindTo($scope, 'profile');

    var onlineusers = fbutil.syncObject('presences');
    onlineusers.$bindTo($scope, 'onlineusers');

    var duels = fbutil.syncObject(['duels', user.uid]);
    duels.$bindTo($scope, 'duels');

    $scope.versus = {};

    profile.$loaded().then(function(snap) {
      var listRef = fbutil.ref('presences');
      console.log(snap);
      var userObj = {
        uid: user.uid,
        name: snap.name,
        avatar: snap.avatar,
        score: snap.score,
        status: '★ online'
      };
      var userRef = fbutil.ref('presences', user.uid);
      userRef.set(userObj);

      $scope.duel = function(uid) {
        console.log('duels');
        var roomid = user.uid + '::' + uid;
        var dueling = fbutil.syncObject(['duels', uid]);
        dueling.versus = userObj;
        dueling.roomid = roomid;
        dueling.$save();

        var check_accepted = fbutil.syncObject(['versus', roomid]);
        check_accepted.$watch(function() {
          if (check_accepted.start)
            $location.path('versus/'+roomid);
        })
      }

      $scope.accept_duel = function(roomid) {
        console.log('accept duels');
        var dueling = fbutil.ref('duels', user.uid);
        dueling.remove();
        //redirect to room id
        $location.path('versus/'+roomid);
      }

      var presenceRef = fbutil.ref('.info', 'connected');
      presenceRef.on('value', function(snap) {
        userRef.onDisconnect().remove();
      });

      var onIdle = function () {
        userRef.update({status: '☆ idle'});
      }
      var onAway = function () {
        userRef.update({status: '☄ away'});
      }
      var onBack = function () {
        userRef.update({status: '★ online'});
      }

      var idle = new $window.Idle({
        onHidden : onIdle,
        onVisible : onBack,
        onAway : onAway,
        onAwayBack : onBack,
        awayTimeout : 8000 //away with default value of the textbox
      });
    });
  }])

  .controller('GameoverCtrl', ['$scope', '$rootScope', '$location', function($scope, $rootScope, $location) {

  }])

  .controller('VersusOverCtrl', ['$scope', '$rootScope', '$location', 'fbutil', function($scope, $rootScope, $location, fbutil) {
    $scope.reset = function() {
      console.log('delete versus');
      var ref = fbutil.ref('versus', $rootScope.roomid);
      ref.remove();
    }
  }])

  .controller('GameCtrl', ['$scope','$rootScope', '$location', function($scope, $rootScope, $location) {
    $scope.p1 = [{
      id: 0,
      source: 1,
      val: 1
    },{
      id: 1,
      source: 1,
      val: 1
    }];
    $scope.p2 = [{
      id: 0,
      source: 2,
      val: 1
    },{
      id: 1,
      source: 2,
      val: 1
    }];
    $scope.turn = 1;
    $scope.getParent = function(target) {
      if (target.source == 1) {
        return $scope.p1;
      } else {
        return $scope.p2;
      }
    }
    $scope.checkSwapped = function(source, target, given) {
      var temp1, temp2; //check whether just swapped or not
      temp1 = $scope.getParent(target)[0].val;
      temp2 = $scope.getParent(target)[1].val;
      if (target.id == 0) {
        temp1 += given;
        temp2 -= given;
      } else {
        temp1 -= given;
        temp2 += given;
      }
      return ($scope.getParent(target)[0].val == temp2 && $scope.getParent(target)[1].val == temp1);
    }
    $scope.checkExceed = function(source, target, given) {
      var tmptarget = $.extend(true,{},target);
      tmptarget.val += given;
      return (tmptarget.val >= 5);
    }
    $scope.changeTurn = function() {
      if (parseInt($scope.turn) == 1) {
        $scope.turn = 2;
      } else {
        $scope.turn = 1;
      }
      //check winner
      if ($scope.p1[0].val == 0 && $scope.p1[1].val == 0) {
        $rootScope.winner = 2;
        $location.path('/game/over');
      } else if ($scope.p2[0].val == 0 && $scope.p2[1].val == 0) {
        $rootScope.winner = 1;
        $location.path('/game/over');
      }
    }
    $scope.validate = function(source, target) {
      if (source.val == 0) {
        // do nothing
      } else if (source.source != $scope.turn) {
        alert('Not your turn');
      } else if (source.source == target.source && source.id == target.id) {
        alert('You cannot drop here...');
      } else if (target.val == 0 && (source.source != target.source)) {
        alert('You cannot drop to zero...');
      } else if (source.source != target.source) { //diffrent source
        target.val += source.val;
        if (target.val > 5) {
          target.val -= 5;
        } else if (target.val == 5) {
          target.val = 0;
        }
        $scope.changeTurn();
      } else { //same source
        var given, error = '', finish = false;
        while (!finish) {
          given = prompt('How many stick ['+ ((source.val == 1) ? 1 : ('1-'+source.val) ) +']\n'+error, 1);
          if (given == undefined) break;
          given = parseInt(given);
          if (given < 1 || given > source.val) {
            finish = false;
            error = 'stick number out of range';
          } else if ($scope.checkSwapped(source, target, given)) {
            finish = false;
            error = 'the hand is just swapped, try diffrent number';
          } else if ($scope.checkExceed(source, target, given)) {
            finish = false;
            error = 'the target hand is too much';
          } else {
            finish = true;
          }
        }
        if (given != undefined) {
          target.val += given;
          source.val -= given;
          $scope.changeTurn();
        }
      }
    }

    $scope.onDropCompleteP1_0=function(data,evt){
      $scope.validate(data, $scope.p1[0]);
    }
    $scope.onDropCompleteP1_1=function(data,evt){
      $scope.validate(data, $scope.p1[1]);
    }
    $scope.onDropCompleteP2_0=function(data,evt){
      $scope.validate(data, $scope.p2[0]);
    }
    $scope.onDropCompleteP2_1=function(data,evt){
      $scope.validate(data, $scope.p2[1]);
    }
  }])

  .controller('VersusCtrl', ['$scope','$rootScope', '$location', '$routeParams', 'fbutil', 'user', function($scope, $rootScope, $location, $routeParams, fbutil, user) {
    var roomid = String($routeParams.id);
    $rootScope.roomid = roomid;
    var roomsplit = roomid.split("::");

    if (roomsplit[0] == user.uid)
      $scope.statusPlayer = 1;
    else
      $scope.statusPlayer = 2;

    var player1 = fbutil.syncObject(['users_login', roomsplit[0]]);
    player1.$bindTo($scope, 'player1');

    var player2 = fbutil.syncObject(['users_login', roomsplit[1]]);
    player2.$bindTo($scope, 'player2');

    var p1 = [{
      id: 0,
      source: 1,
      val: 1
    },{
      id: 1,
      source: 1,
      val: 1
    }];

    var p2 = [{
      id: 0,
      source: 2,
      val: 1
    },{
      id: 1,
      source: 2,
      val: 1
    }];

    var turn = 1;
    var win = false;
    var winner = null;

    var current_game = fbutil.syncObject(['versus', roomid]);
    current_game.$loaded().then(function() {
      if (!current_game.start) {
        //init new game
        current_game.start = true;
        current_game.state = {p1: p1, p2: p2, turn: turn, win: win, winner: winner};
        current_game.$save();
        $scope.state = current_game.state;
      }
    });

    var state = fbutil.syncObject(['versus', roomid, 'state']);
    state.$bindTo($scope, 'state');

    state.$watch(function() {
      if (state.win) {
        $rootScope.winner = state.winner;
        $location.path('/versus/over');
      }
    });

    $scope.getParent = function(target) {
      if (target.source == 1) {
        return $scope.state.p1;
      } else {
        return $scope.state.p2;
      }
    }
    $scope.checkSwapped = function(source, target, given) {
      var temp1, temp2; //check whether just swapped or not
      temp1 = $scope.getParent(target)[0].val;
      temp2 = $scope.getParent(target)[1].val;
      if (target.id == 0) {
        temp1 += given;
        temp2 -= given;
      } else {
        temp1 -= given;
        temp2 += given;
      }
      return ($scope.getParent(target)[0].val == temp2 && $scope.getParent(target)[1].val == temp1);
    }
    $scope.checkExceed = function(source, target, given) {
      var tmptarget = $.extend(true,{},target);
      tmptarget.val += given;
      return (tmptarget.val >= 5);
    }
    $scope.changeTurn = function() {
      if (parseInt($scope.state.turn) == 1) {
        $scope.state.turn = 2;
      } else {
        $scope.state.turn = 1;
      }
      //check winner
      if ($scope.state.p1[0].val == 0 && $scope.state.p1[1].val == 0) {
        $scope.state.winner = $scope.player2.name;
        $scope.player2.score += 10;
        $scope.player1.score += 1;
        $scope.state.win = true;
        $location.path('/versus/over');
      } else if ($scope.state.p2[0].val == 0 && $scope.state.p2[1].val == 0) {
        $scope.state.winner = $scope.player1.name;
        $scope.player1.score += 10;
        $scope.player2.score += 1;
        $scope.state.win = true;
        $location.path('/versus/over');
      }
    }
    $scope.validate = function(source, target) {
      if (source.val == 0) {
        // do nothing
      } else if (source.source != $scope.statusPlayer) {
        alert("It's not your hand");
      } else if (source.source != $scope.state.turn) {
        alert("It's not your turn");
      } else if (source.source == target.source && source.id == target.id) {
        alert('You cannot drop here...');
      } else if (target.val == 0 && (source.source != target.source)) {
        alert('You cannot drop to zero...');
      } else if (source.source != target.source) { //diffrent source
        target.val += source.val;
        if (target.val > 5) {
          target.val -= 5;
        } else if (target.val == 5) {
          target.val = 0;
        }
        $scope.changeTurn();
      } else { //same source
        var given, error = '', finish = false;
        while (!finish) {
          given = prompt('How many stick ['+ ((source.val == 1) ? 1 : ('1-'+source.val) ) +']\n'+error, 1);
          if (given == undefined) break;
          given = parseInt(given);
          if (given < 1 || given > source.val) {
            finish = false;
            error = 'stick number out of range';
          } else if ($scope.checkSwapped(source, target, given)) {
            finish = false;
            error = 'the hand is just swapped, try diffrent number';
          } else if ($scope.checkExceed(source, target, given)) {
            finish = false;
            error = 'the target hand is too much';
          } else {
            finish = true;
          }
        }
        if (given != undefined) {
          target.val += given;
          source.val -= given;
          $scope.changeTurn();
        }
      }
    }

    $scope.onDropCompleteP1_0=function(data,evt){
      $scope.validate(data, $scope.state.p1[0]);
    }
    $scope.onDropCompleteP1_1=function(data,evt){
      $scope.validate(data, $scope.state.p1[1]);
    }
    $scope.onDropCompleteP2_0=function(data,evt){
      $scope.validate(data, $scope.state.p2[0]);
    }
    $scope.onDropCompleteP2_1=function(data,evt){
      $scope.validate(data, $scope.state.p2[1]);
    }
  }])

  .controller('MenuCtrl', ['$scope', 'simpleLogin', '$location', 'createProfile', function($scope, simpleLogin, $location, createProfile) {

    $scope.login = function() {
      $scope.err = null;
      simpleLogin.login()
        .then(function( user ) {
          console.log(user);
          createProfile(user.uid, user.displayName, user.thirdPartyUserData.picture.data.url, 0).then(function() {
            $location.path('/lounge');
          });
        }, function(err) {
          $scope.err = errMessage(err);
        });
    };

    function errMessage(err) {
      return angular.isObject(err) && err.code? err.code : err + '';
    }
  }])

  .controller('AccountCtrl', ['$scope', 'simpleLogin', 'fbutil', 'user', '$location',
    function($scope, simpleLogin, fbutil, user, $location) {
      // create a 3-way binding with the user profile object in Firebase
      var profile = fbutil.syncObject(['users_login', user.uid]);
      profile.$bindTo($scope, 'profile');

      // expose logout function to scope
      $scope.logout = function() {
        profile.$destroy();
        simpleLogin.logout();
        $location.path('/menu');
      };

      $scope.clear = resetMessages;

      function resetMessages() {
        $scope.err = null;
        $scope.msg = null;
        $scope.emailerr = null;
        $scope.emailmsg = null;
      }
    }
  ]);<|endoftext|>


<commit_before>class CaretakerFormObject extends CaretakerFormElementPrototype{
	constructor(props){
		super(props)
		this.state = {}
		this.loadValue(props)
	}
	onReportValidity(isValid, name){
		this.state.validationUpdated = false
		if(this.isObject() && !this.isMany() && !this.isChildless()){
			//if validity node is null or not an object, make new validity node
			if(typeof this.state.isValidMap != "object" || this.state.isValidMap == null){
				this.state.isValidMap = {}
				if(typeof this.props.has == "object" && this.props.has != null){
					var has = this.props.has
					for(var i in has){
						var currentName = has[i].name
						if(!currentName){
							currentName = i
						}
						this.state.isValidMap[currentName] = false
					}
				}
			}
			this.state.isValidMap[name] = isValid
		}else{
			this.state.isValid = isValid
		}
		this.reportValidity()
	}
	reportValidity(){
		if(this.props.onReportValidity && this.state.isValidating && !this.state.validationUpdated){
			this.state.validationUpdated = true
			if(this.isObject() && !this.isMany() && !this.isChildless()){
				var isValid = true
				if(typeof this.props.has == "object" && this.props.has){
					var has = this.props.has
					for(var i in has){
						var name = has[i].name
						if(!name){
							name = i
						}
						if(this.state.isValidMap[name] != true){
							isValid = false
							break
						}
					}
				}
				this.state.isValid = isValid
			}

			if(typeof this.props.validate == "function"){
				var tempValid = Array.isArray(this.state.isValid) || this.state.isValid == true ? this.state.isValid : [this.state.isValid]
				var newValid
				try{
					newValid = this.props.validate(this.state.value, tempValid)
				}catch(throwable){
					if(throwable instanceof Error){
						console.error("Something happened while validating", throwable)
					}else{
						newValid = throwable
					}
				}
				if(typeof newValid == "string" || Array.isArray(newValid) || newValid === true || newValid === false ){
					this.state.isValid = newValid
				}
			}

			this.props.onReportValidity(this.state.isValid, this.props.name)
			// this.setState(this.state)
		}
	}
	componentDidMount(){
		this.updateParent()
	}
	componentWillReceiveProps(props){
		this.loadValue(props)
		this.state.isValidating = props.isValidating
		// this.setState(this.state)
		if(this.isChildless()){
			this.state.isValid = true
			this.reportValidity()
		}
	}
	assertValues(){
		if(this.isMany() && !(Array.isArray(this.state.value) || this.state.value == null)){
			throw "Value for manyObjects must be an array"
		}else if(this.isObject() && !(typeof this.state.value == "object" || this.state.value == null)){
			throw "Value for Object must be an object"
		}
	}
	loadValueConversion(possibleValue){
		if(Array.isArray(possibleValue)){
			this.state.value = Caretaker.ValueArray.from(possibleValue)
		}else if(typeof possibleValue == "object" && possibleValue.__proto__.constructor == Object && possibleValue){
			this.state.value = Caretaker.ValueNode.from(possibleValue)
		}else{
			this.state.value = possibleValue
		}
	}
	loadValue(props){
		if(this.isMany()){
			this.state.value = new Caretaker.ValueArray()
			this.state.name = "arr"
		}
		else if(this.isObject()){
			this.state.value = new Caretaker.ValueNode()
			this.state.name = "obj"
		}else{
			this.state.value = null
			this.state.name = "val"
		}
		//update name;
		if(props.name != null){
			this.state.name = props.name
		}else{
			throw new Error("This object scheme doesn't have name attribute:\n"+JSON.stringify(props,null,2))
		}
		//update value
		if(props.value != null){
			this.loadValueConversion(props.value)
		}else if(props.defaultValue != null){
			this.loadValueConversion(props.defaultValue)
		}
		this.assertValues()
	}
	isMany(){
		return this.props.quantity == "many"
	}
	isObject(){
		return this.props.type == "object" || this.props.type == null
	}
	isInput(){
		return !this.isObject() && !this.isMany()
	}
	isChildless(){
		return this.isObject() && (this.props.has == null || (typeof this.props.has == "object" && Object.keys(this.props.has).length == 0 ))
	}
	updateParent(){
		this.state.validationUpdated = false
		if(this.props.onChange){
			this.props.onChange(this.state.value, this.state.name)
		}
	}
	onChange(value, name){

		if(name != null){
			this.state.value[name] = value
		}else{
			this.state.value = value
		}
		this.updateParent()
	}
	getOnChangeListener(){
		return this.onChange.bind(this)
	}
	getNegativeChildPropKeys(){
		return ["label","description","htmlLabel","htmlDescription","quantity"]
	}
	getNegativeInputPropKeys(){
		return ["label","description","htmlLabel","htmlDescription","quantity","has","defaultValue","validate"]
	}
	getInputProps(){
		var props = Object.assign({}, this.props)
		this.getNegativeInputPropKeys().forEach(function(key){
			props[key] = null
			delete props[key]
		})
		props.onChange = this.getOnChangeListener()
		props.onReportValidity = this.onReportValidity.bind(this);
		props.isValidating = this.state.isValidating
		props.value = this.state.value
		return props
	}
	getCollectionProps(){
		var props = Object.assign({}, this.props)
		this.getNegativeChildPropKeys().forEach(function(key){
			props[key] = null
			delete props[key]
		})
		props.onChange = this.getOnChangeListener()
		props.onReportValidity = this.onReportValidity.bind(this)
		props.isValidating = this.state.isValidating
		props.value = this.state.value
		return props
	}
	appearanceGetLabel(){
		if(this.props.htmlLabel && typeof this.props.htmlLabel == "string"){
			return React.createElement('label',
				{
					className: this.appearanceProtoGetClassName("label", "CaretakerLabel"),
					htmlFor: this.state.name,
					key:"label",
					dangerouslySetInnerHTML: {__html:this.props.htmlLabel}
				}
			)
		}else if(this.props.label){
			return React.createElement('label',
				{
					className: this.appearanceProtoGetClassName("label", "CaretakerLabel"),
					htmlFor: this.state.name,
					key:"label"
				},
				this.props.label
			)
		}
		return false
	}
	appearanceGetDescription(){
		if(this.props.htmlDescription){
			return React.createElement('p',
				{
					className: this.appearanceProtoGetClassName("p", "CaretakerDescription"),
					key:"description",
					dangerouslySetInnerHTML: {__html:this.props.htmlDescription}
				}
			)
		}else if(this.props.description){
			return React.createElement('p',
				{
					className: this.appearanceProtoGetClassName("p", "CaretakerDescription"),
					key:"description"
				},
				this.props.description
			)
		}
		return false;
	}
	appearanceGetObject(){
		if(this.isMany()){
			var props = this.getCollectionProps()
			props.key = "object"
			return React.createElement(CaretakerFormObjectCollection, props)
		}else if(this.isObject()){
			var objects = []
			if(this.props.has){
				var has = this.props.has
				for(var i in has){
					var childProps = Object.assign({},has[i])
					childProps.key = i
					if(this.state.value[i] != null){
						childProps.value = this.state.value[i]
					}
					if(has[i].name != null){
						childProps.name = has[i].name
						if(this.state.value[childProps.name] != null){
							childProps.value = this.state.value[childProps.name]
						}
					}
					childProps.onChange = this.getOnChangeListener()
					childProps.onReportValidity = this.onReportValidity.bind(this)
					childProps.isValidating = this.state.isValidating
					objects.push( React.createElement(CaretakerFormObject, childProps) )
				}
			}
			return objects
		}else{
			var props = this.getInputProps()
			props.key = "object"
			props.value = this.state.value
			return React.createElement(CaretakerInput,props)
		}
	}
	appearanceGetErrorMessage(){
		if(typeof this.state.isValid == "string"){
			return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, this.state.isValid)
		}else if (Array.isArray(this.state.isValid) && this.state.isValid.length > 0){
			if(this.state.isValid.length == 1){
				return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, this.state.isValid[0])
			}else if(this.state.isValid.length > 1){
				return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, (
					React.createElement('ul', {}, (function(validityList){
						var lis = []
						for(var i in validityList){
							var message = validityList[i]
							lis.push(React.createElement('li',{key:i}, message))
						}
						return lis
					}(this.state.isValid)))
				))
			}
		}
	}
	appearanceGetInsideObjectContainer(){
		var insideObjectContainer = []

		var label = this.appearanceGetLabel();
		var description = this.appearanceGetDescription()
		var errorMessages = this.appearanceGetErrorMessage()
		var object = this.appearanceGetObject();

		if(label){ insideObjectContainer.push(label) }
		if(description){ insideObjectContainer.push(description) }
		if(errorMessages){ insideObjectContainer.push(errorMessages) }
		if(object){ insideObjectContainer.push(object) }

		return insideObjectContainer
	}
	appearanceGetValidClassname(){
		if(this.state.isValid != null){
			if(this.state.isValid == true){
				return this.appearanceProtoGetClassName("valid")
			}else{
				return this.appearanceProtoGetClassName("invalid")
			}
		}
		return ""
	}
	render(){
		var props = {}
		props.className = this.appearanceProtoGetClassName("div", "CaretakerFormObject")
		props.className += (this.state.name ? this.appearanceProtoGetClassName(null, this.state.name || "") : "")
		props.className += (this.isInput() ? this.appearanceProtoGetClassName(null, "CaretakerInputContainer") : "")
		props.className += this.appearanceGetValidClassname()
		return React.createElement(
			'div',
			props,
			this.appearanceGetInsideObjectContainer())
	}
}
<commit_msg>Now users cannot edit value with validate function<commit_after>class CaretakerFormObject extends CaretakerFormElementPrototype{
	constructor(props){
		super(props)
		this.state = {}
		this.loadValue(props)
	}
	onReportValidity(isValid, name){
		this.state.validationUpdated = false
		if(this.isObject() && !this.isMany() && !this.isChildless()){
			//if validity node is null or not an object, make new validity node
			if(typeof this.state.isValidMap != "object" || this.state.isValidMap == null){
				this.state.isValidMap = {}
				if(typeof this.props.has == "object" && this.props.has != null){
					var has = this.props.has
					for(var i in has){
						var currentName = has[i].name
						if(!currentName){
							currentName = i
						}
						this.state.isValidMap[currentName] = false
					}
				}
			}
			this.state.isValidMap[name] = isValid
		}else{
			this.state.isValid = isValid
		}
		this.reportValidity()
	}
	reportValidity(){
		if(this.props.onReportValidity && this.state.isValidating && !this.state.validationUpdated){
			this.state.validationUpdated = true
			if(this.isObject() && !this.isMany() && !this.isChildless()){
				var isValid = true
				if(typeof this.props.has == "object" && this.props.has){
					var has = this.props.has
					for(var i in has){
						var name = has[i].name
						if(!name){
							name = i
						}
						if(this.state.isValidMap[name] != true){
							isValid = false
							break
						}
					}
				}
				this.state.isValid = isValid
			}

			if(typeof this.props.validate == "function"){
				var tempValid = Array.isArray(this.state.isValid) || this.state.isValid == true ? this.state.isValid : [this.state.isValid]
				var newValid
				try{
					var copyValue = Array.isArray(this.state.value) ? Array.from(this.state.value) : typeof this.state.value == "object" ? Object.assign({}, this.state.value) : this.state.value
					newValid = this.props.validate(copyValue, tempValid)
				}catch(throwable){
					if(throwable instanceof Error){
						console.error("Something happened while validating", throwable)
					}else{
						newValid = throwable
					}
				}
				if(typeof newValid == "string" || Array.isArray(newValid) || newValid === true || newValid === false ){
					this.state.isValid = newValid
				}
			}

			this.props.onReportValidity(this.state.isValid, this.props.name)
			// this.setState(this.state)
		}
	}
	componentDidMount(){
		this.updateParent()
	}
	componentWillReceiveProps(props){
		this.loadValue(props)
		this.state.isValidating = props.isValidating
		// this.setState(this.state)
		if(this.isChildless()){
			this.state.isValid = true
			this.reportValidity()
		}
	}
	assertValues(){
		if(this.isMany() && !(Array.isArray(this.state.value) || this.state.value == null)){
			throw "Value for manyObjects must be an array"
		}else if(this.isObject() && !(typeof this.state.value == "object" || this.state.value == null)){
			throw "Value for Object must be an object"
		}
	}
	loadValueConversion(possibleValue){
		if(Array.isArray(possibleValue)){
			this.state.value = Caretaker.ValueArray.from(possibleValue)
		}else if(typeof possibleValue == "object" && possibleValue.__proto__.constructor == Object && possibleValue){
			this.state.value = Caretaker.ValueNode.from(possibleValue)
		}else{
			this.state.value = possibleValue
		}
	}
	loadValue(props){
		if(this.isMany()){
			this.state.value = new Caretaker.ValueArray()
			this.state.name = "arr"
		}
		else if(this.isObject()){
			this.state.value = new Caretaker.ValueNode()
			this.state.name = "obj"
		}else{
			this.state.value = null
			this.state.name = "val"
		}
		//update name;
		if(props.name != null){
			this.state.name = props.name
		}else{
			throw new Error("This object scheme doesn't have name attribute:\n"+JSON.stringify(props,null,2))
		}
		//update value
		if(props.value != null){
			this.loadValueConversion(props.value)
		}else if(props.defaultValue != null){
			this.loadValueConversion(props.defaultValue)
		}
		this.assertValues()
	}
	isMany(){
		return this.props.quantity == "many"
	}
	isObject(){
		return this.props.type == "object" || this.props.type == null
	}
	isInput(){
		return !this.isObject() && !this.isMany()
	}
	isChildless(){
		return this.isObject() && (this.props.has == null || (typeof this.props.has == "object" && Object.keys(this.props.has).length == 0 ))
	}
	updateParent(){
		this.state.validationUpdated = false
		if(this.props.onChange){
			this.props.onChange(this.state.value, this.state.name)
		}
	}
	onChange(value, name){

		if(name != null){
			this.state.value[name] = value
		}else{
			this.state.value = value
		}
		this.updateParent()
	}
	getOnChangeListener(){
		return this.onChange.bind(this)
	}
	getNegativeChildPropKeys(){
		return ["label","description","htmlLabel","htmlDescription","quantity"]
	}
	getNegativeInputPropKeys(){
		return ["label","description","htmlLabel","htmlDescription","quantity","has","defaultValue","validate"]
	}
	getInputProps(){
		var props = Object.assign({}, this.props)
		this.getNegativeInputPropKeys().forEach(function(key){
			props[key] = null
			delete props[key]
		})
		props.onChange = this.getOnChangeListener()
		props.onReportValidity = this.onReportValidity.bind(this);
		props.isValidating = this.state.isValidating
		props.value = this.state.value
		return props
	}
	getCollectionProps(){
		var props = Object.assign({}, this.props)
		this.getNegativeChildPropKeys().forEach(function(key){
			props[key] = null
			delete props[key]
		})
		props.onChange = this.getOnChangeListener()
		props.onReportValidity = this.onReportValidity.bind(this)
		props.isValidating = this.state.isValidating
		props.value = this.state.value
		return props
	}
	appearanceGetLabel(){
		if(this.props.htmlLabel && typeof this.props.htmlLabel == "string"){
			return React.createElement('label',
				{
					className: this.appearanceProtoGetClassName("label", "CaretakerLabel"),
					htmlFor: this.state.name,
					key:"label",
					dangerouslySetInnerHTML: {__html:this.props.htmlLabel}
				}
			)
		}else if(this.props.label){
			return React.createElement('label',
				{
					className: this.appearanceProtoGetClassName("label", "CaretakerLabel"),
					htmlFor: this.state.name,
					key:"label"
				},
				this.props.label
			)
		}
		return false
	}
	appearanceGetDescription(){
		if(this.props.htmlDescription){
			return React.createElement('p',
				{
					className: this.appearanceProtoGetClassName("p", "CaretakerDescription"),
					key:"description",
					dangerouslySetInnerHTML: {__html:this.props.htmlDescription}
				}
			)
		}else if(this.props.description){
			return React.createElement('p',
				{
					className: this.appearanceProtoGetClassName("p", "CaretakerDescription"),
					key:"description"
				},
				this.props.description
			)
		}
		return false;
	}
	appearanceGetObject(){
		if(this.isMany()){
			var props = this.getCollectionProps()
			props.key = "object"
			return React.createElement(CaretakerFormObjectCollection, props)
		}else if(this.isObject()){
			var objects = []
			if(this.props.has){
				var has = this.props.has
				for(var i in has){
					var childProps = Object.assign({},has[i])
					childProps.key = i
					if(this.state.value[i] != null){
						childProps.value = this.state.value[i]
					}
					if(has[i].name != null){
						childProps.name = has[i].name
						if(this.state.value[childProps.name] != null){
							childProps.value = this.state.value[childProps.name]
						}
					}
					childProps.onChange = this.getOnChangeListener()
					childProps.onReportValidity = this.onReportValidity.bind(this)
					childProps.isValidating = this.state.isValidating
					objects.push( React.createElement(CaretakerFormObject, childProps) )
				}
			}
			return objects
		}else{
			var props = this.getInputProps()
			props.key = "object"
			props.value = this.state.value
			return React.createElement(CaretakerInput,props)
		}
	}
	appearanceGetErrorMessage(){
		if(typeof this.state.isValid == "string"){
			return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, this.state.isValid)
		}else if (Array.isArray(this.state.isValid) && this.state.isValid.length > 0){
			if(this.state.isValid.length == 1){
				return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, this.state.isValid[0])
			}else if(this.state.isValid.length > 1){
				return React.createElement('div', {className: this.appearanceProtoGetClassName("div", "CaretakerErrorMessage"), key:"errorMessage"}, (
					React.createElement('ul', {}, (function(validityList){
						var lis = []
						for(var i in validityList){
							var message = validityList[i]
							lis.push(React.createElement('li',{key:i}, message))
						}
						return lis
					}(this.state.isValid)))
				))
			}
		}
	}
	appearanceGetInsideObjectContainer(){
		var insideObjectContainer = []

		var label = this.appearanceGetLabel();
		var description = this.appearanceGetDescription()
		var errorMessages = this.appearanceGetErrorMessage()
		var object = this.appearanceGetObject();

		if(label){ insideObjectContainer.push(label) }
		if(description){ insideObjectContainer.push(description) }
		if(errorMessages){ insideObjectContainer.push(errorMessages) }
		if(object){ insideObjectContainer.push(object) }

		return insideObjectContainer
	}
	appearanceGetValidClassname(){
		if(this.state.isValid != null){
			if(this.state.isValid == true){
				return this.appearanceProtoGetClassName("valid")
			}else{
				return this.appearanceProtoGetClassName("invalid")
			}
		}
		return ""
	}
	render(){
		var props = {}
		props.className = this.appearanceProtoGetClassName("div", "CaretakerFormObject")
		props.className += (this.state.name ? this.appearanceProtoGetClassName(null, this.state.name || "") : "")
		props.className += (this.isInput() ? this.appearanceProtoGetClassName(null, "CaretakerInputContainer") : "")
		props.className += this.appearanceGetValidClassname()
		return React.createElement(
			'div',
			props,
			this.appearanceGetInsideObjectContainer())
	}
}
<|endoftext|>


<commit_before>// TODO
game.PlayerEntity = me.Entity.extend({// game and me .Entity is a class
	init: function (x, y, settings) { // this is our constructor function
		this._super(me.Entity, 'init', [x, y,{
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function (){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();

				}
		}]);

	    this.body.setVelocity(5, 20); // this part sets the locating of the player

	    this.renderable.addAnimation("idle", [78]);
	    this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);

	    this.renderable.setCurrentAnimation("idle");
	},

	update: function (delta){
		if(me.input.isKeyPressed("right")){
			//sets the position of my x by adding the velocity defined above in.
			//seVelocity() and multiplying itby me.timer.tick.
			//me.timer.tick makes the movement look smoot
			this.body.vel.x += this.body.accel.x * me.timer.tick;

			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;
		}

		if(this.body.vel.x !== 0){

		if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
		}
	}else{
		this.renderable.setCurrentAnimation("idle");
	}

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	}

});

<commit_msg>video 10 common message<commit_after>// TODO
game.PlayerEntity = me.Entity.extend({// game and me .Entity is a class
	init: function (x, y, settings) { // this is our constructor function
		this._super(me.Entity, 'init', [x, y,{
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function (){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();

				}
		}]);

	    this.body.setVelocity(5, 20); // this part sets the locating of the player
	    //this renderable addanimation idle sets the animation went nothing is pressing
	    this.renderable.addAnimation("idle", [78]);
	    this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
	    // this renderable addanimation controls the animation walk
	    this.renderable.setCurrentAnimation("idle");
	},

	update: function (delta){
		if(me.input.isKeyPressed("right")){
			//sets the position of my x by adding the velocity defined above in.
			//seVelocity() and multiplying itby me.timer.tick.
			//me.timer.tick makes the movement look smoot
			this.body.vel.x += this.body.accel.x * me.timer.tick;

			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;
		}

		if(this.body.vel.x !== 0){

		if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
		}
	}else{
		this.renderable.setCurrentAnimation("idle");
	}

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);// the code delta runs the animation from your renderable addanimation.
		return true;

	}

});

<|endoftext|>


<commit_before>// Create the Ember.js application
window.App = Ember.Application.create();

// Models
App.Contribution = Ember.Object.extend({
  project_name: '',
  project_url : ''
});

// Controllers
App.contributionController = Ember.ArrayController.create({
  content: [],
  message: null,
  forks: null,

  forksChanged: function() {
    if(this.get("forks") == 0) {
      if(this.get("content").length == 0)
        this.set("message","Couldn't find any contributions...");
      else
        this.set("message","Done");
    }
  }.observes("forks"),

  createContribution: function(project_data) {
    this.clearMessages();
    var contribution = App.Contribution.create(project_data);
    this.pushObject(contribution);
  },

  clearContributions: function() {
    this.set("content", []);
  },

  clearMessages: function() {
    this.set("message", null);
  },

  // Searches the username in the list of contributors of a given cloned project
  // If the username is found, a new contributor object is created.
  fetchContributions: function(username, clone_uri, project_data) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/repos/" + clone_uri + "/contributors",
      success: function(data) {
        data.forEach(function(contributor, index, array) {
          if(contributor.login == username)
            App.contributionController.createContribution(project_data);
          if(index == (array.length-1)) {
            var old_forks = self.get('forks');
            self.set("forks",old_forks-1);
          }
        });
      },
      dataType: "json"
    });
  },

  // Given a username and a repo, fetch the clone repo and proceeds with checking the
  // contributors' list
  fetchCloneRepo: function(username, repo) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/repos/" + repo.full_name,
      success: function(data) {
        var clone_uri = data.parent.full_name;
        self.fetchContributions(username, clone_uri, {project_name: data.parent.full_name, project_url: data.parent.html_url});
      },
      dataType: "json"
    });
  },

  // Fetch the user repos and for each fork, proceed with the searching for contributions
  fetchUserContributions: function(username) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/users/" + username + "/repos",
      success: function(data) {
        var forks = data.filter(function(repo) { return (repo.fork == true);});
        if(forks.length) {
          self.set("forks", forks.length);
          forks.forEach(function(repo) {
            self.fetchCloneRepo(username, repo);
          });
        }
        else
          self.set("message","The user " + username + " didn't fork a repo yet!");
      },
      error: function(e) {
        if(e.status == 404)
          self.set("message","Oops... It appears that the user '" + username + "' doesn't exist...");
        else
          self.set("message","Oops... something went wrong, plesse try again!");
      },
      dataType: "json"
    });
  }

});

// Views

// View responsible for the text field and handling the value
App.SearchUserView = Ember.TextField.extend({
  insertNewline: function() {
    App.contributionController.clearContributions();
    App.contributionController.set("message","searching");
    var value = this.get('value');
    if (value) {
      App.contributionController.fetchUserContributions(value);
      this.set('value', '');
    }
  }
});

// Display messages based on the controller's message property
App.messageView = Ember.View.extend({
  messageBinding: "App.contributionController.message",
  template: Ember.Handlebars.compile("{{message}}")
});

// Display the contribution links based on the array of
// contributions from the controller
App.contributionView = Ember.View.extend({
  urlBinding: "content.project_url",
  template: Ember.Handlebars.compile('{{content.project_name}}')
});

// Handle the list of contributions
App.contributionsView = Ember.CollectionView.extend({
  content: App.contributionController,
  tagName: "ul",
  emptyView: App.SearchingView,
  itemViewClass: App.contributionView
});
<commit_msg>search box should have class span3<commit_after>// Create the Ember.js application
window.App = Ember.Application.create();

// Models
App.Contribution = Ember.Object.extend({
  project_name: '',
  project_url : ''
});

// Controllers
App.contributionController = Ember.ArrayController.create({
  content: [],
  message: null,
  forks: null,

  forksChanged: function() {
    if(this.get("forks") == 0) {
      if(this.get("content").length == 0)
        this.set("message","Couldn't find any contributions...");
      else
        this.set("message","Done");
    }
  }.observes("forks"),

  createContribution: function(project_data) {
    this.clearMessages();
    var contribution = App.Contribution.create(project_data);
    this.pushObject(contribution);
  },

  clearContributions: function() {
    this.set("content", []);
  },

  clearMessages: function() {
    this.set("message", null);
  },

  // Searches the username in the list of contributors of a given cloned project
  // If the username is found, a new contributor object is created.
  fetchContributions: function(username, clone_uri, project_data) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/repos/" + clone_uri + "/contributors",
      success: function(data) {
        data.forEach(function(contributor, index, array) {
          if(contributor.login == username)
            App.contributionController.createContribution(project_data);
          if(index == (array.length-1)) {
            var old_forks = self.get('forks');
            self.set("forks",old_forks-1);
          }
        });
      },
      dataType: "json"
    });
  },

  // Given a username and a repo, fetch the clone repo and proceeds with checking the
  // contributors' list
  fetchCloneRepo: function(username, repo) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/repos/" + repo.full_name,
      success: function(data) {
        var clone_uri = data.parent.full_name;
        self.fetchContributions(username, clone_uri, {project_name: data.parent.full_name, project_url: data.parent.html_url});
      },
      dataType: "json"
    });
  },

  // Fetch the user repos and for each fork, proceed with the searching for contributions
  fetchUserContributions: function(username) {
    var self = this;
    $.ajax({
      url: "https://api.github.com/users/" + username + "/repos",
      success: function(data) {
        var forks = data.filter(function(repo) { return (repo.fork == true);});
        if(forks.length) {
          self.set("forks", forks.length);
          forks.forEach(function(repo) {
            self.fetchCloneRepo(username, repo);
          });
        }
        else
          self.set("message","The user " + username + " didn't fork a repo yet!");
      },
      error: function(e) {
        if(e.status == 404)
          self.set("message","Oops... It appears that the user '" + username + "' doesn't exist...");
        else
          self.set("message","Oops... something went wrong, plesse try again!");
      },
      dataType: "json"
    });
  }

});

// Views

// View responsible for the text field and handling the value
App.SearchUserView = Ember.TextField.extend({
  classNames: ["span3"],
  insertNewline: function() {
    App.contributionController.clearContributions();
    App.contributionController.set("message","searching");
    var value = this.get('value');
    if (value) {
      App.contributionController.fetchUserContributions(value);
      this.set('value', '');
    }
  }
});

// Display messages based on the controller's message property
App.messageView = Ember.View.extend({
  messageBinding: "App.contributionController.message",
  template: Ember.Handlebars.compile("{{message}}")
});

// Display the contribution links based on the array of
// contributions from the controller
App.contributionView = Ember.View.extend({
  urlBinding: "content.project_url",
  template: Ember.Handlebars.compile('{{content.project_name}}')
});

// Handle the list of contributions
App.contributionsView = Ember.CollectionView.extend({
  content: App.contributionController,
  tagName: "ul",
  emptyView: App.SearchingView,
  itemViewClass: App.contributionView
});
<|endoftext|>


<commit_before>var storeControllers = angular.module("storeControllers", []);
var db = new DB();

storeControllers.controller("ProductListController", ["$scope", function ($scope) {
	$scope.products = db.getObjects("products");

	$scope.predicate = "id";
	$scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("ProductNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.product = {};

	$scope.submit = function (product) {
		db.insertAndSaveObject("products", product);

		$location.path("/products");
	};
}]);

storeControllers.controller("ProductUpdateController", ["$scope", "$routeParams", "$location", function ($scope, $routeParams, $location) {
	$scope.product = db.getObject("products", parseInt($routeParams.product_id));

	$scope.submit = function (product) {
		db.updateAndSaveObject("products", product);

		$location.path("/products");
	};
}]);

storeControllers.controller("CustomerListController", ["$scope", function ($scope) {
	$scope.customers = db.getObjects("customers");

	$scope.predicate = "id";
	$scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("CustomerNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.customer = {};

	$scope.submit = function (customer) {
		db.insertAndSaveObject("customers", customer);

		$location.path("/customers");
	};
}]);

storeControllers.controller("CustomerUpdateController", ["$scope", "$routeParams", "$location", function ($scope, $routeParams, $location) {
	$scope.customer = db.getObject("customers", parseInt($routeParams.customer_id));

	$scope.submit = function (customer) {
		db.updateAndSaveObject("customers", customer);

		$location.path("/customers");
	};
}]);

storeControllers.controller("CreditNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.credit = {
		products: [],
		total_price: 0,
		purchase_date: Date.now(),
	};

	$scope.customers = db.getObjects("customers");
	$scope.products = db.getObjects("products");

	$scope.add_product = function (credit) {
		credit.products.push({quantity: 1});
	};

	$scope.update_product = function (item) {
		var product = $scope.products.filter(function (element, index, array) {
			return element.id === parseInt(item.id);
		})[0];

		item.name = product.name;
		item.price = product.price;
	};

	$scope.submit = function (credit) {
		for (var i = 0; i < credit.products.length; i++) {
			var product = $scope.products.filter(function (element, index, array) {
				return element.id === parseInt(credit.products[i].id);
			})[0];
			product.quantity -= credit.products[i].quantity;
			db.updateObject("products", product);

      credit.total_price += credit.products[i].price * credit.products[i].quantity;
		}

    db.insertObject("credits", credit);
		db.saveObjects();

		$location.path("/products");
	};
}]);

storeControllers.controller("CustomerCreditListController", ["$scope", "$routeParams", function ($scope, $routeParams) {
  var credits = db.getObjects("credits");
  $scope.customer_credits = credits.filter(function (element, index, array) {
    return element.customer_id == parseInt($routeParams.customer_id);
  });

  $scope.predicate = "id";
  $scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("CustomerCreditDetailController", ["$scope", "$routeParams", function ($scope, $routeParams) {
	$scope.customer = db.getObject("customers", parseInt($routeParams.customer_id));
	$scope.credit = db.getObject("credits", parseInt($routeParams.credit_id));

	$scope.toggle_payment = function (credit) {
		db.updateObject("credits", credit);
	};
}]);
<commit_msg>Redirect to credit detail after purchase<commit_after>var storeControllers = angular.module("storeControllers", []);
var db = new DB();

storeControllers.controller("ProductListController", ["$scope", function ($scope) {
	$scope.products = db.getObjects("products");

	$scope.predicate = "id";
	$scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("ProductNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.product = {};

	$scope.submit = function (product) {
		db.insertAndSaveObject("products", product);

		$location.path("/products");
	};
}]);

storeControllers.controller("ProductUpdateController", ["$scope", "$routeParams", "$location", function ($scope, $routeParams, $location) {
	$scope.product = db.getObject("products", parseInt($routeParams.product_id));

	$scope.submit = function (product) {
		db.updateAndSaveObject("products", product);

		$location.path("/products");
	};
}]);

storeControllers.controller("CustomerListController", ["$scope", function ($scope) {
	$scope.customers = db.getObjects("customers");

	$scope.predicate = "id";
	$scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("CustomerNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.customer = {};

	$scope.submit = function (customer) {
		db.insertAndSaveObject("customers", customer);

		$location.path("/customers");
	};
}]);

storeControllers.controller("CustomerUpdateController", ["$scope", "$routeParams", "$location", function ($scope, $routeParams, $location) {
	$scope.customer = db.getObject("customers", parseInt($routeParams.customer_id));

	$scope.submit = function (customer) {
		db.updateAndSaveObject("customers", customer);

		$location.path("/customers");
	};
}]);

storeControllers.controller("CreditNewController", ["$scope", "$location", function ($scope, $location) {
	$scope.credit = {
		products: [],
		total_price: 0,
		purchase_date: Date.now(),
	};

	$scope.customers = db.getObjects("customers");
	$scope.products = db.getObjects("products");

	$scope.add_product = function (credit) {
		credit.products.push({quantity: 1});
	};

	$scope.update_product = function (item) {
		var product = $scope.products.filter(function (element, index, array) {
			return element.id === parseInt(item.id);
		})[0];

		item.name = product.name;
		item.price = product.price;
	};

	$scope.submit = function (credit) {
		for (var i = 0; i < credit.products.length; i++) {
			var product = $scope.products.filter(function (element, index, array) {
				return element.id === parseInt(credit.products[i].id);
			})[0];
			product.quantity -= credit.products[i].quantity;
			db.updateObject("products", product);

      credit.total_price += credit.products[i].price * credit.products[i].quantity;
		}

    db.insertObject("credits", credit);
		db.saveObjects();

		$location.path("/customers/" + credit.customer_id + "/credits/" + credit.id);
	};
}]);

storeControllers.controller("CustomerCreditListController", ["$scope", "$routeParams", function ($scope, $routeParams) {
  var credits = db.getObjects("credits");
  $scope.customer_credits = credits.filter(function (element, index, array) {
    return element.customer_id == parseInt($routeParams.customer_id);
  });

  $scope.predicate = "id";
  $scope.order = function (predicate) {
		$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
		$scope.predicate = predicate;
	};
}]);

storeControllers.controller("CustomerCreditDetailController", ["$scope", "$routeParams", function ($scope, $routeParams) {
	$scope.customer = db.getObject("customers", parseInt($routeParams.customer_id));
	$scope.credit = db.getObject("credits", parseInt($routeParams.credit_id));

	$scope.toggle_payment = function (credit) {
		db.updateObject("credits", credit);
	};
}]);
<|endoftext|>


<commit_before>/*
 * Blacksmith - Top-level include for the blacksmith project
 *
 * (C) 2011, Nodejitsu Inc.
 *
 */

var smith    = exports,
    winston  = smith.winston = require('winston'),
    path     = require('path'),
    jsdom    = require('jsdom'),
    fs       = require('fs'),
    nconf    = require('nconf'),
    prompt   = require('prompt');

smith.helpers = require('./helpers');
smith.sites = require('blacksmith-sites');

smith.log = winston;

winston.level = 'info';

// Use nconf to manage global configuration. Attached to smith object for later
// use.
smith.config = nconf;

// Try to load configuration if the file exists.
if (path.existsSync('./config.json')) {
  smith.config.add("global", { type: "file", file: "./config.json"});
}

// smith.loaders is a list of key/value pairs so we can depend on method
// execution being in-order.
smith.loaders = [
  'authors',
  'theme',
  'content',
  'toc',
  'rss',
  'errors'
].map(function (k) {
  var t = {};
  t[k] = require('./loaders/' + k);
  return t;
});

// smith.renderers is a list of key/value pairs so we can depend on method
// execution being in-order.
smith.renderers = [
  'theme',
  'content',
  'archive',
  'files',
  'rss',
  'errors'
].map(function (k) {
  var t = {};
  t[k] = require('./renderers/' + k);
  return t;
});

// smith.content will store static content during generation.
// Examples include articles, themes and authors.
smith.content = {};

smith.generate = exports.generate = function (src, dst, cb) {

  smith.content = {};

  // Attach source and destination paths to the smith. This will eventually
  // enable multi-site generation.
  smith.src = path.resolve(src);
  smith.dst = path.resolve(dst);

  jsdom.env( "", ['./jquery.js'], function (err, window) {
    if (err) {
      winston.error("jsdom error: "+err);
      throw err;
    }

    // This is so we can call jquery later (smith.window.$)
    smith.window = window;

    // We pass an empty DOM element to each generator. This is used for
    // Weld-based templating.
    //
    // We could pass the window object around, or create multiple windows, or
    // even just create multiple jsdoms. Using a div, however, is simple and
    // relatively performant.
    var div = window.document.createElement('div');

    smith.loaders.forEach( function (loader) {
      var name = Object.keys(loader)[0];

      winston.info('Loading "' + name + '"');

      try {
        // Load assets
        // TODO: Rename "content" to something more appropriate
        smith.content[name] = loader[name].load(true);

      } catch (err) {
        winston.error( 'Problem loading "' + name + '"' );
        String(err.stack).split("\n").forEach(winston.error);
        cb(1);
      }

    });

    // Iterate through every generator, each of which may output a set of
    // files and/or directories.
    // This block is wrapped in a try / catch since JSDOM is squashing some
    // errors.
    smith.renderers.forEach( function (renderer) {
      // Grabs the name given to the generator.
      var name = Object.keys(renderer)[0];

      winston.info('Rendering "'+name+'"');

      try {
        // Perform a weld on the div.
        renderer[name].weld(div, smith.content[name]);

        // Write the content to disk.
        //
        // Note: jsdom strips doctypes. If we were using full doms we could
        // access the doctype for each individual page, but
        // because we're using the div to contain our document this
        // information never gets added to jsdom.
        //
        // The doctype for jsdom gets set explicitly during content loading.
        renderer[name].generate(
          smith.window.document.doctype
          + '\n'
          + div.innerHTML, smith.content[name]
        );
      } catch (err) {
        winston.error( 'Problem rendering "' + name + '"' );
        String(err.stack).split("\n").forEach(winston.error);
        cb(1);
      }
    });

    cb(0);

  });

};
<commit_msg>[ux] Using customized cli logger, with loglevel set to silly for now<commit_after>/*
 * Blacksmith - Top-level include for the blacksmith project
 *
 * (C) 2011, Nodejitsu Inc.
 *
 */

var smith    = exports,
    winston  = require('winston'),
    path     = require('path'),
    jsdom    = require('jsdom'),
    fs       = require('fs'),
    nconf    = require('nconf'),
    prompt   = require('prompt');

smith.helpers = require('./helpers');
smith.sites = require('blacksmith-sites');

smith.log = new winston.Logger({
  transports: [
    new winston.transports.Console({
      level: 'silly',
      colorize: true
    })
  ]
});

// Use nconf to manage global configuration. Attached to smith object for later
// use.
smith.config = nconf;

// Try to load configuration if the file exists.
if (path.existsSync('./config.json')) {
  smith.config.add("global", { type: "file", file: "./config.json"});
}

// smith.loaders is a list of key/value pairs so we can depend on method
// execution being in-order.
smith.loaders = [
  'authors',
  'theme',
  'content',
  'toc',
  'rss',
  'errors'
].map(function (k) {
  var t = {};
  t[k] = require('./loaders/' + k);
  return t;
});

// smith.renderers is a list of key/value pairs so we can depend on method
// execution being in-order.
smith.renderers = [
  'theme',
  'content',
  'archive',
  'files',
  'rss',
  'errors'
].map(function (k) {
  var t = {};
  t[k] = require('./renderers/' + k);
  return t;
});

// smith.content will store static content during generation.
// Examples include articles, themes and authors.
smith.content = {};

smith.generate = exports.generate = function (src, dst, cb) {

  smith.content = {};

  // Attach source and destination paths to the smith. This will eventually
  // enable multi-site generation.
  smith.src = path.resolve(src);
  smith.dst = path.resolve(dst);

  jsdom.env( "", ['./jquery.js'], function (err, window) {
    if (err) {
      winston.error("jsdom error: "+err);
      throw err;
    }

    // This is so we can call jquery later (smith.window.$)
    smith.window = window;

    // We pass an empty DOM element to each generator. This is used for
    // Weld-based templating.
    //
    // We could pass the window object around, or create multiple windows, or
    // even just create multiple jsdoms. Using a div, however, is simple and
    // relatively performant.
    var div = window.document.createElement('div');

    smith.loaders.forEach( function (loader) {
      var name = Object.keys(loader)[0];

      winston.info('Loading "' + name + '"');

      try {
        // Load assets
        // TODO: Rename "content" to something more appropriate
        smith.content[name] = loader[name].load(true);

      } catch (err) {
        winston.error( 'Problem loading "' + name + '"' );
        String(err.stack).split("\n").forEach(winston.error);
        cb(1);
      }

    });

    // Iterate through every generator, each of which may output a set of
    // files and/or directories.
    // This block is wrapped in a try / catch since JSDOM is squashing some
    // errors.
    smith.renderers.forEach( function (renderer) {
      // Grabs the name given to the generator.
      var name = Object.keys(renderer)[0];

      winston.info('Rendering "'+name+'"');

      try {
        // Perform a weld on the div.
        renderer[name].weld(div, smith.content[name]);

        // Write the content to disk.
        //
        // Note: jsdom strips doctypes. If we were using full doms we could
        // access the doctype for each individual page, but
        // because we're using the div to contain our document this
        // information never gets added to jsdom.
        //
        // The doctype for jsdom gets set explicitly during content loading.
        renderer[name].generate(
          smith.window.document.doctype
          + '\n'
          + div.innerHTML, smith.content[name]
        );
      } catch (err) {
        winston.error( 'Problem rendering "' + name + '"' );
        String(err.stack).split("\n").forEach(winston.error);
        cb(1);
      }
    });

    cb(0);

  });

};
<|endoftext|>


<commit_before>//adds a specific player
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
			//sets the spawn
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your character is going
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//grabs animation from image
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		this.renderable.setCurrentAnimation("idle");

	},

	update: function(delta){
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		else if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
			//Makes perameter
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},
			//Hold all information for collision
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif" + xdif + ydif);

			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				this.body.vel.y = -1;
			}
			//sets barrier on right side of the enemy base
			else if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			//sets barrier on left side of the enemy base
			// && x(y)dif>(<)0 makes it so the barrier doesn't work while facibg the other way
			}else if(xdif<70 && this.facing=='left' && xdif>0){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
			}
		}
	}
});
	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});<commit_msg>Video 16 Comments<commit_after>//adds a specific player
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
			//sets the spawn
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your character is going
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//grabs animation from image
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		this.renderable.setCurrentAnimation("idle");

	},

	update: function(delta){
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		else if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
			//Makes perameter
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},
			//Hold all information for collision
	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif" + xdif + ydif);
			//sets barrier on the top of the enemy base
			//y axis must come first because it;s more important
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				this.body.vel.y = -1;
			}
			//sets barrier on right side of the enemy base
			else if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			//sets barrier on left side of the enemy base
			// && x(y)dif>(<)0 makes it so the barrier doesn't work while facibg the other way
			}else if(xdif<70 && this.facing=='left' && xdif>0){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
			}
		}
	}
});
	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

	this._super(me.Entity, "update", [delta]);
	return true;
	},

	onCollision: function(){

	}

});<|endoftext|>


<commit_before>$('#emailAddress').append('');
<commit_msg>email replacer bug fix<commit_after>$('#emailAddress').append('');
<|endoftext|>


<commit_before>'use strict';

/* Controllers */
angular.module('myApp.controllers', []).
    controller('SiteController', function($scope) {
        $scope.welcome = "Welcome to My Website!";
        $scope.currentYear = (new Date()).getFullYear();
    }).
    controller('HomeController', function() {

    }).
    controller('BlogController', function() {

    }).
    controller('BioController', function() {

    }).
    controller('ProjectsController', function() {

    });<commit_msg>Updating welcome.<commit_after>'use strict';

/* Controllers */
angular.module('myApp.controllers', []).
    controller('SiteController', function($scope) {
        $scope.welcome = "JasonBerry.io";
        $scope.currentYear = (new Date()).getFullYear();
    }).
    controller('HomeController', function() {

    }).
    controller('BlogController', function() {

    }).
    controller('BioController', function() {

    }).
    controller('ProjectsController', function() {

    });<|endoftext|>


<commit_before>import React, { useState } from 'react'
import Img from 'gatsby-image'
import { chunk, sum } from 'lodash'
import { Box } from 'rebass'
import FsLightbox from 'fslightbox-react'
import styled from 'styled-components'

const GalleryContent = styled.div``

const Gallery = ({ title, images, itemsPerRow: itemsPerRowByBreakpoints }) => {
  const aspectRatios = images.map(image => image.fluid.aspectRatio)
  const lightboxImages = images.map(image => image.fluid.src)
  const rowAspectRatioSumsByBreakpoints = itemsPerRowByBreakpoints.map(
    itemsPerRow =>
      chunk(aspectRatios, itemsPerRow).map(rowAspectRatios =>
        sum(rowAspectRatios)
      )
  )

  const [toggler, setToggler] = useState(false)
  const [imageIndex, setImageIndex] = useState(0)

  const closeLightbox = () => setToggler(false)
  const openLightbox = (imageIndex: number) => {
    setImageIndex(imageIndex + 1)
    setToggler(!toggler)
  }

  return (
    <GalleryContent>

{title}

      {images.map((image, i) => (
        <Box
          onClick={() => openLightbox(i)}
          as={Img}
          key={image.id}
          fluid={image.thumbnail}
          title={image.title}
          width={rowAspectRatioSumsByBreakpoints.map(
            (rowAspectRatioSums, j) => {
              const rowIndex = Math.floor(i / itemsPerRowByBreakpoints[j])
              const rowAspectRatioSum = rowAspectRatioSums[rowIndex]
              return `${(image.fluid.aspectRatio / rowAspectRatioSum) * 100}%`
            }
          )}
          css={`
            display: inline-block;
            vertical-align: middle;
            width: auto;
          `}
        />
      ))}
      <FsLightbox
        toggler={toggler}
        sources={lightboxImages}
        slide={imageIndex}
      />
    </GalleryContent>
  )
}
export default Gallery
<commit_msg>tweak<commit_after>import React, { useState } from 'react'
import Img from 'gatsby-image'
import { chunk, sum } from 'lodash'
import { Box } from 'rebass'
import FsLightbox from 'fslightbox-react'
import styled from 'styled-components'

const GalleryContent = styled.div``

const Gallery = ({ title, images, itemsPerRow: itemsPerRowByBreakpoints }) => {
  const aspectRatios = images.map(image => image.fluid.aspectRatio)
  const lightboxImages = images.map(image => image.fluid.src)
  const rowAspectRatioSumsByBreakpoints = itemsPerRowByBreakpoints.map(
    itemsPerRow =>
      chunk(aspectRatios, itemsPerRow).map(rowAspectRatios =>
        sum(rowAspectRatios)
      )
  )

  const [toggler, setToggler] = useState(false)
  const [imageIndex, setImageIndex] = useState(0)

  const openLightbox = imageIndex => {
    setImageIndex(imageIndex + 1)
    setToggler(!toggler)
  }

  return (
    <GalleryContent>

{title}

      {images.map((image, i) => (
        <Box
          onClick={() => openLightbox(i)}
          as={Img}
          key={image.id}
          fluid={image.thumbnail}
          title={image.title}
          width={rowAspectRatioSumsByBreakpoints.map(
            (rowAspectRatioSums, j) => {
              const rowIndex = Math.floor(i / itemsPerRowByBreakpoints[j])
              const rowAspectRatioSum = rowAspectRatioSums[rowIndex]
              return `${(image.fluid.aspectRatio / rowAspectRatioSum) * 100}%`
            }
          )}
          css={`
            display: inline-block;
            vertical-align: middle;
            width: auto;
          `}
        />
      ))}
      <FsLightbox
        toggler={toggler}
        sources={lightboxImages}
        slide={imageIndex}
      />
    </GalleryContent>
  )
}
export default Gallery
<|endoftext|>


<commit_before>// blowup.min.js
// Paul Krishnamurthy 2016

$(function(o){o.fn.blowup=function(e){var t=this;if(!t.is("img"))return void console.log("%c Blowup.js Error: %cTarget element is not an image.","background: #FCEBB6; color: #F07818; font-size: 17px; font-weight: bold;","background: #FCEBB6; color: #F07818; font-size: 17px;");var i=t.attr("src"),n=(t.width(),t.height(),new Image);n.src=t.attr("src");var r={round:!0,width:180,height:180,background:"#FFF",shadow:"0 8px 17px 0 rgba(0, 0, 0, 0.2)",border:"6px solid #FFF",cursor:!0},s=o.extend(r,e);t.on("dragstart",function(o){o.preventDefault()}),t.css("cursor",s.cursor?"crosshair":"none");var a=document.createElement("div");a.id="BlowupLens",o("body").append(a),$blowupLens=o("#BlowupLens"),$blowupLens.css({position:"absolute",visibility:"hidden",zIndex:999999,"pointer-events":"none",width:s.width,height:s.height,border:s.border,background:s.background,"border-radius":s.round?"50%":"none","box-shadow":s.shadow,"background-repeat":"no-repeat"}),t.mouseenter(function(){$blowupLens.css("visibility","visible")}),t.mousemove(function(o){var e=o.pageX-s.width/2,r=o.pageY-s.height/2,a=o.pageX-this.offsetLeft,d=o.pageY-this.offsetTop,u=-Math.floor(a/t.width()*n.width-s.width/2),h=-Math.floor(d/t.height()*n.height-s.height/2);$blowupLens.css({left:e,top:r,"background-image":"url("+i+")","background-position":u+" "+h})}),t.mouseleave(function(){$blowupLens.css("visibility","hidden")})}});<commit_msg>update minified version<commit_after>// blowup.min.js
// Paul Krishnamurthy 2016

$(function(o){o.fn.blowup=function(e){var t=this;if(!t.is("img"))return void console.log("%c Blowup.js Error: %cTarget element is not an image.","background: #FCEBB6; color: #F07818; font-size: 17px; font-weight: bold;","background: #FCEBB6; color: #F07818; font-size: 17px;");var n=t.attr("src"),i=(t.width(),t.height(),new Image);i.src=t.attr("src");var r={round:!0,width:200,height:200,background:"#FFF",shadow:"0 8px 17px 0 rgba(0, 0, 0, 0.2)",border:"6px solid #FFF",cursor:!0,zIndex:999999},s=o.extend(r,e);t.on("dragstart",function(o){o.preventDefault()}),t.css("cursor",s.cursor?"crosshair":"none");var d=document.createElement("div");d.id="BlowupLens",o("body").append(d),$blowupLens=o("#BlowupLens"),$blowupLens.css({position:"absolute",visibility:"hidden","pointer-events":"none",zIndex:s.zIndex,width:s.width,height:s.height,border:s.border,background:s.background,"border-radius":s.round?"50%":"none","box-shadow":s.shadow,"background-repeat":"no-repeat"}),t.mouseenter(function(){$blowupLens.css("visibility","visible")}),t.mousemove(function(o){var e=o.pageX-s.width/2,r=o.pageY-s.height/2,d=o.pageX-this.offsetLeft,a=o.pageY-this.offsetTop,u=-Math.floor(d/t.width()*i.width-s.width/2),h=-Math.floor(a/t.height()*i.height-s.height/2);$blowupLens.css({left:e,top:r,"background-image":"url("+n+")","background-position":u+" "+h})}),t.mouseleave(function(){$blowupLens.css("visibility","hidden")})}});<|endoftext|>