<commit_before>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {int, isInt} from './integer';

/**
  * A ResultSummary instance contains structured metadata for a {Result}.
  * @access public
  */
class ResultSummary {
  /**
   * @constructor
   * @param {string} statement - The statement this summary is for
   * @param {Object} parameters - Parameters for the statement
   * @param {Object} metadata - Statement metadata
   */
  constructor(statement, parameters, metadata) {
    this.statement = {text: statement, parameters};
    this.statementType = metadata.type;
    this.updateStatistics = new StatementStatistics(metadata.stats || {});
    this.plan = metadata.plan || metadata.profile ? new Plan(metadata.plan || metadata.profile) : false;
    this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false;
    this.notifications = this._buildNotifications(metadata.notifications);
  }

  _buildNotifications(notifications) {
    if(!notifications) {
      return [];
    }
    return notifications.map(function(n) { return new Notification(n) });
  }

  /**
   * Check if the result summary has a plan
   * @return {boolean}
   */
  hasPlan() {
    return this.plan instanceof Plan
  }

  /**
   * Check if the result summary has a profile
   * @return {boolean}
   */
  hasProfile() {
    return this.profile instanceof ProfiledPlan
  }
}

/**
  * Class for execution plan received by prepending Cypher with EXPLAIN.
  * @access public
  */
class Plan {
  /**
   * Create a Plan instance
   * @constructor
   * @param {Object} plan - Object with plan data
   */
  constructor(plan) {
    this.operatorType = plan.operatorType;
    this.identifiers = plan.identifiers;
    this.arguments = plan.args;
    this.children = plan.children ? plan.children.map((child) => new Plan(child)) : [];
  }
}

/**
  * Class for execution plan received by prepending Cypher with PROFILE.
  * @access public
  */
class ProfiledPlan {
  /**
   * Create a ProfiledPlan instance
   * @constructor
   * @param {Object} plan - Object with plan data
   */
  constructor(profile) {
    this.operatorType = profile.operatorType;
    this.identifiers = profile.identifiers;
    this.arguments = profile.args;
    this.dbHits = profile.args.DbHits.toInt();
    this.rows = profile.args.Rows.toInt();
    this.children = profile.children ? profile.children.map((child) => new ProfiledPlan(child)) : [];
  }
}

/**
  * Get statistical information for a {Result}.
  * @access public
  */
class StatementStatistics {
  /**
   * Structurize the statistics
   * @constructor
   * @param {Object} statistics - Result statistics
   */
  constructor(statistics) {
    this._stats = {
      nodesCreated: 0,
      nodesDelete: 0,
      relationshipsCreated: 0,
      relationshipsDeleted: 0,
      propertiesSet: 0,
      labelsAdded: 0,
      labelsRemoved: 0,
      indexesAdded: 0,
      indexesRemoved: 0,
      constraintsAdded: 0,
      constraintsRemoved: 0
    }
    Object.keys(statistics).forEach((index) => {
      let val = isInt(statistics[index]) ? statistics[index].toInt() : statistics[index];
      //To camelCase
      this._stats[index.replace(/(\-\w)/g, (m) => m[1].toUpperCase())] = val;
    });
  }

  /**
   * Did the database get updated?
   * @return {boolean}
   */
  containsUpdates() {
    return Object.keys(this._stats).reduce((last, current) => {
      return last + this._stats[current];
    }, 0) > 0;
  }

  /**
   * @return {Number} - Number of nodes created.
   */
  nodesCreated() {
    return this._stats.nodesCreated;
  }

  /**
   * @return {Number} - Number of nodes deleted.
   */
  nodesDeleted() {
    return this._stats.nodesDeleted;
  }

  /**
   * @return {Number} - Number of relationships created.
   */
  relationshipsCreated() {
    return this._stats.relationshipsCreated;
  }

  /**
   * @return {Number} - Number of nodes deleted.
   */
  relationshipsDeleted() {
    return this._stats.relationshipsDeleted;
  }

  /**
   * @return {Number} - Number of properties set.
   */
  propertiesSet() {
    return this._stats.propertiesSet;
  }

  /**
   * @return {Number} - Number of labels added.
   */
  labelsAdded() {
    return this._stats.labelsAdded;
  }

  /**
   * @return {Number} - Number of labels removed.
   */
  labelsRemoved() {
    return this._stats.labelsRemoved;
  }

  /**
   * @return {Number} - Number of indexes added.
   */
  indexesAdded() {
    return this._stats.indexesAdded;
  }

  /**
   * @return {Number} - Number of indexes removed.
   */
  indexesRemoved() {
    return this._stats.indexesRemoved;
  }

  /**
   * @return {Number} - Number of contraints added.
   */
  constraintsAdded() {
    return this._stats.constraintsAdded;
  }

  /**
   * @return {Number} - Number of contraints removed.
   */
  constraintsRemoved() {
    return this._stats.constraintsRemoved;
  }
}

/**
  * Class for Cypher notifications
  * @access public
  */
class Notification {
  /**
   * Create a Notification instance
   * @constructor
   * @param {Object} notification - Object with notification data
   */
  constructor(notification) {
    this.code = notification.code;
    this.title = notification.title;
    this.description = notification.desciption;
    this.position = this._constructPosition(notification.position);
  }

  _constructPosition(pos) {
    if(!pos) {
      return {};
    }
    return {
      offset: pos.offset.toInt(),
      line: pos.line.toInt(),
      column: pos.column.toInt()
    }
  }
}

const statementType = {
  READ_ONLY: 'r',
  READ_WRITE: 'rw',
  WRITE_ONLY: 'w',
  SCHEMA_WRITE: 's'
}

export default {
  ResultSummary,
  statementType
}
<commit_msg>Fixed typos<commit_after>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {int, isInt} from './integer';

/**
  * A ResultSummary instance contains structured metadata for a {Result}.
  * @access public
  */
class ResultSummary {
  /**
   * @constructor
   * @param {string} statement - The statement this summary is for
   * @param {Object} parameters - Parameters for the statement
   * @param {Object} metadata - Statement metadata
   */
  constructor(statement, parameters, metadata) {
    this.statement = {text: statement, parameters};
    this.statementType = metadata.type;
    this.updateStatistics = new StatementStatistics(metadata.stats || {});
    this.plan = metadata.plan || metadata.profile ? new Plan(metadata.plan || metadata.profile) : false;
    this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false;
    this.notifications = this._buildNotifications(metadata.notifications);
  }

  _buildNotifications(notifications) {
    if(!notifications) {
      return [];
    }
    return notifications.map(function(n) { return new Notification(n) });
  }

  /**
   * Check if the result summary has a plan
   * @return {boolean}
   */
  hasPlan() {
    return this.plan instanceof Plan
  }

  /**
   * Check if the result summary has a profile
   * @return {boolean}
   */
  hasProfile() {
    return this.profile instanceof ProfiledPlan
  }
}

/**
  * Class for execution plan received by prepending Cypher with EXPLAIN.
  * @access public
  */
class Plan {
  /**
   * Create a Plan instance
   * @constructor
   * @param {Object} plan - Object with plan data
   */
  constructor(plan) {
    this.operatorType = plan.operatorType;
    this.identifiers = plan.identifiers;
    this.arguments = plan.args;
    this.children = plan.children ? plan.children.map((child) => new Plan(child)) : [];
  }
}

/**
  * Class for execution plan received by prepending Cypher with PROFILE.
  * @access public
  */
class ProfiledPlan {
  /**
   * Create a ProfiledPlan instance
   * @constructor
   * @param {Object} plan - Object with plan data
   */
  constructor(profile) {
    this.operatorType = profile.operatorType;
    this.identifiers = profile.identifiers;
    this.arguments = profile.args;
    this.dbHits = profile.args.DbHits.toInt();
    this.rows = profile.args.Rows.toInt();
    this.children = profile.children ? profile.children.map((child) => new ProfiledPlan(child)) : [];
  }
}

/**
  * Get statistical information for a {Result}.
  * @access public
  */
class StatementStatistics {
  /**
   * Structurize the statistics
   * @constructor
   * @param {Object} statistics - Result statistics
   */
  constructor(statistics) {
    this._stats = {
      nodesCreated: 0,
      nodesDeleted: 0,
      relationshipsCreated: 0,
      relationshipsDeleted: 0,
      propertiesSet: 0,
      labelsAdded: 0,
      labelsRemoved: 0,
      indexesAdded: 0,
      indexesRemoved: 0,
      constraintsAdded: 0,
      constraintsRemoved: 0
    };
    Object.keys(statistics).forEach((index) => {
      //To camelCase
      this._stats[index.replace(/(\-\w)/g, (m) => m[1].toUpperCase())] =
        isInt(statistics[index]) ? statistics[index].toInt() : statistics[index];
    });
  }

  /**
   * Did the database get updated?
   * @return {boolean}
   */
  containsUpdates() {
    return Object.keys(this._stats).reduce((last, current) => {
      return last + this._stats[current];
    }, 0) > 0;
  }

  /**
   * @return {Number} - Number of nodes created.
   */
  nodesCreated() {
    return this._stats.nodesCreated;
  }

  /**
   * @return {Number} - Number of nodes deleted.
   */
  nodesDeleted() {
    return this._stats.nodesDeleted;
  }

  /**
   * @return {Number} - Number of relationships created.
   */
  relationshipsCreated() {
    return this._stats.relationshipsCreated;
  }

  /**
   * @return {Number} - Number of nodes deleted.
   */
  relationshipsDeleted() {
    return this._stats.relationshipsDeleted;
  }

  /**
   * @return {Number} - Number of properties set.
   */
  propertiesSet() {
    return this._stats.propertiesSet;
  }

  /**
   * @return {Number} - Number of labels added.
   */
  labelsAdded() {
    return this._stats.labelsAdded;
  }

  /**
   * @return {Number} - Number of labels removed.
   */
  labelsRemoved() {
    return this._stats.labelsRemoved;
  }

  /**
   * @return {Number} - Number of indexes added.
   */
  indexesAdded() {
    return this._stats.indexesAdded;
  }

  /**
   * @return {Number} - Number of indexes removed.
   */
  indexesRemoved() {
    return this._stats.indexesRemoved;
  }

  /**
   * @return {Number} - Number of contraints added.
   */
  constraintsAdded() {
    return this._stats.constraintsAdded;
  }

  /**
   * @return {Number} - Number of contraints removed.
   */
  constraintsRemoved() {
    return this._stats.constraintsRemoved;
  }
}

/**
  * Class for Cypher notifications
  * @access public
  */
class Notification {
  /**
   * Create a Notification instance
   * @constructor
   * @param {Object} notification - Object with notification data
   */
  constructor(notification) {
    this.code = notification.code;
    this.title = notification.title;
    this.description = notification.description;
    this.position = this._constructPosition(notification.position);
  }

  _constructPosition(pos) {
    if(!pos) {
      return {};
    }
    return {
      offset: pos.offset.toInt(),
      line: pos.line.toInt(),
      column: pos.column.toInt()
    }
  }
}

const statementType = {
  READ_ONLY: 'r',
  READ_WRITE: 'rw',
  WRITE_ONLY: 'w',
  SCHEMA_WRITE: 's'
}

export default {
  ResultSummary,
  statementType
}
<|endoftext|>


<commit_before>//
// パズル固有スクリプト部 島国・チョコナ・ストストーン版 shimaguni.js
//
(function(pidlist, classbase){
	if(typeof module==='object' && module.exports){module.exports = [pidlist, classbase];}
	else{ pzpr.classmgr.makeCustom(pidlist, classbase);}
}(
['shimaguni','chocona','stostone'], {
//---------------------------------------------------------
// マウス入力系
MouseEvent:{
	use : true,

	mouseinput : function(){
		if(this.puzzle.playmode){
			if(this.mousestart || this.mousemove){ this.inputcell();}
		}
		else if(this.puzzle.editmode){
			if(this.mousestart || this.mousemove){ this.inputborder();}
			else if(this.mouseend && this.notInputted()){ this.inputqnum();}
		}
	}
},

//---------------------------------------------------------
// キーボード入力系
KeyEvent:{
	enablemake : true
},

//---------------------------------------------------------
// 盤面管理系
Cell:{
	maxnum : function(){
		return Math.min(255, this.room.clist.length);
	}
},
"Cell@chocona":{
	minnum : 0
},
"Cell@stostone":{
	getFallableLength : function(isdrop){
		if(!this.base.sblk){ return 0;}
		var cell2 = this, len = 0, move = ((isdrop!==false) ? 2 : -2);
		while(!cell2.isnull){
			cell2 = cell2.relcell(0,move);
			if(cell2.isnull || (!!cell2.base.sblk && this.base.sblk!==cell2.base.sblk)){ break;}
			len++;
		}
		return len;
	}
},

Board:{
	hasborder : 1
},
"Board@stostone":{
	cols : 8,
	rows : 8,

	falling : false,

	initBoardSize : function(col,row){
		this.common.initBoardSize.call(this,col,row);
		this.falling = false;
	},
	errclear : function(){
		this.falling = false;
		this.common.errclear.call(this);
	},
	operate : function(type){
		switch(type){
		case 'drop':
		case 'raise':
			this.drop(type==='drop');
			this.falling = true;
			this.haserror = true;
			this.puzzle.redraw();
			break;
		case 'resetpos':
			this.resetpos();
			this.board.errclear();
			break;
		default:
			this.common.operate.call(this,type);
			break;
		}
	},
	resetpos : function(){
		for(var i=0;i<this.cell.length;i++){
			var cell = this.cell[i];
			cell.base = cell.destination = (cell.isShade() ? cell : this.emptycell);
		}
	},
	drop : function(isdrop){
		this.resetpos();
		var fallable = true, blks = this.sblkmgr.components;
		while(fallable){
			fallable = false;
			for(var n=blks.length-1;n>=0;--n){
				var length = blks[n].clist.fall(isdrop);
				if(length>0){ fallable = true;}
			}
		}
	}
},

CellList:{
	getLandAreaOfClist : function(){
		var cnt = 0;
		for(var i=0,len=this.length;i<len;i++){
			if(this[i].isShade()){ cnt++;}
		}
		return cnt;
	},

	isSeqBlock : function(){
		var stack=(this.length>0?[this[0]]:[]), count=this.length, passed={};
		for(var i=0;i<count;i++){ passed[this[i].id]=0;}
		while(stack.length>0){
			var cell=stack.pop();
			if(passed[cell.id]===1){ continue;}
			count--;
			passed[cell.id]=1;
			var list = cell.getdir4clist();
			for(var i=0;i<list.length;i++){
				if(passed[list[i][0].id]===0){ stack.push(list[i][0]);}
			}
		}
		return (count===0);
	}
},
"CellList@stostone":{
	fall : function(isdrop){
		var length = this.board.rows, move = ((isdrop!==false) ? 2 : -2);
		for(var i=0;i<this.length;i++){
			if(this[i].sblk===this[i].relcell(0,move).sblk){ continue;} // Skip if the block also contains bottom neighbor cell
			var len = this[i].destination.getFallableLength(isdrop);
			if(length>len){ length = len;}
			if(length===0){ return 0;}
		}
		var totallen = length + (Math.abs(this[0].destination.by - this[0].by)>>1);
		for(var i=0;i<this.length;i++){
			this[i].destination.base = this.board.emptycell;
		}
		for(var i=0;i<this.length;i++){
			var newcell = this[i].relcell(0,move*totallen);
			this[i].destination = newcell;
			newcell.base = this[i];
		}
		return length;
	}
},

AreaShadeGraph:{
	enabled : true
},
AreaRoomGraph:{
	enabled : true,
	hastop : true
},

//---------------------------------------------------------
// 画像表示系
Graphic:{
	gridcolor_type : "LIGHT",

	enablebcolor : true,
	bgcellcolor_func : "qsub1",

	paint : function(){
		this.drawBGCells();
		this.drawGrid();
		if(this.pid==='stostone'){ this.drawDotCells();}
		this.drawShadedCells();

		this.drawNumbers();

		this.drawBorders();

		this.drawChassis();

		this.drawBoxBorders(false);

		this.drawTarget();
	}
},
"Graphic@shimaguni":{
	bcolor : "rgb(191, 191, 255)"
},
"Graphic@stostone":{
	irowakeblk : true,
	enablebcolor : false,
	bgcellcolor_func : "error1",

	minYdeg : 0.08,
	maxYdeg : 0.50,

	getShadedCellColor : function(cell){
		var cell0 = cell;
		if(this.board.falling){ cell = cell.base;}
		if(cell.qans!==1){ return null;}
		var info = cell0.error || cell0.qinfo;
		if     (info===1){ return this.errcolor1;}
		else if(info===2){ return this.errcolor2;}
		else if(cell.trial){ return this.trialcolor;}
		else if(this.puzzle.execConfig('irowakeblk')){ return cell.sblk.color;}
		return this.shadecolor;
	},
	getBorderColor : function(border){
		if(this.board.falling){
			var sblk1 = border.sidecell[0].base.sblk;
			var sblk2 = border.sidecell[1].base.sblk;
			if(!!sblk1 && !!sblk2 && sblk1!==sblk2){ return "white";}
			else if(!!sblk1 || !!sblk2){ return null;}
		}
		if(border.isBorder()){ return this.quescolor;}
		return null;
	},
	getNumberColor : function(cell){
		if(this.board.falling){ cell = cell.base;}
		return this.common.getNumberColor_mixed.call(this,cell);
	}
},

//---------------------------------------------------------
// URLエンコード/デコード処理
Encode:{
	decodePzpr : function(type){
		this.decodeBorder();
		this.decodeRoomNumber16();
	},
	encodePzpr : function(type){
		this.encodeBorder();
		this.encodeRoomNumber16();
	}
},
//---------------------------------------------------------
FileIO:{
	decodeData : function(){
		this.decodeAreaRoom();
		this.decodeCellQnum();
		this.decodeCellAns();
	},
	encodeData : function(){
		this.encodeAreaRoom();
		this.encodeCellQnum();
		this.encodeCellAns();
	}
},

//---------------------------------------------------------
// 正解判定処理実行部
"AnsCheck@shimaguni,stostone#1":{
	checklist : [
		"checkSideAreaShadeCell",
		"checkSeqBlocksInRoom",
		"checkFallenBlock@stostone",
		"checkShadeCellCount",
		"checkSideAreaLandSide@shimaguni",
		"checkRemainingSpace@stostone",
		"checkNoShadeCellInArea"
	]
},
"AnsCheck@chocona#1":{
	checklist : [
		"checkShadeCellExist",
		"checkShadeRect",
		"checkShadeCellCount"
	]
},
"AnsCheck@shimaguni,stostone":{
	checkSideAreaShadeCell : function(){
		this.checkSideAreaCell(function(cell1,cell2){ return (cell1.isShade() && cell2.isShade());}, true, "cbShade");
	},
	checkSideAreaLandSide : function(){
		this.checkSideAreaSize(function(area){ return area.clist.getLandAreaOfClist();}, "bsEqShade");
	},

	// 部屋の中限定で、黒マスがひとつながりかどうか判定する
	checkSeqBlocksInRoom : function(){
		var rooms = this.board.roommgr.components;
		for(var r=0;r<rooms.length;r++){
			var clist = rooms[r].clist.filter(function(cell){ return cell.isShade();});
			if(clist.isSeqBlock()){ continue;}

			this.failcode.add("bkShadeDivide");
			if(this.checkOnly){ break;}
			clist.seterr(1);
		}
	}
},
"AnsCheck@stostone":{
	checkAns : function(break_if_error){
		this.board.drop();
		this.common.checkAns.call(this,break_if_error);
	},
	checkFallenBlock : function(){
		var bd = this.board;
		for(var c=0;c<bd.cell.length;c++){
			var cell = bd.cell[c];
			if(cell.by>bd.maxby/2 || cell.base.isnull){ continue;}

			this.failcode.add("csUpper");
			if(this.checkOnly){ break;}
			bd.falling = true;
			cell.seterr(1);
		}
	},
	checkRemainingSpace : function(){
		var bd = this.board;
		for(var c=0;c<bd.cell.length;c++){
			var cell = bd.cell[c];
			if(cell.by<bd.maxby/2 || !cell.base.isnull){ continue;}

			this.failcode.add("cuLower");
			if(this.checkOnly){ break;}
			bd.falling = true;
			if(cell.base.isnull){ cell.seterr(1);}
		}
	}
},
"AnsCheck@chocona":{
	checkShadeRect : function(){
		this.checkAllArea(this.board.sblkmgr, function(w,h,a,n){ return (w*h===a);}, "csNotRect");
	}
},

"FailCode@shimaguni,stostone":{
	bkShadeNe     : ["海域内の数字と国のマス数が一致していません。","The number of shaded cells is not equals to the number."],
	bkShadeDivide : ["1つの海域に入る国が2つ以上に分裂しています。","Countries in one marine area are divided to plural ones."],
	bkNoShade     : ["黒マスのカタマリがない海域があります。","A marine area has no shaded cells."],
	cbShade       : ["異なる海域にある国どうしが辺を共有しています。","Countries in other marine area share the side over border line."],
	bsEqShade     : ["隣り合う海域にある国の大きさが同じです。","The size of countries that there are in adjacent marine areas are the same."]
},

"FailCode@chocona":{
	csNotRect : ["黒マスのカタマリが正方形か長方形ではありません。","A mass of shaded cells is not rectangle."],
	bkShadeNe : ["数字のある領域と、領域の中にある黒マスの数が違います。","The number of shaded cells in the area and the number written in the area is different."]
},

"FailCode@stostone":{
	cbShade : ["異なる領域にある黒マスどうしが辺を共有しています。","Shade cell blocks in other region are adjacent over border line."],
	csUpper : ["ブロックを落とした後に黒マスが盤面の上半分に残っています。","Shaded cells are remained in upper half of the board after they are fallen."],
	cuLower : ["ブロックを落とした後の空間が盤面の下半分にあります。","Unshaded cells exist in lower half of the board after blocks are fallen."]
}
}));
<commit_msg>stostone: Fix the shape of the blocks when they are moving<commit_after>//
// パズル固有スクリプト部 島国・チョコナ・ストストーン版 shimaguni.js
//
(function(pidlist, classbase){
	if(typeof module==='object' && module.exports){module.exports = [pidlist, classbase];}
	else{ pzpr.classmgr.makeCustom(pidlist, classbase);}
}(
['shimaguni','chocona','stostone'], {
//---------------------------------------------------------
// マウス入力系
MouseEvent:{
	use : true,

	mouseinput : function(){
		if(this.puzzle.playmode){
			if(this.mousestart || this.mousemove){ this.inputcell();}
		}
		else if(this.puzzle.editmode){
			if(this.mousestart || this.mousemove){ this.inputborder();}
			else if(this.mouseend && this.notInputted()){ this.inputqnum();}
		}
	}
},

//---------------------------------------------------------
// キーボード入力系
KeyEvent:{
	enablemake : true
},

//---------------------------------------------------------
// 盤面管理系
Cell:{
	maxnum : function(){
		return Math.min(255, this.room.clist.length);
	}
},
"Cell@chocona":{
	minnum : 0
},
"Cell@stostone":{
	getFallableLength : function(isdrop){
		if(!this.base.sblk){ return 0;}
		var cell2 = this, len = 0, move = ((isdrop!==false) ? 2 : -2);
		while(!cell2.isnull){
			cell2 = cell2.relcell(0,move);
			if(cell2.isnull || (!!cell2.base.sblk && this.base.sblk!==cell2.base.sblk)){ break;}
			len++;
		}
		return len;
	}
},

Board:{
	hasborder : 1
},
"Board@stostone":{
	cols : 8,
	rows : 8,

	falling : false,

	initBoardSize : function(col,row){
		this.common.initBoardSize.call(this,col,row);
		this.falling = false;
	},
	errclear : function(){
		this.falling = false;
		this.common.errclear.call(this);
	},
	operate : function(type){
		switch(type){
		case 'drop':
		case 'raise':
			this.drop(type==='drop');
			this.falling = true;
			this.haserror = true;
			this.puzzle.redraw();
			break;
		case 'resetpos':
			this.resetpos();
			this.board.errclear();
			break;
		default:
			this.common.operate.call(this,type);
			break;
		}
	},
	resetpos : function(){
		for(var i=0;i<this.cell.length;i++){
			var cell = this.cell[i];
			cell.base = cell.destination = (cell.isShade() ? cell : this.emptycell);
		}
	},
	drop : function(isdrop){
		this.resetpos();
		var fallable = true, blks = this.sblkmgr.components;
		while(fallable){
			fallable = false;
			for(var n=blks.length-1;n>=0;--n){
				var length = blks[n].clist.fall(isdrop);
				if(length>0){ fallable = true;}
			}
		}
	}
},

CellList:{
	getLandAreaOfClist : function(){
		var cnt = 0;
		for(var i=0,len=this.length;i<len;i++){
			if(this[i].isShade()){ cnt++;}
		}
		return cnt;
	},

	isSeqBlock : function(){
		var stack=(this.length>0?[this[0]]:[]), count=this.length, passed={};
		for(var i=0;i<count;i++){ passed[this[i].id]=0;}
		while(stack.length>0){
			var cell=stack.pop();
			if(passed[cell.id]===1){ continue;}
			count--;
			passed[cell.id]=1;
			var list = cell.getdir4clist();
			for(var i=0;i<list.length;i++){
				if(passed[list[i][0].id]===0){ stack.push(list[i][0]);}
			}
		}
		return (count===0);
	}
},
"CellList@stostone":{
	fall : function(isdrop){
		var length = this.board.rows, move = ((isdrop!==false) ? 2 : -2);
		for(var i=0;i<this.length;i++){
			if(this[i].sblk===this[i].relcell(0,move).sblk){ continue;} // Skip if the block also contains bottom neighbor cell
			var len = this[i].destination.getFallableLength(isdrop);
			if(length>len){ length = len;}
			if(length===0){ return 0;}
		}
		var totallen = length + (Math.abs(this[0].destination.by - this[0].by)>>1);
		for(var i=0;i<this.length;i++){
			this[i].destination.base = this.board.emptycell;
		}
		for(var i=0;i<this.length;i++){
			var newcell = this[i].relcell(0,move*totallen);
			this[i].destination = newcell;
			newcell.base = this[i];
		}
		return length;
	}
},

AreaShadeGraph:{
	enabled : true
},
AreaRoomGraph:{
	enabled : true,
	hastop : true
},

//---------------------------------------------------------
// 画像表示系
Graphic:{
	gridcolor_type : "LIGHT",

	enablebcolor : true,
	bgcellcolor_func : "qsub1",

	paint : function(){
		this.drawBGCells();
		this.drawGrid();
		if(this.pid==='stostone'){ this.drawDotCells();}
		this.drawShadedCells();

		this.drawNumbers();

		this.drawBorders();

		this.drawChassis();

		this.drawBoxBorders(false);

		this.drawTarget();
	}
},
"Graphic@shimaguni":{
	bcolor : "rgb(191, 191, 255)"
},
"Graphic@stostone":{
	irowakeblk : true,
	enablebcolor : false,
	bgcellcolor_func : "error1",

	minYdeg : 0.08,
	maxYdeg : 0.50,

	getShadedCellColor : function(cell){
		var cell0 = cell;
		if(this.board.falling){ cell = cell.base;}
		if(cell.qans!==1){ return null;}
		var info = cell0.error || cell0.qinfo;
		if     (info===1){ return this.errcolor1;}
		else if(info===2){ return this.errcolor2;}
		else if(cell.trial){ return this.trialcolor;}
		else if(this.puzzle.execConfig('irowakeblk')){ return cell.sblk.color;}
		return this.shadecolor;
	},
	getBorderColor : function(border){
		if(this.board.falling){
			var sblk1 = border.sidecell[0].base.sblk;
			var sblk2 = border.sidecell[1].base.sblk;
			if(sblk1!==sblk2){ return "white";}
			else if(!!sblk1 || !!sblk2){ return null;}
		}
		if(border.isBorder()){ return this.quescolor;}
		return null;
	},
	getNumberColor : function(cell){
		if(this.board.falling){ cell = cell.base;}
		return this.common.getNumberColor_mixed.call(this,cell);
	}
},

//---------------------------------------------------------
// URLエンコード/デコード処理
Encode:{
	decodePzpr : function(type){
		this.decodeBorder();
		this.decodeRoomNumber16();
	},
	encodePzpr : function(type){
		this.encodeBorder();
		this.encodeRoomNumber16();
	}
},
//---------------------------------------------------------
FileIO:{
	decodeData : function(){
		this.decodeAreaRoom();
		this.decodeCellQnum();
		this.decodeCellAns();
	},
	encodeData : function(){
		this.encodeAreaRoom();
		this.encodeCellQnum();
		this.encodeCellAns();
	}
},

//---------------------------------------------------------
// 正解判定処理実行部
"AnsCheck@shimaguni,stostone#1":{
	checklist : [
		"checkSideAreaShadeCell",
		"checkSeqBlocksInRoom",
		"checkFallenBlock@stostone",
		"checkShadeCellCount",
		"checkSideAreaLandSide@shimaguni",
		"checkRemainingSpace@stostone",
		"checkNoShadeCellInArea"
	]
},
"AnsCheck@chocona#1":{
	checklist : [
		"checkShadeCellExist",
		"checkShadeRect",
		"checkShadeCellCount"
	]
},
"AnsCheck@shimaguni,stostone":{
	checkSideAreaShadeCell : function(){
		this.checkSideAreaCell(function(cell1,cell2){ return (cell1.isShade() && cell2.isShade());}, true, "cbShade");
	},
	checkSideAreaLandSide : function(){
		this.checkSideAreaSize(function(area){ return area.clist.getLandAreaOfClist();}, "bsEqShade");
	},

	// 部屋の中限定で、黒マスがひとつながりかどうか判定する
	checkSeqBlocksInRoom : function(){
		var rooms = this.board.roommgr.components;
		for(var r=0;r<rooms.length;r++){
			var clist = rooms[r].clist.filter(function(cell){ return cell.isShade();});
			if(clist.isSeqBlock()){ continue;}

			this.failcode.add("bkShadeDivide");
			if(this.checkOnly){ break;}
			clist.seterr(1);
		}
	}
},
"AnsCheck@stostone":{
	checkAns : function(break_if_error){
		this.board.drop();
		this.common.checkAns.call(this,break_if_error);
	},
	checkFallenBlock : function(){
		var bd = this.board;
		for(var c=0;c<bd.cell.length;c++){
			var cell = bd.cell[c];
			if(cell.by>bd.maxby/2 || cell.base.isnull){ continue;}

			this.failcode.add("csUpper");
			if(this.checkOnly){ break;}
			bd.falling = true;
			cell.seterr(1);
		}
	},
	checkRemainingSpace : function(){
		var bd = this.board;
		for(var c=0;c<bd.cell.length;c++){
			var cell = bd.cell[c];
			if(cell.by<bd.maxby/2 || !cell.base.isnull){ continue;}

			this.failcode.add("cuLower");
			if(this.checkOnly){ break;}
			bd.falling = true;
			if(cell.base.isnull){ cell.seterr(1);}
		}
	}
},
"AnsCheck@chocona":{
	checkShadeRect : function(){
		this.checkAllArea(this.board.sblkmgr, function(w,h,a,n){ return (w*h===a);}, "csNotRect");
	}
},

"FailCode@shimaguni,stostone":{
	bkShadeNe     : ["海域内の数字と国のマス数が一致していません。","The number of shaded cells is not equals to the number."],
	bkShadeDivide : ["1つの海域に入る国が2つ以上に分裂しています。","Countries in one marine area are divided to plural ones."],
	bkNoShade     : ["黒マスのカタマリがない海域があります。","A marine area has no shaded cells."],
	cbShade       : ["異なる海域にある国どうしが辺を共有しています。","Countries in other marine area share the side over border line."],
	bsEqShade     : ["隣り合う海域にある国の大きさが同じです。","The size of countries that there are in adjacent marine areas are the same."]
},

"FailCode@chocona":{
	csNotRect : ["黒マスのカタマリが正方形か長方形ではありません。","A mass of shaded cells is not rectangle."],
	bkShadeNe : ["数字のある領域と、領域の中にある黒マスの数が違います。","The number of shaded cells in the area and the number written in the area is different."]
},

"FailCode@stostone":{
	cbShade : ["異なる領域にある黒マスどうしが辺を共有しています。","Shade cell blocks in other region are adjacent over border line."],
	csUpper : ["ブロックを落とした後に黒マスが盤面の上半分に残っています。","Shaded cells are remained in upper half of the board after they are fallen."],
	cuLower : ["ブロックを落とした後の空間が盤面の下半分にあります。","Unshaded cells exist in lower half of the board after blocks are fallen."]
}
}));
<|endoftext|>


<commit_before>'use strict';

describe("Directives: Currency", function() {

  var element;
  var $scope;
  var form;

  beforeEach(module('mortgageCalculatorApp'));

  beforeEach(inject(function($compile, $rootScope){
    $scope = $rootScope;
    element = angular.element(
      '<form name="form">' +
        '<input type="text" name="annualIncome" ng-model="model.annualIncome" currency data-a-sign="£">' +
      '</form>'
    );
    $scope.model = { annualIncome: null};
    $compile(element)($scope);
    $scope.$digest();
    form = $scope.form;
  }));

  it('should be valid initially', function() {
    expect(form.annualIncome.$valid).toBe(true);
  });

  it('element should be initially empty', function() {
    expect(element.find('input').val()).toBe('');
  });

  it('sets the view value to the correct format', function() {
    form.annualIncome.$setViewValue('£30,000.00');
    expect(form.annualIncome.$viewValue).toBe('£30,000.00');
  });

  it('converts input values to integer types', function() {
    form.annualIncome.$setViewValue('£30,000.00');
    expect($scope.model.annualIncome).toEqual(30000);
    expect(form.annualIncome.$valid).toBe(true);
  });

});

<commit_msg>fix build: pend wip test<commit_after>'use strict';

describe("Directives: Currency", function() {

  var element;
  var $scope;
  var form;

  beforeEach(module('mortgageCalculatorApp'));

  beforeEach(inject(function($compile, $rootScope){
    $scope = $rootScope;
    element = angular.element(
      '<form name="form">' +
        '<input type="text" name="annualIncome" ng-model="model.annualIncome" currency data-a-sign="£">' +
      '</form>'
    );
    $scope.model = { annualIncome: null};
    $compile(element)($scope);
    $scope.$digest();
    form = $scope.form;
  }));

  it('should be valid initially', function() {
    expect(form.annualIncome.$valid).toBe(true);
  });

  xit('element should be initially empty', function() {
    expect(element.find('input').val()).toBe('');
  });

  it('sets the view value to the correct format', function() {
    form.annualIncome.$setViewValue('£30,000.00');
    expect(form.annualIncome.$viewValue).toBe('£30,000.00');
  });

  it('converts input values to integer types', function() {
    form.annualIncome.$setViewValue('£30,000.00');
    expect($scope.model.annualIncome).toEqual(30000);
    expect(form.annualIncome.$valid).toBe(true);
  });

});

<|endoftext|>


<commit_before>/**
 * Created by sebastian.kaim on 26.04.2016.
 */
"use strict";

(function ($) {

    // dot helper class
    var dot = function (_x, _y, _text) {
        this.x = _x;
        this.y = _y;
        this.text = _text;
        this.radius = 16; // hover event radius

        this.render = function (context) {
            context.beginPath();
            context.arc(this.x, this.y, 4, 0, Math.PI * 2, true);
            context.fill();
        };
    };

    // register the plugin
    $.fn.dotHover = function (dots, options) {

        // settings
        var settings = $.extend({
            // defaults
            img: "karte.png", //$('#example.jpg').first(),
            dots: [],
            width: "100px",
            height: "100px",
            setmode: true
        }, options );

        //
        // create tooltip canvas
        //
        var tooltip = $('<canvas/>')
            .appendTo('body')
            .addClass('hoverDotTooltip')
            .hide();
        var tooltipctx = tooltip.get(0).getContext('2d');
        tooltipctx.font = "30px Arial";

        var contexts = [];

        //
        // handle tooltip positioning on mouse move
        //
        var mouseMoveEvent = function(event, img, offsetX, offsetY) {
            var mouseX = parseInt(event.clientX - offsetX);
            var mouseY = parseInt(event.clientY - offsetY);

            var hit = false;
            for (var i = 0; i < settings.dots.length; i++) {
                var dot = settings.dots[i];
                var dx = mouseX - dot.x;
                var dy = mouseY - dot.y;

                if (dx * dx + dy * dy < dot.radius) {
                    tooltip.get(0).style.top = (dot.y - 40) + "px";
                    tooltip.get(0).style.left = (dot.x) + "px";

                    tooltipctx.clearRect(0, 0, tooltip.width, tooltip.height);
                    tooltipctx.fillText(dot.text, 10, 30);
                    hit = true;
                }
            }

            if(hit) tooltip.show(); else tooltip.hide();
        };

        // re-renders all dots
        var render = function () {
            $.each(contexts, function (i, ctx) {
                $.each(settings.dots, function (j, dot) {
                    dot.render(ctx);
                });
            });
        };

        //
        // places a new dot
        //
        var placedot = function (e) {
            settings.dots.push(new dot(e.clientX, e.clientY, "Example Text"));
            render();
        };

        // init mouse move on each element
        this.each(function(i, el) {
            el.style= 'background: url(' + settings.img + ');' +
            'background-repeat: no-repeat; ' +
            'background-size: contain;' +
            'width: ' + settings.width + '; ';
            //'height: ' + settings.height + '; '

            contexts.push(el.getContext('2d'));

            $(el).mousemove (function (event) {
                mouseMoveEvent(event, el, el.offsetLeft, el.offsetTop);
            });

            if(settings.setmode) $(el).click(placedot);
        });

        return this;
    };

})(jQuery);
<commit_msg>renamed settings<commit_after>/**
 * Created by sebastian.kaim on 26.04.2016.
 */
"use strict";

(function ($) {

    // dot helper class
    var dot = function (_x, _y, _text) {
        this.x = _x;
        this.y = _y;
        this.text = _text;
        this.radius = 16; // hover event radius

        this.render = function (context) {
            context.beginPath();
            context.arc(this.x, this.y, 4, 0, Math.PI * 2, true);
            context.fill();
        };
    };

    // register the plugin
    $.fn.dotHover = function (dots, options) {

        // settings
        this.settings = $.extend({
            // defaults
            img: "karte.png", //$('#example.jpg').first(),
            dots: [],
            width: "100px",
            height: "100px",
            setmode: true
        }, options );

        //
        // create tooltip canvas
        //
        var tooltip = $('<canvas/>')
            .appendTo('body')
            .addClass('hoverDotTooltip')
            .hide();
        var tooltipctx = tooltip.get(0).getContext('2d');
        tooltipctx.font = "30px Arial";

        var contexts = [];

        //
        // handle tooltip positioning on mouse move
        //
        var mouseMoveEvent = function(event, img, offsetX, offsetY) {
            var mouseX = parseInt(event.clientX - offsetX);
            var mouseY = parseInt(event.clientY - offsetY);

            var hit = false;
            for (var i = 0; i < settings.dots.length; i++) {
                var dot = this.settings.dots[i];
                var dx = mouseX - dot.x;
                var dy = mouseY - dot.y;

                if (dx * dx + dy * dy < dot.radius) {
                    tooltip.get(0).style.top = (dot.y - 40) + "px";
                    tooltip.get(0).style.left = (dot.x) + "px";

                    tooltipctx.clearRect(0, 0, tooltip.width, tooltip.height);
                    tooltipctx.fillText(dot.text, 10, 30);
                    hit = true;
                }
            }

            if(hit) tooltip.show(); else tooltip.hide();
        };

        // re-renders all dots
        var render = function () {
            $.each(contexts, function (i, ctx) {
                $.each(this.settings.dots, function (j, dot) {
                    dot.render(ctx);
                });
            });
        };

        //
        // places a new dot
        //
        var placedot = function (e) {
            this.settings.dots.push(new dot(e.clientX, e.clientY, "Example Text"));
            render();
        };

        // init mouse move on each element
        this.each(function(i, el) {
            el.style= 'background: url(' + this.settings.img + ');' +
            'background-repeat: no-repeat; ' +
            'background-size: contain;' +
            'width: ' + this.settings.width + '; ';
            //'height: ' + settings.height + '; '

            contexts.push(el.getContext('2d'));

            $(el).mousemove (function (event) {
                mouseMoveEvent(event, el, el.offsetLeft, el.offsetTop);
            });

            if(this.settings.setmode) $(el).click(placedot);
        });

        return this;
    };

})(jQuery);
<|endoftext|>


<commit_before>function createBookmarkletHref (name) {
  var baseURI = document.baseURI;
  var bookmarklet = "window.a11y" + name;
  var scriptname = name.toLowerCase() + '.js';
  return "javascript:if(" + bookmarklet + ")" + bookmarklet + ".run();else{(function(){var%20link=document.createElement('link');link.rel='stylesheet';link.type='text/css';link.href='" + baseURI + "build/styles.css';document.getElementsByTagName('head')[0].appendChild(link);var%20script=document.createElement('script');script.type='text/javascript';script.src='" + baseURI + "build/" + scriptname + "';document.getElementsByTagName('head')[0].appendChild(script);})();}";
}
<commit_msg>Replace http with https for specified domains<commit_after>function createBookmarkletHref (name) {
  var bookmarklet = "window.a11y" + name;
  var scriptname = name.toLowerCase() + '.js';

  var baseURI = document.baseURI;
  var baseURIArray = baseURI.split('/');
  var protocol = baseURIArray[0];
  var domain = baseURIArray[2];
  if (domain === 'accessibility-bookmarklets.org' || domain === 'oaa-tools.github.io' || domain === 'nhoyt.com') {
    if (protocol === 'http') baseURI = baseURI.replace(/http/, 'https');
  }
  return "javascript:if(" + bookmarklet + ")" + bookmarklet + ".run();else{(function(){var%20link=document.createElement('link');link.rel='stylesheet';link.type='text/css';link.href='" + baseURI + "build/styles.css';document.getElementsByTagName('head')[0].appendChild(link);var%20script=document.createElement('script');script.type='text/javascript';script.src='" + baseURI + "build/" + scriptname + "';document.getElementsByTagName('head')[0].appendChild(script);})();}";
}
<|endoftext|>


<commit_before>import { moduleForComponent } from 'ember-qunit';
import { skip } from 'qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('curriculum-inventory-sequence-block-details', 'Integration | Component | curriculum inventory sequence block details', {
  integration: true
});

skip('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{curriculum-inventory-sequence-block-details}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#curriculum-inventory-sequence-block-details}}
      template block text
    {{/curriculum-inventory-sequence-block-details}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});
<commit_msg>added integration test for ci seq block details component.<commit_after>import Ember from 'ember';
import { moduleForComponent } from 'ember-qunit';
import { test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
import moment from 'moment';
import tHelper from "ember-i18n/helper";

const { RSVP, Object } = Ember;
const { resolve } = RSVP;

moduleForComponent('curriculum-inventory-sequence-block-details', 'Integration | Component | curriculum inventory sequence block details', {
  integration: true,
  beforeEach: function() {
    this.container.lookup('service:i18n').set('locale', 'en');
    this.registry.register('helper:t', tHelper);
  }
});

test('it renders', function(assert) {
  assert.expect(7);

  let school = Object.create({ id() { return 1; }});

  let academicLevels = [];
  for (let i = 0; i < 10; i++) {
    academicLevels.pushObject(Object.create({ id: i, name: `Year ${i + 1}` }));
  }

  let program = Object.create({
    belongsTo() {
      return school;
    }
  });

  let report = Object.create({
    academicLevels,
    year: '2016',
    program: resolve(program),
    linkedCourses: resolve([]),
    isFinalized: resolve(false)
  });

  let grandParentBlock = Object.create({
    id: 1,
    title: 'Okely Dokely',
  });

  let parentBlock = Object.create({
    id: 2,
    title: 'Foo',
    parent: resolve(grandParentBlock)
  });

  grandParentBlock.set('children', resolve([ parentBlock ]));

  let academicLevel = academicLevels[0];

  let block = Object.create({
    id: 3,
    description: 'lorem ipsum',
    report: resolve(report),
    parent: resolve(parentBlock),
    sessions: resolve([]),
    duration: 12,
    startDate: moment('2015-01-02'),
    endDate: moment('2015-04-30'),
    childSequenceOrder: 1,
    orderInSequence: 1,
    course: resolve(null),
    required: 2,
    track: true,
    minimum: 2,
    maximum: 15,
    academicLevel: resolve(academicLevel),
    title: 'bar',
    allParents: resolve([ parentBlock, grandParentBlock ])
  });

  parentBlock.set('children', resolve([ block ]));

  this.set('report', report);
  this.set('sequenceBlock', block);
  this.set('sortBy', 'title');
  this.set('setSortSessionsBy', null);

  this.render(hbs`{{curriculum-inventory-sequence-block-details sequenceBlock=sequenceBlock sortSessionsBy=sortBy setSortSessionBy=(action (mut sortSessionsBy))}}
`);
  return wait().then(() => {
    assert.equal(this.$('.curriculum-inventory-sequence-block-header .title').text().trim(),
      block.get('title'), 'Block header is visible.');
    assert.equal(this.$('.curriculum-inventory-sequence-block-overview .description .editinplace').text().trim(),
      block.get('description'), 'Block overview is visible.');
    assert.equal(this.$('.breadcrumbs span').length, 4, 'Breadcrumb has the right number of elements');
    assert.equal(this.$('.breadcrumbs span:eq(0)').text().trim(), 'Curriculum Inventory Report');
    assert.equal(this.$('.breadcrumbs span:eq(1)').text().trim(), grandParentBlock.get('title'));
    assert.equal(this.$('.breadcrumbs span:eq(2)').text().trim(), parentBlock.get('title'));
    assert.equal(this.$('.breadcrumbs span:eq(3)').text().trim(), block.get('title'));
  });
});

<|endoftext|>


<commit_before>import isEmpty from 'lodash/isEmpty';
import { hasNetwork, getBoardBounds, playerName, oppositeColor, noNull } from '../../../utils';
import i18n from '../../../i18n';
import gameApi from '../../../lichess/game';
import gameStatusApi from '../../../lichess/status';
import continuePopup from '../../shared/continuePopup';
import { view as renderPromotion } from '../../shared/offlineRound/promotion';
import { connectingHeader, header, backButton as renderBackbutton, viewOnlyBoardContent } from '../../shared/common';
import Board from '../../shared/Board';
import helper from '../../helper';
import layout from '../../layout';
import notes from '../../round/notes';
import { formatClockTime } from '../../round/clock/clockView';
import importPgnPopup from '../importPgnPopup';
import control from '../control';
import menu from '../menu';
import analyseSettings from '../analyseSettings';
import { defined, renderEval, isSynthetic } from '../util';
import crazyView from '../crazy/crazyView';
import explorerView from '../explorer/explorerView';
import evalSummary from '../evalSummaryPopup';
import { renderTree } from './treeView';

export default function analyseView() {
  const ctrl = this;

  const isPortrait = helper.isPortrait();

  if (ctrl.data) {

    const backButton = ctrl.vm.shouldGoBack ? renderBackbutton(gameApi.title(ctrl.data)) : null;
    const title = ctrl.vm.shouldGoBack ? null : i18n('analysis');

    return layout.board(
      () => header(title, backButton),
      () => renderContent(ctrl, isPortrait),
      () => overlay(ctrl, isPortrait)
    );
  } else {
    return layout.board(
      connectingHeader,
      viewOnlyBoardContent
    );
  }
}

function overlay(ctrl) {
  return [
    renderPromotion(ctrl),
    menu.view(ctrl.menu),
    analyseSettings.view(ctrl.settings),
    ctrl.notes ? notes.view(ctrl.notes) : null,
    ctrl.evalSummary ? evalSummary.view(ctrl.evalSummary) : null,
    continuePopup.view(ctrl.continuePopup),
    importPgnPopup.view(ctrl.importPgnPopup)
  ];
}

function renderContent(ctrl, isPortrait) {
  const bounds = getBoardBounds(helper.viewportDim(), isPortrait, helper.isIpadLike(), helper.isLandscapeSmall(), 'analyse');
  const ceval = ctrl.vm.step && ctrl.vm.step.ceval;
  const rEval = ctrl.vm.step && ctrl.vm.step.rEval;
  let nextBest, curBestMove, pastBest;
  if (!ctrl.explorer.enabled() && ctrl.ceval.enabled() && ctrl.vm.showBestMove) {
    nextBest = ctrl.nextStepBest();
    curBestMove = nextBest ? {
      brush: 'paleBlue',
      orig: nextBest.slice(0, 2),
      dest: nextBest.slice(2, 4)
    } : ceval && ceval.best ? {
      brush: 'paleBlue',
      orig: ceval.best.slice(0, 2),
      dest: ceval.best.slice(2, 4)
    } : null;
  }
  if (ctrl.vm.showComments) {
    pastBest = rEval && rEval.best ? {
      brush: 'paleGreen',
      orig: rEval.best.slice(0, 2),
      dest: rEval.best.slice(2, 4)
    } : null;
  }

  const nextStep = ctrl.explorer.enabled() && ctrl.analyse.getStepAtPly(ctrl.vm.step.ply + 1);
  const nextMove = nextStep ? nextStep.uci.includes('@') ? {
    brush: 'palePurple',
    orig: nextStep.uci.slice(2, 4)
  } : {
    brush: 'palePurple',
    orig: nextStep.uci.slice(0, 2),
    dest: nextStep.uci.slice(2, 4)
  } : null;

  const board = Board(
    ctrl.data,
    ctrl.chessground,
    bounds,
    isPortrait,
    null,
    null,
    nextMove ? [nextMove] : [pastBest, curBestMove].filter(noNull)
  );

  return [
    board,

      {ctrl.explorer.enabled() ?
        explorerView(ctrl) :
        renderAnalyseTable(ctrl, isPortrait)
      }
      {renderActionsBar(ctrl, isPortrait)}

  ];
}

function renderAnalyseTable(ctrl, isPortrait) {
  const className = [
    isSynthetic(ctrl.data) ? 'synthetic' : '',
    'analyseTable'
  ].join(' ');

  return (

        {renderReplay(ctrl)}

      {renderInfos(ctrl, isPortrait)}

  );
}

function renderInfos(ctrl, isPortrait) {
  const cevalEnabled = ctrl.ceval.enabled();

  return (

      { cevalEnabled || ctrl.data.analysis ?
        renderEvalBox(ctrl) : null
      }
      { !isSynthetic(ctrl.data) ?

          {renderOpponents(ctrl, isPortrait)}

 : null
      }

  );
}

function getChecksCount(ctrl, color) {
  const step = ctrl.vm.step;
  return step.checkCount[oppositeColor(color)];
}

function renderEvalBox(ctrl) {
  const ceval = ctrl.currentAnyEval() || {};
  let pearl, percent;

  if (defined(ceval.cp) && ctrl.nextStepBest()) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (defined(ceval.cp)) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? ctrl.ceval.percentComplete() : 0;
  }
  else if (defined(ceval.mate)) {
    pearl = <pearl>{'#' + ceval.mate}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (ctrl.ceval.enabled() && isEmpty(ctrl.vm.step.dests)) {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }
  else if (ctrl.ceval.enabled()) {
    pearl =

;
    percent = 0;
  }
  else {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }

  return (

      { pearl }

      { ctrl.data.analysis ?

 : null
      }

  );
}

function renderOpponents(ctrl, isPortrait) {
  if (isSynthetic(ctrl.data)) return null;

  const player = ctrl.data.player;
  const opponent = ctrl.data.opponent;
  if (!player || !opponent) return null;

  const isCrazy = !!ctrl.vm.step.crazy;

  // TODO get that from server
  if (opponent.ai) {
    opponent.engineName = isCrazy ? 'Sunsetter' : 'Stockfish';
  }

  return (

          {playerName(player, true)}
          {helper.renderRatingDiff(player)}
          { ctrl.data.game.variant.key === 'threeCheck' && ctrl.vm.step.checkCount ?
            ' +' + getChecksCount(ctrl, player.color) : null
          }

        {ctrl.data.clock && (!isCrazy || !isPortrait) ?

            {formatClockTime(ctrl.data.clock[player.color] * 1000, false)}

 : null
        }
        {crazyView.pocket(ctrl, ctrl.vm.step.crazy, player.color, 'top')}

          {playerName(opponent, true)}
          {helper.renderRatingDiff(opponent)}
          { ctrl.data.game.variant.key === 'threeCheck' && ctrl.vm.step.checkCount ?
            ' +' + getChecksCount(ctrl, opponent.color) : null
          }

        {ctrl.data.clock && (!isCrazy || !isPortrait) ?

            {formatClockTime(ctrl.data.clock[opponent.color] * 1000, false)}

 : null
        }
        {crazyView.pocket(ctrl, ctrl.vm.step.crazy, opponent.color, 'bottom')}

      {!isCrazy || !isPortrait ? renderStatus(ctrl) : null}

  );
}

function renderStatus(ctrl) {
  const winner = gameApi.getPlayer(ctrl.data, ctrl.data.game.winner);
  return (

      {gameStatusApi.toLabel(ctrl.data.game.status.name, ctrl.data.game.winner, ctrl.data.game.variant.key)}

      {winner ? '. ' + i18n(winner.color === 'white' ? 'whiteIsVictorious' : 'blackIsVictorious') + '.' : null}

  );
}

function renderReplay(ctrl) {

  var result;
  if (ctrl.data.game.status.id >= 30) switch (ctrl.data.game.winner) {
    case 'white':
      result = '1-0';
      break;
    case 'black':
      result = '0-1';
      break;
    default:
      result = '½-½';
  }
  const tree = renderTree(ctrl, ctrl.analyse.tree);
  if (result) {
    tree.push(
{result}
);
    tree.push(renderStatus(ctrl));
  }

  return (

      {tree}

  );
}

function buttons(ctrl) {
  return [
    ['first', 'fast-backward', control.first ],
    ['prev', 'backward', control.prev],
    ['next', 'forward', control.next],
    ['last', 'fast-forward', control.last]
  ].map(b => {
    const className = [
      'action_bar_button',
      'fa',
      'fa-' + b[1]
    ].join(' ');

    const action = b[0] === 'prev' || b[0] === 'next' ?
      helper.ontouch(() => b[2](ctrl), null, () => b[2](ctrl)) :
      helper.ontouch(() => b[2](ctrl));

    return (
      <button className={className} key={b[1]} oncreate={action} />
    );
  });
}

function renderActionsBar(ctrl) {

  const explorerBtnClass = [
    'action_bar_button',
    'fa',
    'fa-book',
    ctrl.explorer.enabled() ? 'highlight' : ''
  ].join(' ');

  return (

      <button className="action_bar_button fa fa-ellipsis-h" key="analyseMenu"
        oncreate={helper.ontouch(ctrl.menu.open)}
      />
      {ctrl.ceval.allowed() ?
        <button className="action_bar_button fa fa-gear" key="analyseSettings"
          oncreate={helper.ontouch(ctrl.settings.open)}
        /> : null
      }
      {hasNetwork() ?
        <button className={explorerBtnClass} key="explorer"
          oncreate={helper.ontouch(
            ctrl.explorer.toggle,
            () => window.plugins.toast.show('Opening explorer & tablebase', 'short', 'bottom')
          )}
        /> : null
      }
      <button className="action_bar_button" data-icon="B" key="flipBoard"
        oncreate={helper.ontouch(
          ctrl.flip,
          () => window.plugins.toast.show(i18n('flipBoard'), 'short', 'bottom')
        )}
      />
      {buttons(ctrl)}

  );
}
<commit_msg>Don't show eval box in crazyhouse portrait<commit_after>import isEmpty from 'lodash/isEmpty';
import { hasNetwork, getBoardBounds, playerName, oppositeColor, noNull } from '../../../utils';
import i18n from '../../../i18n';
import gameApi from '../../../lichess/game';
import gameStatusApi from '../../../lichess/status';
import continuePopup from '../../shared/continuePopup';
import { view as renderPromotion } from '../../shared/offlineRound/promotion';
import { connectingHeader, header, backButton as renderBackbutton, viewOnlyBoardContent } from '../../shared/common';
import Board from '../../shared/Board';
import helper from '../../helper';
import layout from '../../layout';
import notes from '../../round/notes';
import { formatClockTime } from '../../round/clock/clockView';
import importPgnPopup from '../importPgnPopup';
import control from '../control';
import menu from '../menu';
import analyseSettings from '../analyseSettings';
import { defined, renderEval, isSynthetic } from '../util';
import crazyView from '../crazy/crazyView';
import explorerView from '../explorer/explorerView';
import evalSummary from '../evalSummaryPopup';
import { renderTree } from './treeView';

export default function analyseView() {
  const ctrl = this;

  const isPortrait = helper.isPortrait();

  if (ctrl.data) {

    const backButton = ctrl.vm.shouldGoBack ? renderBackbutton(gameApi.title(ctrl.data)) : null;
    const title = ctrl.vm.shouldGoBack ? null : i18n('analysis');

    return layout.board(
      () => header(title, backButton),
      () => renderContent(ctrl, isPortrait),
      () => overlay(ctrl, isPortrait)
    );
  } else {
    return layout.board(
      connectingHeader,
      viewOnlyBoardContent
    );
  }
}

function overlay(ctrl) {
  return [
    renderPromotion(ctrl),
    menu.view(ctrl.menu),
    analyseSettings.view(ctrl.settings),
    ctrl.notes ? notes.view(ctrl.notes) : null,
    ctrl.evalSummary ? evalSummary.view(ctrl.evalSummary) : null,
    continuePopup.view(ctrl.continuePopup),
    importPgnPopup.view(ctrl.importPgnPopup)
  ];
}

function renderContent(ctrl, isPortrait) {
  const bounds = getBoardBounds(helper.viewportDim(), isPortrait, helper.isIpadLike(), helper.isLandscapeSmall(), 'analyse');
  const ceval = ctrl.vm.step && ctrl.vm.step.ceval;
  const rEval = ctrl.vm.step && ctrl.vm.step.rEval;
  let nextBest, curBestMove, pastBest;
  if (!ctrl.explorer.enabled() && ctrl.ceval.enabled() && ctrl.vm.showBestMove) {
    nextBest = ctrl.nextStepBest();
    curBestMove = nextBest ? {
      brush: 'paleBlue',
      orig: nextBest.slice(0, 2),
      dest: nextBest.slice(2, 4)
    } : ceval && ceval.best ? {
      brush: 'paleBlue',
      orig: ceval.best.slice(0, 2),
      dest: ceval.best.slice(2, 4)
    } : null;
  }
  if (ctrl.vm.showComments) {
    pastBest = rEval && rEval.best ? {
      brush: 'paleGreen',
      orig: rEval.best.slice(0, 2),
      dest: rEval.best.slice(2, 4)
    } : null;
  }

  const nextStep = ctrl.explorer.enabled() && ctrl.analyse.getStepAtPly(ctrl.vm.step.ply + 1);
  const nextMove = nextStep ? nextStep.uci.includes('@') ? {
    brush: 'palePurple',
    orig: nextStep.uci.slice(2, 4)
  } : {
    brush: 'palePurple',
    orig: nextStep.uci.slice(0, 2),
    dest: nextStep.uci.slice(2, 4)
  } : null;

  const board = Board(
    ctrl.data,
    ctrl.chessground,
    bounds,
    isPortrait,
    null,
    null,
    nextMove ? [nextMove] : [pastBest, curBestMove].filter(noNull)
  );

  return [
    board,

      {ctrl.explorer.enabled() ?
        explorerView(ctrl) :
        renderAnalyseTable(ctrl, isPortrait)
      }
      {renderActionsBar(ctrl, isPortrait)}

  ];
}

function renderAnalyseTable(ctrl, isPortrait) {
  const className = [
    isSynthetic(ctrl.data) ? 'synthetic' : '',
    'analyseTable'
  ].join(' ');

  return (

        {renderReplay(ctrl)}

      {renderInfos(ctrl, isPortrait)}

  );
}

function renderInfos(ctrl, isPortrait) {
  const cevalEnabled = ctrl.ceval.enabled();
  const isCrazy = !!ctrl.vm.step.crazy;

  return (

      { (!isCrazy || !isPortrait) && (cevalEnabled || ctrl.data.analysis) ?
        renderEvalBox(ctrl) : null
      }
      { !isSynthetic(ctrl.data) ?

          {renderOpponents(ctrl, isPortrait)}

 : null
      }

  );
}

function getChecksCount(ctrl, color) {
  const step = ctrl.vm.step;
  return step.checkCount[oppositeColor(color)];
}

function renderEvalBox(ctrl) {
  const ceval = ctrl.currentAnyEval() || {};
  let pearl, percent;

  if (defined(ceval.cp) && ctrl.nextStepBest()) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (defined(ceval.cp)) {
    pearl = <pearl>{renderEval(ceval.cp)}</pearl>;
    percent = ctrl.ceval.enabled() ? ctrl.ceval.percentComplete() : 0;
  }
  else if (defined(ceval.mate)) {
    pearl = <pearl>{'#' + ceval.mate}</pearl>;
    percent = ctrl.ceval.enabled() ? 100 : 0;
  }
  else if (ctrl.ceval.enabled() && isEmpty(ctrl.vm.step.dests)) {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }
  else if (ctrl.ceval.enabled()) {
    pearl =

;
    percent = 0;
  }
  else {
    pearl = <pearl>-</pearl>;
    percent = 0;
  }

  return (

      { pearl }

      { ctrl.data.analysis ?

 : null
      }

  );
}

function renderOpponents(ctrl, isPortrait) {
  if (isSynthetic(ctrl.data)) return null;

  const player = ctrl.data.player;
  const opponent = ctrl.data.opponent;
  if (!player || !opponent) return null;

  const isCrazy = !!ctrl.vm.step.crazy;

  // TODO get that from server
  if (opponent.ai) {
    opponent.engineName = isCrazy ? 'Sunsetter' : 'Stockfish';
  }

  return (

          {playerName(player, true)}
          {helper.renderRatingDiff(player)}
          { ctrl.data.game.variant.key === 'threeCheck' && ctrl.vm.step.checkCount ?
            ' +' + getChecksCount(ctrl, player.color) : null
          }

        {ctrl.data.clock && (!isCrazy || !isPortrait) ?

            {formatClockTime(ctrl.data.clock[player.color] * 1000, false)}

 : null
        }
        {crazyView.pocket(ctrl, ctrl.vm.step.crazy, player.color, 'top')}

          {playerName(opponent, true)}
          {helper.renderRatingDiff(opponent)}
          { ctrl.data.game.variant.key === 'threeCheck' && ctrl.vm.step.checkCount ?
            ' +' + getChecksCount(ctrl, opponent.color) : null
          }

        {ctrl.data.clock && (!isCrazy || !isPortrait) ?

            {formatClockTime(ctrl.data.clock[opponent.color] * 1000, false)}

 : null
        }
        {crazyView.pocket(ctrl, ctrl.vm.step.crazy, opponent.color, 'bottom')}

      {!isCrazy || !isPortrait ? renderStatus(ctrl) : null}

  );
}

function renderStatus(ctrl) {
  const winner = gameApi.getPlayer(ctrl.data, ctrl.data.game.winner);
  return (

      {gameStatusApi.toLabel(ctrl.data.game.status.name, ctrl.data.game.winner, ctrl.data.game.variant.key)}

      {winner ? '. ' + i18n(winner.color === 'white' ? 'whiteIsVictorious' : 'blackIsVictorious') + '.' : null}

  );
}

function renderReplay(ctrl) {

  var result;
  if (ctrl.data.game.status.id >= 30) switch (ctrl.data.game.winner) {
    case 'white':
      result = '1-0';
      break;
    case 'black':
      result = '0-1';
      break;
    default:
      result = '½-½';
  }
  const tree = renderTree(ctrl, ctrl.analyse.tree);
  if (result) {
    tree.push(
{result}
);
    tree.push(renderStatus(ctrl));
  }

  return (

      {tree}

  );
}

function buttons(ctrl) {
  return [
    ['first', 'fast-backward', control.first ],
    ['prev', 'backward', control.prev],
    ['next', 'forward', control.next],
    ['last', 'fast-forward', control.last]
  ].map(b => {
    const className = [
      'action_bar_button',
      'fa',
      'fa-' + b[1]
    ].join(' ');

    const action = b[0] === 'prev' || b[0] === 'next' ?
      helper.ontouch(() => b[2](ctrl), null, () => b[2](ctrl)) :
      helper.ontouch(() => b[2](ctrl));

    return (
      <button className={className} key={b[1]} oncreate={action} />
    );
  });
}

function renderActionsBar(ctrl) {

  const explorerBtnClass = [
    'action_bar_button',
    'fa',
    'fa-book',
    ctrl.explorer.enabled() ? 'highlight' : ''
  ].join(' ');

  return (

      <button className="action_bar_button fa fa-ellipsis-h" key="analyseMenu"
        oncreate={helper.ontouch(ctrl.menu.open)}
      />
      {ctrl.ceval.allowed() ?
        <button className="action_bar_button fa fa-gear" key="analyseSettings"
          oncreate={helper.ontouch(ctrl.settings.open)}
        /> : null
      }
      {hasNetwork() ?
        <button className={explorerBtnClass} key="explorer"
          oncreate={helper.ontouch(
            ctrl.explorer.toggle,
            () => window.plugins.toast.show('Opening explorer & tablebase', 'short', 'bottom')
          )}
        /> : null
      }
      <button className="action_bar_button" data-icon="B" key="flipBoard"
        oncreate={helper.ontouch(
          ctrl.flip,
          () => window.plugins.toast.show(i18n('flipBoard'), 'short', 'bottom')
        )}
      />
      {buttons(ctrl)}

  );
}
<|endoftext|>


<commit_before>/**
 * Created by Crystian on 3/16/2015.
 */

var gulp = require('gulp'),
	utils = require('./utils'),
	strip = require('gulp-strip-comments'),
	minifycss = require('gulp-minify-css'),
	sass = require('gulp-sass'),
	autoprefixer = require('gulp-autoprefixer'),
	csslint = require('gulp-csslint'),
	replace = require('gulp-replace'),
	concat = require('gulp-concat'),
	fs = require('fs-extra'),
	extend = require('extend'),
	gif = require('gulp-if'),
	less = require('gulp-less'),
	debug = require('gulp-debug'),
	rename = require('gulp-rename'),
	StreamQueue = require('streamqueue'),
	aux = require('./auxiliar'),
	gutil = require('gulp-util');
	//es = require('event-stream')
	//htmlreplace = require('gulp-html-replace'),
	//htmlmin = require('gulp-htmlmin'),
	//concat = require('gulp-concat'),
	//jshint = require('gulp-jshint'),
	//header = require('gulp-header'),
	//footer = require('gulp-footer'),
	//runSequence = require('run-sequence'),

var defaults = {
	file: {
		'file': 'file.css',		//extension define the flow, can be tipicals and file for preprocessor, automaticaly determine with one will be use
		'active': 'true',		//it will eval this field
		'path': 'www',			//it can be a statement, and it will be evaluated
		//'min': 'file.min.css',//file name final for minificated file, just use it if you want another name, by default is 'min.'+ext
		'linter': true,			//if you want to lint, will not apply for libraries
		'autoPrefix': true,		//auto prefix when source is active
		'overwrite': true,		//specially for libs, just make it once
		'minificated': false,	//if it is a lib for don't re do the minifcation
		'makeMin': false,		//it should be create a minificate version
		'replaces': {
			'pre': [			//pre minificatedd
				//['/(\'build\'.*\\:[ ]?)(\\w*)/', '$1true']
			],
			'post': [			//post minificatedd
				//['/(\'build\'.*\\:[ ]?)(\\w*)/', '$1true']
			]
		}
	},
	validCssExtensions : ['sass', 'scss','less'],
	validExtensions : ['html', 'js'],
	options: {
		extensionToProcess : {
			'scss': true,
			'sass': true,
			'less': true,
			'css': true,
			'js': true,
			'html': true
		}
	}
};

exports.runPreprocessors = function(appsJson) {
	return runEachApp(appsJson, runEachPreprocessors);
};

exports.runMagic = function(appsJson) {
	return runEachApp(appsJson, doMagic);
};

exports.runJsonify = function(appsJson) {
	return runEachApp(appsJson, runJsonify);
};

function runEachApp(appsJson, fnEach){
	var apps = require('../../../'+ appsJson),
		stream = undefined;

	var i = 0,
		l = apps.length;

	for (; i < l; i++) {
		var app = apps[i];
		stream = aux.merge(stream, fnEach(global.cfg.app.folders.www +'/'+ app +'/app.json', app));
	}

	return stream;
}

function runEachPreprocessors(url, appName){
	var files = require('../../../'+ url);
	var i = 0,
		l = files.length,
		streams = undefined;

	for (; i < l; i++) {
		var file = extend(true, {}, defaults.file, files[i]);

		if(aux.isNotActive(file) || file.minificated){continue;}

		var fileName = utils.getFileName(file.file),
			type = utils.getExtensionFile(file.file);

		//valid types
		if(defaults.validCssExtensions.indexOf(type)===-1){continue;}

		file.path = aux.makePath(file.path);

		var source = file.path + '/' + file.file,
			final = file.path + '/' + fileName +'.css';

		//which name have min file?, default: *.min.*
		file.min = file.min || utils.setExtensionFilename(file.file, 'min.css');

		if(!fs.existsSync(source)){
			console.logRed('File not found: '+ source);
			aux.exit(1);
		}

		//just for detect potentian file exists
		file._cssFile = final;

		if( !(global.cfg.loader.release || file.overwrite)
			&& (aux.fileDestExist(file)
			&& !file.overwrite)) {//for the overwrite = false
			//exist, and don't overwrite it
			console.log('File found, don\'t overwrite ('+ file.file +')');
			continue;
		}

		var stream = gulp.src(source)
			.pipe(debug({verbose: true}))
			.on('error', gutil.log);

		switch (type){
			case 'scss':
			case 'sass':
				var sassOptions = {errLogToConsole: true, indentedSyntax: (type === 'sass')};

				stream = stream.pipe(sass(sassOptions));
				break;
			case 'less':
				stream = stream.pipe(less());
				break;
		}

		if (file.autoPrefix) {
			stream = stream.pipe(autoprefixer(global.cfg.autoprefixer))
				.pipe(replace(' 0px', ' 0'));
		}

		if (file.linter) {
			stream = stream.pipe(csslint('csslintrc.json'))
				.pipe(csslint.reporter()).on('error', gutil.log);
		}

		stream = stream.pipe(gulp.dest(file.path));

		if(file.makeMin){
			stream = _minificateAndSave(stream, file, 'css')
		}

		streams = aux.merge(streams, stream);
	}

	return streams;
}

function doMagic(url, appName) {
	var files = require('../../../' + url);
	var i = 0,
		l = files.length,
		streamsFinal = undefined,
		streams = [];

	for (; i < l; i++) {
		var file = extend(true, {}, defaults.file, files[i]);

		if(aux.isNotActive(file)){continue;}

		var fileName = utils.getFileName(file.file),
			type = utils.getExtensionFile(file.file);

		//valid types and normalize it
		var flagTypeValid = false;
		if (type === 'css' || defaults.validCssExtensions.indexOf(type) !== -1) {
			flagTypeValid = true;
			type = 'css';
		} else if(defaults.validExtensions.indexOf(type) !== -1) {
			flagTypeValid = true;
		}

		if(!flagTypeValid){
			console.logWarn('Invalid file type: '+ file.file);
			continue;
		}

		file.min = file.min || utils.setPreExtensionFilename(file.file, 'min');

		file.path = aux.makePath(file.path);

		var source = file.path +'/'+ fileName + '.' + type;

		if(file.minificated || file.makeMin){
			source = file.path +'/'+ file.min;
		}

		var stream = gulp.src(source)
			.pipe(debug({verbose: true}))
			.on('error', gutil.log);

		if(!file.minificated && !file.makeMin){
			stream = _minificate(stream, file, type)
		}

		if(!streams[type]){
			streams[type] = new StreamQueue({ objectMode: true });
		}
		streams[type] = streams[type].queue(stream);
	}

	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'css', appName));
	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'js', appName));
	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'html', appName));
	return streamsFinal;
}

function runJsonify(url, app){
	var json = {};
	json.v = global.cfg.version;
	json.j = fs.readFileSync('build/'+ app +'.js', {encoding: 'utf8'});
	json.c = fs.readFileSync('build/'+ app +'.css', {encoding: 'utf8'});
	json.h = fs.readFileSync('build/'+ app +'.html', {encoding: 'utf8'});

	var b = JSON.stringify(json);

	if(cfg.compress){
		b = LZString.compressToUTF16(b);
		console.logGreen(app +' compressed!');
	}

	fs.writeFileSync('build/'+ app +'.json', b);
}

function _concat(_streams, _type, _appName){
	var s = _streams[_type].done();
	s = s.pipe(concat(_appName+'.'+ _type, {newLine: ';'}))
		.pipe(gulp.dest(global.cfg.app.folders.temp));

	return s;
}

function _minificateAndSave(stream, file, type){
	stream = _minificate(stream, file, type);

	stream = stream.pipe(gulp.dest(file.path));

	return stream;
}

function _minificate(stream, file, type){
	//replaces previously to minimisation
	stream = aux.replace(stream, file.replaces.pre);

	if (_handle[type]) {
		console.log('File to process: ', file.file);
		stream = _handle[type](stream, file);
	} else {
		console.logRed('Type not found on _minificate, file: '+ file.file);
	}

	//* replaces posterity to minimisation
	stream = aux.replace(stream, file.replaces.post);

	return stream;
}

var _handle = {
	'css' : function(stream, file) {
		console.logWarn('CSS');

		stream = stream
			.pipe(strip({safe:false, block:false}))
			.pipe(gif(global.cfg.app.release, minifycss()))
			.pipe(rename(utils.setExtensionFilename(file.min,'css')));

		return stream;
	},

	'js': function(stream, file){
		console.log('NADA AUN JS');
		return stream;
	},
	'html': function(stream, file) {
		console.log('NADA AUN HTML');
		return stream;
	}
};

<commit_msg>fixes<commit_after>/**
 * Created by Crystian on 3/16/2015.
 */

var gulp = require('gulp'),
	utils = require('./utils'),
	strip = require('gulp-strip-comments'),
	minifycss = require('gulp-minify-css'),
	sass = require('gulp-sass'),
	autoprefixer = require('gulp-autoprefixer'),
	csslint = require('gulp-csslint'),
	replace = require('gulp-replace'),
	concat = require('gulp-concat'),
	fs = require('fs-extra'),
	extend = require('extend'),
	gif = require('gulp-if'),
	less = require('gulp-less'),
	debug = require('gulp-debug'),
	rename = require('gulp-rename'),
	StreamQueue = require('streamqueue'),
	aux = require('./auxiliar'),
	LZString = require('../../vendors/lz-string/libs/lz-string'),
	gutil = require('gulp-util');
	//es = require('event-stream')
	//htmlreplace = require('gulp-html-replace'),
	//htmlmin = require('gulp-htmlmin'),
	//concat = require('gulp-concat'),
	//jshint = require('gulp-jshint'),
	//header = require('gulp-header'),
	//footer = require('gulp-footer'),
	//runSequence = require('run-sequence'),

var defaults = {
	file: {
		'file': 'file.css',		//extension define the flow, can be tipicals and file for preprocessor, automaticaly determine with one will be use
		'active': 'true',		//it will eval this field
		'path': 'www',			//it can be a statement, and it will be evaluated
		//'min': 'file.min.css',//file name final for minificated file, just use it if you want another name, by default is 'min.'+ext
		'linter': true,			//if you want to lint, will not apply for libraries
		'autoPrefix': true,		//auto prefix when source is active
		'overwrite': true,		//specially for libs, just make it once
		'minificated': false,	//if it is a lib for don't re do the minifcation
		'makeMin': false,		//it should be create a minificate version
		'replaces': {
			'pre': [			//pre minificatedd
				//['/(\'build\'.*\\:[ ]?)(\\w*)/', '$1true']
			],
			'post': [			//post minificatedd
				//['/(\'build\'.*\\:[ ]?)(\\w*)/', '$1true']
			]
		}
	},
	validCssExtensions : ['sass', 'scss','less'],
	validExtensions : ['html', 'js'],
	options: {
		extensionToProcess : {
			'scss': true,
			'sass': true,
			'less': true,
			'css': true,
			'js': true,
			'html': true
		}
	}
};

exports.runPreprocessors = function(appsJson) {
	return runEachApp(appsJson, runEachPreprocessors);
};

exports.runMagic = function(appsJson) {
	return runEachApp(appsJson, doMagic);
};

exports.runJsonify = function(appsJson) {
	return runEachApp(appsJson, runJsonify);
};

function runEachApp(appsJson, fnEach){
	var apps = require('../../../'+ appsJson),
		stream = undefined;

	var i = 0,
		l = apps.length;

	for (; i < l; i++) {
		var app = apps[i];
		stream = aux.merge(stream, fnEach(global.cfg.app.folders.www +'/'+ app +'/app.json', app));
	}

	return stream;
}

function runEachPreprocessors(url, appName){
	var files = require('../../../'+ url);
	var i = 0,
		l = files.length,
		streams = undefined;

	for (; i < l; i++) {
		var file = extend(true, {}, defaults.file, files[i]);

		if(aux.isNotActive(file) || file.minificated){continue;}

		var fileName = utils.getFileName(file.file),
			type = utils.getExtensionFile(file.file);

		//valid types
		if(defaults.validCssExtensions.indexOf(type)===-1){continue;}

		file.path = aux.makePath(file.path);

		var source = file.path + '/' + file.file,
			final = file.path + '/' + fileName +'.css';

		//which name have min file?, default: *.min.*
		file.min = file.min || utils.setExtensionFilename(file.file, 'min.css');

		if(!fs.existsSync(source)){
			console.logRed('File not found: '+ source);
			aux.exit(1);
		}

		//just for detect potentian file exists
		file._cssFile = final;

		if( !(global.cfg.loader.release || file.overwrite)
			&& (aux.fileDestExist(file)
			&& !file.overwrite)) {//for the overwrite = false
			//exist, and don't overwrite it
			console.log('File found, don\'t overwrite ('+ file.file +')');
			continue;
		}

		var stream = gulp.src(source)
			.pipe(debug({verbose: true}))
			.on('error', gutil.log);

		switch (type){
			case 'scss':
			case 'sass':
				var sassOptions = {errLogToConsole: true, indentedSyntax: (type === 'sass')};

				stream = stream.pipe(sass(sassOptions));
				break;
			case 'less':
				stream = stream.pipe(less());
				break;
		}

		if (file.autoPrefix) {
			stream = stream.pipe(autoprefixer(global.cfg.autoprefixer))
				.pipe(replace(' 0px', ' 0'));
		}

		if (file.linter) {
			stream = stream.pipe(csslint('csslintrc.json'))
				.pipe(csslint.reporter()).on('error', gutil.log);
		}

		stream = stream.pipe(gulp.dest(file.path));

		if(file.makeMin){
			stream = _minificateAndSave(stream, file, 'css')
		}

		streams = aux.merge(streams, stream);
	}

	return streams;
}

function doMagic(url, appName) {
	var files = require('../../../' + url);
	var i = 0,
		l = files.length,
		streamsFinal = undefined,
		streams = [];

	for (; i < l; i++) {
		var file = extend(true, {}, defaults.file, files[i]);

		if(aux.isNotActive(file)){continue;}

		var fileName = utils.getFileName(file.file),
			type = utils.getExtensionFile(file.file);

		//valid types and normalize it
		var flagTypeValid = false;
		if (type === 'css' || defaults.validCssExtensions.indexOf(type) !== -1) {
			flagTypeValid = true;
			type = 'css';
		} else if(defaults.validExtensions.indexOf(type) !== -1) {
			flagTypeValid = true;
		}

		if(!flagTypeValid){
			console.logWarn('Invalid file type: '+ file.file);
			continue;
		}

		file.min = file.min || utils.setPreExtensionFilename(file.file, 'min');

		file.path = aux.makePath(file.path);

		var source = file.path +'/'+ fileName + '.' + type;

		if(file.minificated || file.makeMin){
			source = file.path +'/'+ file.min;
		}

		var stream = gulp.src(source)
			.pipe(debug({verbose: true}))
			.on('error', gutil.log);

		if(!file.minificated && !file.makeMin){
			stream = _minificate(stream, file, type)
		}

		if(!streams[type]){
			streams[type] = new StreamQueue({ objectMode: true });
		}
		streams[type] = streams[type].queue(stream);
	}

	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'css', appName));
	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'js', appName));
	streamsFinal = aux.merge(streamsFinal, _concat(streams, 'html', appName));
	return streamsFinal;
}

function runJsonify(url, app){
	var json = {};
	json.v = global.cfg.version;
	json.j = fs.readFileSync(global.cfg.app.folders.temp +'/'+ app +'.js', {encoding: 'utf8'});
	json.c = fs.readFileSync(global.cfg.app.folders.temp +'/'+ app +'.css', {encoding: 'utf8'});
	json.h = fs.readFileSync(global.cfg.app.folders.temp +'/'+ app +'.html', {encoding: 'utf8'});

	var b = JSON.stringify(json);

	if(cfg.compress){
		b = LZString.compressToUTF16(b);
		console.logGreen(app +' compressed!');
	}

	fs.writeFileSync('build/'+ app +'.json', b);
}

function _concat(_streams, _type, _appName){
	var s = _streams[_type].done();
	s = s.pipe(concat(_appName+'.'+ _type, {newLine: ';'}))
		.pipe(gulp.dest(global.cfg.app.folders.temp));

	return s;
}

function _minificateAndSave(stream, file, type){
	stream = _minificate(stream, file, type);

	stream = stream.pipe(gulp.dest(file.path));

	return stream;
}

function _minificate(stream, file, type){
	//replaces previously to minimisation
	stream = aux.replace(stream, file.replaces.pre);

	if (_handle[type]) {
		console.log('File to process: ', file.file);
		stream = _handle[type](stream, file);
	} else {
		console.logRed('Type not found on _minificate, file: '+ file.file);
	}

	//* replaces posterity to minimisation
	stream = aux.replace(stream, file.replaces.post);

	return stream;
}

var _handle = {
	'css' : function(stream, file) {
		console.logWarn('CSS');

		stream = stream
			.pipe(strip({safe:false, block:false}))
			.pipe(gif(global.cfg.app.release, minifycss()))
			.pipe(rename(utils.setExtensionFilename(file.min,'css')));

		return stream;
	},

	'js': function(stream, file){
		console.log('NADA AUN JS');
		return stream;
	},
	'html': function(stream, file) {
		console.log('NADA AUN HTML');
		return stream;
	}
};

<|endoftext|>


<commit_before>/* TODO :
    *-add a check to not re-call pokeSearch if the name of the pokemon hasn't changed so spamming the button doesn't make multiple calls to the backend

    -add client side caching of pokemon they look up in a session so if they re-look them up it doesn't have to make extranious calls to the backend (web-storage)
    store: localstorage.setItem('key', JSON.stringify({name: 'value'}));
    get: JSON.parse(localStorage.getItem('key')).name;
    -set up JSON objects for each pokemon for storage
    {name: 'name', id: '', type: 'type', img: 'url'}

    -add section for what types they are good against

    *-remove overlapping types on pokemon weakness

    -some double pokemon show types they aren't weak against due to having types that are resistant to something as well as the other being weak to it, the algorithm needs to be expanded to include these

    UI UPDATE NOTES
    grey : #b7b7b7
    pick a color for all types
    make the top bar resize? look vs usability
    USE ALL CAPS ON ERRYTHING
*/

var xmlhttp = new XMLHttpRequest();
var baseurl = "http://pokeapi.co/api/v2/pokemon/";

function pokeSearch() {
    //grab the pokemon they search for
    var pokemon = document.getElementById("searchBar").value.lowerFirstLetter();
    var currentShowing = document.getElementById("pokeName").innerHTML.lowerFirstLetter();
    //test if they are re-searching for whats already there
    //prevent another api call
    if (pokemon === currentShowing) {
        //keep the current showing
    } else {

        console.log("no currently showing or diff");
        document.getElementById("pokeDisplay").style.display = "none";
        document.getElementById("errorState").style.display = "none";
        document.getElementById("loader").style.display = "block";
        //make the full URL based on search
        var url = baseurl.concat(pokemon);
        url = url.concat("/");

        xmlhttp.open("GET", url, true);
        xmlhttp.onload = function () {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                var json = JSON.parse(xmlhttp.responseText);
                pokeDisplay(json);
            } else {
                document.getElementById("errorMessage").innerHTML = pokemon + " can't be found!";
                document.getElementById("loader").style.display = "none";
                document.getElementById("errorState").style.display = "block";
                console.error(xmlhttp.statusText);
            }
        };
        xmlhttp.send();
    }
}

//placing the data into the page
function pokeDisplay(json) {
    var name = json.name.capitalizeString();
    var weaknesses = "";

    //var urls = [];
    var formattedTypes = [];
    //place information we already have
    document.getElementById("pokeDisplay").style.display = "block";
    document.getElementById("pokeName").innerHTML = name;
    console.log(json.id < 10);
    if(json.id < 10) {
        document.getElementById("pokeID").innerHTML = "#00" + json.id;
    } else if (json.id < 100) {
        document.getElementById("pokeID").innerHTML = "#0" + json.id;
    } else {
        document.getElementById("pokeID").innerHTML = "#" + json.id;
    }

    document.getElementById("pokeImg").src = json.sprites.front_default;
    document.getElementById("type1").style.display = "none";
    document.getElementById("type2").style.display = "none";
    document.getElementById("weaknesses").innerHTML = "";

    console.log(json.id);
    showRegion(json.id);

    var types = [];
    //create an array of type names for finding weaknesses and display
    for (i = 0; i < json.types.length; i++) {
        types.push(json.types[i].type.name);
    }
    document.getElementById("weakTitle").style.visibility = "visible";
    localType(types);

    document.getElementById("loader").style.display = "none";

}

function localType(pTypes) {
    var allWeaknesses = [];
    for (i = 0; i < pTypes.length; i++) {
        var color;
        for (j = 0; j < typeJSON.types.length; j++) {
            var type = typeJSON.types[j];
            if (pTypes[i] === type.name) {
                color = type.color;
                for (k = 0; k < type.effects.weak_to.length; k++) {
                    allWeaknesses.push(type.effects.weak_to[k]);
                }
            }
        }
        if(i === 0) {
            var type = document.getElementById("type2");
            type.style.display = "block";
            type.innerHTML = pTypes[i];
            type.style.background = color;
        } else {
            var type = document.getElementById("type1");
            type.style.display = "block";
            type.innerHTML = pTypes[i];
            type.style.background = color;
        }

    }
    displayTypeWeaknesses(allWeaknesses);
}

function displayTypeWeaknesses(weaknesses) {
    var alreadyDisplayed = [];
    var pokeWeak = document.getElementById("weaknesses");
    for (i = 0; i < weaknesses.length; i++) {
        var found = false;
        for (j = 0; j < alreadyDisplayed.length; j++) {
            if (alreadyDisplayed[j] === weaknesses[i]) {
                found = true;
                break;
            }
        }
        if (!found) {
            alreadyDisplayed.push(weaknesses[i]);
            pokeWeak.innerHTML += weaknesses[i];
            if (!(i === weaknesses.length - 1)) {
                pokeWeak.innerHTML += "  ";
            }
        }

    }
}

function showRegion(id) {
    console.log("in region: " + id);
    var regionHolder = document.getElementById("region");
    var regionName = "";
    if (id < 152){
        regionName = regionNames[0];
    } else if (152 <= id && id < 252) {
        regionName = regionNames[1];
    } else if (252 <= id && id < 387) {
        regionName = regionNames[2];
    } else if (387 <= id && id < 494) {
        regionName = regionNames[3];
    } else if (494 <= id && id < 650) {
        regionName = regionNames[4];
    } else {
        regionName = regionNames[5];
    }
    regionHolder.innerHTML = regionName.capitalizeString();
    regionHolder.innerHTML += " REGION";
}

window.onload = function () {
    document.getElementById("searchButton").addEventListener("click", pokeSearch);
    document.getElementById("searchBar").addEventListener("keyup", function (event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            pokeSearch();
        }
    });
};

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.lowerFirstLetter = function () {
    return this.charAt(0).toLowerCase() + this.slice(1);
};

String.prototype.capitalizeString = function () {
    var capString = "";
    for (i = 0; i < this.length; i++){
        capString += this.charAt(i).toUpperCase();
    }
    return capString;
};

var regionNames = ["Kanto", "Johto", "Hoenn", "Sinnoh", "Unova", "Kalos"];

var typeJSON = {"types": [{"name": "normal", "color": "#aaa", "effects": {"weak_to": ["fighting"], "resistant_to":[],"immune_to":["ghost"]}},
{"name":"fighting", "color": "#aaa", "effects":{"weak_to":["flying","psychic","fairy"],"resistant_to":["rock","bug","dark"],"immune_to":[]}},
{"name":"flying", "color": "#aaa", "effects":{"weak_to":["rock","electric","ice"],"resistant_to":["fighting","bug","grass"],"immune_to":["ground"]}},
{"name":"poison", "color": "#aaa", "effects":{"weak_to":["ground","psychic"],"resistant_to":["fighting","poison","bug","grass","fairy"],"immune_to":[]}},
{"name":"ground", "color": "#aaa", "effects":{"weak_to":["water","grass","ice"],"resistant_to":["poison","rock"],"immune_to":["electric"]}},
{"name":"rock", "color": "#aaa", "effects":{"weak_to":["fighting","ground","steel","water","grass"],"resistant_to":["normal","flying","poison","fire"],"immune_to":[]}},
{"name":"bug", "color": "#aaa", "effects":{"weak_to":["flying","rock","fire"],"resistant_to":["fighting","ground","grass"],"immune_to":[]}},
{"name":"ghost", "color": "#aaa", "effects":{"weak_to":["ghost","dark"],"resistant_to":["poison","bug"],"immune_to":["normal","fighting"]}},
{"name":"steel", "color": "#aaa", "effects":{"weak_to":["fighting","ground","fire"],"resistant_to":["normal","flying","rock","bug","steel","grass","psychic","ice","dragon","fairy"],"immune_to":["poison"]}},
{"name":"fire", "color": "#aaa", "effects":{"weak_to":["ground","rock","water"],"resistant_to":["bug","steel","fire","grass","ice","fairy"],"immune_to":[]}},
{"name":"water", "color": "#aaa", "effects":{"weak_to":["grass","electric"],"resistant_to":["steel","fire","water","ice"],"immune_to":[]}},
{"name":"grass", "color": "#aaa", "effects":{"weak_to":["flying","poison","bug","fire","ice"],"resistant_to":["ground","water","grass","electric"],"immune_to":[]}},
{"name":"electric", "color": "#aaa", "effects":{"weak_to":["ground"],"resistant_to":["flying","steel","electric"],"immune_to":[]}},
{"name":"psychic", "color": "#aaa", "effects":{"weak_to":["bug","ghost","dark"],"resistant_to":["fighting","psychic"],"immune_to":[]}},
{"name":"ice", "color": "#aaa", "effects":{"weak_to":["fighting","rock","steel","fire"],"resistant_to":["ice"],"immune_to":[]}},
{"name":"dragon", "color": "#aaa", "effects":{"weak_to":["ice","dragon","fairy"],"resistant_to":["fire","water","grass","electric"],"immune_to":[]}},
{"name":"dark", "color": "#aaa", "effects":{"weak_to":["fighting","bug","fairy"],"resistant_to":["ghost","dark"],"immune_to":["psychic"]}},
{"name":"fairy", "color": "#aaa", "effects":{"weak_to":["poison","steel"],"resistant_to":["fighting","bug","dark"],"immune_to":["dragon"]}}]};<commit_msg>created a color palette for all of the types and added them to my typeData JSON<commit_after>/* TODO :
    -add client side caching of pokemon they look up in a session so if they re-look them up it doesn't have to make extranious calls to the backend (web-storage)
    store: localstorage.setItem('key', JSON.stringify({name: 'value'}));
    get: JSON.parse(localStorage.getItem('key')).name;
    -set up JSON objects for each pokemon for storage
    {name: 'name', id: '', type: 'type', img: 'url'}

    -add section for what types they are good against

    -some double pokemon show types they aren't weak against due to having types that are resistant to something as well as the other being weak to it, the algorithm needs to be expanded to include these

    UI UPDATE NOTES
    Type colors :

*/

var xmlhttp = new XMLHttpRequest();
var baseurl = "http://pokeapi.co/api/v2/pokemon/";

function pokeSearch() {
    //grab the pokemon they search for
    var pokemon = document.getElementById("searchBar").value.lowerFirstLetter();
    var currentShowing = document.getElementById("pokeName").innerHTML.lowerFirstLetter();
    //test if they are re-searching for whats already there
    //prevent another api call
    if (pokemon === currentShowing) {
        //keep the current showing
    } else {

        console.log("no currently showing or diff");
        document.getElementById("pokeDisplay").style.display = "none";
        document.getElementById("errorState").style.display = "none";
        document.getElementById("loader").style.display = "block";
        //make the full URL based on search
        var url = baseurl.concat(pokemon);
        url = url.concat("/");
        console.log("begin request");
        xmlhttp.open("GET", url, true);
        xmlhttp.onload = function () {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                var json = JSON.parse(xmlhttp.responseText);
                console.log("end request");
                pokeDisplay(json);
            } else {
                document.getElementById("errorMessage").innerHTML = pokemon + " can't be found!";
                document.getElementById("loader").style.display = "none";
                document.getElementById("errorState").style.display = "block";
                console.error(xmlhttp.statusText);
            }
        };
        xmlhttp.send();
    }
}

//placing the data into the page
function pokeDisplay(json) {
    var name = json.name.capitalizeString();
    var weaknesses = "";

    //var urls = [];
    var formattedTypes = [];
    //place information we already have
    document.getElementById("pokeDisplay").style.display = "block";
    document.getElementById("pokeName").innerHTML = name;
    console.log(json.id < 10);
    if(json.id < 10) {
        document.getElementById("pokeID").innerHTML = "#00" + json.id;
    } else if (json.id < 100) {
        document.getElementById("pokeID").innerHTML = "#0" + json.id;
    } else {
        document.getElementById("pokeID").innerHTML = "#" + json.id;
    }

    document.getElementById("pokeImg").src = json.sprites.front_default;
    document.getElementById("type1").style.display = "none";
    document.getElementById("type2").style.display = "none";
    document.getElementById("weaknesses").innerHTML = "";

    console.log(json.id);
    showRegion(json.id);

    var types = [];
    //create an array of type names for finding weaknesses and display
    for (i = 0; i < json.types.length; i++) {
        types.push(json.types[i].type.name);
    }
    document.getElementById("weakTitle").style.visibility = "visible";
    localType(types);

    document.getElementById("loader").style.display = "none";

}

function localType(pTypes) {
    var allWeaknesses = [];
    for (i = 0; i < pTypes.length; i++) {
        var color;
        for (j = 0; j < typeJSON.types.length; j++) {
            var type = typeJSON.types[j];
            if (pTypes[i] === type.name) {
                color = type.color;
                for (k = 0; k < type.effects.weak_to.length; k++) {
                    allWeaknesses.push(type.effects.weak_to[k]);
                }
            }
        }
        if(i === 0) {
            var type = document.getElementById("type2");
            type.style.display = "block";
            type.innerHTML = pTypes[i];
            type.style.background = color;
        } else {
            var type = document.getElementById("type1");
            type.style.display = "block";
            type.innerHTML = pTypes[i];
            type.style.background = color;
        }

    }
    displayTypeWeaknesses(allWeaknesses);
}

function displayTypeWeaknesses(weaknesses) {
    var alreadyDisplayed = [];
    var pokeWeak = document.getElementById("weaknesses");
    for (i = 0; i < weaknesses.length; i++) {
        var found = false;
        for (j = 0; j < alreadyDisplayed.length; j++) {
            if (alreadyDisplayed[j] === weaknesses[i]) {
                found = true;
                break;
            }
        }
        if (!found) {
            alreadyDisplayed.push(weaknesses[i]);
            pokeWeak.innerHTML += weaknesses[i];
            if (!(i === weaknesses.length - 1)) {
                pokeWeak.innerHTML += "  ";
            }
        }

    }
}

function showRegion(id) {
    console.log("in region: " + id);
    var regionHolder = document.getElementById("region");
    var regionName = "";
    if (id < 152){
        regionName = regionNames[0];
    } else if (152 <= id && id < 252) {
        regionName = regionNames[1];
    } else if (252 <= id && id < 387) {
        regionName = regionNames[2];
    } else if (387 <= id && id < 494) {
        regionName = regionNames[3];
    } else if (494 <= id && id < 650) {
        regionName = regionNames[4];
    } else {
        regionName = regionNames[5];
    }
    regionHolder.innerHTML = regionName.capitalizeString();
    regionHolder.innerHTML += " REGION";
}

window.onload = function () {
    document.getElementById("searchButton").addEventListener("click", pokeSearch);
    document.getElementById("searchBar").addEventListener("keyup", function (event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            pokeSearch();
        }
    });
};

String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.lowerFirstLetter = function () {
    return this.charAt(0).toLowerCase() + this.slice(1);
};

String.prototype.capitalizeString = function () {
    var capString = "";
    for (i = 0; i < this.length; i++){
        capString += this.charAt(i).toUpperCase();
    }
    return capString;
};

var regionNames = ["Kanto", "Johto", "Hoenn", "Sinnoh", "Unova", "Kalos"];
/*
normal: #aaa
    fighting: #C25942
    flying: #B3BAE6
    poison: #A246E8
    ground: #D19F41
    rock: #946715
    bug: #92B368
    ghost: #291B3B
    steel: #DBDBDB
    fire: #F2452E
    water: #6B9DED
    grass: #94DB76
    electric: #E8E83F
    psychic: #E23FE8
    ice: #AAFAF2
    dragon: #032B63
    dark: #1D2024
    fairy: #F7B5EE
*/
var typeJSON = {"types": [{"name": "normal", "color": "#aaa", "effects": {"weak_to": ["fighting"], "resistant_to":[],"immune_to":["ghost"]}},
{"name":"fighting", "color": "#C25942", "effects":{"weak_to":["flying","psychic","fairy"],"resistant_to":["rock","bug","dark"],"immune_to":[]}},
{"name":"flying", "color": "#B3BAE6", "effects":{"weak_to":["rock","electric","ice"],"resistant_to":["fighting","bug","grass"],"immune_to":["ground"]}},
{"name":"poison", "color": "#A246E8", "effects":{"weak_to":["ground","psychic"],"resistant_to":["fighting","poison","bug","grass","fairy"],"immune_to":[]}},
{"name":"ground", "color": "#D19F41", "effects":{"weak_to":["water","grass","ice"],"resistant_to":["poison","rock"],"immune_to":["electric"]}},
{"name":"rock", "color": "#946715", "effects":{"weak_to":["fighting","ground","steel","water","grass"],"resistant_to":["normal","flying","poison","fire"],"immune_to":[]}},
{"name":"bug", "color": "#92B368", "effects":{"weak_to":["flying","rock","fire"],"resistant_to":["fighting","ground","grass"],"immune_to":[]}},
{"name":"ghost", "color": "#291B3B", "effects":{"weak_to":["ghost","dark"],"resistant_to":["poison","bug"],"immune_to":["normal","fighting"]}},
{"name":"steel", "color": "#DBDBDB", "effects":{"weak_to":["fighting","ground","fire"],"resistant_to":["normal","flying","rock","bug","steel","grass","psychic","ice","dragon","fairy"],"immune_to":["poison"]}},
{"name":"fire", "color": "#F2452E", "effects":{"weak_to":["ground","rock","water"],"resistant_to":["bug","steel","fire","grass","ice","fairy"],"immune_to":[]}},
{"name":"water", "color": "#6B9DED", "effects":{"weak_to":["grass","electric"],"resistant_to":["steel","fire","water","ice"],"immune_to":[]}},
{"name":"grass", "color": "#94DB76", "effects":{"weak_to":["flying","poison","bug","fire","ice"],"resistant_to":["ground","water","grass","electric"],"immune_to":[]}},
{"name":"electric", "color": "#E8E83F", "effects":{"weak_to":["ground"],"resistant_to":["flying","steel","electric"],"immune_to":[]}},
{"name":"psychic", "color": "#E23FE8", "effects":{"weak_to":["bug","ghost","dark"],"resistant_to":["fighting","psychic"],"immune_to":[]}},
{"name":"ice", "color": "#AAFAF2", "effects":{"weak_to":["fighting","rock","steel","fire"],"resistant_to":["ice"],"immune_to":[]}},
{"name":"dragon", "color": "#032B63", "effects":{"weak_to":["ice","dragon","fairy"],"resistant_to":["fire","water","grass","electric"],"immune_to":[]}},
{"name":"dark", "color": "#1D2024", "effects":{"weak_to":["fighting","bug","fairy"],"resistant_to":["ghost","dark"],"immune_to":["psychic"]}},
{"name":"fairy", "color": "F7B5EE", "effects":{"weak_to":["poison","steel"],"resistant_to":["fighting","bug","dark"],"immune_to":["dragon"]}}]};<|endoftext|>