<commit_before>/**
 * The Layout Row Component
 *
 * @module aui-layout-row
 */

var ALLOWED_SIZE = 12,
    MAXIMUM_COLS = 4,
    TPL_ROW = '
';

/**
 * A base class for Layout Row.
 *
 * @class A.LayoutRow
 * @extends Base
 * @param {Object} config Object literal specifying layout configuration
 *     properties.
 * @constructor
 */
A.LayoutRow = A.Base.create('layout-row', A.Base, [], {
    /**
     * Construction logic executed during `A.LayoutRow` instantiation. Lifecycle.
     *
     * @method initializer
     * @protected
     */
    initializer: function() {
        this.after({
            colsChange: this._afterColsChange
        });

        this._uiSetCols(this.get('cols'));
    },

    /**
     * Adds a col to this row.
     *
     * @method addCol
     * @param {Number} index Index to add the the col.
     * @param {A.LayoutCol} col Col to be added.
     */
    addCol: function(index, col) {
        var cols = this.get('cols').concat();

        if (A.Lang.isUndefined(index)) {
            index = cols.length;
        }

        if (!col) {
            col = new A.LayoutCol();
        }

        cols.splice(index, 0, col);

        cols = this._resizeCols(cols);

        this.set('cols', cols);
    },

    /**
     * Removes a col from this row.
     *
     * @method removeCol
     * @param {Number | A.LayoutCol} col Column index or column to be removed from this row
     */
    removeCol: function(col) {
        if (A.Lang.isNumber(col)) {
            this._removeColByIndex(col);
        }
        else if (A.instanceOf(col, A.LayoutCol)) {
            this._removeColByReference(col);
        }
    },

    /**
     * Fired after the `cols` attribute is set.
     *
     * @method _afterColsChange
     * @protected
     */
    _afterColsChange: function() {
        this._uiSetCols(this.get('cols'));
    },

    /**
     * Returns the sum of all this row's column sizes.
     *
     * @method getSize
     * @return {Number}
     */
    _getSize: function(cols) {
        return A.Array.reduce(cols, 0, function(prev, current) {
            prev += current.get('size');
            return prev;
        });
    },

    /**
     * Removes a col from this row by it's index.
     *
     * @method _removeColByIndex
     * @param {Number} index Column index to be removed from this row
     * @protected
     */
    _removeColByIndex: function(index) {
        var cols = this.get('cols').concat();
        cols.splice(index, 1);
        cols = this._resizeCols(cols);
        this.set('cols', cols);
    },

    /**
     * Removes a col from this row by it's reference.
     *
     * @method _removeColByReference
     * @param {A.LayoutCol} col Column to be removed from this row
     * @protected
     */
    _removeColByReference: function(col) {
        var cols = this.get('cols').concat(),
            index = A.Array.indexOf(cols, col);

        if (index >= 0) {
            this._removeColByIndex(index);
        }
    },

    /**
     * Resizes cols size.
     *
     * @method _resizeCols
     * @param {Array} cols Columns to be resized.
     * @return {Array} Columns resized.
     * @protected
     */
    _resizeCols: function(cols) {
        var length = cols.length,
            size = ALLOWED_SIZE / length;

        A.each(cols, function(col) {
            col.set('size', size);
        });

        return cols;
    },

    /**
     * Update the UI according to the value of the `cols` attribute.
     *
     * @method _uiSetCols
     * @param {Array} cols
     * @protected
     */
    _uiSetCols: function(cols) {
        var node = this.get('node');

        node.empty();
        A.each(cols, function(col) {
            node.append(col.get('node'));
        });
    }
}, {

    /**
     * Static property used to define the default attribute
     * configuration for the Layout Row.
     *
     * @property ATTRS
     * @type Object
     * @static
     */
    ATTRS: {

        /**
         * Array containing `A.LayoutCol` objects
         *
         * @attribute cols
         * @default []
         * @type {Array}
         */
        cols: {
            setter: function(cols) {
                var size = this._getSize(cols);

                if (size < ALLOWED_SIZE) {
                    cols.push(new A.LayoutCol({ size: ALLOWED_SIZE - size }));
                }

                return cols;
            },
            validator: function(cols) {
                var size = this._getSize(cols);

                if (size > ALLOWED_SIZE || size < 0 || !A.Lang.isArray(cols) || cols.length > MAXIMUM_COLS) {
                    return false;
                }

                return true;
            },
            valueFn: function() {
                return [new A.LayoutCol({ size: ALLOWED_SIZE })];
            }
        },

        /**
         * The node where this column will be rendered.
         *
         * @attribute node
         * @type Node
         */
        node: {
            setter: function(val) {
                val.setData('layout-row', this);
                return val;
            },
            validator: A.Lang.isNode,
            valueFn: function() {
                return A.Node.create(TPL_ROW);
            },
            writeOnce: 'initOnly'
        }
    }
});
<commit_msg>AUI-1703 Moving setter and validator to named functions<commit_after>/**
 * The Layout Row Component
 *
 * @module aui-layout-row
 */

var ALLOWED_SIZE = 12,
    MAXIMUM_COLS = 4,
    TPL_ROW = '
';

/**
 * A base class for Layout Row.
 *
 * @class A.LayoutRow
 * @extends Base
 * @param {Object} config Object literal specifying layout configuration
 *     properties.
 * @constructor
 */
A.LayoutRow = A.Base.create('layout-row', A.Base, [], {
    /**
     * Construction logic executed during `A.LayoutRow` instantiation. Lifecycle.
     *
     * @method initializer
     * @protected
     */
    initializer: function() {
        this.after({
            colsChange: this._afterColsChange
        });

        this._uiSetCols(this.get('cols'));
    },

    /**
     * Adds a col to this row.
     *
     * @method addCol
     * @param {Number} index Index to add the the col.
     * @param {A.LayoutCol} col Col to be added.
     */
    addCol: function(index, col) {
        var cols = this.get('cols').concat();

        if (A.Lang.isUndefined(index)) {
            index = cols.length;
        }

        if (!col) {
            col = new A.LayoutCol();
        }

        cols.splice(index, 0, col);

        cols = this._resizeCols(cols);

        this.set('cols', cols);
    },

    /**
     * Removes a col from this row.
     *
     * @method removeCol
     * @param {Number | A.LayoutCol} col Column index or column to be removed from this row
     */
    removeCol: function(col) {
        if (A.Lang.isNumber(col)) {
            this._removeColByIndex(col);
        }
        else if (A.instanceOf(col, A.LayoutCol)) {
            this._removeColByReference(col);
        }
    },

    /**
     * Fired after the `cols` attribute is set.
     *
     * @method _afterColsChange
     * @protected
     */
    _afterColsChange: function() {
        this._uiSetCols(this.get('cols'));
    },

    /**
     * Returns the sum of all this row's column sizes.
     *
     * @method getSize
     * @return {Number}
     */
    _getSize: function(cols) {
        return A.Array.reduce(cols, 0, function(prev, current) {
            prev += current.get('size');
            return prev;
        });
    },

    /**
     * Removes a col from this row by it's index.
     *
     * @method _removeColByIndex
     * @param {Number} index Column index to be removed from this row
     * @protected
     */
    _removeColByIndex: function(index) {
        var cols = this.get('cols').concat();
        cols.splice(index, 1);
        cols = this._resizeCols(cols);
        this.set('cols', cols);
    },

    /**
     * Removes a col from this row by it's reference.
     *
     * @method _removeColByReference
     * @param {A.LayoutCol} col Column to be removed from this row
     * @protected
     */
    _removeColByReference: function(col) {
        var cols = this.get('cols').concat(),
            index = A.Array.indexOf(cols, col);

        if (index >= 0) {
            this._removeColByIndex(index);
        }
    },

    /**
     * Resizes cols size.
     *
     * @method _resizeCols
     * @param {Array} cols Columns to be resized.
     * @return {Array} Columns resized.
     * @protected
     */
    _resizeCols: function(cols) {
        var length = cols.length,
            size = ALLOWED_SIZE / length;

        A.each(cols, function(col) {
            col.set('size', size);
        });

        return cols;
    },

    /**
     * Sets the `cols` attribute.
     *
     * @method _setCols
     * @param {Array} cols
     * @return {Array}
     * @protected
     */
    _setCols: function(cols) {
        var size = this._getSize(cols);

        if (size < ALLOWED_SIZE) {
            cols.push(new A.LayoutCol({ size: ALLOWED_SIZE - size }));
        }

        return cols;
    },

    /**
     * Update the UI according to the value of the `cols` attribute.
     *
     * @method _uiSetCols
     * @param {Array} cols
     * @protected
     */
    _uiSetCols: function(cols) {
        var node = this.get('node');

        node.empty();
        A.each(cols, function(col) {
            node.append(col.get('node'));
        });
    },

    /**
     * Validates the `cols` attribute.
     *
     * @method _validateCols
     * @param  {Array} cols
     * @return {Boolean}
     * @protected
     */
    _validateCols: function(cols) {
        var size = this._getSize(cols);

        if (size > ALLOWED_SIZE || size < 0 || !A.Lang.isArray(cols) || cols.length > MAXIMUM_COLS) {
            return false;
        }

        return true;
    }
}, {

    /**
     * Static property used to define the default attribute
     * configuration for the Layout Row.
     *
     * @property ATTRS
     * @type Object
     * @static
     */
    ATTRS: {

        /**
         * Array containing `A.LayoutCol` objects
         *
         * @attribute cols
         * @default []
         * @type {Array}
         */
        cols: {
            setter: '_setCols',
            validator: '_validateCols',
            valueFn: function() {
                return [new A.LayoutCol({ size: ALLOWED_SIZE })];
            }
        },

        /**
         * The node where this column will be rendered.
         *
         * @attribute node
         * @type Node
         */
        node: {
            setter: function(val) {
                val.setData('layout-row', this);
                return val;
            },
            validator: A.Lang.isNode,
            valueFn: function() {
                return A.Node.create(TPL_ROW);
            },
            writeOnce: 'initOnly'
        }
    }
});
<|endoftext|>


<commit_before>//Neutrine version
export {version} from "./src/version.js";

//Import global styles
import "./src/style.scss";

//Export helpers
export * from "./src/global.js";
export * from "./src/helpers.js";
export * from "./src/ready.js";

//Export basic components
export * from "./src/core/index.js";
export * from "./src/dashboard/index.js";
export * from "./src/experiments/index.js";
export * from "./src/future/index.js";
export * from "./src/icon/index.js";

//Loaders
export * from "./src/loaders/basic-loader/index.js";
export * from "./src/loaders/dna-loader/index.js";

//Widgets
export * from "./src/datatable/index.js";
//export * from "./src/text-editor/index.js";

//Export testing components
export * from "./src/test/index.js";

//Export utils components
export * from "./src/utils/choose.js";
export * from "./src/utils/for-each.js";
export * from "./src/utils/if.js";
export * from "./src/utils/renderer.js";

<commit_msg>Reorder exports and added widgets export<commit_after>//Neutrine version
export {version} from "./src/version.js";

//Import global styles
import "./src/style.scss";

//Export helpers
export * from "./src/global.js";
export * from "./src/helpers.js";
export * from "./src/ready.js";

//Export basic components
export * from "./src/core/index.js";
export * from "./src/experiments/index.js";
export * from "./src/future/index.js";
export * from "./src/icon/index.js";
export * from "./src/widgets/index.js";

//Loaders
export * from "./src/loaders/basic-loader/index.js";
export * from "./src/loaders/dna-loader/index.js";

//Big components
export * from "./src/dashboard/index.js";
export * from "./src/datatable/index.js";

//Export testing components
export * from "./src/test/index.js";

//Export utils components
export * from "./src/utils/choose.js";
export * from "./src/utils/for-each.js";
export * from "./src/utils/if.js";
export * from "./src/utils/renderer.js";

<|endoftext|>


<commit_before>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2017  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

/**************************************************************************
 ...
**************************************************************************/
function show_intelligence_report_dialog()
{
  if (selected_player == -1) return;
  var pplayer = players[selected_player];

  var msg = "Ruler " + pplayer['name'] + "
";
  if (pplayer['government'] > 0) {
    msg += "Government: " + governments[pplayer['government']]['name'] + "
";
  }

  if (pplayer['gold'] > 0) {
      msg += "Gold: " + pplayer['gold'] + "
";
    }

  if (pplayer['researching'] != null) {
    msg += "Researching: " + techs[pplayer['researching']]['name'] + "
";
  }

  msg += "

Establishing an embassy will show a detailed intelligence report."

  show_dialog_message("Intelligence report for " + pplayer['name'],
      msg);

}<commit_msg>Bugfix.<commit_after>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2017  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

/**************************************************************************
 ...
**************************************************************************/
function show_intelligence_report_dialog()
{
  if (selected_player == -1) return;
  var pplayer = players[selected_player];

  var msg = "Ruler " + pplayer['name'] + "
";
  if (pplayer['government'] > 0) {
    msg += "Government: " + governments[pplayer['government']]['name'] + "
";
  }

  if (pplayer['gold'] > 0) {
      msg += "Gold: " + pplayer['gold'] + "
";
    }

  if (pplayer['researching'] != null && pplayer['researching'] > 0 && techs[pplayer['researching']] != null) {
    msg += "Researching: " + techs[pplayer['researching']]['name'] + "
";
  }

  msg += "

Establishing an embassy will show a detailed intelligence report."

  show_dialog_message("Intelligence report for " + pplayer['name'],
      msg);

}<|endoftext|>


<commit_before>// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

(function() {
  if (navigator.userAgent.indexOf('(Dart)') === -1) {
    var scripts = document.getElementsByTagName("script");

    for (var i = 0; i < scripts.length; ++i) {
      if (scripts[i].type == "application/dart") {
        if (scripts[i].src && scripts[i].src != '') {
          var script = document.createElement('script');
          script.src = scripts[i].src.replace(/\.dart(?=\?|$)/, '.dart.precompiled.js');
          document.currentScript = script;
          scripts[i].parentNode.replaceChild(script, scripts[i]);
        }
      } else if (scripts[i].src.indexOf('.dart.js') == scripts[i].src.length - 8) {
        var script = document.createElement('script');
        script.src = scripts[i].src.replace(/\.dart\.js$/, '.dart.precompiled.js');
        document.currentScript = script;
        scripts[i].parentNode.replaceChild(script, scripts[i]);
      }
    }
  }
})();
<commit_msg>partial revert of bootstrap.js change<commit_after>// Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

(function() {
  if (navigator.webkitStartDart) {
    // TODO(sergeygs): Remove this completely after Dart 1.0.
    // This is unnecessary for upcoming releses of Dartium.
    navigator.webkitStartDart();
  }

  if (navigator.userAgent.indexOf('(Dart)') === -1) {
    var scripts = document.getElementsByTagName("script");

    for (var i = 0; i < scripts.length; ++i) {
      if (scripts[i].type == "application/dart") {
        if (scripts[i].src && scripts[i].src != '') {
          var script = document.createElement('script');
          script.src = scripts[i].src.replace(/\.dart(?=\?|$)/, '.dart.precompiled.js');
          document.currentScript = script;
          scripts[i].parentNode.replaceChild(script, scripts[i]);
        }
      } else if (scripts[i].src.indexOf('.dart.js') == scripts[i].src.length - 8) {
        var script = document.createElement('script');
        script.src = scripts[i].src.replace(/\.dart\.js$/, '.dart.precompiled.js');
        document.currentScript = script;
        scripts[i].parentNode.replaceChild(script, scripts[i]);
      }
    }
  }
})();
<|endoftext|>


<commit_before>function minbet(gs) {
  return gs.current_buy_in - gs.players[gs.in_action]['bet'] + gs.minimum_raise;
}

var l = console.log;

function checkCard(card) {
  switch (card) {
    case "J" :
      card = 11;
      break;
    case "Q" :
      card = 12;
      break;
    case "K" :
      card = 13;
      break;
    case "A" :
      card = 14;
      break;
    default:
      card = card;
  }
  return card;
}

function calculateBet(gs) {
  var bet;
  var r = ranking(gs)
  if (r) {
    return minbet(gs) + raise(r);
  } else {
    if (!checkAfterTheTurn(gs)) {
      return highCards(gs);
    } else {
      return 10;
    }
  }
}

function highCards(gs) {
  var ours = gs.players[gs.in_action].hole_cards;
  var card1 = checkCard(ours[0].rank);
  var card2 = checkCard(ours[1].rank);

  if (card1 < 2 && card2 < 2) {
    return 10;
  } else if (card1 < 6 && card2 < 6 && !lotsOfMoney(gs)) {
    l("low cards");
    return minbet(gs);
  } else if (card1 < 10 && card2 < 10 && !lotsOfMoney(gs)) {
    l("middle cards");
    return minbet(gs) + 50;
  } else if (!lotsOfMoney(gs)) {
    l("high cards");
    return minbet(gs) + 200;
  } else {
    return 2;
  }
}

function cardholder(game_state) {
  var ours = game_state.players[game_state.in_action].hole_cards;
  var common = game_state.community_cards;
  var cards = common.map(function(x) {
    return checkCard(x.rank);
  });
  cards.push(checkCard(ours[0].rank));
  cards.push(checkCard(ours[1].rank));
  return cards.sort(function(a,b) {return a-b;});
}

function findPair(cards) {
  for (var i=0; i < cards.length-1; i++) {
    if (cards[i] === cards[i+1]) {
      return true;
    }
  }
  return false;
}

function twoPair(cards) {
  counter = 0;
  for (var i = 0; i < cards.length - 2; i++) {
    if (cards[i] === cards[i+1]) {
      counter++;
      i++;
    }
  }
  if (counter >= 2) {
    return true;
  }
  return false;
}

function threeOfaKind(cards) {
  for (var i in cards) { //TODO: rewrite this as regular for loop
    if (cards[i] === cards[i+1] && cards[i+1] === cards[i+2]) {
      return true;
    }
  }
  return false;
}

function raise(rank) {
  var small = 100;
  var big = 300;
  return big * rank;
}

function lotsOfMoney(gs) {
  if (minbet(gs) >= gs.players[gs.in_action].stack / 3) {
    return true;
  }
}

function checkAfterTheTurn(gs) {
  if (gs.community_cards.length === 3) {
    return true;
  } else {
    return false;
  }
}

function ranking(gs) {
  var cards = cardholder(gs);
  if (threeOfaKind(cards)) return odds.three
    if (twoPair(cards)) return odds.twoPair;
  if (findPair(cards)) {
    return odds.pair;
  } else {
    return false;
  }
}

var odds = {
  highCard : 1,
  pair : 1.37,
  twoPair : 20,
  three : 46.3,
  straight : 254
}

module.exports = {
  calBet: calculateBet,
  minbet: minbet,
  checkCard: checkCard,
  calculateBet: calculateBet,
  highCards: highCards,
  cardholder: cardholder,
  findPair: findPair,
  twoPair: twoPair,
  threeOfaKind: threeOfaKind,
  raise: raise,
  lotsOfMoney: lotsOfMoney,
  ranking: ranking,
}
<commit_msg>rewrite threeOfaKind for regular for loop<commit_after>function minbet(gs) {
  return gs.current_buy_in - gs.players[gs.in_action]['bet'] + gs.minimum_raise;
}

var l = console.log;

function checkCard(card) {
  switch (card) {
    case "J" :
      card = 11;
      break;
    case "Q" :
      card = 12;
      break;
    case "K" :
      card = 13;
      break;
    case "A" :
      card = 14;
      break;
    default:
      card = card;
  }
  return card;
}

function calculateBet(gs) {
  var bet;
  var r = ranking(gs)
  if (r) {
    return minbet(gs) + raise(r);
  } else {
    if (!checkAfterTheTurn(gs)) {
      return highCards(gs);
    } else {
      return 10;
    }
  }
}

function highCards(gs) {
  var ours = gs.players[gs.in_action].hole_cards;
  var card1 = checkCard(ours[0].rank);
  var card2 = checkCard(ours[1].rank);

  if (card1 < 2 && card2 < 2) {
    return 10;
  } else if (card1 < 6 && card2 < 6 && !lotsOfMoney(gs)) {
    l("low cards");
    return minbet(gs);
  } else if (card1 < 10 && card2 < 10 && !lotsOfMoney(gs)) {
    l("middle cards");
    return minbet(gs) + 50;
  } else if (!lotsOfMoney(gs)) {
    l("high cards");
    return minbet(gs) + 200;
  } else {
    return 2;
  }
}

function cardholder(game_state) {
  var ours = game_state.players[game_state.in_action].hole_cards;
  var common = game_state.community_cards;
  var cards = common.map(function(x) {
    return checkCard(x.rank);
  });
  cards.push(checkCard(ours[0].rank));
  cards.push(checkCard(ours[1].rank));
  return cards.sort(function(a,b) {return a-b;});
}

function findPair(cards) {
  for (var i=0; i < cards.length-1; i++) {
    if (cards[i] === cards[i+1]) {
      return true;
    }
  }
  return false;
}

function twoPair(cards) {
  counter = 0;
  for (var i = 0; i < cards.length - 2; i++) {
    if (cards[i] === cards[i+1]) {
      counter++;
      i++;
    }
  }
  if (counter >= 2) {
    return true;
  }
  return false;
}

function threeOfaKind(cards) {
  for (var i = 0; i < cards.length-2; i++) {
    if (cards[i] === cards[i+1] && cards[i+1] === cards[i+2]) {
      return true;
    }
  }
  return false;
}

function raise(rank) {
  var small = 100;
  var big = 300;
  return big * rank;
}

function lotsOfMoney(gs) {
  if (minbet(gs) >= gs.players[gs.in_action].stack / 3) {
    return true;
  }
}

function checkAfterTheTurn(gs) {
  if (gs.community_cards.length === 3) {
    return true;
  } else {
    return false;
  }
}

function ranking(gs) {
  var cards = cardholder(gs);
  if (threeOfaKind(cards)) return odds.three
    if (twoPair(cards)) return odds.twoPair;
  if (findPair(cards)) {
    return odds.pair;
  } else {
    return false;
  }
}

var odds = {
  highCard : 1,
  pair : 1.37,
  twoPair : 20,
  three : 46.3,
  straight : 254
}

module.exports = {
  calBet: calculateBet,
  minbet: minbet,
  checkCard: checkCard,
  calculateBet: calculateBet,
  highCards: highCards,
  cardholder: cardholder,
  findPair: findPair,
  twoPair: twoPair,
  threeOfaKind: threeOfaKind,
  raise: raise,
  lotsOfMoney: lotsOfMoney,
  ranking: ranking,
}
<|endoftext|>


<commit_before>const config = {
    canvasClass: 'drawArea',
    cellSize: 20,
    radioInputName: 'gridInput',
    tileTypeEnums: {
        CANDIDATE_NEW: 'CANDIDATE_NEW',
        CANDIDATE_OLD: 'CANDIDATE_OLD',
        DESTINATION: 'DESTINATION',
        EMPTY: 'EMPTY',
        START: 'START',
        PATH: 'PATH',
        WALL: 'WALL',
    },
};

setDefault = (argument, defaultValue) =>
    typeof argument === 'undefined'
        ? defaultValue
        : argument;

const gridController = (() => {

    let canvas = null,
        context = null,
        config = null,
        gridData = null,
        tileTypeEnums = null,
        mouse = {
            isDown: false,
            currentPosition: {
                x: 0,
                y: 0
            },
            previousPosition: {
                x: 0,
                y: 0
            },
            currentGridPosition: {
                x: null,
                y: null
            }
        };

    initGridData = () => {
        let { height, width } = getGridSize();
        gridData = new Array(width);
        for (let i=0; i < width; i++){
            gridData[i] = new Array(height).fill(tileTypeEnums.EMPTY);
        }
    };

    tileColorPicker = (type) => {
        switch(type){
            case tileTypeEnums.CANDIDATE_NEW:
                return 'orange';
            case tileTypeEnums.CANDIDATE_OLD:
                return 'yellow';
            case tileTypeEnums.DESTINATION:
                return 'purple';
            case tileTypeEnums.EMPTY:
                return 'white';
            case tileTypeEnums.START:
                return 'blue';
            case tileTypeEnums.PATH:
                return 'green';
            case tileTypeEnums.WALL:
                return 'black';
            default:
                throw 'INVALID TILE TYPE';
        }
    };

    removeUniqueFromGrid = (type) => {
        gridData.map((column, columnIndex) => {
            column.map((element, rowIndex) => {
                if (gridData[columnIndex][rowIndex] === type) {
                    gridData[columnIndex][rowIndex] = tileTypeEnums.EMPTY;
                }
            })
        });
    };

    updateGridData = (x, y, type) => {
        if (gridData[x][y] !== type) {
            switch(type){
                case tileTypeEnums.WALL:
                case tileTypeEnums.EMPTY:
                case tileTypeEnums.CANDIDATE_NEW:
                case tileTypeEnums.CANDIDATE_OLD:
                case tileTypeEnums.PATH:
                    gridData[x][y] = type;
                    break;
                case tileTypeEnums.START:
                case tileTypeEnums.DESTINATION:
                    removeUniqueFromGrid(type);
                    gridData[x][y] = type;
                    break;
                default:
                    throw('Invalid input type!');
            }
            render();
        }
    };

    findCanvas = (canvasClass) => {
        canvas = $('canvas.' + canvasClass)[0];
        context = canvas.getContext('2d');
        context.translate(0.5, 0.5);
    };

    checkPositionOnCanvas = (event) => [
        Math.floor((event.pageX - event.target.offsetLeft)),
        Math.floor((event.pageY - event.target.offsetTop))
    ];

    setCoordinates = (coords, event) => {
        [coords.x, coords.y] = checkPositionOnCanvas(event);
    };

    drawLine = (x1, y1, x2, y2, brushColor, brushSize) => {
        brushColor = setDefault(brushColor, 'lightgrey');
        brushSize = setDefault(brushSize, 1);
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.strokeStyle = brushColor;
        context.lineWidth = brushSize;
        context.stroke();
        context.closePath();
    };

    drawGrid = (cellSize) => {
        for(let i = cellSize, canvasSize = canvas.width; i < canvasSize; i += cellSize){
            drawLine(0, i, canvasSize, i);
            drawLine(i, 0, i, canvasSize);
        }
    };

    render = () => {
        clearCanvas();
        drawGrid(config.cellSize);
        gridData.forEach((column, columnIndex) => {
            column.forEach((cell, rowIndex) => {
                fillGridCell(columnIndex, rowIndex, tileColorPicker(cell));
            });
        });
    };

    fillGridCell = (cellX, cellY, fillColor) => {
        context.fillStyle = setDefault(fillColor, 'black');
        context.fillRect(
            cellX * config.cellSize,
            cellY * config.cellSize,
            config.cellSize,
            config.cellSize
        );
    };

    handleMouseUp = () => {
        mouse.isDown = false;
        mouse.currentPosition.x = null;
    };

    currentGridPosition = () => [
        Math.floor(mouse.currentPosition.x / config.cellSize),
        Math.floor(mouse.currentPosition.y / config.cellSize)
    ];

    // let pixelMouseHandlers = {
    //     mouseDown: (event) => {
    //         mouse.isDown = true;
    //         setCoordinates(mouse.currentPosition, event);
    //         let current = mouse.currentPosition;
    //         context.fillRect(current.x, current.y, 1, 1);
    //     },
    //     mouseMove: (event) => {
    //         if (mouse.isDown) {
    //             mouse.previousPosition.x = mouse.currentPosition.x;
    //             mouse.previousPosition.y = mouse.currentPosition.y;
    //             setCoordinates(mouse.currentPosition, event);
    //             drawLine(
    //                 mouse.previousPosition.x,
    //                 mouse.previousPosition.y,
    //                 mouse.currentPosition.x,
    //                 mouse.currentPosition.y,
    //                 'black',
    //                 2
    //             );
    //         }
    //     },
    // };

    let gridMouseHandlers = {
        mouseDown: (event) => {
            mouse.isDown = true;
            setCoordinates(mouse.currentPosition, event);
            updateGridData(...currentGridPosition(), getInputType());
        },
        mouseMove: (event) => {
            if (mouse.isDown) {
                let oldGridPos = [mouse.currentGridPosition.x, mouse.currentGridPosition.y];
                let currentGridPos = currentGridPosition();
                if (!((oldGridPos[0] === currentGridPos[0]) && (oldGridPos[1] === currentGridPos[1]))){
                    gridMouseHandlers.mouseDown(event);
                }
            }
        }
    };

    activateMouseControls = (gridBased) => {
        if (gridBased){
            mountMouseEvents(gridMouseHandlers);
        } else {
            mountMouseEvents(pixelMouseHandlers);
        }
    };

    mountMouseEvents = (handlers) => {
        canvas.addEventListener('mousedown', handlers.mouseDown);
        canvas.addEventListener('mousemove', handlers.mouseMove);
    };

    unMountMouseEvents = () => {
        canvas.removeEventListener('mousedown', pixelMouseHandlers.mouseDown);
        canvas.removeEventListener('mousemove', pixelMouseHandlers.mouseMove);
        canvas.removeEventListener('mousedown', gridMouseHandlers.mouseDown);
        canvas.removeEventListener('mousemove', gridMouseHandlers.mouseMove);
    };

    initialize = (configObj) => {
        config = configObj;
        tileTypeEnums = configObj.tileTypeEnums;
        findCanvas(config.canvasClass);
        initGridData();
        render();
        window.addEventListener('mouseup', handleMouseUp);
    };

    clearCanvas = () => {
        context.save();
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.restore();
    };

    clearGridData = () => {
        gridData.forEach((column) => {
            column.fill(tileTypeEnums.EMPTY);
        });
    };

    clear = () => {
        clearCanvas();
        clearGridData();
        render();
    };

    getGridSize = () => ({
        width: Math.ceil(canvas.width / config.cellSize),
        height: Math.ceil(canvas.height / config.cellSize),
    });

    getInputType = () =>
        Object.keys(tileTypeEnums).filter(type =>
            type === document.querySelector(`input[name="${config.radioInputName}"]:checked`).value
        )[0];

    return {
        activateMouse: activateMouseControls,
        clear,
        deactivateMouse: unMountMouseEvents,
        getGridSize,
        gridData,
        init: initialize,
    };

})();

const aStar = (() => {

    let height = 0,
        width = 0,
        tileTypeEnums,
        grid = null;

    initialize = (config, data) => {
        height = config.height;
        width = config.width;
        tileTypeEnums = config.tileTypeEnums;
        grid = data;
    };

    isCandidateValid = (x,y) => {
        return (
            (
                (grid[x][y] === tileTypeEnums.EMPTY)
                || (grid[x][y] === tileTypeEnums.DESTINATION)
            )
            && (x+1 < width)
            && (x-1 >= 0)
            && (y+1 < height)
            && (y-1 >= 0)
        );
    };

    getNextCandidates = (x, y) => {
        let nextCandidates = [];
        if (isCandidateValid(x, y-1)) nextCandidates.push({
            x,
            y: y-1,
            cost: null,
        });
        if (isCandidateValid(x-1, y)) nextCandidates.push({
            x: x-1,
            y,
            cost: null,
        });
        if (isCandidateValid(x, y+1)) nextCandidates.push({
            x,
            y: y+1,
            cost: null,
        });
        if (isCandidateValid(x+1, y)) nextCandidates.push({
            x: x+1,
            y,
            cost: null,
        });
        return nextCandidates;
    };

})();

$('document').ready(function(){
    let canvas = gridController;
    $('button.clear').click(() => {canvas.clear()});
    canvas.init(config);
    canvas.activateMouse(true);
});
<commit_msg>Removed old pixel controls<commit_after>const config = {
    canvasClass: 'drawArea',
    cellSize: 20,
    radioInputName: 'gridInput',
    tileTypeEnums: {
        CANDIDATE_NEW: 'CANDIDATE_NEW',
        CANDIDATE_OLD: 'CANDIDATE_OLD',
        DESTINATION: 'DESTINATION',
        EMPTY: 'EMPTY',
        START: 'START',
        PATH: 'PATH',
        WALL: 'WALL',
    },
};

setDefault = (argument, defaultValue) =>
    typeof argument === 'undefined'
        ? defaultValue
        : argument;

const gridController = (() => {

    let canvas = null,
        context = null,
        config = null,
        gridData = null,
        tileTypeEnums = null,
        mouse = {
            isDown: false,
            currentPosition: {
                x: 0,
                y: 0
            },
            previousPosition: {
                x: 0,
                y: 0
            },
            currentGridPosition: {
                x: null,
                y: null
            }
        };

    initGridData = () => {
        let { height, width } = getGridSize();
        gridData = new Array(width);
        for (let i=0; i < width; i++){
            gridData[i] = new Array(height).fill(tileTypeEnums.EMPTY);
        }
    };

    tileColorPicker = (type) => {
        switch(type){
            case tileTypeEnums.CANDIDATE_NEW:
                return 'orange';
            case tileTypeEnums.CANDIDATE_OLD:
                return 'yellow';
            case tileTypeEnums.DESTINATION:
                return 'purple';
            case tileTypeEnums.EMPTY:
                return 'white';
            case tileTypeEnums.START:
                return 'blue';
            case tileTypeEnums.PATH:
                return 'green';
            case tileTypeEnums.WALL:
                return 'black';
            default:
                throw 'INVALID TILE TYPE';
        }
    };

    removeUniqueFromGrid = (type) => {
        gridData.map((column, columnIndex) => {
            column.map((element, rowIndex) => {
                if (gridData[columnIndex][rowIndex] === type) {
                    gridData[columnIndex][rowIndex] = tileTypeEnums.EMPTY;
                }
            })
        });
    };

    updateGridData = (x, y, type) => {
        if (gridData[x][y] !== type) {
            switch(type){
                case tileTypeEnums.WALL:
                case tileTypeEnums.EMPTY:
                case tileTypeEnums.CANDIDATE_NEW:
                case tileTypeEnums.CANDIDATE_OLD:
                case tileTypeEnums.PATH:
                    gridData[x][y] = type;
                    break;
                case tileTypeEnums.START:
                case tileTypeEnums.DESTINATION:
                    removeUniqueFromGrid(type);
                    gridData[x][y] = type;
                    break;
                default:
                    throw('Invalid input type!');
            }
            render();
        }
    };

    findCanvas = (canvasClass) => {
        canvas = $('canvas.' + canvasClass)[0];
        context = canvas.getContext('2d');
        context.translate(0.5, 0.5);
    };

    checkPositionOnCanvas = (event) => [
        Math.floor((event.pageX - event.target.offsetLeft)),
        Math.floor((event.pageY - event.target.offsetTop))
    ];

    setCoordinates = (coords, event) => {
        [coords.x, coords.y] = checkPositionOnCanvas(event);
    };

    drawLine = (x1, y1, x2, y2, brushColor, brushSize) => {
        brushColor = setDefault(brushColor, 'lightgrey');
        brushSize = setDefault(brushSize, 1);
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.strokeStyle = brushColor;
        context.lineWidth = brushSize;
        context.stroke();
        context.closePath();
    };

    drawGrid = (cellSize) => {
        for(let i = cellSize, canvasSize = canvas.width; i < canvasSize; i += cellSize){
            drawLine(0, i, canvasSize, i);
            drawLine(i, 0, i, canvasSize);
        }
    };

    render = () => {
        clearCanvas();
        drawGrid(config.cellSize);
        gridData.forEach((column, columnIndex) => {
            column.forEach((cell, rowIndex) => {
                fillGridCell(columnIndex, rowIndex, tileColorPicker(cell));
            });
        });
    };

    fillGridCell = (cellX, cellY, fillColor) => {
        context.fillStyle = setDefault(fillColor, 'black');
        context.fillRect(
            cellX * config.cellSize,
            cellY * config.cellSize,
            config.cellSize,
            config.cellSize
        );
    };

    handleMouseUp = () => {
        mouse.isDown = false;
        mouse.currentPosition.x = null;
    };

    currentGridPosition = () => [
        Math.floor(mouse.currentPosition.x / config.cellSize),
        Math.floor(mouse.currentPosition.y / config.cellSize)
    ];

    let gridMouseHandlers = {
        mouseDown: (event) => {
            mouse.isDown = true;
            setCoordinates(mouse.currentPosition, event);
            updateGridData(...currentGridPosition(), getInputType());
        },
        mouseMove: (event) => {
            if (mouse.isDown) {
                let oldGridPos = [mouse.currentGridPosition.x, mouse.currentGridPosition.y];
                let currentGridPos = currentGridPosition();
                if (!((oldGridPos[0] === currentGridPos[0]) && (oldGridPos[1] === currentGridPos[1]))){
                    gridMouseHandlers.mouseDown(event);
                }
            }
        }
    };

    mountMouseEvents = (handlers) => {
        canvas.addEventListener('mousedown', handlers.mouseDown);
        canvas.addEventListener('mousemove', handlers.mouseMove);
    };

    unMountMouseEvents = () => {
        canvas.removeEventListener('mousedown', pixelMouseHandlers.mouseDown);
        canvas.removeEventListener('mousemove', pixelMouseHandlers.mouseMove);
        canvas.removeEventListener('mousedown', gridMouseHandlers.mouseDown);
        canvas.removeEventListener('mousemove', gridMouseHandlers.mouseMove);
    };

    initialize = (configObj) => {
        config = configObj;
        tileTypeEnums = configObj.tileTypeEnums;
        findCanvas(config.canvasClass);
        initGridData();
        render();
        window.addEventListener('mouseup', handleMouseUp);
        mountMouseEvents(gridMouseHandlers);
    };

    clearCanvas = () => {
        context.save();
        context.setTransform(1, 0, 0, 1, 0, 0);
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.restore();
    };

    clearGridData = () => {
        gridData.forEach((column) => {
            column.fill(tileTypeEnums.EMPTY);
        });
    };

    clear = () => {
        clearCanvas();
        clearGridData();
        render();
    };

    getGridSize = () => ({
        width: Math.ceil(canvas.width / config.cellSize),
        height: Math.ceil(canvas.height / config.cellSize),
    });

    getInputType = () =>
        Object.keys(tileTypeEnums).filter(type =>
            type === document.querySelector(`input[name="${config.radioInputName}"]:checked`).value
        )[0];

    return {
        clear,
        deactivateMouse: unMountMouseEvents,
        getGridSize,
        gridData,
        init: initialize,
    };

})();

const aStar = (() => {

    let height = 0,
        width = 0,
        tileTypeEnums,
        grid = null;

    initialize = (config, data) => {
        height = config.height;
        width = config.width;
        tileTypeEnums = config.tileTypeEnums;
        grid = data;
    };

    isCandidateValid = (x,y) => {
        return (
            (
                (grid[x][y] === tileTypeEnums.EMPTY)
                || (grid[x][y] === tileTypeEnums.DESTINATION)
            )
            && (x+1 < width)
            && (x-1 >= 0)
            && (y+1 < height)
            && (y-1 >= 0)
        );
    };

    getNextCandidates = (x, y) => {
        let nextCandidates = [];
        if (isCandidateValid(x, y-1)) nextCandidates.push({
            x,
            y: y-1,
            cost: null,
        });
        if (isCandidateValid(x-1, y)) nextCandidates.push({
            x: x-1,
            y,
            cost: null,
        });
        if (isCandidateValid(x, y+1)) nextCandidates.push({
            x,
            y: y+1,
            cost: null,
        });
        if (isCandidateValid(x+1, y)) nextCandidates.push({
            x: x+1,
            y,
            cost: null,
        });
        return nextCandidates;
    };

    findStart = () => {

    };

})();

$('document').ready(function(){
    let canvas = gridController;
    $('button.clear').click(() => {canvas.clear()});
    canvas.init(config);
});
<|endoftext|>


<commit_before> var request = require('request');
 describe('Localr API', function() {
     describe('Users', function() {
         describe('create the user', function(done) {
             //             beforeEach(function() {
             //                 var restify = require('restify');
             //                 var test = require('../register.js');
             //                 var server = restify.createServer();
             //                 test.init(server);
             //                 server.listen('8080', 'localhost', function() {
             //                     console.log('%s server listen at %s', server.name, server.url);
             //                 });
             //             })
             it("be able to create a user", function(done) {
                 var url = 'http://api.adam-holt.co.uk/users/register';
                 // getting params
                 var params = {
                     uri: url,
                     headers: {
                         authorization: getBasic('testuser', 'test')
                     }
                 };
                 request.post(params, function(error, response, body) {
                     expect(response.statusCode).toBe(200);
                     if(error) {
                         expect(error.code).not.toBe('ECONNREFUSED');
                     }
                     done();
                 })
             })
             it("be not able to create duplicate user", function(done) {
                 var url = 'http://api.adam-holt.co.uk/users/register';
                 // getting params
                 var params = {
                     uri: url,
                     headers: {
                         authorization: getBasic('testuser', 'test')
                     }
                 };
                 request.post(params, function(error, response, body) {
                     expect(response.statusCode).toBe(409);
                     if(error) {
                         expect(error.code).not.toBe('ECONNREFUSED');
                     }
                     done();
                 })
             })
         })
     })
     describe('checkin', function(done) {
         it("be able to checkin", function(done) {
             var url = 'http://api.adam-holt.co.uk/users/checkin?username=testuser&points=10';
             var doc = {
                 username: "testuser",
                 points: 10
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("check points have been added", function() {
             var url = 'http://api.adam-holt.co.uk/users/testuser';
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 }
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 body = JSON.parse(body);
                 expect(body.points).toBe(10);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to see where you've checked in", function() {})
     })
     describe("groups", function() {
         it("be able to create a group", function() {
             var url = 'http://api.adam-holt.co.uk/users/groups';
             var doc = {
                 username: "testuser",
                 description: "testgroup",
                 competition: "freshers"
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.post(params, function(error, response, body) {
                 expect(response.statusCode).toBe(201);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to join a group", function() {
             var url = 'http: //api.adam-holt.co.uk/users/groups/testgroup';
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to delete a group", function(done) {
             var url = 'http: //api.adam-holt.co.uk/users/groups';
             var doc = {
                 username: "testuser",
                 groupname: "testgroup",
                 description: "testgroup",
                 competition: "freshers"
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.del(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
     });
     describe('businesses', function() {
         it('able to create new business', function() {})

         it('be able to create an offer', function() {})

         it('cant create duplicate offer', function() {})
     })
     describe('Offers', function() {
         it("Be able to get the latest offers", function(done) {
             var url = 'http: //api.adam-holt.co.uk/business/offers/';
             // getting params
             console.log('get all offers')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to get a businesses offers", function(done) {
             var url = 'http: //api.adam-holt.co.uk/business/offers/testbusiness';
             // getting params
             console.log('get testbusiness offers')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
     })
     it("be able to check what offers youve redeemed", function() {})
     describe('delete all', function() {
         it("be able delete the user", function(done) {
             var url = 'http://api.adam-holt.co.uk/users/testuser';
             // getting params
             console.log('at delete')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.del(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it('delete business', function() {})
         it('delete offers', function() {})
         it('delete group', function() {})
     })
 });
 getBasic = function(username, password) {
     return "Basic " + new Buffer(username + ":" + password).toString('base64')
 };<commit_msg>Jasmine<commit_after> var request = require('request');
 describe('Localr API', function() {
     describe('Users', function() {
         describe('create the user', function(done) {
             //             beforeEach(function() {
             //                 var restify = require('restify');
             //                 var test = require('../register.js');
             //                 var server = restify.createServer();
             //                 test.init(server);
             //                 server.listen('8080', 'localhost', function() {
             //                     console.log('%s server listen at %s', server.name, server.url);
             //                 });
             //             })
             it("be able to create a user", function(done) {
                 var url = 'http://api.adam-holt.co.uk/users/register';
                 // getting params
                 var params = {
                     uri: url,
                     headers: {
                         authorization: getBasic('testuser', 'test')
                     }
                 };
                 request.post(params, function(error, response, body) {
                     expect(response.statusCode).toBe(200);
                     if(error) {
                         expect(error.code).not.toBe('ECONNREFUSED');
                     }
                     done();
                 })
             })
             it("be not able to create duplicate user", function(done) {
                 var url = 'http://api.adam-holt.co.uk/users/register';
                 // getting params
                 var params = {
                     uri: url,
                     headers: {
                         authorization: getBasic('testuser', 'test')
                     }
                 };
                 request.post(params, function(error, response, body) {
                     expect(response.statusCode).toBe(409);
                     if(error) {
                         expect(error.code).not.toBe('ECONNREFUSED');
                     }
                     done();
                 })
             })
         })
     })
     describe('checkin', function(done) {
         it("be able to checkin", function(done) {
             var url = 'http://api.adam-holt.co.uk/users/checkin?username=testuser&points=10';
             var doc = {
                 username: "testuser",
                 points: 10
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("check points have been added", function() {
             var url = 'http://api.adam-holt.co.uk/users/testuser';
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 }
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 body = JSON.parse(body);
                 expect(body.points).toBe(10);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to see where you've checked in", function() {})
     })
     describe("groups", function() {
         it("be able to create a group", function() {
             var url = 'http://api.adam-holt.co.uk/users/groups';
             var doc = {
                 username: "testuser",
                 description: "testgroup",
                 competition: "freshers"
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.post(params, function(error, response, body) {
                 expect(response.statusCode).toBe(201);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to join a group", function() {
             var url = 'http: //api.adam-holt.co.uk/users/groups/testgroup';
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to delete a group", function(done) {
             var url = 'http: //api.adam-holt.co.uk/users/groups';
             var doc = {
                 username: "testuser",
                 groupname: "testgroup",
                 description: "testgroup",
                 competition: "freshers"
             };
             // getting params
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
                 body: JSON.stringify(doc)
             };
             request.del(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
     });
     describe('businesses', function() {
         it('able to create new business', function() {})
            var url = 'http: //api.adam-holt.co.uk/';
             // getting the parameters
             //
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })

         it('be able to create an offer', function() {})
            var url = 'http: //api.adam-holt.co.uk/';
             // getting the parameters
             //
             console.log('create offer')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.put(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })

         it('cant create duplicate offer', function() {})
            var url = 'http: //api.adam-holt.co.uk/';
             // getting the parameters

             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
     })
     describe('Offers', function() {
         it("Be able to get the latest offers", function(done) {
             var url = 'http: //api.adam-holt.co.uk/business/offers/';
             // getting params
             console.log('get all offers')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it("be able to get a businesses offers", function(done) {
             var url = 'http: //api.adam-holt.co.uk/business/offers/testbusiness';
             // getting params
             console.log('get testbusiness offers')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.get(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
     })
     it("be able to check what offers youve redeemed", function() {})
     describe('delete all', function() {
         it("be able delete the user", function(done) {
             var url = 'http://api.adam-holt.co.uk/users/testuser';
             // getting params
             console.log('at delete')
             var params = {
                 uri: url,
                 headers: {
                     authorization: getBasic('testuser', 'test')
                 },
             };
             request.del(params, function(error, response, body) {
                 expect(response.statusCode).toBe(200);
                 if(error) {
                     expect(error.code).not.toBe('ECONNREFUSED');
                 }
                 done();
             })
         })
         it('delete business', function() {})
         it('delete offers', function() {})
         it('delete group', function() {})
     })
 });
 getBasic = function(username, password) {
     return "Basic " + new Buffer(username + ":" + password).toString('base64')
 };<|endoftext|>


<commit_before>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    ExtJS
 * @subpackage Window
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author     Stephan Pohl
 * @author     $Author$
 */

/**
 * Shopware UI - Window
 *
 * This class overrides the default Ext.window.Window object
 * to add our necessary functionality.
 *
 * The class renders the Ext.window.Window in the active
 * desktop, renders the header tools and sets the needed
 * event listeners.
 */
Ext.define('Enlight.app.Window', {
    ui: 'default',
    width: 800,
    height: 600,
    maximizable: true,
    minimizable: true,
    stateful: true,
    border: false,
    minimized: false,
    focusable: true,

    /**
     * Property which indicates that the window should first just set to hidden before destroying it.
     * @boolean
     */
    hideOnClose: true,

    /**
     * Forces the window to be on front at start up
     * @boolean
     */
    forceToFront: false,

    /**
     * Extend from the standard ExtJS 4 controller
     * @string
     */
    extend: 'Ext.window.Window',

    /**
     * Requires classes which needs to be initialized before the initComponent
     * of this component is fired.
     * @array
     */
    requires: [ 'Ext.WindowManager' ],

    /**
     * Should a footer button be created
     *
     * @boolean
     */
    footerButton: true,

    /**
     * Property which indicates that the window is on the front.
     * @boolean
     */
    isWindowOnFront: false,

    /**
     * CSS class if the window is active
     * @string
     */
    activeCls: Ext.baseCSSPrefix + 'window-active',

    /**
     * Truthy when this component is the main window of the sub application.
     * @boolean
     */
    isMainWindow: false,

    /**
     * Truthy when this component is the sub window of the sub application.
     * @boolean
     */
    isSubWindow: false,

    /**
     * Provides the window management functionality for
     * the new event bus.
     *
     * This method registers the window into the window manager
     * for the asssociated sub application and terminates the
     * main window and it's sub windows.
     *
     * @private
     * @return void
     */
    onAfterRenderComponent: function() {
        var me = this,
            subApp = me.subApplication || me.subApp, windowManager, windowCount;

        if(!subApp) {
            return;
        }

        windowManager = subApp.windowManager;
        windowCount = windowManager.subWindows.getCount();

        windowManager.register(me, true, true);
        if(windowManager.zIndexStack.length == 1) {
            var mainWindow = me;
            mainWindow.isMainWindow = true;
            windowManager.mainWindow = mainWindow;

            mainWindow.on({
                beforeclose: me.onBeforeDestroyMainWindow,
                scope: me
            });
        } else {
            if(!windowManager.multipleSubWindows && windowCount == 1) {

                // Just throw a warning, not a error to prevent layout issues at further opened windows.
                if(Ext.isDefined(Ext.global.console)) {
                    Ext.global.console.warn('Enlight.app.Window: The sub application is configured to only support one opened sub window at once.');
                }
            }
            this.$subWindowId = Ext.id();
            windowManager.subWindows.add(this.$subWindowId, this);
            me.isSubWindow = true;

            // Remove the sub windows from the window manager before destroying
            me.on({
                scope: me,
                beforedestroy: function() {
                    windowManager.subWindows.removeAtKey(this.$subWindowId);
                }
            });
        }

        windowManager.bringToFront(me);
    },

    /**
     * Will be called when the main application window will be destroyed. The method
     * checks if one or more sub windows are opened and throws an confirm dialog. If
     * the user accepts that with a click on the button "yes", all sub windows
     * and the main application window will be destroyed.
     *
     * @event beforeclose
     * @privaate
     * @return [boolean]
     */
    onBeforeDestroyMainWindow: function () {
        var me = this,
            subApp = me.subApplication,
            windowManager, count, subWindows,
            subWindowConfirmationBlackList = [ 'Shopware.apps.Category', 'Shopware.apps.Voucher' ];

        // we don't have the window manager, so just return true to resume the `destroy` event
        if (!subApp.hasOwnProperty('windowManager') || !subApp.windowManager) {
            return true;
        }
        windowManager = subApp.windowManager;
        count = windowManager.subWindows.getCount();

        if (!count) {
            // Hide the window before destroy to increase the visual closing of the window
            // only when the window has no subWindows
            if (Ext.isFunction(me.hide)) {
                me.hide();
                return true;
            }
        }
        subWindows = windowManager.subWindows.items;

        if (Ext.Array.contains(subWindowConfirmationBlackList, me.subApplication.$className)) {

            //if the subApp is in the black list don't ask just close the sub windows
            me.closeSubWindows(subWindows, windowManager);
            return true;
        }

        Ext.Msg.confirm('Modul schließen', 'Sollen alle Unterfenster vom "' + me.title + '"-Modul geschlossen werden?', function (button) {
            if (button == 'yes') {
                me.closeSubWindows(subWindows, windowManager);
                me.destroy();
            }
        });

        // Prevent the event to continue to the the fact that we're triggering the destroying programmically...
        return false;
    },

	/**
	 * Initialize the Ext.window.Window and defines the necessary
	 * default configuration
     *
     * @return void
	 */
	initComponent: function() {
		var me = this;

        me.subApplication = me.initialConfig.subApp || this.subApp;
        delete this.subApp;

		// Set the rendering options
        if(!me.preventHeader) {
            me.constrain = true;
            me.isWindow = true;
        }

        // Add additional events
        me.on({
            dragstart: me.onMoveStart,
            dragend: me.onMoveEnd
        }, me);

        // Define the render area of the window
        var viewport = Shopware.app.Application.viewport;
        if(viewport && Shopware.apps.Index && me.forceToFront == false) {
            var activeDesktop = viewport.getActiveDesktop(),
                activeEl = activeDesktop.getEl();

            me.desktop = activeDesktop;
            me.desktopPosition =  viewport.getActiveDesktopPosition();
            me.renderTo = activeEl;
            me.constrainTo = activeEl;
        } else {
            /** We're in the development mode */
            me.renderTo = Ext.getBody();
        }

        // Prevent windows with no footerButton from getting lost
        // after minimizing. This way windows with no footerButton
        // will be neither minimizable nor maximizable but modal
        if(!me.footerButton) {
            me.maximizable = false;
            me.minimizable = false;
        }

        if(me.forceToFront) {
            me.minimizable = false;
        }

        me.callParent(arguments);
        me.isWindowOnFront = true;
        me.center();
	},

    /**
     * Special ExtJS method which will be called
     * after the window is shown.
     *
     * @public
     * @return void
     */
    afterShow: function() {
        var me = this;

        me.callParent(arguments);
        Ext.Function.defer(function() {
            window.scrollTo(0, 0);
        }, 10);

        if(me.forceToFront) {
            var el = me.getEl(), elDom;

            // If we're not having a window, don't try to set the style(s)
            if(!el) {
                return false;
            }
            elDom = el.dom;

            // Setting the style with vanilla js to prevent issues with the Ext.ZIndexManager
            el.dom.style.zIndex = "999999";
        }
    },

    /**
     * Special ExtJS method which will be called
     * after the window is rendered.
     *
     * @public
     * @return void
     */
    afterRender: function() {
        var me = this;
        me.callParent(arguments);
        me.onAfterRenderComponent.call(me);

        // Create footer item for this window
        if(me.footerButton) {
            Shopware.WindowManagement.addItem(me.title, me);
        }
    },

	/**
	 * Event listener which minimizes the Ext.window.Window
     *
     * @return void
	 */
	minimize: function() {
		this.fireEvent('minimize', this);

		this.minimized = true;
		this.hide();

        // Toggle toolbar button
        if(this._toolbarBtn) {
            this._toolbarBtn.toggle(false, true);
        }
	},

    // private
    doClose: function() {
        var me = this;

        if(me.hideOnClose) {
            me.hideOnClose = false;
            me.hide(me.animateTarget, me.doClose, me);
        }

        // Being called as callback after going through the hide call below
        if (me.hidden) {
            me.fireEvent('close', me);
            if (me.closeAction == 'destroy') {
                this.destroy();
            }
        } else {
            // close after hiding
            me.hide(me.animateTarget, me.doClose, me);
        }

        if(this._toolbarBtn) {
            Shopware.WindowManagement.removeItem(this._toolbarBtn);
        }
    },

    // private
    onMoveStart: function() {
        var me = this, activeWindows = Shopware.app.Application.getActiveWindows(), viewport = Shopware.app.Application.viewport;

        if(viewport) {
            me.hiddenLayer = viewport.getHiddenLayer();
            me.hiddenLayer.setStyle('z-index', '9999999');
            me.hiddenLayer.appendTo(Ext.getBody());

        }
        Ext.each(activeWindows, function(window) {
            if(window != me) {
                if(window.$className !== 'Shopware.apps.Deprecated.view.main.Window') {
                    window.ghost('', true);
                }
            }
        });
    },

    // private
    onMoveEnd: function() {
        var me = this, activeWindows = Shopware.app.Application.getActiveWindows(), viewport = Shopware.app.Application.viewport;

        Ext.each(activeWindows, function(window) {
            if(!window.minimized && window != me) {
                if(window.$className !== 'Shopware.apps.Deprecated.view.main.Window') {
                    window.unghost(true, true, true);
                }
            }
        });

        Ext.WindowManager.bringToFront(me);
        if(viewport) {
            viewport.jumpTo(me.desktopPosition, true);
            me.hiddenLayer.setStyle('z-index', null);
            Ext.removeNode(me.hiddenLayer.dom);
        }
    },

    /**
     * Event listener method which will be called when the user clicks somewhere
     * in a window.
     *
     * This method syncs the zseed (z-index) with the globally availble Ext.WindowManager
     * to set the clicked window to front.
     *
     * @event mousedown
     * @private
     * @return void
     */
    onMouseDown: function() {
        var me = this,
            subApp = me.subApplication || me.subApp,
            windowManager = subApp.windowManager;

        // We need a try & catch here to prevent errors if the will be activated and
        // destroyed immediately after that.
        try {
            windowManager.bringToFront(me);
        } catch(e) {}

        me.callParent(arguments);
    },

    // private
    fitContainer: function() {
        var me = this,
            parent = me.floatParent,
            container = parent ? parent.getTargetEl() : me.container,
            size = container.getViewSize(false);

        size.height = size.height - 20;
        me.setSize(size);
        me.setPosition.apply(me, [0, 0]);
    },

    maximize: function() {
        var me = this;

        if (!me.maximized) {
            me.expand(false);
            if (!me.hasSavedRestore) {
                me.restoreSize = me.getSize();
                me.restorePos = me.getPosition(true);
            }
            if (me.maximizable) {
                if(!me.tools.maximize) {
                    me.tools.maximize = me.header.tools.maximize.cloneConfig();
                }
                me.tools.maximize.hide();

                if(!me.tools.restore) {
                    me.tools.restore = me.header.tools.restore.cloneConfig();
                }
                me.tools.restore.show();
            }
            me.maximized = true;
            me.el.disableShadow();

            if (me.dd) {
                me.dd.disable();
            }
            if (me.resizer) {
                me.resizer.disable();
            }
            if (me.collapseTool) {
                me.collapseTool.hide();
            }
            me.el.addCls(Ext.baseCSSPrefix + 'window-maximized');
            me.container.addCls(Ext.baseCSSPrefix + 'window-maximized-ct');

            me.syncMonitorWindowResize();
            me.fitContainer();
            me.fireEvent('maximize', me);
        }
        return me;
    },

    /**
     * helper function to close all subwindows
     */
    closeSubWindows: function(subWindows, windowManager) {
        Ext.each(subWindows, function(subWindow) {
            if(subWindow) {
                windowManager.subWindows.removeAtKey(subWindow.$subWindowId);
                subWindow.destroy();
            }
        });
    }
});<commit_msg>SW-6350 - Fixed: Remapped the tools from me.tools to me.header.tools to prevent errors in the product module while maximizing, minimizing or restoring the window<commit_after>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    ExtJS
 * @subpackage Window
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author     Stephan Pohl
 * @author     $Author$
 */

/**
 * Shopware UI - Window
 *
 * This class overrides the default Ext.window.Window object
 * to add our necessary functionality.
 *
 * The class renders the Ext.window.Window in the active
 * desktop, renders the header tools and sets the needed
 * event listeners.
 */
Ext.define('Enlight.app.Window', {
    ui: 'default',
    width: 800,
    height: 600,
    maximizable: true,
    minimizable: true,
    stateful: true,
    border: false,
    minimized: false,
    focusable: true,

    /**
     * Property which indicates that the window should first just set to hidden before destroying it.
     * @boolean
     */
    hideOnClose: true,

    /**
     * Forces the window to be on front at start up
     * @boolean
     */
    forceToFront: false,

    /**
     * Extend from the standard ExtJS 4 controller
     * @string
     */
    extend: 'Ext.window.Window',

    /**
     * Requires classes which needs to be initialized before the initComponent
     * of this component is fired.
     * @array
     */
    requires: [ 'Ext.WindowManager' ],

    /**
     * Should a footer button be created
     *
     * @boolean
     */
    footerButton: true,

    /**
     * Property which indicates that the window is on the front.
     * @boolean
     */
    isWindowOnFront: false,

    /**
     * CSS class if the window is active
     * @string
     */
    activeCls: Ext.baseCSSPrefix + 'window-active',

    /**
     * Truthy when this component is the main window of the sub application.
     * @boolean
     */
    isMainWindow: false,

    /**
     * Truthy when this component is the sub window of the sub application.
     * @boolean
     */
    isSubWindow: false,

    /**
     * Provides the window management functionality for
     * the new event bus.
     *
     * This method registers the window into the window manager
     * for the asssociated sub application and terminates the
     * main window and it's sub windows.
     *
     * @private
     * @return void
     */
    onAfterRenderComponent: function() {
        var me = this,
            subApp = me.subApplication || me.subApp, windowManager, windowCount;

        if(!subApp) {
            return;
        }

        windowManager = subApp.windowManager;
        windowCount = windowManager.subWindows.getCount();

        windowManager.register(me, true, true);
        if(windowManager.zIndexStack.length == 1) {
            var mainWindow = me;
            mainWindow.isMainWindow = true;
            windowManager.mainWindow = mainWindow;

            mainWindow.on({
                beforeclose: me.onBeforeDestroyMainWindow,
                scope: me
            });
        } else {
            if(!windowManager.multipleSubWindows && windowCount == 1) {

                // Just throw a warning, not a error to prevent layout issues at further opened windows.
                if(Ext.isDefined(Ext.global.console)) {
                    Ext.global.console.warn('Enlight.app.Window: The sub application is configured to only support one opened sub window at once.');
                }
            }
            this.$subWindowId = Ext.id();
            windowManager.subWindows.add(this.$subWindowId, this);
            me.isSubWindow = true;

            // Remove the sub windows from the window manager before destroying
            me.on({
                scope: me,
                beforedestroy: function() {
                    windowManager.subWindows.removeAtKey(this.$subWindowId);
                }
            });
        }

        windowManager.bringToFront(me);
    },

    /**
     * Will be called when the main application window will be destroyed. The method
     * checks if one or more sub windows are opened and throws an confirm dialog. If
     * the user accepts that with a click on the button "yes", all sub windows
     * and the main application window will be destroyed.
     *
     * @event beforeclose
     * @privaate
     * @return [boolean]
     */
    onBeforeDestroyMainWindow: function () {
        var me = this,
            subApp = me.subApplication,
            windowManager, count, subWindows,
            subWindowConfirmationBlackList = [ 'Shopware.apps.Category', 'Shopware.apps.Voucher' ];

        // we don't have the window manager, so just return true to resume the `destroy` event
        if (!subApp.hasOwnProperty('windowManager') || !subApp.windowManager) {
            return true;
        }
        windowManager = subApp.windowManager;
        count = windowManager.subWindows.getCount();

        if (!count) {
            // Hide the window before destroy to increase the visual closing of the window
            // only when the window has no subWindows
            if (Ext.isFunction(me.hide)) {
                me.hide();
                return true;
            }
        }
        subWindows = windowManager.subWindows.items;

        if (Ext.Array.contains(subWindowConfirmationBlackList, me.subApplication.$className)) {

            //if the subApp is in the black list don't ask just close the sub windows
            me.closeSubWindows(subWindows, windowManager);
            return true;
        }

        Ext.Msg.confirm('Modul schließen', 'Sollen alle Unterfenster vom "' + me.title + '"-Modul geschlossen werden?', function (button) {
            if (button == 'yes') {
                me.closeSubWindows(subWindows, windowManager);
                me.destroy();
            }
        });

        // Prevent the event to continue to the the fact that we're triggering the destroying programmically...
        return false;
    },

	/**
	 * Initialize the Ext.window.Window and defines the necessary
	 * default configuration
     *
     * @return void
	 */
	initComponent: function() {
		var me = this;

        me.subApplication = me.initialConfig.subApp || this.subApp;
        delete this.subApp;

		// Set the rendering options
        if(!me.preventHeader) {
            me.constrain = true;
            me.isWindow = true;
        }

        // Add additional events
        me.on({
            dragstart: me.onMoveStart,
            dragend: me.onMoveEnd
        }, me);

        // Define the render area of the window
        var viewport = Shopware.app.Application.viewport;
        if(viewport && Shopware.apps.Index && me.forceToFront == false) {
            var activeDesktop = viewport.getActiveDesktop(),
                activeEl = activeDesktop.getEl();

            me.desktop = activeDesktop;
            me.desktopPosition =  viewport.getActiveDesktopPosition();
            me.renderTo = activeEl;
            me.constrainTo = activeEl;
        } else {
            /** We're in the development mode */
            me.renderTo = Ext.getBody();
        }

        // Prevent windows with no footerButton from getting lost
        // after minimizing. This way windows with no footerButton
        // will be neither minimizable nor maximizable but modal
        if(!me.footerButton) {
            me.maximizable = false;
            me.minimizable = false;
        }

        if(me.forceToFront) {
            me.minimizable = false;
        }

        me.callParent(arguments);
        me.isWindowOnFront = true;
        me.center();
	},

    /**
     * Special ExtJS method which will be called
     * after the window is shown.
     *
     * @public
     * @return void
     */
    afterShow: function() {
        var me = this;

        me.callParent(arguments);
        Ext.Function.defer(function() {
            window.scrollTo(0, 0);
        }, 10);

        if(me.forceToFront) {
            var el = me.getEl(), elDom;

            // If we're not having a window, don't try to set the style(s)
            if(!el) {
                return false;
            }
            elDom = el.dom;

            // Setting the style with vanilla js to prevent issues with the Ext.ZIndexManager
            el.dom.style.zIndex = "999999";
        }
    },

    /**
     * Special ExtJS method which will be called
     * after the window is rendered.
     *
     * @public
     * @return void
     */
    afterRender: function() {
        var me = this;
        me.callParent(arguments);
        me.onAfterRenderComponent.call(me);

        // Create footer item for this window
        if(me.footerButton) {
            Shopware.WindowManagement.addItem(me.title, me);
        }
    },

	/**
	 * Event listener which minimizes the Ext.window.Window
     *
     * @return void
	 */
	minimize: function() {
		this.fireEvent('minimize', this);

		this.minimized = true;
		this.hide();

        // Toggle toolbar button
        if(this._toolbarBtn) {
            this._toolbarBtn.toggle(false, true);
        }
	},

    // private
    doClose: function() {
        var me = this;

        if(me.hideOnClose) {
            me.hideOnClose = false;
            me.hide(me.animateTarget, me.doClose, me);
        }

        // Being called as callback after going through the hide call below
        if (me.hidden) {
            me.fireEvent('close', me);
            if (me.closeAction == 'destroy') {
                this.destroy();
            }
        } else {
            // close after hiding
            me.hide(me.animateTarget, me.doClose, me);
        }

        if(this._toolbarBtn) {
            Shopware.WindowManagement.removeItem(this._toolbarBtn);
        }
    },

    // private
    onMoveStart: function() {
        var me = this, activeWindows = Shopware.app.Application.getActiveWindows(), viewport = Shopware.app.Application.viewport;

        if(viewport) {
            me.hiddenLayer = viewport.getHiddenLayer();
            me.hiddenLayer.setStyle('z-index', '9999999');
            me.hiddenLayer.appendTo(Ext.getBody());

        }
        Ext.each(activeWindows, function(window) {
            if(window != me) {
                if(window.$className !== 'Shopware.apps.Deprecated.view.main.Window') {
                    window.ghost('', true);
                }
            }
        });
    },

    // private
    onMoveEnd: function() {
        var me = this, activeWindows = Shopware.app.Application.getActiveWindows(), viewport = Shopware.app.Application.viewport;

        Ext.each(activeWindows, function(window) {
            if(!window.minimized && window != me) {
                if(window.$className !== 'Shopware.apps.Deprecated.view.main.Window') {
                    window.unghost(true, true, true);
                }
            }
        });

        Ext.WindowManager.bringToFront(me);
        if(viewport) {
            viewport.jumpTo(me.desktopPosition, true);
            me.hiddenLayer.setStyle('z-index', null);
            Ext.removeNode(me.hiddenLayer.dom);
        }
    },

    /**
     * Event listener method which will be called when the user clicks somewhere
     * in a window.
     *
     * This method syncs the zseed (z-index) with the globally availble Ext.WindowManager
     * to set the clicked window to front.
     *
     * @event mousedown
     * @private
     * @return void
     */
    onMouseDown: function() {
        var me = this,
            subApp = me.subApplication || me.subApp,
            windowManager = subApp.windowManager;

        // We need a try & catch here to prevent errors if the will be activated and
        // destroyed immediately after that.
        try {
            windowManager.bringToFront(me);
        } catch(e) {}

        me.callParent(arguments);
    },

    // private
    fitContainer: function() {
        var me = this,
            parent = me.floatParent,
            container = parent ? parent.getTargetEl() : me.container,
            size = container.getViewSize(false);

        size.height = size.height - 20;
        me.setSize(size);
        me.setPosition.apply(me, [0, 0]);
    },

    maximize: function() {
        var me = this;

        if (!me.maximized) {
            me.expand(false);
            if (!me.hasSavedRestore) {
                me.restoreSize = me.getSize();
                me.restorePos = me.getPosition(true);
            }
            if (me.maximizable) {
                me.header.tools.maximize.hide();
                me.header.tools.restore.show();
            }
            me.maximized = true;
            me.el.disableShadow();

            if (me.dd) {
                me.dd.disable();
            }
            if (me.resizer) {
                me.resizer.disable();
            }
            if (me.collapseTool) {
                me.collapseTool.hide();
            }
            me.el.addCls(Ext.baseCSSPrefix + 'window-maximized');
            me.container.addCls(Ext.baseCSSPrefix + 'window-maximized-ct');

            me.syncMonitorWindowResize();
            me.fitContainer();
            me.fireEvent('maximize', me);
        }
        return me;
    },

    restore: function() {
        var me = this,
            header = me.header,
            tools = header.tools;

        if (me.maximized) {
            delete me.hasSavedRestore;
            me.removeCls(Ext.baseCSSPrefix + 'window-maximized');

            // Toggle tool visibility
            if (tools.restore) {
                tools.restore.hide();
            }
            if (tools.maximize) {
                tools.maximize.show();
            }
            if (me.collapseTool) {
                me.collapseTool.show();
            }

            me.maximized = false;

            // Restore the position/sizing
            me.setPosition(me.restorePos);
            me.setSize(me.restoreSize);

            // Unset old position/sizing
            delete me.restorePos;
            delete me.restoreSize;

            me.el.enableShadow(true);

            // Allow users to drag and drop again
            if (me.dd) {
                me.dd.enable();
                if (header) {
                    header.addCls(header.indicateDragCls)
                }
            }

            if (me.resizer) {
                me.resizer.enable();
            }

            me.container.removeCls(Ext.baseCSSPrefix + 'window-maximized-ct');

            me.syncMonitorWindowResize();
            me.doConstrain();
            me.fireEvent('restore', me);
        }
        return me;
    },

    /**
     * helper function to close all subwindows
     */
    closeSubWindows: function(subWindows, windowManager) {
        Ext.each(subWindows, function(subWindow) {
            if(subWindow) {
                windowManager.subWindows.removeAtKey(subWindow.$subWindowId);
                subWindow.destroy();
            }
        });
    }
});<|endoftext|>