<commit_before>'use strict';

let angular = require('angular');

require('./project.less');

module.exports = angular.module('spinnaker.core.projects.project.controller', [
  require('./configure/configureProject.modal.controller.js'),
  require('./service/project.read.service.js'),
  require('../history/recentHistory.service.js'),
])
  .controller('ProjectCtrl', function ($scope, $modal, projectReader, $state, projectConfiguration, recentHistoryService) {

    $scope.project = projectConfiguration;

    recentHistoryService.addExtraDataToLatest('projects',
      {
        config: {
          applications: projectConfiguration.config.applications
        }
      });

    projectConfiguration.config.applications = projectConfiguration.config.applications || [];

    let selectedApplication = null;

    // $stateParams is scoped to parent state, so if an application is selected, it will not be visible
    $scope.$on('$stateChangeSuccess', function(event, toState, toParams) {
      selectedApplication = toParams.application;
      if (selectedApplication) {
        $scope.viewState.navSelection = $scope.navOptions.find(option => option.title === selectedApplication);
      }
      $scope.viewState.dashboard = !selectedApplication;
    });

    $scope.viewState = {
      projectLoaded: false,
    };

    $scope.navOptions = [
      {
        title: 'Project Dashboard',
        view: 'home.project.dashboard',
        params: { project: projectConfiguration.name }
      }
    ];

    projectConfiguration.config.applications.forEach((application) => $scope.navOptions.push(
      {
        title: application,
        view: 'home.project.application.insight.clusters',
        params: { application: application, project: projectConfiguration.name}
      }
    ));

    if (selectedApplication) {
      $scope.viewState.navSelection = $scope.navOptions.find(option => option.title === selectedApplication);
    } else {
      $scope.viewState.navSelection = $scope.navOptions[0];
    }
    $scope.viewState.dashboard = !selectedApplication;

    this.navigate = () => {
      var selection = $scope.viewState.navSelection;
      $state.go(selection.view, selection.params);
    };

    this.configureProject = () => {
      $modal.open({
        templateUrl: require('./configure/configureProject.modal.html'),
        controller: 'ConfigureProjectModalCtrl',
        controllerAs: 'ctrl',
        resolve: {
          projectConfig: () => projectConfiguration,
        },
      }).result.then((result) => {
          if (result.action === 'delete') {
            $state.go('home.infrastructure');
          }
          if (result.action === 'upsert') {
            if (result.name !== projectConfiguration.name) {
              $state.go($state.current, {project: result.name}, {location: 'replace'});
            } else {
              $state.go($state.current, {}, {reload: true});
            }
          }
      });
    };

  }).name;
<commit_msg>sort applications in dropdown nav<commit_after>'use strict';

let angular = require('angular');

require('./project.less');

module.exports = angular.module('spinnaker.core.projects.project.controller', [
  require('./configure/configureProject.modal.controller.js'),
  require('./service/project.read.service.js'),
  require('../history/recentHistory.service.js'),
])
  .controller('ProjectCtrl', function ($scope, $modal, projectReader, $state, projectConfiguration, recentHistoryService) {

    $scope.project = projectConfiguration;

    recentHistoryService.addExtraDataToLatest('projects',
      {
        config: {
          applications: projectConfiguration.config.applications
        }
      });

    projectConfiguration.config.applications = projectConfiguration.config.applications || [];

    let selectedApplication = null;

    // $stateParams is scoped to parent state, so if an application is selected, it will not be visible
    $scope.$on('$stateChangeSuccess', function(event, toState, toParams) {
      selectedApplication = toParams.application;
      if (selectedApplication) {
        $scope.viewState.navSelection = $scope.navOptions.find(option => option.title === selectedApplication);
      }
      $scope.viewState.dashboard = !selectedApplication;
    });

    $scope.viewState = {
      projectLoaded: false,
    };

    $scope.navOptions = [
      {
        title: 'Project Dashboard',
        view: 'home.project.dashboard',
        params: { project: projectConfiguration.name }
      }
    ];

    projectConfiguration.config.applications.sort().forEach((application) => $scope.navOptions.push(
      {
        title: application,
        view: 'home.project.application.insight.clusters',
        params: { application: application, project: projectConfiguration.name}
      }
    ));

    if (selectedApplication) {
      $scope.viewState.navSelection = $scope.navOptions.find(option => option.title === selectedApplication);
    } else {
      $scope.viewState.navSelection = $scope.navOptions[0];
    }
    $scope.viewState.dashboard = !selectedApplication;

    this.navigate = () => {
      var selection = $scope.viewState.navSelection;
      $state.go(selection.view, selection.params);
    };

    this.configureProject = () => {
      $modal.open({
        templateUrl: require('./configure/configureProject.modal.html'),
        controller: 'ConfigureProjectModalCtrl',
        controllerAs: 'ctrl',
        resolve: {
          projectConfig: () => projectConfiguration,
        },
      }).result.then((result) => {
          if (result.action === 'delete') {
            $state.go('home.infrastructure');
          }
          if (result.action === 'upsert') {
            if (result.name !== projectConfiguration.name) {
              $state.go($state.current, {project: result.name}, {location: 'replace'});
            } else {
              $state.go($state.current, {}, {reload: true});
            }
          }
      });
    };

  }).name;
<|endoftext|>


<commit_before>var board,
    game = new Chess(),
    whiteDepth = 1,
    blackDepth = 1;

/*The "AI" part starts here */

/* board visualization and games state handling */

var onDragStart = function (source, piece, position, orientation) {
    if (game.in_checkmate() === true || game.in_draw() === true ||
        piece.search(/^b/) !== -1) {
        return false;
    }
};
var checkmate = function(game) {
    if(game.ugly_moves().length === 0)
    {
        var winner = movingnow + 'Checkmate';

        var checkmateCount = localStorage.getItem(winner)
        localStorage.setItem(winner, ++checkmateCount);
        log(winner);
        return winner;
    }else{
        var checkmateCount = localStorage.getItem('stalemate')
        localStorage.setItem('stalemate', ++checkmateCount);
        log('stalemate');
        return 'stalemate';
    }
};

var movingnow = '';

var whiteMove = function () {
    movingnow = 'white';
    //var bestMove = getBestMove(game, whiteDepth, minimaxRootWhite);
    var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    //var bestMove = avoidBeingCaptured(game);

    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());

    if (game.game_over()) {
        //alert('Game over ['+checkmate(game)+']');
        checkmate(game);
        stopGame();
        return;
    }
    window.setTimeout(blackMove, 5);
};

var blackMove = function () {
    movingnow = 'black';
    //var bestMove = getBestMove(game, blackDepth, minimaxRoot);
    var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());
    if (game.game_over()) {
      //  alert('Game over ['+checkmate(game)+']');
      checkmate(game);
      stopGame();
      return;
    }
    window.setTimeout(whiteMove, 5);
};

var getRandomMove = function(moves){
    //get random index
    var turnRandomIndex = Math.floor(Math.random() * moves.length);
    //get move from random index
    var randomMoove = moves[turnRandomIndex];
    //return move
    return randomMoove;
};

/**
 * RANDOMMOVE AI
 * @param {*} game
 */
var randomMove = function(game) {
    //get moves
    var turnPossibleMoves = game.ugly_moves();
    //get random move
    var randomMoove = getRandomMove(turnPossibleMoves);
    //return move
    return randomMoove;
};

/**
 * RANDOMCAPTURE AI
 * @param {*} possibleMoves
 */
var getCaptureMoves = function (possibleMoves) {
    //declare the capture moves array
    var captureMoves = [];
    //loop over all the moves
    var i = 0;
    while (i < possibleMoves.length) {
        //get a single move from all moves using the index
        var move = possibleMoves[i];
        //if the move is captured
        if (move.captured) {
            //add the move to the capture moves array
            captureMoves.push(move);
        }
        i++;
    }
    return captureMoves;
};

var randomCapture = function (game){
    //get all the capturemoves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare nextmove
    var nextMove;
    //if there are capturemoves, get  a random one
    if (captureMoves.length > 0) {
        nextMove = getRandomMove(captureMoves);
    } else {
        //else get any random move from the game
        nextMove = randomMove(game);
    }
    //return nextmove
    return nextMove;
};
/**
 * BESTCAPTURE AI
 * @param {*} game
 */
var bestCapture = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r' && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n' && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b' && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p' && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var resultsInCapture = function(theMove){
    game.ugly_move(theMove);
    var foundCapture = (getCaptureMoves(game.ugly_moves()).length > 0);
    game.undo();
    return foundCapture;
};

/**
 * AVOIDBEINGCAPTURED AI
 * @param {*} game
 */
var avoidBeingCaptured = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
        if(resultsInCapture(theMove))
        {
            theMove = randomMove(game);
        }
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r'
                && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n'
                && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b'
                && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p'
                && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var positionCount;
var getBestMove = function (game, depth, findBestMove) {
    if (game.game_over()) {
        //alert('Game over');
        return;
    }

    positionCount = 0;
    //var depth = parseInt($('#search-depth').find(':selected').text());

    var d = new Date().getTime();
    var bestMove = findBestMove(depth, game, true);
    var d2 = new Date().getTime();
    var moveTime = (d2 - d);
    var positionsPerS = ( positionCount * 1000 / moveTime);

    $('#position-count').text(positionCount);
    $('#time').text(moveTime/1000 + 's');
    $('#positions-per-s').text(positionsPerS);
    return bestMove;
};

var renderMoveHistory = function (moves) {
    var historyElement = $('#move-history').empty();
    historyElement.empty();
    for (var i = 0; i < moves.length; i = i + 2) {
        historyElement.append('' + moves[i] + ' ' + ( moves[i + 1] ? moves[i + 1] : ' ') + '
')
    }
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var log = function (text) {
    var historyElement = $('#move-history');
    historyElement.append('' + text + '
');
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var onDrop = function (source, target) {

    // Removing to make both sides fully CPU, not first move as human
    // var move = game.move({
    //     from: source,
    //     to: target,
    //     promotion: 'q'
    // });
    startGame();
};
var startGame = function() {
    removeGreySquares();
    // if (move === null) {
    //     return 'snapback';
    // }

    renderMoveHistory(game.history());
    window.setTimeout(whiteMove, 1000);
};
var stopGame = function () {
    var whiteCheckmate = parseInt(localStorage.getItem('whiteCheckmate'));
    whiteCheckmate = whiteCheckmate ? whiteCheckmate : 0;
    var blackCheckmate = parseInt(localStorage.getItem('blackCheckmate'));
    blackCheckmate = blackCheckmate ? blackCheckmate : 0;
    var stalemate = parseInt(localStorage.getItem('stalemate'));
    stalemate = stalemate ? stalemate : 0;
    if (whiteCheckmate + blackCheckmate + stalemate >= 100) {
        var result = " black checkmate: "+blackCheckmate + "," + "white checkmate: "+ whiteCheckmate + "," + " stalemate: "+stalemate;
        //log the results
        log(result);
        //alert the results
        alert(result);
        localStorage.removeItem('whiteCheckmate');
        localStorage.removeItem('blackCheckmate');
        localStorage.removeItem('stalemate');
    }else{
        //automatically reload here
        location.reload();
    }
};

var onSnapEnd = function () {
    board.position(game.fen());
};

var onMouseoverSquare = function(square, piece) {
    var moves = game.moves({
        square: square,
        verbose: true
    });

    if (moves.length === 0) return;

    greySquare(square);

    for (var i = 0; i < moves.length; i++) {
        greySquare(moves[i].to);
    }
};

var onMouseoutSquare = function(square, piece) {
    removeGreySquares();
};

var removeGreySquares = function() {
    $('#board .square-55d63').css('background', '');
};

var greySquare = function(square) {
    var squareEl = $('#board .square-' + square);

    var background = '#a9a9a9';
    if (squareEl.hasClass('black-3c85d') === true) {
        background = '#696969';
    }

    squareEl.css('background', background);
};

var cfg = {
    draggable: true,
    position: 'start',
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

startGame();<commit_msg>Random vs. Random Capture<commit_after>var board,
    game = new Chess(),
    whiteDepth = 1,
    blackDepth = 1;

/*The "AI" part starts here */

/* board visualization and games state handling */

var onDragStart = function (source, piece, position, orientation) {
    if (game.in_checkmate() === true || game.in_draw() === true ||
        piece.search(/^b/) !== -1) {
        return false;
    }
};
var checkmate = function(game) {
    if(game.ugly_moves().length === 0)
    {
        var winner = movingnow + 'Checkmate';

        var checkmateCount = localStorage.getItem(winner)
        localStorage.setItem(winner, ++checkmateCount);
        log(winner);
        return winner;
    }else{
        var checkmateCount = localStorage.getItem('stalemate')
        localStorage.setItem('stalemate', ++checkmateCount);
        log('stalemate');
        return 'stalemate';
    }
};

var movingnow = '';

var whiteMove = function () {
    movingnow = 'white';
    //var bestMove = getBestMove(game, whiteDepth, minimaxRootWhite);
    //var bestMove = randomMove(game);
    var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    //var bestMove = avoidBeingCaptured(game);

    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());

    if (game.game_over()) {
        //alert('Game over ['+checkmate(game)+']');
        checkmate(game);
        stopGame();
        return;
    }
    window.setTimeout(blackMove, 5);
};

var blackMove = function () {
    movingnow = 'black';
    //var bestMove = getBestMove(game, blackDepth, minimaxRoot);
    var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());
    if (game.game_over()) {
      //  alert('Game over ['+checkmate(game)+']');
      checkmate(game);
      stopGame();
      return;
    }
    window.setTimeout(whiteMove, 5);
};

var getRandomMove = function(moves){
    //get random index
    var turnRandomIndex = Math.floor(Math.random() * moves.length);
    //get move from random index
    var randomMoove = moves[turnRandomIndex];
    //return move
    return randomMoove;
};

/**
 * RANDOMMOVE AI
 * @param {*} game
 */
var randomMove = function(game) {
    //get moves
    var turnPossibleMoves = game.ugly_moves();
    //get random move
    var randomMoove = getRandomMove(turnPossibleMoves);
    //return move
    return randomMoove;
};

/**
 * RANDOMCAPTURE AI
 * @param {*} possibleMoves
 */
var getCaptureMoves = function (possibleMoves) {
    //declare the capture moves array
    var captureMoves = [];
    //loop over all the moves
    var i = 0;
    while (i < possibleMoves.length) {
        //get a single move from all moves using the index
        var move = possibleMoves[i];
        //if the move is captured
        if (move.captured) {
            //add the move to the capture moves array
            captureMoves.push(move);
        }
        i++;
    }
    return captureMoves;
};

var randomCapture = function (game){
    //get all the capturemoves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare nextmove
    var nextMove;
    //if there are capturemoves, get  a random one
    if (captureMoves.length > 0) {
        nextMove = getRandomMove(captureMoves);
    } else {
        //else get any random move from the game
        nextMove = randomMove(game);
    }
    //return nextmove
    return nextMove;
};
/**
 * BESTCAPTURE AI
 * @param {*} game
 */
var bestCapture = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r' && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n' && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b' && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p' && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var resultsInCapture = function(theMove){
    game.ugly_move(theMove);
    var foundCapture = (getCaptureMoves(game.ugly_moves()).length > 0);
    game.undo();
    return foundCapture;
};

/**
 * AVOIDBEINGCAPTURED AI
 * @param {*} game
 */
var avoidBeingCaptured = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
        if(resultsInCapture(theMove))
        {
            theMove = randomMove(game);
        }
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r'
                && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n'
                && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b'
                && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p'
                && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var positionCount;
var getBestMove = function (game, depth, findBestMove) {
    if (game.game_over()) {
        //alert('Game over');
        return;
    }

    positionCount = 0;
    //var depth = parseInt($('#search-depth').find(':selected').text());

    var d = new Date().getTime();
    var bestMove = findBestMove(depth, game, true);
    var d2 = new Date().getTime();
    var moveTime = (d2 - d);
    var positionsPerS = ( positionCount * 1000 / moveTime);

    $('#position-count').text(positionCount);
    $('#time').text(moveTime/1000 + 's');
    $('#positions-per-s').text(positionsPerS);
    return bestMove;
};

var renderMoveHistory = function (moves) {
    var historyElement = $('#move-history').empty();
    historyElement.empty();
    for (var i = 0; i < moves.length; i = i + 2) {
        historyElement.append('' + moves[i] + ' ' + ( moves[i + 1] ? moves[i + 1] : ' ') + '
')
    }
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var log = function (text) {
    var historyElement = $('#move-history');
    historyElement.append('' + text + '
');
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var onDrop = function (source, target) {

    // Removing to make both sides fully CPU, not first move as human
    // var move = game.move({
    //     from: source,
    //     to: target,
    //     promotion: 'q'
    // });
    startGame();
};
var startGame = function() {
    removeGreySquares();
    // if (move === null) {
    //     return 'snapback';
    // }

    renderMoveHistory(game.history());
    window.setTimeout(whiteMove, 1000);
};
var stopGame = function () {
    var whiteCheckmate = parseInt(localStorage.getItem('whiteCheckmate'));
    whiteCheckmate = whiteCheckmate ? whiteCheckmate : 0;
    var blackCheckmate = parseInt(localStorage.getItem('blackCheckmate'));
    blackCheckmate = blackCheckmate ? blackCheckmate : 0;
    var stalemate = parseInt(localStorage.getItem('stalemate'));
    stalemate = stalemate ? stalemate : 0;
    if (whiteCheckmate + blackCheckmate + stalemate >= 100) {
        var result = " black checkmate: "+blackCheckmate + ", " + " white checkmate: "+ whiteCheckmate + "," + " stalemate: "+stalemate;
        //log the results
        log(result);
        //alert the results
        alert(result);
        localStorage.removeItem('whiteCheckmate');
        localStorage.removeItem('blackCheckmate');
        localStorage.removeItem('stalemate');
    }else{
        //automatically reload here
        location.reload();
    }
};

var onSnapEnd = function () {
    board.position(game.fen());
};

var onMouseoverSquare = function(square, piece) {
    var moves = game.moves({
        square: square,
        verbose: true
    });

    if (moves.length === 0) return;

    greySquare(square);

    for (var i = 0; i < moves.length; i++) {
        greySquare(moves[i].to);
    }
};

var onMouseoutSquare = function(square, piece) {
    removeGreySquares();
};

var removeGreySquares = function() {
    $('#board .square-55d63').css('background', '');
};

var greySquare = function(square) {
    var squareEl = $('#board .square-' + square);

    var background = '#a9a9a9';
    if (squareEl.hasClass('black-3c85d') === true) {
        background = '#696969';
    }

    squareEl.css('background', background);
};

var cfg = {
    draggable: true,
    position: 'start',
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

startGame();<|endoftext|>


<commit_before>'use strict';
define(
    ['three', 'app/classes/SpaceObject'],
    function(THREE, SpaceObject) {
        return class Grid extends SpaceObject {

            // ##############################################
            // # Constructor ################################
            // ##############################################

            constructor(scene, name, position, width, height, segments, camera) {
                super();

                this.scene  = scene;
                if(camera) {
                    this.camera = camera;
                }

                this.name     = name;
                this.position = position;
                this.width    = width;
                this.height   = height;
                this.segments = segments;

                if(camera) {
                    this.cameraOffset   = this.position.clone().add(this.camera.position);
                }

                this._createMesh(segments);
                this.scene.add(this.mesh);
            }

            // ##############################################
            // # Private functions ##########################
            // ##############################################

            _createMesh(segments) {
                let geometry = new THREE.Geometry();

                for(let x = -this.width / 2; x <= this.width / 2; x += this.width / segments) {
                    geometry.vertices.push(
                        new THREE.Vector3(x, -this.height / 2, 0),
                        new THREE.Vector3(x,  this.height / 2, 0)
                    );
                }

                for(let y = -this.height / 2; y <= this.height / 2; y += this.height / segments) {
                    geometry.vertices.push(
                        new THREE.Vector3(-this.width / 2, y, 0),
                        new THREE.Vector3( this.width / 2, y, 0)
                    );
                }

                let material = new THREE.LineBasicMaterial({ color:0x333333 });

                this.mesh = new THREE.LineSegments(geometry, material);
                this.mesh.position.set(this.position.x, this.position.y, this.position.z);
            }

            // ##############################################
            // # Public functions ###########################
            // ##############################################

            update(deltaT) {
                super.update(deltaT);

                if(this.camera) {
                    let roundedOffset = new THREE.Vector3(
                        (this.camera.position.x - this.cameraOffset.x) % (this.width  / this.segments),
                        (this.camera.position.y - this.cameraOffset.y) % (this.height / this.segments),
                        this.camera.position.z - this.cameraOffset.z
                    );

                    let newPosition = this.camera.position
                        .clone()
                        .sub(this.cameraOffset)
                        .sub(roundedOffset);

                    this.position.set(
                        newPosition.x,
                        newPosition.y,
                        newPosition.z
                    );

                    this.mesh.position.set(this.position.x, this.position.y, this.position.z);
                }
            }

            // ##############################################

        } // class
    }
);<commit_msg>Changing condition for grid creation loops<commit_after>'use strict';
define(
    ['three', 'app/classes/SpaceObject'],
    function(THREE, SpaceObject) {
        return class Grid extends SpaceObject {

            // ##############################################
            // # Constructor ################################
            // ##############################################

            constructor(scene, name, position, width, height, segments, camera) {
                super();

                this.scene  = scene;
                if(camera) {
                    this.camera = camera;
                }

                this.name     = name;
                this.position = position;
                this.width    = width;
                this.height   = height;
                this.segments = segments;

                if(camera) {
                    this.cameraOffset   = this.position.clone().add(this.camera.position);
                }

                this._createMesh(segments);
                this.scene.add(this.mesh);
            }

            // ##############################################
            // # Private functions ##########################
            // ##############################################

            _createMesh(segments) {
                let geometry = new THREE.Geometry();

                let condition = (segments % 2 == 0) ? this.width / 2 + 1 : this.width / 2;
                for(let x = -this.width / 2; x <= condition; x += this.width / segments) {
                    geometry.vertices.push(
                        new THREE.Vector3(x, -this.height / 2, 0),
                        new THREE.Vector3(x,  this.height / 2, 0)
                    );
                }

                condition = (segments % 2 == 0) ? this.height / 2 + 1 : this.height / 2;
                for(let y = -this.height / 2; y <= condition; y += this.height / segments) {
                    geometry.vertices.push(
                        new THREE.Vector3(-this.width / 2, y, 0),
                        new THREE.Vector3( this.width / 2, y, 0)
                    );
                }

                let material = new THREE.LineBasicMaterial({ color:0x333333 });

                this.mesh = new THREE.LineSegments(geometry, material);
                this.mesh.position.set(this.position.x, this.position.y, this.position.z);
            }

            // ##############################################
            // # Public functions ###########################
            // ##############################################

            update(deltaT) {
                super.update(deltaT);

                if(this.camera) {
                    let roundedOffset = new THREE.Vector3(
                        (this.camera.position.x - this.cameraOffset.x) % (this.width  / this.segments),
                        (this.camera.position.y - this.cameraOffset.y) % (this.height / this.segments),
                        this.camera.position.z - this.cameraOffset.z
                    );

                    let newPosition = this.camera.position
                        .clone()
                        .sub(this.cameraOffset)
                        .sub(roundedOffset);

                    this.position.set(
                        newPosition.x,
                        newPosition.y,
                        newPosition.z
                    );

                    this.mesh.position.set(this.position.x, this.position.y, this.position.z);
                }
            }

            // ##############################################

        } // class
    }
);<|endoftext|>


<commit_before>var labelType,
useGradients,
nativeTextSupport,
animate;

 (function() {
    var ua = navigator.userAgent,
    iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
    typeOfCanvas = typeof HTMLCanvasElement,
    nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
    textSupport = nativeCanvasSupport
    && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
    //I'm setting this based on the fact that ExCanvas provides text support for IE
    //and that as of today iPhone/iPad current text support is lame
    labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native': 'HTML';
    nativeTextSupport = labelType == 'Native';
    useGradients = nativeCanvasSupport;
    animate = !(iStuff || !nativeCanvasSupport);
})();

function init(data) {
    //treemap
    initTreeMap(data);

    //jstree
    initJsTree(data);
}

function initTreeMap(data) {
    //init TreeMap
    var tm = new $jit.TM.Squarified({
        //where to inject the visualization
        injectInto: 'treeMap',
        //parent box title heights
        titleHeight: 15,
        //enable animations
        animate: animate,
        //box offsets
        offset: 0,
        //constrained: true,
        //levelsToShow: 1,
        //Attach left and right click events
        Events: {
            enable: true,
            onClick: function(node) {
                if (node) {
                    tm.enter(node);
                    $("#jstree_search").val(node.name);
                    $("#jstree_search").change();
                }
            },
            onRightClick: function() {
                tm.out();
            }
        },
        duration: 1000,
        //Enable tips
        Tips: {
            enable: true,
            //add positioning offsets
            offsetX: 20,
            offsetY: 20,
            //implement the onShow method to
            //add content to the tooltip when a node
            //is hovered
            onShow: function(tip, node, isLeaf, domElement) {
                var title = "";
                if (node.data.count != 0)
                title = node.name + " (" + node.data.count + ")";
                else
                title = node.name;
                var html = "
" + title
                + "

";
                var data = node.data;
                tip.innerHTML = html;
            }
        },

        //Add the name of the node in the correponding label
        //This method is called once, on label creation.
        onCreateLabel: function(domElement, node) {
            if (node.data.count != 0)
            domElement.innerHTML = node.name + " (" + node.data.count + ")";
            else
            domElement.innerHTML = node.name;
            var style = domElement.style;
            style.display = '';
            style.border = '2px solid transparent';
            domElement.onmouseover = function() {
                style.border = '2px solid #9FD4FF';
            };
            domElement.onmouseout = function() {
                style.border = '2px solid transparent';
            };
        }
    });
    tm.loadJSON(data);
    tm.refresh();
    //end
}

function initJsTree(data) {
    //set themes dir
    $.jstree._themes = "/javascripts/jstree/themes/";

    //add onSelect action
    $("#jstree").bind("select_node.jstree",
    function(node, tree) {
        var peptides = $(tree.rslt.obj).data();
        var margin = tree.rslt.obj.context.offsetTop - $("#jstree").offset().top;
        var innertext = $(tree.rslt.obj).find("a").text().split("(")[0];
        var list = $("#jstree_data").html("
" + innertext + "

").find("ul");
        $("#jstree_data").animate({
            marginTop: margin
        },
        1000);
        for (var peptide in peptides) {
            list.append("
" + peptides[peptide] + "
")
        }
    });

    //add search
    $("#jstree_search").keyup(function() {
        $("#jstree").jstree("search", ($(this).val()));
        $(".jstree-search").parent().find("li").show();
        $("#jstree ul").each(function() {
            $(this).children("li:visible").eq( - 1).addClass("jstree-last");
        });
    });
    $('#jstree_search').click(function() {
        $(this).keyup();
    });
    $('#jstree_search').change(function() {
        $(this).keyup();
    });

    //create the tree
    $("#jstree").jstree({
        core: {
            /* core options go here */
        },
        plugins: ["themes", "json_data", "ui", "search"],
        json_data: {
            "data": data
        },
        themes: {
            "icons": false
        },
        ui: {
            "select_limit": 1
        },
        search: {
            "show_only_matches": true
        }
    });
}<commit_msg>fix leafs<commit_after>var labelType,
useGradients,
nativeTextSupport,
animate;

 (function() {
    var ua = navigator.userAgent,
    iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
    typeOfCanvas = typeof HTMLCanvasElement,
    nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
    textSupport = nativeCanvasSupport
    && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
    //I'm setting this based on the fact that ExCanvas provides text support for IE
    //and that as of today iPhone/iPad current text support is lame
    labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native': 'HTML';
    nativeTextSupport = labelType == 'Native';
    useGradients = nativeCanvasSupport;
    animate = !(iStuff || !nativeCanvasSupport);
})();

function init(data) {
    //treemap
    initTreeMap(data);

    //jstree
    initJsTree(data);
}

function initTreeMap(data) {
    //init TreeMap
    var tm = new $jit.TM.Squarified({
        //where to inject the visualization
        injectInto: 'treeMap',
        //parent box title heights
        titleHeight: 15,
        //enable animations
        animate: animate,
        //box offsets
        offset: 0,
        //constrained: true,
        //levelsToShow: 1,
        //Attach left and right click events
        Events: {
            enable: true,
            onClick: function(node) {
                if (node) {
                    tm.enter(node);
                    $("#jstree_search").val(node.name);
                    $("#jstree_search").change();
                }
            },
            onRightClick: function() {
                tm.out();
            }
        },
        duration: 1000,
        //Enable tips
        Tips: {
            enable: true,
            //add positioning offsets
            offsetX: 20,
            offsetY: 20,
            //implement the onShow method to
            //add content to the tooltip when a node
            //is hovered
            onShow: function(tip, node, isLeaf, domElement) {
                var title = "";
                if (node.data.count != 0)
                title = node.name + " (" + node.data.count + ")";
                else
                title = node.name;
                var html = "
" + title
                + "

";
                var data = node.data;
                tip.innerHTML = html;
            }
        },

        //Add the name of the node in the correponding label
        //This method is called once, on label creation.
        onCreateLabel: function(domElement, node) {
            if (node.data.count != 0)
            domElement.innerHTML = node.name + " (" + node.data.count + ")";
            else
            domElement.innerHTML = node.name;
            var style = domElement.style;
            style.display = '';
            style.border = '2px solid transparent';
            domElement.onmouseover = function() {
                style.border = '2px solid #9FD4FF';
            };
            domElement.onmouseout = function() {
                style.border = '2px solid transparent';
            };
        }
    });
    tm.loadJSON(data);
    tm.refresh();
    //end
}

function initJsTree(data) {
    //set themes dir
    $.jstree._themes = "/javascripts/jstree/themes/";

    //add onSelect action
    $("#jstree").bind("select_node.jstree",
    function(node, tree) {
        var peptides = $(tree.rslt.obj).data();
        var margin = tree.rslt.obj.context.offsetTop - $("#jstree").offset().top;
        var innertext = $(tree.rslt.obj).find("a").text().split("(")[0];
        var list = $("#jstree_data").html("
" + innertext + "

").find("ul");
        $("#jstree_data").animate({
            marginTop: margin
        },
        1000);
        for (var peptide in peptides) {
            list.append("
" + peptides[peptide] + "
")
        }
    });

	//fix leafs
	$("#jstree").bind("loaded.jstree", function(event, data){
		$("#jstree li").not(":has(li)").addClass("jstree-leaf");
	});

    //add search
    $("#jstree_search").keyup(function() {
        $("#jstree").jstree("search", ($(this).val()));
        $(".jstree-search").parent().find("li").show();
        $("#jstree ul").each(function() {
            $(this).children("li:visible").eq( - 1).addClass("jstree-last");
        });
    });
    $('#jstree_search').click(function() {
        $(this).keyup();
    });
    $('#jstree_search').change(function() {
        $(this).keyup();
    });

    //create the tree
    $("#jstree").jstree({
        core: {
            /* core options go here */
        },
        plugins: ["themes", "json_data", "ui", "search"],
        json_data: {
            "data": data
        },
        themes: {
            "icons": false
        },
        ui: {
            "select_limit": 1
        },
        search: {
            "show_only_matches": true
        }
    });
}<|endoftext|>


<commit_before>/*Constantes*/
//                            stop   |    prevent     | prevent "same element"
//                          bubbling | default action | event handlers
//
//return false                 Yes           Yes             No
//preventDefault()             No            Yes             No
//stopPropagation()            Yes           No              No
//stopImmediatePropagation()   Yes           No              Yes

var wsAnimationTime = 200;

//var evt = (evt) ? evt : ((event) ? event : null);
//var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

$(document).on("keydown", function(e){
	if ((e.which == 13) && //ENTER
		(e.target.type=="text"))  {
		return false;
	}
	if ((e.which == 8 //BACKSPACE
	  || e.which == 46) && //DELETE
		(e.target.type=="select-one" ||
		 e.target.type=="radio" ||
		 e.target.type=="submit" ||
		 e.target.type=="checkbox"))  {
			return false;
	}
});

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

dbsfaces = {
	CSS : {
		MODIFIER : {
			CLOSABLE : " -closable ",
			CLOSED : " -closed ",
			SELECTED : " -selected ",
			SELECTABLE : " -selectable ",
			TITLE : " -title ",
			LABEL : " -label ",
			ICON : " -icon ",
			ICONCLOSE : " -iconclose ",
			DISABLED : " -disabled "
		}
	},

	ID: {
		DIALOG: "dialog",
		INPUTTEXT: "inputText"
	},

	EVENT: {
		ON_AJAX_BEGIN: "dbs_ON_AJAX_BEGIN",
		ON_AJAX_COMPLETE: "dbs_ON_AJAX_COMPLETE",
		ON_AJAX_SUCCESS: "dbs_ON_AJAX_SUCESS",
		ON_AJAX_ERROR: "dbs_ON_AJAX_ERROR",
		ON_ROW_SELECTED: "dbs_ON_ROW_SELECTED"
	}

}

var wAjaxTimeout;

dbsfaces.sound = {
	beep : function(){
		$("#dbs_beep").remove();
		$("body").append('<audio id="dbs_beep" src="sound/alert.mp3" preload autoplay/>');
//		$("body").append('<embed id="dbs_beep" src="sound/alert.mp3" showcontrols="false" hidden="true" autostart="true" loop="false" />');
	}
}

dbsfaces.ui = {
	centerVertical : function(pId){
		var xH = $(pId).outerHeight() / 2;
		$(pId).css("margin-top",  -xH + "px")
		      .css("top", "50%")
		      .css("position", "absolute");
	},

	/*Centraliza via código. Procure utilizar o centralização por CSS*/
	centerWindow : function (pMinWidth, pMinHeight, pElement){
			var xParentWidth;
			var xParentHeight;
			if (window.innerWidth<pMinWidth){
				xParentWidth = pMinWidth;
			}else{
				xParentWidth = window.innerWidth;
			}
			if (window.innerHeight<pMinHeight){
				xParentHeight = pMinHeight;
			}else{
				xParentHeight = window.innerHeight;
			}
		    xHCenter = (xParentWidth - $(pElement).outerWidth()) / 2;
		    xVCenter = (xParentHeight - $(pElement).outerHeight()) / 2;
			$(pElement).css("left", xHCenter + "px")
					   .css("top", xVCenter + "px")
					   .css("position", "fixed");
	},

	/*Centaliza todos os elementos que possuem a classe dbsAlignCenterThis*/
	centerWindows : function(pMinWidth, pMinHeight, pSelector){
		$(pSelector).each(function(index, value) {
			dbsfaces.util.centerWindow(pMinWidth, pMinHeight, this);
		});
	},

	/*Exibe a imagem de que indica que está aguardando o recebimento dos dados*/
	showLoading : function(pId, pShow){

		var xId = "dbs_ajaximg_" + $.trim(pId);
		//Sempre remove loading se já existir
		if ($("#" + xId).length > 0){
	    	$("#" + xId).remove();
		}

		//Exibe loading
	    if (pShow){
//			console.log("showLoading:" + pId + ":" + pStatus);
	        $('body').append("");
//	    }else{
//			console.log("HIDELoading:" + pId + ":" + pStatus);
	    }
	},

	showLoadingError : function(pId){
		var xId = "dbs_ajaximg_" + $.trim(pId);
		$("#" + xId).css("background-color", "rgba(255,255,180,0.8)");
		$("#" + xId).fadeOut(2000, function(){
			$("#" + xId).remove();
			$("div .-loading").remove();
		});
	},

	getRectangle : function(obj) {
	   var off = obj.offset();

	   return {
	          top: off.top,
	          left: off.left,
	          height: obj.outerHeight(),
	          width: obj.outerWidth()
	   };
	},

	isInsideRectangle : function(pX, pY, pRect) {
        if ((pX > pRect.left && pX < (pRect.left + pRect.width))
            && (pY > pRect.top && pY < (pRect.top + pRect.height))){
        	return true;
        }else{
	        return false;
        }
	},

	isOverlappingRectagle : function(pRectA, pRectB) {
		if (dbsfaces.ui.isInsideRectangle(pRectA.left, pRectA.top, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left + pRectA.width, pRectA.top, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left, pRectA.top + pRectA.height, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left + pRectA.width, pRectA.top + pRectA.height, pRectB)){
			return true;
		}else{
			return false;
		}
	},

	//Captura evento ajax dbsoft
	ajaxShowLoading : function(pSelector){
//		console.log("ajaxShowLoading:" + pSelector);
		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_BEGIN);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_BEGIN, function(e){
			dbsfaces.ui.showLoading("main",true);
		});
		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_COMPLETE);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_COMPLETE, function(e){
			//Reinicia a contagem do timeout a cada complete, já que existe respostas ajax em andamento
			window.clearTimeout(wAjaxTimeout);
			wAjaxTimeout = window.setTimeout(function(e){
				dbsfaces.ui.showLoadingError("main");
			}, 1000); //Time de delay para efetuar a chamada acima(showLoadingError). A chamada será cancelada em caso de sucesso.
		});

		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_SUCCESS);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_SUCCESS, function(e){
			window.clearTimeout(wAjaxTimeout); //Cancela o timeout definido no evento COMPLETE, cancelando a respectiva chamada ao showLoadingError.
			dbsfaces.ui.showLoading("main",false);
		});
	},
	//Posiciona do próximo campo dentro do container informado
	focusOnFirstInput: function(pContainer){
		//Seta foco no primeiro campo de input
		var xEle = pContainer.find("input:first, select:first, textarea:first");
		if (xEle.length != 0 ){
			xEle.get(0).focus();
		}
	},
	//Seleciona todo o texto
	selectAll: function(pObj){
		//timeout para evitar que o click desmarque o item selecionado
		setTimeout( function(){
			dbsfaces.ui.selectRange(pObj, 0, $(pObj).get(0).value.length);
		}, 1 );
	},
	//Retira a seleção de qualquer texto
	selectNone: function(pObj){
		dbsfaces.ui.selectRange(pObj, 0, 0);
	},
	//Seleciona da posição atual até o final do texto
	selectEnd: function(pObj){
		dbsfaces.ui.selectRange(pObj, $(pObj).get(0).selectionStart, $(pObj).get(0).value.length);
	},
	//Seleciona intervalo
	selectRange: function(pObj, pStart, pEnd){
		$(pObj).get(0).setSelectionRange(pStart, pEnd);
	},

	//Dispara evento click
	ajaxTriggerChange: function(e){
		if ($(e.source).length == 0){
			return;
		}
		if (e.status == "success"){
			$(e.source).trigger("click");
		}
	}

}

dbsfaces.util = {
	/*Verifica se elemento existe*/
	exists: function(pId){
		if(!dbsfaces.util.isEmpty(pId)){
			if ($(pId).length>0){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	},

	//Retorna vazio se for nulo
	getNotNull: function(pValue, pDefaultValue){
		if(pValue == null){
			return pDefaultValue;
		}
	},

	//Verifica se � nulo ou vazio
	isEmpty: function(pValue){
		if(pValue == null){
			return true;
		}
		if(pValue == ''){
			return true;
		}
		return false;
	},

	/*dispara evento para o elemento informado*/
	trigger: function (pEventName, pId){
		if (dbsfaces.util.exists(pId) &&
			!dbsfaces.util.isEmpty(pEventName)){
				//Cria evento com parametro para indicar que é dbsoft
				var xEvent = $.Event(pEventName, {dbs: true});
				//Dispara evento depois de fechar
				$(pId).trigger(xEvent);
				return xEvent;
		}else{
			alert('Parametros inválidos! pId=' + pId + ' pEventName=' + pEventName + ' dbsFaces.trigger');
			return false;
		}
	}
}

dbsfaces.util.isiOS = function(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPad
        (navigator.platform.indexOf("iPad") != -1)
    );
}

dbsfaces.util.isTablet = function(){
    return dbsfaces.util.isiOS();
}

dbsfaces.util.jsid = function(pClientId){
	return pClientId.replace(/:/g,"\\:");
}

dbsfaces.date = {
	isDate:function(pYear, pMonth, pDay, pHour, pSeconds, pMilliseconds){
		pMonth = pMonth - 1;
		var xD =  new Date(pYear, pMonth, pDay, pHour, pSeconds, pMilliseconds);
		if (xD.getDate() != pDay){
			return "";
		}
		if (xD.getMonth() != pMonth){
			return "";
		}
		if (xD.getFullYear() != pYear){
			return "";
		}
		return xD;
	}
}

dbsfaces.number = {
	isNumber: function(pVal){
		return !isNaN(parseFloat(pVal)) && isFinite(pVal);
	},

	sizeInBytes: function(pVal){
		if (typeof(pVal) != 'undefined'){
			var xVal = pVal.trim().toUpperCase();
			var xI = xVal.indexOf("KB");
			var xN = 1024;
			if (xI == -1){
				xI = xVal.indexOf("MB");
				if (xI != -1){
					xN *= xN;
				}else{
					xI = xVal.indexOf("GB");
					if (xI != -1){
						xN *= xN;
					}else{
						xI = xVal.indexOf("TB");
						if (xI != -1){
							xN *= xN;
						}else{
							xI = xVal.indexOf("B");
							if (xI == -1){
								xI = xVal.length;
							}
							xN = 1;
						}
					}
				}
			}
			xVal = xVal.substr(0, xI);
			if (dbsfaces.number.isNumber(xVal)){
				return xVal * xN;
			}
		}
		return 0;
	}
};

dbsfaces.string = {
	fromCharCode: function(pVal){
		//Ajuste para os códigos numéricos retornados pelo teclado estendido.
		return String.fromCharCode((96 <= pVal && pVal <= 105)? pVal-48 : pVal);
	}
}

//Monitora evento ajax recebido e dispara evento dbsoft
dbsfaces.onajax = function(e){
	if ($(e.source).length == 0){
		return;
	}
	if (e.status == "begin"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_BEGIN);
	}else if (e.status == "complete"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_COMPLETE);
	}else if (e.status == "success"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_SUCCESS);
	}
};

dbsfaces.onajaxerror = function(e){
	$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_ERROR);
	return false;
};

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index).focus();
        }
        return false;
    });
};
<commit_msg>Alteração do nome do método ajaxTriggerChange para ajaxTriggerClick<commit_after>/*Constantes*/
//                            stop   |    prevent     | prevent "same element"
//                          bubbling | default action | event handlers
//
//return false                 Yes           Yes             No
//preventDefault()             No            Yes             No
//stopPropagation()            Yes           No              No
//stopImmediatePropagation()   Yes           No              Yes

var wsAnimationTime = 200;

//var evt = (evt) ? evt : ((event) ? event : null);
//var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

$(document).on("keydown", function(e){
	if ((e.which == 13) && //ENTER
		(e.target.type=="text"))  {
		return false;
	}
	if ((e.which == 8 //BACKSPACE
	  || e.which == 46) && //DELETE
		(e.target.type=="select-one" ||
		 e.target.type=="radio" ||
		 e.target.type=="submit" ||
		 e.target.type=="checkbox"))  {
			return false;
	}
});

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

dbsfaces = {
	CSS : {
		MODIFIER : {
			CLOSABLE : " -closable ",
			CLOSED : " -closed ",
			SELECTED : " -selected ",
			SELECTABLE : " -selectable ",
			TITLE : " -title ",
			LABEL : " -label ",
			ICON : " -icon ",
			ICONCLOSE : " -iconclose ",
			DISABLED : " -disabled "
		}
	},

	ID: {
		DIALOG: "dialog",
		INPUTTEXT: "inputText"
	},

	EVENT: {
		ON_AJAX_BEGIN: "dbs_ON_AJAX_BEGIN",
		ON_AJAX_COMPLETE: "dbs_ON_AJAX_COMPLETE",
		ON_AJAX_SUCCESS: "dbs_ON_AJAX_SUCESS",
		ON_AJAX_ERROR: "dbs_ON_AJAX_ERROR",
		ON_ROW_SELECTED: "dbs_ON_ROW_SELECTED"
	}

}

var wAjaxTimeout;

dbsfaces.sound = {
	beep : function(){
		$("#dbs_beep").remove();
		$("body").append('<audio id="dbs_beep" src="sound/alert.mp3" preload autoplay/>');
//		$("body").append('<embed id="dbs_beep" src="sound/alert.mp3" showcontrols="false" hidden="true" autostart="true" loop="false" />');
	}
}

dbsfaces.ui = {
	centerVertical : function(pId){
		var xH = $(pId).outerHeight() / 2;
		$(pId).css("margin-top",  -xH + "px")
		      .css("top", "50%")
		      .css("position", "absolute");
	},

	/*Centraliza via código. Procure utilizar o centralização por CSS*/
	centerWindow : function (pMinWidth, pMinHeight, pElement){
			var xParentWidth;
			var xParentHeight;
			if (window.innerWidth<pMinWidth){
				xParentWidth = pMinWidth;
			}else{
				xParentWidth = window.innerWidth;
			}
			if (window.innerHeight<pMinHeight){
				xParentHeight = pMinHeight;
			}else{
				xParentHeight = window.innerHeight;
			}
		    xHCenter = (xParentWidth - $(pElement).outerWidth()) / 2;
		    xVCenter = (xParentHeight - $(pElement).outerHeight()) / 2;
			$(pElement).css("left", xHCenter + "px")
					   .css("top", xVCenter + "px")
					   .css("position", "fixed");
	},

	/*Centaliza todos os elementos que possuem a classe dbsAlignCenterThis*/
	centerWindows : function(pMinWidth, pMinHeight, pSelector){
		$(pSelector).each(function(index, value) {
			dbsfaces.util.centerWindow(pMinWidth, pMinHeight, this);
		});
	},

	/*Exibe a imagem de que indica que está aguardando o recebimento dos dados*/
	showLoading : function(pId, pShow){

		var xId = "dbs_ajaximg_" + $.trim(pId);
		//Sempre remove loading se já existir
		if ($("#" + xId).length > 0){
	    	$("#" + xId).remove();
		}

		//Exibe loading
	    if (pShow){
//			console.log("showLoading:" + pId + ":" + pStatus);
	        $('body').append("");
//	    }else{
//			console.log("HIDELoading:" + pId + ":" + pStatus);
	    }
	},

	showLoadingError : function(pId){
		var xId = "dbs_ajaximg_" + $.trim(pId);
		$("#" + xId).css("background-color", "rgba(255,255,180,0.8)");
		$("#" + xId).fadeOut(2000, function(){
			$("#" + xId).remove();
			$("div .-loading").remove();
		});
	},

	getRectangle : function(obj) {
	   var off = obj.offset();

	   return {
	          top: off.top,
	          left: off.left,
	          height: obj.outerHeight(),
	          width: obj.outerWidth()
	   };
	},

	isInsideRectangle : function(pX, pY, pRect) {
        if ((pX > pRect.left && pX < (pRect.left + pRect.width))
            && (pY > pRect.top && pY < (pRect.top + pRect.height))){
        	return true;
        }else{
	        return false;
        }
	},

	isOverlappingRectagle : function(pRectA, pRectB) {
		if (dbsfaces.ui.isInsideRectangle(pRectA.left, pRectA.top, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left + pRectA.width, pRectA.top, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left, pRectA.top + pRectA.height, pRectB) ||
			dbsfaces.ui.isInsideRectangle(pRectA.left + pRectA.width, pRectA.top + pRectA.height, pRectB)){
			return true;
		}else{
			return false;
		}
	},

	//Captura evento ajax dbsoft
	ajaxShowLoading : function(pSelector){
//		console.log("ajaxShowLoading:" + pSelector);
		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_BEGIN);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_BEGIN, function(e){
			dbsfaces.ui.showLoading("main",true);
		});
		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_COMPLETE);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_COMPLETE, function(e){
			//Reinicia a contagem do timeout a cada complete, já que existe respostas ajax em andamento
			window.clearTimeout(wAjaxTimeout);
			wAjaxTimeout = window.setTimeout(function(e){
				dbsfaces.ui.showLoadingError("main");
			}, 1000); //Time de delay para efetuar a chamada acima(showLoadingError). A chamada será cancelada em caso de sucesso.
		});

		$(pSelector).off(dbsfaces.EVENT.ON_AJAX_SUCCESS);
		$(pSelector).on(dbsfaces.EVENT.ON_AJAX_SUCCESS, function(e){
			window.clearTimeout(wAjaxTimeout); //Cancela o timeout definido no evento COMPLETE, cancelando a respectiva chamada ao showLoadingError.
			dbsfaces.ui.showLoading("main",false);
		});
	},
	//Posiciona do próximo campo dentro do container informado
	focusOnFirstInput: function(pContainer){
		//Seta foco no primeiro campo de input
		var xEle = pContainer.find("input:first, select:first, textarea:first");
		if (xEle.length != 0 ){
			xEle.get(0).focus();
		}
	},
	//Seleciona todo o texto
	selectAll: function(pObj){
		//timeout para evitar que o click desmarque o item selecionado
		setTimeout( function(){
			dbsfaces.ui.selectRange(pObj, 0, $(pObj).get(0).value.length);
		}, 1 );
	},
	//Retira a seleção de qualquer texto
	selectNone: function(pObj){
		dbsfaces.ui.selectRange(pObj, 0, 0);
	},
	//Seleciona da posição atual até o final do texto
	selectEnd: function(pObj){
		dbsfaces.ui.selectRange(pObj, $(pObj).get(0).selectionStart, $(pObj).get(0).value.length);
	},
	//Seleciona intervalo
	selectRange: function(pObj, pStart, pEnd){
		$(pObj).get(0).setSelectionRange(pStart, pEnd);
	},

	//Dispara evento click
	ajaxTriggerClick: function(e){
		if ($(e.source).length == 0){
			return;
		}
		if (e.status == "success"){
			$(e.source).trigger("click");
		}
	}

}

dbsfaces.util = {
	/*Verifica se elemento existe*/
	exists: function(pId){
		if(!dbsfaces.util.isEmpty(pId)){
			if ($(pId).length>0){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	},

	//Retorna vazio se for nulo
	getNotNull: function(pValue, pDefaultValue){
		if(pValue == null){
			return pDefaultValue;
		}
	},

	//Verifica se � nulo ou vazio
	isEmpty: function(pValue){
		if(pValue == null){
			return true;
		}
		if(pValue == ''){
			return true;
		}
		return false;
	},

	/*dispara evento para o elemento informado*/
	trigger: function (pEventName, pId){
		if (dbsfaces.util.exists(pId) &&
			!dbsfaces.util.isEmpty(pEventName)){
				//Cria evento com parametro para indicar que é dbsoft
				var xEvent = $.Event(pEventName, {dbs: true});
				//Dispara evento depois de fechar
				$(pId).trigger(xEvent);
				return xEvent;
		}else{
			alert('Parametros inválidos! pId=' + pId + ' pEventName=' + pEventName + ' dbsFaces.trigger');
			return false;
		}
	}
}

dbsfaces.util.isiOS = function(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPad
        (navigator.platform.indexOf("iPad") != -1)
    );
}

dbsfaces.util.isTablet = function(){
    return dbsfaces.util.isiOS();
}

dbsfaces.util.jsid = function(pClientId){
	return pClientId.replace(/:/g,"\\:");
}

dbsfaces.date = {
	isDate:function(pYear, pMonth, pDay, pHour, pSeconds, pMilliseconds){
		pMonth = pMonth - 1;
		var xD =  new Date(pYear, pMonth, pDay, pHour, pSeconds, pMilliseconds);
		if (xD.getDate() != pDay){
			return "";
		}
		if (xD.getMonth() != pMonth){
			return "";
		}
		if (xD.getFullYear() != pYear){
			return "";
		}
		return xD;
	}
}

dbsfaces.number = {
	isNumber: function(pVal){
		return !isNaN(parseFloat(pVal)) && isFinite(pVal);
	},

	sizeInBytes: function(pVal){
		if (typeof(pVal) != 'undefined'){
			var xVal = pVal.trim().toUpperCase();
			var xI = xVal.indexOf("KB");
			var xN = 1024;
			if (xI == -1){
				xI = xVal.indexOf("MB");
				if (xI != -1){
					xN *= xN;
				}else{
					xI = xVal.indexOf("GB");
					if (xI != -1){
						xN *= xN;
					}else{
						xI = xVal.indexOf("TB");
						if (xI != -1){
							xN *= xN;
						}else{
							xI = xVal.indexOf("B");
							if (xI == -1){
								xI = xVal.length;
							}
							xN = 1;
						}
					}
				}
			}
			xVal = xVal.substr(0, xI);
			if (dbsfaces.number.isNumber(xVal)){
				return xVal * xN;
			}
		}
		return 0;
	}
};

dbsfaces.string = {
	fromCharCode: function(pVal){
		//Ajuste para os códigos numéricos retornados pelo teclado estendido.
		return String.fromCharCode((96 <= pVal && pVal <= 105)? pVal-48 : pVal);
	}
}

//Monitora evento ajax recebido e dispara evento dbsoft
dbsfaces.onajax = function(e){
	if ($(e.source).length == 0){
		return;
	}
	if (e.status == "begin"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_BEGIN);
	}else if (e.status == "complete"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_COMPLETE);
	}else if (e.status == "success"){
		$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_SUCCESS);
	}
};

dbsfaces.onajaxerror = function(e){
	$(e.source).trigger(dbsfaces.EVENT.ON_AJAX_ERROR);
	return false;
};

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index).focus();
        }
        return false;
    });
};
<|endoftext|>


<commit_before>import RedditModel from './RedditModel';
import { POST } from './thingTypes';
import votable from './mixins/votable';
import replyable from './mixins/replyable';

const T = RedditModel.Types;

const IGNORED_THUMBNAILS = new Set(['default', 'self', 'nsfw']);
const cleanThumbnail = thumbnail => {
  return IGNORED_THUMBNAILS.has(thumbnail) ? '' : thumbnail;
};

export default class PostModel extends RedditModel {
  static type = POST;

  static PROPERTIES = {
    adserverImpPixel: T.string,
    archived: T.bool,
    author: T.string,
    cleanPermalink: T.link,
    cleanUrl: T.link,
    distinguished: T.string,
    domain: T.string,
    downs: T.number,
    gilded: T.number,
    hidden: T.bool,
    id: T.string,
    impPixel: T.string,
    likes: T.cubit,
    locked: T.bool,
    malink: T.link,
    media: T.nop,
    name: T.string,
    over18: T.bool,
    postHint: T.string,
    promoted: T.bool,
    quarantine: T.bool,
    saved: T.bool,
    score: T.number,
    stickied: T.bool,
    subreddit: T.string,
    subredditDetail: T.nop,
    subredditId: T.string,
    thumbnail: T.string,
    title: T.string,
    ups: T.number,

    // aliases
    authorFlairCSSClass: T.string,
    authorFlairText: T.string,
    createdUTC: T.number,
    hideScore: T.bool,
    isSelf: T.bool,
    linkFlairCSSClass: T.string,
    linkFlairText: T.string,
    mediaOembed: T.nop,
    modReports: T.array,
    numComments: T.number,
    secureMedia: T.nop,
    selfTextHTML: T.string,
    sendReplies: T.bool,
    userReports: T.array,

    // derived
    expandable: T.bool,
    expandedContent: T.html,
    preview: T.nop, // it's in data as well but we want to transform it
  };

  static API_ALIASES = {
    adserver_imp_pixel: 'adserverImpPixel',
    author_flair_css_class: 'authorFlairCSSClass',
    author_flair_text: 'authorFlairText',
    created_utc: 'createdUTC',
    hide_score: 'hideScore',
    imp_pixel: 'impPixel',
    is_self: 'isSelf',
    link_flair_css_class: 'linkFlairCSSClass',
    link_flair_text: 'linkFlairText',
    media_oembed: 'mediaOembed',
    mod_reports: 'modReports',
    num_comments: 'numComments',
    over_18: 'over18',
    permalink: 'cleanPermalink',
    post_hint: 'postHint',
    secure_media: 'secureMedia',
    selftext_html: 'selfTextHTML',
    sr_detail: 'subredditDetail',
    subreddit_id: 'subredditId',
    sendreplies: 'sendReplies',
    url: 'cleanUrl',
    user_reports: 'userReports',
  };

  static DERIVED_PROPERTIES = {
    expandable(data) {
      // If it has secure_media, or media, or selftext, it has expandable.
      return !!(
        (data.secure_media && data.secure_media.content) ||
        (data.media_embed && data.media_embed.content) ||
        (data.selftext_html)
      );
    },

    expandedContent(data) {
      let content;

      content = (
        (data.secure_media_embed && data.secure_media_embed.content) ||
        (data.media_embed && data.media_embed.content)
      );

      if (!content && data.selftext_html) {
        content = data.selftext_html;
      }

      return content;
    },

    preview(data) {
      if (!(data.promoted && !data.preview)) { return data.preview; }
      // we build fake preview data for ads and normal thumbnails

      const resolutions = [];

      if (data.mobile_ad_url) {
        resolutions.push({
          url: data.mobile_ad_url,
          height: 628,
          width: 1200,
        });
      }

      const thumbnail = cleanThumbnail(data.thumbnail);
      if (thumbnail) {
        resolutions.push({
          url: thumbnail,
          height: 140,
          width: 140,
        });
      }

      return {
        images: [{
          resolutions,
        }],
      };
    },

    thumbnail(data) {
      return cleanThumbnail(data.thumbnail);
    },
  };
}

votable(PostModel);
replyable(PostModel);
<commit_msg>Don't accept a thumbnail value of "image"<commit_after>import RedditModel from './RedditModel';
import { POST } from './thingTypes';
import votable from './mixins/votable';
import replyable from './mixins/replyable';

const T = RedditModel.Types;

const IGNORED_THUMBNAILS = new Set(['default', 'image', 'self', 'nsfw']);
const cleanThumbnail = thumbnail => {
  return IGNORED_THUMBNAILS.has(thumbnail) ? '' : thumbnail;
};

export default class PostModel extends RedditModel {
  static type = POST;

  static PROPERTIES = {
    adserverImpPixel: T.string,
    archived: T.bool,
    author: T.string,
    cleanPermalink: T.link,
    cleanUrl: T.link,
    distinguished: T.string,
    domain: T.string,
    downs: T.number,
    gilded: T.number,
    hidden: T.bool,
    id: T.string,
    impPixel: T.string,
    likes: T.cubit,
    locked: T.bool,
    malink: T.link,
    media: T.nop,
    name: T.string,
    over18: T.bool,
    postHint: T.string,
    promoted: T.bool,
    quarantine: T.bool,
    saved: T.bool,
    score: T.number,
    stickied: T.bool,
    subreddit: T.string,
    subredditDetail: T.nop,
    subredditId: T.string,
    thumbnail: T.string,
    title: T.string,
    ups: T.number,

    // aliases
    authorFlairCSSClass: T.string,
    authorFlairText: T.string,
    createdUTC: T.number,
    hideScore: T.bool,
    isSelf: T.bool,
    linkFlairCSSClass: T.string,
    linkFlairText: T.string,
    mediaOembed: T.nop,
    modReports: T.array,
    numComments: T.number,
    secureMedia: T.nop,
    selfTextHTML: T.string,
    sendReplies: T.bool,
    userReports: T.array,

    // derived
    expandable: T.bool,
    expandedContent: T.html,
    preview: T.nop, // it's in data as well but we want to transform it
  };

  static API_ALIASES = {
    adserver_imp_pixel: 'adserverImpPixel',
    author_flair_css_class: 'authorFlairCSSClass',
    author_flair_text: 'authorFlairText',
    created_utc: 'createdUTC',
    hide_score: 'hideScore',
    imp_pixel: 'impPixel',
    is_self: 'isSelf',
    link_flair_css_class: 'linkFlairCSSClass',
    link_flair_text: 'linkFlairText',
    media_oembed: 'mediaOembed',
    mod_reports: 'modReports',
    num_comments: 'numComments',
    over_18: 'over18',
    permalink: 'cleanPermalink',
    post_hint: 'postHint',
    secure_media: 'secureMedia',
    selftext_html: 'selfTextHTML',
    sr_detail: 'subredditDetail',
    subreddit_id: 'subredditId',
    sendreplies: 'sendReplies',
    url: 'cleanUrl',
    user_reports: 'userReports',
  };

  static DERIVED_PROPERTIES = {
    expandable(data) {
      // If it has secure_media, or media, or selftext, it has expandable.
      return !!(
        (data.secure_media && data.secure_media.content) ||
        (data.media_embed && data.media_embed.content) ||
        (data.selftext_html)
      );
    },

    expandedContent(data) {
      let content;

      content = (
        (data.secure_media_embed && data.secure_media_embed.content) ||
        (data.media_embed && data.media_embed.content)
      );

      if (!content && data.selftext_html) {
        content = data.selftext_html;
      }

      return content;
    },

    preview(data) {
      if (!(data.promoted && !data.preview)) { return data.preview; }
      // we build fake preview data for ads and normal thumbnails

      const resolutions = [];

      if (data.mobile_ad_url) {
        resolutions.push({
          url: data.mobile_ad_url,
          height: 628,
          width: 1200,
        });
      }

      const thumbnail = cleanThumbnail(data.thumbnail);
      if (thumbnail) {
        resolutions.push({
          url: thumbnail,
          height: 140,
          width: 140,
        });
      }

      return {
        images: [{
          resolutions,
        }],
      };
    },

    thumbnail(data) {
      return cleanThumbnail(data.thumbnail);
    },
  };
}

votable(PostModel);
replyable(PostModel);
<|endoftext|>


<commit_before>define([], function() {

  /**
  * List of the key languages of the platform
  */

  var languageList = {
    en: 'English',
    zh: '中文',
    fr: 'Français',
    id: 'Bahasa Indonesia',
    pt_BR: 'Português (Brasil)',
    es_MX: 'Español (Mexico)'
  };

  var languagesHelper = {

    /**
     * Returns the list of key languages
     * @returns {Object} key languages list
     */
    getList: function() {
      return languageList;
    },

    /**
     * Returns a list of the key languages
     * with the selected option passed by param
     * @param {string} selected language
     * @returns {Array} list of languages with selection
     */
    getListSelected: function(selectedLanguage) {
      var langList = [];

      for (var lang in languageList) {
        langList.push({
          key: lang,
          name: languageList[lang],
          selected: lang === selectedLanguage ? 'selected' : ''
        });
      }
      return langList;
    }
  }
  return languagesHelper;

});
<commit_msg>Update languages literals in subscription selector<commit_after>define([], function() {

  /**
  * List of the key languages of the platform
  */

  var languageList = {
    en: 'English',
    zh: '中文',
    fr: 'Français',
    id: 'Bahasa Indonesia',
    pt_BR: 'Português',
    es_MX: 'Español'
  };

  var languagesHelper = {

    /**
     * Returns the list of key languages
     * @returns {Object} key languages list
     */
    getList: function() {
      return languageList;
    },

    /**
     * Returns a list of the key languages
     * with the selected option passed by param
     * @param {string} selected language
     * @returns {Array} list of languages with selection
     */
    getListSelected: function(selectedLanguage) {
      var langList = [];

      for (var lang in languageList) {
        langList.push({
          key: lang,
          name: languageList[lang],
          selected: lang === selectedLanguage ? 'selected' : ''
        });
      }
      return langList;
    }
  }
  return languagesHelper;

});
<|endoftext|>