<commit_before>/*!
 * ajl
 *
 * Copyright 2015 Hideki Abe
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */
 /*!
 |*|
 |*|  :: cookies.js ::
 |*|
 |*|  A complete cookies reader/writer framework with full unicode support.
 |*|
 |*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
 |*|
 |*|  Syntaxes:
 |*|
 |*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
 |*|  * docCookies.getItem(name)
 |*|  * docCookies.removeItem(name[, path])
 |*|  * docCookies.hasItem(name)
 |*|  * docCookies.keys()
 |*|
 \*/

(function (window, document) {
"use strict";

// ----------------------------------------------------------------------------
// 名前空間作成
// ----------------------------------------------------------------------------
var ajl;

if (!ajl) {
    ajl = window.ajl = {
        version: "1.0.0"    // コアバージョン
    };
}

// ----------------------------------------------------------------------------
// 機能許可インタフェース（簡易実行ラッパー）格納用
// ----------------------------------------------------------------------------
ajl.enable = {};

// ----------------------------------------------------------------------------
// 各種定義
// ----------------------------------------------------------------------------
ajl.def = {
    keyCode: {
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        LEFT: 37,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        SPACE: 32,
        TAB: 9,
        ENTER: 13
    }
};

// ----------------------------------------------------------------------------
// ユーティリティ
// ----------------------------------------------------------------------------
ajl.util = {
    decapitalize: function (str) {
        return str.charAt(0).toLowerCase() + str.slice(1);
    },

    deepExtend: function (out) {
        var i;

        out = out || {};

        for (i = 1; i < arguments.length; i += 1) {
            var obj = arguments[i],
                key;

            if (!obj) {
                continue;
            }

            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    // ECMAScript 5.1では、typeof /s/ === 'object';
                    // if (!/^\/.*\/$/.test(obj[key]) && typeof obj[key] === "object") {
                    //     ajl.util.deepExtend(out[key], obj[key]);
                    // } else {
                        out[key] = obj[key];
                    // }
                }
            }
        }

        return out;
    },

    proxy: function (obj, fn) {
        return function () {
            fn.apply(obj, arguments);
        };
    },

    getRunner: function (NewObj) {
        return function (className, options) {
            var elems = document.querySelectorAll(className),
                nElems = elems.length,
                ret = new Array(nElems),
                e;

            for (e = 0; e < nElems; e += 1) {
                ret[e] = new NewObj(elems[e], options);
                ret[e].init();
            }

            return ret;
        };
    },

    createRunner: function (newObjName) {
        ajl.enable[ajl.util.decapitalize(newObjName)] = ajl.util.getRunner(ajl[newObjName]);
    }
};

// ----------------------------------------------------------------------------
// Cookieユーティリティ
// https://developer.mozilla.org/ja/docs/Web/API/Document/cookie
// docCookiesをajl.cookieとして取り込み。
// ----------------------------------------------------------------------------
ajl.cookie = {
    getItem: function(sKey) {
        if (!sKey || !this.hasItem(sKey)) {
            return null;
        }
        return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },

    setItem: function(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return;
        }
        var sExpires = "";
        if (vEnd) {
            switch (vEnd.constructor) {
                case Number:
                    sExpires = vEnd === Infinity ? "; expires=Tue, 19 Jan 2038 03:14:07 GMT" : "; max-age=" + vEnd;
                    break;
                case String:
                    sExpires = "; expires=" + vEnd;
                    break;
                case Date:
                    sExpires = "; expires=" + vEnd.toGMTString();
                    break;
            }
        }
        document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    },

    removeItem: function(sKey, sPath) {
        if (!sKey || !this.hasItem(sKey)) {
            return;
        }
        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
    },

    hasItem: function(sKey) {
        return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
    },

    keys: /* optional method: you can safely remove it! */ function() {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
            aKeys[nIdx] = unescape(aKeys[nIdx]);
        }
        return aKeys;
    }
};

// ----------------------------------------------------------------------------
// Event
// ----------------------------------------------------------------------------
ajl.event = {
    _stack: [],

    add: function (elem, type, listener, useCapture) {
        var events = [],
            nEvents,
            i;

        if (type.indexOf(",") > -1) {
            events = type.split(",");
            for (i = 0, nEvents = events.length; i < nEvents; i += 1) {
                // String.prototype.trim(): IE9+
                // See Also: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/trim
                if (elem === window &&
                    events[i].trim() === "load" &&
                    document.readyState === "complete") {
                    listener();
                } else {
                    elem.addEventListener(events[i].trim(), listener, useCapture);
                }
            }
        } else {
            if (elem === window &&
                type === "load" &&
                document.readyState === "complete") {
                listener();
            } else {
                elem.addEventListener(type, listener, useCapture);
            }
        }

        if (type !== "unload") {
            ajl.event._stack.push([elem, type, listener, useCapture]);
        }
    },

    remove: function (elem, type, listener, useCapture) {
        var events = [],
            nEvents,
            i;

        if (type.indexOf(",") > -1) {
            events = type.split(",");
            for (i = 0, nEvents = events.length; i < nEvents; i += 1) {
                // Support IE9+
                elem.removeEventListener(events[i].trim(), listener, useCapture);
            }
        } else {
            elem.removeEventListener(type, listener, useCapture);
        }
    },

    trigger: function (elem, type, data) {
        var e,
            detailObj = {};

        if (data) {
            detailObj.detail = data;
        }

        e = document.createEvent("CustomEvent");
        e.initCustomEvent(type, true, true, data);
        elem.dispatchEvent(e);
    }
};

// ------------------------------------
// メモリリーク防止（IE6-8 custom event）
// ------------------------------------
ajl.event.add(window, "unload", function () {
    var stacks = ajl.event._stack,
        nStacks = stacks.length,
        s;

    for (s = 0; s < nStacks; s += 1) {
        ajl.event.remove.apply(ajl.event, stacks[s]);
    }
});

// ----------------------------------------------------------------------------
// スタイル
// ----------------------------------------------------------------------------
ajl.style = {
    getPropValue: function (elem, property) {
        var style = getComputedStyle(elem);

        return style[property];
    },

    getOuterHeight: function (elem, containMargin) {
        var height = elem.offsetHeight,
            style;

        if (containMargin) {
            style = getComputedStyle(elem);
            height += parseInt(style.marginTop) + parseInt(style.marginBottom);
        }

        return height + "px";
    }
};

// ----------------------------------------------------------------------------
// 外部API呼び出し時のコールバック格納
// ----------------------------------------------------------------------------
ajl.cb = {};

}(window, document));
<commit_msg>ajl.util.deepExtendの修正<commit_after>/*!
 * ajl
 *
 * Copyright 2015 Hideki Abe
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */
 /*!
 |*|
 |*|  :: cookies.js ::
 |*|
 |*|  A complete cookies reader/writer framework with full unicode support.
 |*|
 |*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
 |*|
 |*|  Syntaxes:
 |*|
 |*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
 |*|  * docCookies.getItem(name)
 |*|  * docCookies.removeItem(name[, path])
 |*|  * docCookies.hasItem(name)
 |*|  * docCookies.keys()
 |*|
 \*/

(function (window, document) {
"use strict";

// ----------------------------------------------------------------------------
// 名前空間作成
// ----------------------------------------------------------------------------
var ajl;

if (!ajl) {
    ajl = window.ajl = {
        version: "1.0.0"    // コアバージョン
    };
}

// ----------------------------------------------------------------------------
// 機能許可インタフェース（簡易実行ラッパー）格納用
// ----------------------------------------------------------------------------
ajl.enable = {};

// ----------------------------------------------------------------------------
// 各種定義
// ----------------------------------------------------------------------------
ajl.def = {
    keyCode: {
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        LEFT: 37,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        SPACE: 32,
        TAB: 9,
        ENTER: 13
    }
};

// ----------------------------------------------------------------------------
// ユーティリティ
// ----------------------------------------------------------------------------
ajl.util = {
    decapitalize: function (str) {
        return str.charAt(0).toLowerCase() + str.slice(1);
    },

    deepExtend: function (out) {
        var i;

        out = out || {};

        for (i = 1; i < arguments.length; i += 1) {
            var obj = arguments[i],
                key;

            if (!obj) {
                continue;
            }

            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    // ECMAScript 5.1では、typeof /s/ === 'object';
                    if (!/^\/.*\/$/.test(obj[key]) && typeof obj[key] === "object") {
                        out[key] = ajl.util.deepExtend({}, out[key], obj[key]);
                    } else {
                        out[key] = obj[key];
                    }
                }
            }
        }

        return out;
    },

    proxy: function (obj, fn) {
        return function () {
            fn.apply(obj, arguments);
        };
    },

    getRunner: function (NewObj) {
        return function (className, options) {
            var elems = document.querySelectorAll(className),
                nElems = elems.length,
                ret = new Array(nElems),
                e;

            for (e = 0; e < nElems; e += 1) {
                ret[e] = new NewObj(elems[e], options);
                ret[e].init();
            }

            return ret;
        };
    },

    createRunner: function (newObjName) {
        ajl.enable[ajl.util.decapitalize(newObjName)] = ajl.util.getRunner(ajl[newObjName]);
    }
};

// ----------------------------------------------------------------------------
// Cookieユーティリティ
// https://developer.mozilla.org/ja/docs/Web/API/Document/cookie
// docCookiesをajl.cookieとして取り込み。
// ----------------------------------------------------------------------------
ajl.cookie = {
    getItem: function(sKey) {
        if (!sKey || !this.hasItem(sKey)) {
            return null;
        }
        return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },

    setItem: function(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return;
        }
        var sExpires = "";
        if (vEnd) {
            switch (vEnd.constructor) {
                case Number:
                    sExpires = vEnd === Infinity ? "; expires=Tue, 19 Jan 2038 03:14:07 GMT" : "; max-age=" + vEnd;
                    break;
                case String:
                    sExpires = "; expires=" + vEnd;
                    break;
                case Date:
                    sExpires = "; expires=" + vEnd.toGMTString();
                    break;
            }
        }
        document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    },

    removeItem: function(sKey, sPath) {
        if (!sKey || !this.hasItem(sKey)) {
            return;
        }
        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
    },

    hasItem: function(sKey) {
        return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
    },

    keys: /* optional method: you can safely remove it! */ function() {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
            aKeys[nIdx] = unescape(aKeys[nIdx]);
        }
        return aKeys;
    }
};

// ----------------------------------------------------------------------------
// Event
// ----------------------------------------------------------------------------
ajl.event = {
    _stack: [],

    add: function (elem, type, listener, useCapture) {
        var events = [],
            nEvents,
            i;

        if (type.indexOf(",") > -1) {
            events = type.split(",");
            for (i = 0, nEvents = events.length; i < nEvents; i += 1) {
                // String.prototype.trim(): IE9+
                // See Also: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/trim
                if (elem === window &&
                    events[i].trim() === "load" &&
                    document.readyState === "complete") {
                    listener();
                } else {
                    elem.addEventListener(events[i].trim(), listener, useCapture);
                }
            }
        } else {
            if (elem === window &&
                type === "load" &&
                document.readyState === "complete") {
                listener();
            } else {
                elem.addEventListener(type, listener, useCapture);
            }
        }

        if (type !== "unload") {
            ajl.event._stack.push([elem, type, listener, useCapture]);
        }
    },

    remove: function (elem, type, listener, useCapture) {
        var events = [],
            nEvents,
            i;

        if (type.indexOf(",") > -1) {
            events = type.split(",");
            for (i = 0, nEvents = events.length; i < nEvents; i += 1) {
                // Support IE9+
                elem.removeEventListener(events[i].trim(), listener, useCapture);
            }
        } else {
            elem.removeEventListener(type, listener, useCapture);
        }
    },

    trigger: function (elem, type, data) {
        var e,
            detailObj = {};

        if (data) {
            detailObj.detail = data;
        }

        e = document.createEvent("CustomEvent");
        e.initCustomEvent(type, true, true, data);
        elem.dispatchEvent(e);
    }
};

// ------------------------------------
// メモリリーク防止（IE6-8 custom event）
// ------------------------------------
ajl.event.add(window, "unload", function () {
    var stacks = ajl.event._stack,
        nStacks = stacks.length,
        s;

    for (s = 0; s < nStacks; s += 1) {
        ajl.event.remove.apply(ajl.event, stacks[s]);
    }
});

// ----------------------------------------------------------------------------
// スタイル
// ----------------------------------------------------------------------------
ajl.style = {
    getPropValue: function (elem, property) {
        var style = getComputedStyle(elem);

        return style[property];
    },

    getOuterHeight: function (elem, containMargin) {
        var height = elem.offsetHeight,
            style;

        if (containMargin) {
            style = getComputedStyle(elem);
            height += parseInt(style.marginTop) + parseInt(style.marginBottom);
        }

        return height + "px";
    }
};

// ----------------------------------------------------------------------------
// 外部API呼び出し時のコールバック格納
// ----------------------------------------------------------------------------
ajl.cb = {};

}(window, document));
<|endoftext|>


<commit_before>(function () {
	var Diversibee = {};

	/**
	 * Private methods
	 */
	function setUpBoardState(cellsWide, cellsHigh) {
		// initializes board state

		var cells = [],
			distanceFromSeedCell,
			isForest,
			i,
			//The likelihood a cell contains a "seed"; probability bound 0 <= seedRate <= 1
			seedRate = 0.02,
			//Cells containing an initial "seed". Seeds are used to determine the inital forest growth
			seededCells = generateUniqueRandomCells(cellsHigh, cellsWide, (cellsHigh*cellsWide*seedRate));

		for(i=0; i<cellsWide*cellsHigh; i++){
			distanceFromSeedCell = distancefromSeed(i, cellsWide, seededCells);
			//Does this cell initially become a forest based on the cell"s seed proximity
			isForest = shouldGrowForest(distanceFromSeedCell);

			if(isForest){
				cells[i] = {
					type: "forest",
					beePop: [Math.floor(Math.random()*1000), Math.floor(Math.random()*1000), Math.floor(Math.random()*1000), Math.floor(Math.random()*1000)],
					beeGrowth: [0,0,0,0]
				}
			} else {
				cells[i] = {
					type: "grass",
					beePop: [0,0,0,0],
					beeGrowth: [0,0,0,0]
				}
			}
		}

		return cells;
	}

	function setAnimation(i) {
		//set up the animation for cell i

		store.mapCell[i] = new createjs.Sprite(store.spriteSheet, store.state[i].type);
		store.mapCell[i].x = 20*(i%store.width);
		store.mapCell[i].y = 20*Math.floor(i/store.width);
		store.mapCell[i].addEventListener("click", clickCell.bind(this, i));
		store.mapCell[i].addEventListener("mouseover", showStats.bind(this, i));

		store.stage.addChild(store.mapCell[i]);
		store.mapCell[i].play(store.state[i].type);
	}

	function repaintBoard() {
		//re-paints the board state

		if(store.animationLoop) {
			clearInterval(store.animationLoop);
		}

		store.stage.update();
		store.animationLoop = setInterval(function(){store.stage.update();}, 300);
	}

	function clickCell(i) {
		//handle when a player clicks on the ith cell

		//change the clicked cell to a blueberry patch
		if(store.cash >=100 && store.state[i].type !== "blueberries") {
			store.state[i] = {
				type: "blueberries",
				beePop: [0,0,0,0],
				beeGrowth: [0,0,0,0]
			}
			updateCash(-1*store.blueberryBuildPrice);
			setAnimation(i)
			repaintBoard();
		}
	}

	function showStats(i) {
		//display the current state of cell i in a text box.

		var text = "Current State of cell " + i +":
";

		text += "Type: " + store.state[i].type + "
";

		text += "Bee Populations: " + store.state[i].beePop + "
";

		text += "Bee Growth Rates: " + store.state[i].beeGrowth;

		document.getElementById("cellStats").innerHTML = text;
	}

	function updateCash(income) {
		//update the farmer"s bank account

		store.cash += income;
		document.getElementById("bank").innerHTML = "$"+store.cash;
	}

	function advanceTurn(){
		//trigger to advance to next turn

		var i;

		//update bee populations in forests & gather profits from blueberries
		for(i=0; i<store.width*store.height; i++) {
			if(store.state[i].type === "forest") {
				updateBeePop(i);
				updateBeeGrowth(i, adjacentCells(i));
			} else if (store.state[i].type === "blueberries") {
				updateProfits(i, adjacentCells(i));
			}
		}
	}

	function updateBeePop(i) {
		//update the bee population in cell i based on its current growth rates

		var j;

		for(j=0; j<store.state[i].beePop.length; j++) {
			store.state[i].beePop[j] += store.state[i].beeGrowth[j];
			store.state[i].beePop[j] = Math.max(0, store.state[i].beePop[j]);
		}
	}

	function updateBeeGrowth(i, neighbours) {
		//update the growth rate for the bee populations in cell i based on effects from the cell"s nearest neighbours

		baseBeeSpawning(i);
		forestEdgeEffect(i, neighbours);
	}

	function updateProfits(i, neighbours) {
		//collect profits from cell i, modified by its nearest neghbours

		updateCash(basicProfits(neighbours));
	}

	function distancefromSeed(cell, width, seededCells) {
		//Returns the distance from a cell to the closest seed (seeds are given as an array of cell locations)
		var distance = Number.MAX_SAFE_INTEGER;
		var i;
		var temp_dist;

		for(i=0; i<seededCells.length; i++){
			temp_dist = distanceBetweenCells(seededCells[i], cell, width);
			distance = Math.min(distance, temp_dist);
		}
		return distance;
	}

	function distanceBetweenCells(cellA, cellB, boardWidth) {
		//returns the distance between cell A and cell B

		var xDiff = (cellA % boardWidth) - (cellB % boardWidth);
		var yDiff = (Math.floor(cellA / boardWidth)) - (Math.floor(cellB / boardWidth));
		return Math.abs(xDiff) + Math.abs(yDiff);
	}

	function shouldGrowForest(distanceFromSeed) {
		//A simple forest growth algorithm which clusters around seed locations

		return distanceFromSeed + distanceFromSeed * Math.random() < 5;
	}

	function generateUniqueRandomCells(height, width, numberOfCells) {
		//Returns an array of unique random cells

		var uniqueRandomCells = [],
			i;
		//we can safely choose the first unique random cell number
		var cellNumber = Math.floor(Math.random() * (height * width));

		for(i=0; i<numberOfCells; i++) {
			while ( inArray(cellNumber, uniqueRandomCells) ) {
				cellNumber = Math.floor(Math.random() * (height * width));
			}
			uniqueRandomCells.push(cellNumber);
		}
		return uniqueRandomCells;
	}

	Diversibee.init = function () {

	};

	Diversibee.advanceTurn = function () {

	};

	window.Diversibee = Diversibee;
})();
<commit_msg>Public methods implemented, from stateManagement.js - #30<commit_after>(function () {
	var Diversibee = {};

	/**
	 * Private methods
	 */
	function setUpBoardState(cellsWide, cellsHigh) {
		// initializes board state

		var cells = [],
			distanceFromSeedCell,
			isForest,
			i,
			//The likelihood a cell contains a "seed"; probability bound 0 <= seedRate <= 1
			seedRate = 0.02,
			//Cells containing an initial "seed". Seeds are used to determine the inital forest growth
			seededCells = generateUniqueRandomCells(cellsHigh, cellsWide, (cellsHigh*cellsWide*seedRate));

		for(i=0; i<cellsWide*cellsHigh; i++){
			distanceFromSeedCell = distancefromSeed(i, cellsWide, seededCells);
			//Does this cell initially become a forest based on the cell"s seed proximity
			isForest = shouldGrowForest(distanceFromSeedCell);

			if(isForest){
				cells[i] = {
					type: "forest",
					beePop: [Math.floor(Math.random()*1000), Math.floor(Math.random()*1000), Math.floor(Math.random()*1000), Math.floor(Math.random()*1000)],
					beeGrowth: [0,0,0,0]
				}
			} else {
				cells[i] = {
					type: "grass",
					beePop: [0,0,0,0],
					beeGrowth: [0,0,0,0]
				}
			}
		}

		return cells;
	}

	function setAnimation(i) {
		//set up the animation for cell i

		store.mapCell[i] = new createjs.Sprite(store.spriteSheet, store.state[i].type);
		store.mapCell[i].x = 20*(i%store.width);
		store.mapCell[i].y = 20*Math.floor(i/store.width);
		store.mapCell[i].addEventListener("click", clickCell.bind(this, i));
		store.mapCell[i].addEventListener("mouseover", showStats.bind(this, i));

		store.stage.addChild(store.mapCell[i]);
		store.mapCell[i].play(store.state[i].type);
	}

	function repaintBoard() {
		//re-paints the board state

		if(store.animationLoop) {
			clearInterval(store.animationLoop);
		}

		store.stage.update();
		store.animationLoop = setInterval(function(){store.stage.update();}, 300);
	}

	function clickCell(i) {
		//handle when a player clicks on the ith cell

		//change the clicked cell to a blueberry patch
		if(store.cash >=100 && store.state[i].type !== "blueberries") {
			store.state[i] = {
				type: "blueberries",
				beePop: [0,0,0,0],
				beeGrowth: [0,0,0,0]
			}
			updateCash(-1*store.blueberryBuildPrice);
			setAnimation(i)
			repaintBoard();
		}
	}

	function showStats(i) {
		//display the current state of cell i in a text box.

		var text = "Current State of cell " + i +":
";

		text += "Type: " + store.state[i].type + "
";

		text += "Bee Populations: " + store.state[i].beePop + "
";

		text += "Bee Growth Rates: " + store.state[i].beeGrowth;

		document.getElementById("cellStats").innerHTML = text;
	}

	function updateCash(income) {
		//update the farmer"s bank account

		store.cash += income;
		document.getElementById("bank").innerHTML = "$"+store.cash;
	}

	function advanceTurn(){
		//trigger to advance to next turn

		var i;

		//update bee populations in forests & gather profits from blueberries
		for(i=0; i<store.width*store.height; i++) {
			if(store.state[i].type === "forest") {
				updateBeePop(i);
				updateBeeGrowth(i, adjacentCells(i));
			} else if (store.state[i].type === "blueberries") {
				updateProfits(i, adjacentCells(i));
			}
		}
	}

	function updateBeePop(i) {
		//update the bee population in cell i based on its current growth rates

		var j;

		for(j=0; j<store.state[i].beePop.length; j++) {
			store.state[i].beePop[j] += store.state[i].beeGrowth[j];
			store.state[i].beePop[j] = Math.max(0, store.state[i].beePop[j]);
		}
	}

	function updateBeeGrowth(i, neighbours) {
		//update the growth rate for the bee populations in cell i based on effects from the cell"s nearest neighbours

		baseBeeSpawning(i);
		forestEdgeEffect(i, neighbours);
	}

	function updateProfits(i, neighbours) {
		//collect profits from cell i, modified by its nearest neghbours

		updateCash(basicProfits(neighbours));
	}

	function distancefromSeed(cell, width, seededCells) {
		//Returns the distance from a cell to the closest seed (seeds are given as an array of cell locations)
		var distance = Number.MAX_SAFE_INTEGER;
		var i;
		var temp_dist;

		for(i=0; i<seededCells.length; i++){
			temp_dist = distanceBetweenCells(seededCells[i], cell, width);
			distance = Math.min(distance, temp_dist);
		}
		return distance;
	}

	function distanceBetweenCells(cellA, cellB, boardWidth) {
		//returns the distance between cell A and cell B

		var xDiff = (cellA % boardWidth) - (cellB % boardWidth);
		var yDiff = (Math.floor(cellA / boardWidth)) - (Math.floor(cellB / boardWidth));
		return Math.abs(xDiff) + Math.abs(yDiff);
	}

	function shouldGrowForest(distanceFromSeed) {
		//A simple forest growth algorithm which clusters around seed locations

		return distanceFromSeed + distanceFromSeed * Math.random() < 5;
	}

	function generateUniqueRandomCells(height, width, numberOfCells) {
		//Returns an array of unique random cells

		var uniqueRandomCells = [],
			i;
		//we can safely choose the first unique random cell number
		var cellNumber = Math.floor(Math.random() * (height * width));

		for(i=0; i<numberOfCells; i++) {
			while ( inArray(cellNumber, uniqueRandomCells) ) {
				cellNumber = Math.floor(Math.random() * (height * width));
			}
			uniqueRandomCells.push(cellNumber);
		}
		return uniqueRandomCells;
	}

	/**
	 * Public methods
	 */
	Diversibee.init = function () {
		// Initialize the play area on load

		var i;

		//declare global store with default values
		store = {}
		store.width = 20
		store.height = 20
		store.state = setUpBoardState(store.width, store.height);
		store.animationData = {
			images: ["img/spriteSheet.png"],
			frames: {width:20, height:20},
			animations: {
				grass: [0,3],
				forest: [4,7],
				blueberries: [8,11]
			}
		};
		store.stage = new createjs.Stage("board");
		store.stage.enableMouseOver(10);
		store.mapCell = []
		store.spriteSheet = new createjs.SpriteSheet(store.animationData);
		store.w = store.stage.canvas.width;
		store.h = store.stage.canvas.height;
		store.cash = 1000
		store.blueberryBuildPrice = 100

		//set up initial cell animationsL
		for(i=0; i<store.width*store.height; i++) {
			setAnimation(i);
		}
		//paint the initial state of the board
		repaintBoard()

		//set up turn advancement
		document.getElementById("nextTurn").onclick = advanceTurn
		//trigger a turn to finish configuring the board
		Diversibee.advanceTurn();
	};

	Diversibee.advanceTurn = function () {
		//trigger to advance to next turn

		var i;

		//update bee populations in forests & gather profits from blueberries
		for(i=0; i<store.width*store.height; i++) {
			if(store.state[i].type === "forest") {
				updateBeePop(i);
				updateBeeGrowth(i, adjacentCells(i));
			} else if (store.state[i].type === "blueberries") {
				supdateProfits(i, adjacentCells(i));
			}
		}
	};

	window.Diversibee = Diversibee;
})();
<|endoftext|>


<commit_before>function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$(document).ajaxSend(function(event, xhr, settings) {
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (track_ajax) {
      _gaq.push(['_trackPageview', settings.url.split("?")[0]]);
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

var tab_counter = 0;
var $tabs = null;
var load_data = "";
var tab_paths = {};
var tab_counts = {};
var track_int = 600000;

function CurrentTab () {
  try  {
    var href = $("ul.ui-tabs-nav li.ui-tabs-selected a").attr('href');
    var cnt = split_href(href);
    return tab_counts[cnt];
  }

  catch (e) {
    return false;
  }
}

function SaveCurrentTab () {
  var dp = CurrentTab();
  var contents = editor_global.getSession().getValue();

  $("#status").html('Saving ' + tab_paths[dp].filename);

  $.ajax({
    type: 'POST',
    url: '/filesave/',
    data: {'path': dp, 'contents': contents},
    success: function (data, textStatus, jqXHR) {
      $("#status").html('');
      if (data.result == 'bad') {
        alert(data.error);
      }
    },
    error: function (jqXHR, textStatus, errorThrown) { alert('Error Saving: ' + dp); $("#status").html(''); },
  });
}

function set_all_pref () {
  for (dp in tab_paths) {
    set_edit_pref(tab_paths[dp].session, "editor_" + tab_paths[dp].tab);
  }

  $("#kendoStyle").remove();
  $('head').append('<link rel="stylesheet" href="' + static_url + 'ide/css/kendo_styles/kendo.' + pref.uitheme + '.min.css" id="kendoStyle" type="text/css" />');
}

function set_edit_pref (sess, id) {
  load_theme = true;
  for (i in loaded_themes) {
    if (loaded_themes[i] == pref.theme) {
      load_theme = false;
      break;
    }
  }

  if (load_theme) {
    $.ajax({
      url: static_url + 'ide/js/ace/theme-' + pref.theme + '.js',
      dataType: "script",
      async: false,
    });
    loaded_themes.push(pref.theme);
  }

  editor_global.setTheme("ace/theme/" + pref.theme);

  var handler = null;
  if (pref.keybind == 'emacs') {
    handler = require("ace/keyboard/keybinding/emacs").Emacs;
  }

  else if (pref.keybind == 'vim') {
    handler = require("ace/keyboard/keybinding/vim").Vim;
  }

  editor_global.setKeyboardHandler(handler);

  editor_global.setHighlightActiveLine(pref.hactive);
  editor_global.setHighlightSelectedWord(pref.hword);
  editor_global.setShowInvisibles(pref.invisibles);
  editor_global.setBehavioursEnabled(pref.behave);

  editor_global.renderer.setShowGutter(pref.gutter);
  editor_global.renderer.setShowPrintMargin(pref.pmargin);

  sess.setTabSize(pref.tabsize);
  sess.setUseSoftTabs(pref.softab);

  switch (pref.swrap) {
    case "off":
      sess.setUseWrapMode(false);
      editor_global.renderer.setPrintMarginColumn(80);
      break;

    case "40":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(40, 40);
      editor_global.renderer.setPrintMarginColumn(40);
      break;

    case "80":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(80, 80);
      editor_global.renderer.setPrintMarginColumn(80);
      break;

    case "free":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(null, null);
      editor_global.renderer.setPrintMarginColumn(80);
      break;
  }

  $("#" + id).css('font-size', pref.fontsize);
}

var editor_global = null;
var EditSession = require('ace/edit_session').EditSession;
var UndoManager = require("ace/undomanager").UndoManager;

function create_tab (data, textStatus, jqXHR, range) {
  if (data.path in tab_paths) {
    $tabs.tabs('select', "#tabs-" + tab_paths[data.path].tab);
  }

  else {
    if (data.fileType == 'text') {
      $tabs.tabs("add", "#tabs-" + tab_counter, data.filename);
      $tabs.tabs('select', "#tabs-" + tab_counter);

      if (!editor_global) {
        editor_global = ace.edit("editor_global");
      }

      var sess = new EditSession(data.data);
      sess.setUndoManager(new UndoManager());
      editor_global.setSession(sess);

      if (data.mode) {
        var Mode = require("ace/mode/" + data.mode).Mode;
        sess.setMode(new Mode());
      }

      set_edit_pref(sess, "editor_" + tab_counter);

      editor_global.resize();
      editor_global.focus();

      tab_paths[data.path] = {tab: tab_counter, session: sess, filename: data.filename, uid: data.uid}
      tab_counts[tab_counter] = data.path

      tab_counter++;

      current_edit(data.path);

      if (pref.save_session) {
        save_session();
      }

      if (range) {
        sess.getSelection().setSelectionRange(range, false);
      }
    }

    else if (data.fileType == 'binary') {
      alert('binary file');
    }
  }
}

function current_edit (path) {
  try {
    path = path.replace(basedir + '/', '');

    $("#current_edit").html(path);
  }

  catch (e) {}
}

function resize_editor (skip_splitter) {
  var edith = $(window).height() - 33;

  ksplitter.size("#neutron_body", edith + "px");
  $("#splitter, #splitter > div").height(edith - 2);

  var nbw = $("#neutron_body").width() + 1;
  $("#neutron_body").width(nbw);

  var dp = CurrentTab();
  if (dp) {
    current_edit(dp);
    if (tab_paths[dp]) {
      editor_global.setSession(tab_paths[dp].session);
    }

    var href = $("ul.ui-tabs-nav li.ui-tabs-selected a").attr('href');
    var cnt = split_href(href);
  }

  var h = $("#splitter_right").height();
  $("#editor_global").height(h - $('.ui-widget-header').outerHeight());
  $("#editor_global").width($("#splitter_right").width());

  if (editor_global) {
    editor_global.resize();
    editor_global.focus();
  }

  resize_tabs();
}

function resize_tabs () {
  var h = $('#tooltabs').height();
  var t = $('#tooltabs > ul').height() + 2;

  $("#tooltabs > div").height(h - t);
}

function split_href (href) {
  var cnt = href.split('-');
  return cnt[cnt.length - 1];
}

function remove_tab (ui) {
  $("#current_edit").html('');

  var cnt = split_href(ui.tab.href);
  var dp = tab_counts[cnt];

  tab_paths[dp].session.$stopWorker();
  delete tab_paths[dp].session;
  delete tab_paths[dp];
  delete tab_counts[cnt];

  if (pref.save_session) {
    save_session();
  }

  var dp = CurrentTab();
  if (dp) {
    current_edit(dp);
    resize_editor();
  }

  else {
    editor_global = null;
    $('#editor_global').html('');
  }
}

function uploadProgress(id, evt) {
  if (evt.lengthComputable) {
    var pc = Math.round(evt.loaded * 100 / evt.total);

    $('#span_' + id).html('Uploading ' + pc + '%');
  }
}

function uploadFile(id, onComplete) {
  var xhr = new XMLHttpRequest();
  var fd = document.getElementById(id).files[0];

  xhr.upload.addEventListener("progress", function (evt) { uploadProgress(id, evt); }, false);
  xhr.addEventListener("load", function (evt) { onComplete(evt); }, false);
  xhr.addEventListener("error", function (evt) { alert('Upload Failed'); }, false);
  xhr.addEventListener("abort", function (evt) { alert('Upload Cancel'); }, false);

  xhr.open("POST", "/temp_file/?name=" + encodeURIComponent(fd.fileName));
  xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
  xhr.send(fd);
}

function get_file (file, range) {
  var img_patt = /\.(jpg|jpeg|png|bmp|pxd)$/i;

  if (img_patt.test(file)) {
    window.open('/external_open' + encodeURI(file), '_blank');
  }

  else {
    $.ajax({
      type: 'POST',
      async: false,
      url: '/fileget/',
      data: {f: file},
      success: function (data, textStatus, jqXHR) {create_tab(data, textStatus, jqXHR, range);},
      error: function (jqXHR, textStatus, errorThrown) { alert('Error Opening: ' + file); },
    });
  }
}

function file_browser () {
  $('#file_browser > div.inner').fileTree({ root: '', script: '/filetree/', expandSpeed: 200, collapseSpeed: 200 }, get_file);
}

function save_session () {
  if (skip_session) {}

  else {
    var files = '';
    $("ul.ui-tabs-nav > li > a").each(function (index, ele) {
      var cnt = split_href(ele.href);
      var dp = tab_counts[cnt];
      files = files + dp + "\n";
    });

    files = files.substring(0, files.length-1);

    $.ajax({
      type: 'POST',
      url: '/save_session/',
      data: {'files': files},
      success: function (data, textStatus, jqXHR) {},
      error: function (jqXHR, textStatus, errorThrown) { alert('Error Saving Session'); },
    });
  }
}

function sort_change (event, ui) {
  if (pref.save_session) {
    save_session();
  }
}
$(document).ready( function() {
    file_browser();

    $tabs = $("#tabsinner").tabs({
      tabTemplate: "
#{label} x
",
      show: function( event, ui) { resize_editor(); },
			add: function( event, ui) {
        $(ui.panel).append( "

" );
      },
      remove: function (event, ui) { remove_tab(ui); }
    });
    $tabs.find( ".ui-tabs-nav" ).sortable({ axis: "x", update: sort_change});
    $( "#tabs span.ui-icon-close" ).live( "click", function() {
      var p = $(this).parent();
      var index = $( "li", $tabs ).index(p);
      $tabs.tabs( "remove", index );
    });
});

function size_search (e) {
  setTimeout(function () {
    var width = $("#splitter_left").width() - 83;
    $("#search_panel_results a.expand").width(width);

    $("#editor_global").width($("#splitter_right").width());

    if (editor_global) {
      editor_global.resize();
    }
  }, 400);
}

var ksplitter;
var esplitter;
var tabstrip;
var tooltabs;
var search_panel;

$(document).ready(function () {
  $("body").click(function (eObj) {
    $('.right_menu').css('display', 'none');

    if (eObj.target.id && eObj.target.id == 'menu_button') {}
    else if (eObj.target.parentElement.id && eObj.target.parentElement.id == 'menu_button') {}
    else {
      hide_menu();
    }
  });

  search_panel = $("#search_panel").kendoPanelBar().data("kendoPanelBar");
  $("#search_panel_search > span").click();

  tooltabs = $("#tooltabs").kendoTabStrip({animation: false}).data("kendoTabStrip");
  tooltabs.select("#fbtab");
  $("#tooltabs > ul li").click(resize_tabs);

  ksplitter = $("#neutron_ui").kendoSplitter({
    panes: [{resizable: false, size: '35px', scrollable: false}, {scrollable:false, resizable: false, size: '311px'}],
    orientation: 'vertical'
  }).data("kendoSplitter");

  esplitter = $("#splitter").kendoSplitter({resize: size_search, panes: [{collapsible: true, size: '250px', scrollable: false}, {scrollable: false}], resize: size_search}).data("kendoSplitter");

  if (pref.save_session) {
    for (i in init_session) {
      get_file(init_session[i]);
    }

    skip_session = false;
  }

  //$(window).unbind();
  $(window).resize(resize_editor);
  resize_editor();

  if (track_ajax) {
    setTimeout(track_ide, track_int);
  }

});

function track_ide () {
  var d = new Date();
  var ts = d.getYear() + '-' + d.getMonth() + '-' + d.getDay() + '-' + d.getHours() + '-' + d.getMinutes();
  _gaq.push(['_trackPageview', "/?ts=" + ts]);
  setTimeout(track_ide, track_int);
}

window.onbeforeunload = function() {
    return 'Leaving so soon!';
}

var canon = require('pilot/canon');

canon.addCommand({
    name: 'SaveFile',
    bindKey: {
      win: 'Ctrl-S',
      mac: 'Command-S',
      sender: 'editor'
    },
    exec: function(env, args, request) { SaveCurrentTab(); }
});

<commit_msg>static collect<commit_after>function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$(document).ajaxSend(function(event, xhr, settings) {
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (track_ajax) {
      _gaq.push(['_trackPageview', settings.url.split("?")[0]]);
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

var tab_counter = 0;
var $tabs = null;
var load_data = "";
var tab_paths = {};
var tab_counts = {};
var track_int = 600000;

function CurrentTab () {
  try  {
    var href = $("ul.ui-tabs-nav li.ui-tabs-selected a").attr('href');
    var cnt = split_href(href);
    return tab_counts[cnt];
  }

  catch (e) {
    return false;
  }
}

function SaveCurrentTab () {
  var dp = CurrentTab();
  var contents = editor_global.getSession().getValue();

  $("#status").html('Saving ' + tab_paths[dp].filename);

  $.ajax({
    type: 'POST',
    url: '/filesave/',
    data: {'path': dp, 'contents': contents},
    success: function (data, textStatus, jqXHR) {
      $("#status").html('');
      if (data.result == 'bad') {
        alert(data.error);
      }
    },
    error: function (jqXHR, textStatus, errorThrown) { alert('Error Saving: ' + dp); $("#status").html(''); },
  });
}

function set_all_pref () {
  for (dp in tab_paths) {
    set_edit_pref(tab_paths[dp].session, "editor_" + tab_paths[dp].tab);
  }

  $("#kendoStyle").remove();
  $('head').append('<link rel="stylesheet" href="' + static_url + 'ide/css/kendo_styles/kendo.' + pref.uitheme + '.min.css" id="kendoStyle" type="text/css" />');
}

function set_edit_pref (sess, id) {
  load_theme = true;
  for (i in loaded_themes) {
    if (loaded_themes[i] == pref.theme) {
      load_theme = false;
      break;
    }
  }

  if (load_theme) {
    $.ajax({
      url: static_url + 'ide/js/ace/theme-' + pref.theme + '.js',
      dataType: "script",
      async: false,
    });
    loaded_themes.push(pref.theme);
  }

  editor_global.setTheme("ace/theme/" + pref.theme);

  var handler = null;
  if (pref.keybind == 'emacs') {
    handler = require("ace/keyboard/keybinding/emacs").Emacs;
  }

  else if (pref.keybind == 'vim') {
    handler = require("ace/keyboard/keybinding/vim").Vim;
  }

  editor_global.setKeyboardHandler(handler);

  editor_global.setHighlightActiveLine(pref.hactive);
  editor_global.setHighlightSelectedWord(pref.hword);
  editor_global.setShowInvisibles(pref.invisibles);
  editor_global.setBehavioursEnabled(pref.behave);

  editor_global.renderer.setShowGutter(pref.gutter);
  editor_global.renderer.setShowPrintMargin(pref.pmargin);

  sess.setTabSize(pref.tabsize);
  sess.setUseSoftTabs(pref.softab);

  switch (pref.swrap) {
    case "off":
      sess.setUseWrapMode(false);
      editor_global.renderer.setPrintMarginColumn(80);
      break;

    case "40":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(40, 40);
      editor_global.renderer.setPrintMarginColumn(40);
      break;

    case "80":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(80, 80);
      editor_global.renderer.setPrintMarginColumn(80);
      break;

    case "free":
      sess.setUseWrapMode(true);
      sess.setWrapLimitRange(null, null);
      editor_global.renderer.setPrintMarginColumn(80);
      break;
  }

  $("#" + id).css('font-size', pref.fontsize);
}

var editor_global = null;
var EditSession = require('ace/edit_session').EditSession;
var UndoManager = require("ace/undomanager").UndoManager;

function create_tab (data, textStatus, jqXHR, range) {
  if (data.path in tab_paths) {
    $tabs.tabs('select', "#tabs-" + tab_paths[data.path].tab);
  }

  else {
    if (data.fileType == 'text') {
      $tabs.tabs("add", "#tabs-" + tab_counter, data.filename);
      $tabs.tabs('select', "#tabs-" + tab_counter);

      if (!editor_global) {
        editor_global = ace.edit("editor_global");
      }

      var sess = new EditSession(data.data);
      sess.setUndoManager(new UndoManager());
      editor_global.setSession(sess);

      if (data.mode) {
        var Mode = require("ace/mode/" + data.mode).Mode;
        sess.setMode(new Mode());
      }

      set_edit_pref(sess, "editor_" + tab_counter);

      editor_global.resize();
      editor_global.focus();

      tab_paths[data.path] = {tab: tab_counter, session: sess, filename: data.filename, uid: data.uid}
      tab_counts[tab_counter] = data.path

      tab_counter++;

      current_edit(data.path);

      if (pref.save_session) {
        save_session();
      }

      if (range) {
        sess.getSelection().setSelectionRange(range, false);
      }
    }

    else if (data.fileType == 'binary') {
      alert('binary file');
    }
  }
}

function current_edit (path) {
  try {
    path = path.replace(basedir + '/', '');

    $("#current_edit").html(path);
  }

  catch (e) {}
}

function resize_editor (skip_splitter) {
  var edith = $(window).height() - 33;

  ksplitter.size("#neutron_body", edith + "px");
  $("#splitter, #splitter > div").height(edith - 2);

  var nbw = $("#neutron_body").width() + 1;
  $("#neutron_body").width(nbw);

  var dp = CurrentTab();
  if (dp) {
    current_edit(dp);
    if (tab_paths[dp]) {
      editor_global.setSession(tab_paths[dp].session);
    }

    var href = $("ul.ui-tabs-nav li.ui-tabs-selected a").attr('href');
    var cnt = split_href(href);
  }

  var h = $("#splitter_right").height();
  $("#editor_global").height(h - $('.ui-widget-header').outerHeight());
  $("#editor_global").width($("#splitter_right").width());

  if (editor_global) {
    editor_global.resize();
    editor_global.focus();
  }

  resize_tabs();
}

function resize_tabs () {
  var h = $('#tooltabs').height();
  var t = $('#tooltabs > ul').height() + 2;

  $("#tooltabs > div").height(h - t);
}

function split_href (href) {
  var cnt = href.split('-');
  return cnt[cnt.length - 1];
}

function remove_tab (ui) {
  $("#current_edit").html('');

  var cnt = split_href(ui.tab.href);
  var dp = tab_counts[cnt];

  if (tab_paths[dp] && tab_paths[dp].session) {
    tab_paths[dp].session.$stopWorker();
    delete tab_paths[dp].session;
    delete tab_paths[dp];
  }

  if (tab_counts[cnt]) {
    delete tab_counts[cnt];
  }

  if (pref.save_session) {
    save_session();
  }

  var dp = CurrentTab();
  if (dp) {
    current_edit(dp);
    resize_editor();
  }

  else {
    editor_global = null;
    $('#editor_global').html('');
  }
}

function uploadProgress(id, evt) {
  if (evt.lengthComputable) {
    var pc = Math.round(evt.loaded * 100 / evt.total);

    $('#span_' + id).html('Uploading ' + pc + '%');
  }
}

function uploadFile(id, onComplete) {
  var xhr = new XMLHttpRequest();
  var fd = document.getElementById(id).files[0];

  xhr.upload.addEventListener("progress", function (evt) { uploadProgress(id, evt); }, false);
  xhr.addEventListener("load", function (evt) { onComplete(evt); }, false);
  xhr.addEventListener("error", function (evt) { alert('Upload Failed'); }, false);
  xhr.addEventListener("abort", function (evt) { alert('Upload Cancel'); }, false);

  xhr.open("POST", "/temp_file/?name=" + encodeURIComponent(fd.fileName));
  xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
  xhr.send(fd);
}

function get_file (file, range) {
  var img_patt = /\.(jpg|jpeg|png|bmp|pxd)$/i;

  if (img_patt.test(file)) {
    window.open('/external_open' + encodeURI(file), '_blank');
  }

  else {
    $.ajax({
      type: 'POST',
      async: false,
      url: '/fileget/',
      data: {f: file},
      success: function (data, textStatus, jqXHR) {create_tab(data, textStatus, jqXHR, range);},
      error: function (jqXHR, textStatus, errorThrown) { alert('Error Opening: ' + file); },
    });
  }
}

function file_browser () {
  $('#file_browser > div.inner').fileTree({ root: '', script: '/filetree/', expandSpeed: 200, collapseSpeed: 200 }, get_file);
}

function save_session () {
  if (skip_session) {}

  else {
    var files = '';
    $("ul.ui-tabs-nav > li > a").each(function (index, ele) {
      var cnt = split_href(ele.href);
      var dp = tab_counts[cnt];
      files = files + dp + "\n";
    });

    files = files.substring(0, files.length-1);

    $.ajax({
      type: 'POST',
      url: '/save_session/',
      data: {'files': files},
      success: function (data, textStatus, jqXHR) {},
      error: function (jqXHR, textStatus, errorThrown) { alert('Error Saving Session'); },
    });
  }
}

function sort_change (event, ui) {
  if (pref.save_session) {
    save_session();
  }
}

var stopMiddle = false;
function middleClick (e, ele) {
  if (e && e.button == 1) {
    if (stopMiddle) {
      stopMiddle = false;
    }

    else {
      var p = $(ele).parent();

      if ($(p).hasClass('ui-tabs-selected')) {
        stopMiddle = true;
      }

      var index = $("li", $tabs ).index(p);
      $tabs.tabs("remove", index );

      return false;
    }
  }

  return true;
}

$(document).ready( function() {
    file_browser();

    $tabs = $("#tabsinner").tabs({
      tabTemplate: "
#{label} x
",
      show: function( event, ui) { resize_editor(); },
			add: function( event, ui) {
        $(ui.panel).append( "

" );
      },
      remove: function (event, ui) { remove_tab(ui); }
    });
    $tabs.find( ".ui-tabs-nav" ).sortable({ axis: "x", update: sort_change});
    $( "#tabs span.ui-icon-close" ).live( "click", function() {
      var p = $(this).parent();
      var index = $( "li", $tabs ).index(p);
      $tabs.tabs( "remove", index );
    });
});

function size_search (e) {
  setTimeout(function () {
    var width = $("#splitter_left").width() - 83;
    $("#search_panel_results a.expand").width(width);

    $("#editor_global").width($("#splitter_right").width());

    if (editor_global) {
      editor_global.resize();
    }
  }, 400);
}

var ksplitter;
var esplitter;
var tabstrip;
var tooltabs;
var search_panel;

$(document).ready(function () {
  $("body").click(function (eObj) {
    $('.right_menu').css('display', 'none');

    if (eObj.target.id && eObj.target.id == 'menu_button') {}
    else if (eObj.target.parentElement.id && eObj.target.parentElement.id == 'menu_button') {}
    else {
      hide_menu();
    }
  });

  search_panel = $("#search_panel").kendoPanelBar().data("kendoPanelBar");
  $("#search_panel_search > span").click();

  tooltabs = $("#tooltabs").kendoTabStrip({animation: false}).data("kendoTabStrip");
  tooltabs.select("#fbtab");
  $("#tooltabs > ul li").click(resize_tabs);

  ksplitter = $("#neutron_ui").kendoSplitter({
    panes: [{resizable: false, size: '35px', scrollable: false}, {scrollable:false, resizable: false, size: '311px'}],
    orientation: 'vertical'
  }).data("kendoSplitter");

  esplitter = $("#splitter").kendoSplitter({resize: size_search, panes: [{collapsible: true, size: '250px', scrollable: false}, {scrollable: false}], resize: size_search}).data("kendoSplitter");

  if (pref.save_session) {
    for (i in init_session) {
      get_file(init_session[i]);
    }

    skip_session = false;
  }

  //$(window).unbind();
  $(window).resize(resize_editor);
  resize_editor();

  if (track_ajax) {
    setTimeout(track_ide, track_int);
  }

});

function track_ide () {
  var d = new Date();
  var ts = d.getYear() + '-' + d.getMonth() + '-' + d.getDay() + '-' + d.getHours() + '-' + d.getMinutes();
  _gaq.push(['_trackPageview', "/?ts=" + ts]);
  setTimeout(track_ide, track_int);
}

window.onbeforeunload = function() {
    return 'Leaving so soon!';
}

var canon = require('pilot/canon');

canon.addCommand({
    name: 'SaveFile',
    bindKey: {
      win: 'Ctrl-S',
      mac: 'Command-S',
      sender: 'editor'
    },
    exec: function(env, args, request) { SaveCurrentTab(); }
});

<|endoftext|>


<commit_before>var async = require('async');
var config = require('../config.json');
var outputFile = require('../bin/output-file');
var opt = {
  cfg: config,
  table: 'MOCK_DATA'
};
var destinations = require('../bin/list-dest')(config);
var colParser = require('../bin/col-parser');
var columns;
var Timer = require('../bin/timer');
opt.log = require('../bin/log-dev')(Object.assign({}, config, opt));
opt.timer = new Timer();
var response = require('../bin/response')(Object.assign({}, config, opt));

describe('Run all destinations with MOCK_DATA', function() {
  it('Overrides opfile without error', function(done) {
    outputFile(opt, function(err, op) {
      opt.opfile = op;
      //force to use MOCK_DATA as output-ed data
      opt.opfile.filename = __dirname.replace(/\\/g, '/') + '/assets/MOCK_DATA.txt';
      opt.opfile.twoLines(function(err, data) {
        if (err) return done(err);
        var test2Lines = [
          'id_IND\tfirst_name\tlast_name\temail\tgender\tip_address\ttesting_GPA\ttesting_DATE\ttesting_TIMESTAMP\ttesting_DEC',
          '1\tEmily\tFisher\tefisher0@google.de\tFemale\t161.31.81.163\t89.64\t11/15/2015\t1/29/2016\t89.62'
        ];
        console.log(test2Lines, data);
        if (data[0] !== test2Lines[0] || data[1] !== test2Lines[1]) return done(new Error('Data returned by opfile.twoLines() did not match MOCK_DATA.'));
        done();
      });
    });
  });
  it('Parsed columns without error', function(done) {
    colParser(opt.opfile, function(err, parsedCols) {
      if (err) return done(err);
      columns = parsedCols;
      var cols = ['id', 'first_name', 'last_name', 'email', 'gender', 'ip_address', 'testing_GPA', 'testing_DATE', 'testing_TIMESTAMP', 'testing_DEC'];
      response.source.respond('ok', 1000, cols);
      done();
    });
  });
  it('Runs every destination.', function() {
    async.each(destinations, function(dest) {
      describe('Checking ' + dest, function() {
        this.timeout(30000);
        var destination = require('../bin/dest/' + dest);
        it('Ran destination ' + dest, function(done) {
          destination(opt, columns, function(err, rows, columns) {
            if (err) return done(err);
            response.destination.respond('ok', rows, columns);
            var res = response.check();
            if (res === null) return done();
            done(new Error(res));
          });
        });
      });
    });
  });
});
<commit_msg>proper error handling, new test source<commit_after>var async = require('async');
var config = require('../config.json');
var outputFile = require('../bin/output-file');
var opt = {
  cfg: config,
  table: 'MOCK_DATA'
};
var destinations = require('../bin/list-dest')(config);
var colParser = require('../bin/col-parser');
var columns;
var Timer = require('../bin/timer');
opt.log = require('../bin/log-dev')(Object.assign({}, config, opt));
opt.timer = new Timer();
opt.source = 'DB_TEST';
var response = require('../bin/response')(Object.assign({}, config, opt));

describe('Run all destinations with MOCK_DATA', function() {
  it('Overrides opfile without error', function(done) {
    outputFile(opt, function(err, op) {
      opt.opfile = op;
      //force to use MOCK_DATA as output-ed data
      opt.opfile.filename = __dirname.replace(/\\/g, '/') + '/assets/MOCK_DATA.txt';
      opt.opfile.twoLines(function(err, data) {
        if (err) return done(err);
        var test2Lines = [
          'id_IND\tfirst_name\tlast_name\temail\tgender\tip_address\ttesting_GPA\ttesting_DATE\ttesting_TIMESTAMP\ttesting_DEC',
          '1\tEmily\tFisher\tefisher0@google.de\tFemale\t161.31.81.163\t89.64\t11/15/2015\t1/29/2016\t89.62'
        ];
        if (data[0] !== test2Lines[0] || data[1] !== test2Lines[1]) return done(new Error('Data returned by opfile.twoLines() did not match MOCK_DATA.'));
        done();
      });
    });
  });
  it('Parsed columns without error', function(done) {
    colParser(opt.opfile, function(err, parsedCols) {
      if (err) return done(err);
      columns = parsedCols;
      var cols = ['id', 'first_name', 'last_name', 'email', 'gender', 'ip_address', 'testing_GPA', 'testing_DATE', 'testing_TIMESTAMP', 'testing_DEC'];
      response.source.respond('ok', 1000, cols);
      done();
    });
  });
  it('Runs every destination.', function() {
    async.each(destinations, function(dest) {
      describe('Checking ' + dest, function() {
        this.timeout(30000);
        var destination = require('../bin/dest/' + dest);
        it('Ran destination ' + dest, function(done) {
          destination(opt, columns, function(err, rows, columns) {
            if (err) return done(new Error(err));
            response.destination.respond('ok', rows, columns);
            var res = response.check();
            if (res === null) return done();
            done(new Error(res));
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  /* global exports, require */

  var path = require('path');

  exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: {
      browserName: 'chrome',
      chromeOptions: {
        args: ['--load-extension=' + path.resolve('e2e-app')]
      }
    },
    specs: ['e2e/**/*.js']
  };
})();
<commit_msg>Add --no-sandbox arg to protractor chrome<commit_after>(function() {
  'use strict';

  /* global exports, require */

  var path = require('path');

  exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    capabilities: {
      browserName: 'chrome',
      chromeOptions: {
        args: ['--no-sandbox', '--load-extension=' + path.resolve('e2e-app')]
      }
    },
    specs: ['e2e/**/*.js']
  };
})();
<|endoftext|>


<commit_before><commit_msg>test client added<commit_after>'use strict';

const mq = require('..')();

process.on('SIGINT', () => {
    console.warn(' ~ Got SIGINT, terminating');
    if (mq.isOpen()) {
        mq.terminate();
    }
});

mq.on('open', () => {
    console.log('> got channel opened event');
    mq.assertQueue('test1').then(queue => {
        console.log('> queue exists/created:', queue);
    });
});

mq.on('close', () => {
    console.log('> got channel closed event');
});
<|endoftext|>


<commit_before>/*!
 * jQuery.togglemenu.js
 *
 * A jQuery plugin to assist with hiding and showing navigation menus.
 *
 * Leveragres Modernizr's .mq() method to reset a menu, but will ignore it if
 * Modernizr isn't used.
 *
 * The following options can be configured:
 *
 *   1. nav: the selector for the menu you want to show.
 *   2. subnav: the selector for the submenus within the menu.
 *   3. namespace: all events are namespaced for more control. leaving this
 *      blank will generate a random namespace.
 *   4. reset: an array of media queries that will reset the menu (strip all
 *      classes)
 *
 * @author  Reinier Kaper <mail@thedutchcoder.com>
 * @example

$('.js-toggle-navigation').toggleMenu({
    nav: '.nav--main',
    subnav: '.nav--sub',
    namespace: 'savemenu'
    reset: ['screen and (min-width: 40em)']
});

*/

;(function($, window, document, undefined) {

    /**
     * Add the togglemenu function to the jQuery functions.
     *
     * @param  Object options An object containing options for the plugin.
     * @return Object         Returns the jQuery object.
     */
    $.fn.togglemenu = function(options) {

        // The default options for the plugin.
        var defaults = {
            nav: 'nav > ul',
            subnav: 'ul',
            namespace: (Math.random() + 1).toString(36).substring(7),
            reset: []
        };

        // Extend the options with all the defaults and overwrite any supplied
        // options.
        options = $.extend(defaults, options);

        // Loop through each item that the plugin is attached to.
        this.each(function(index) {

            var $window,
                $document,
                $trigger,
                $nav,
                $subnav,

                nameSpace,
                windowWidth,
                clickEvent,
                isReset;

            $window = $(window);
            $document = $(document);
            $trigger = $(this);
            $nav = $(options.nav);
            $subnav = $(options.nav + ' ' + options.subnav);

            nameSpace = '.' + options.namespace;
            windowWidth = 0;
            isReset = true;

            // The click event is normalized in order to get correct body clicks
            // in certain mobile browsers.
            clickEvent = 'ontouchstart' in document.documentElement ?
                    'touchstart' + nameSpace :
                    'click' + nameSpace;

            /**
             * Opens the menu.
             */
            function openNav() {

                $trigger
                    .addClass('is-active');

                $nav
                    .addClass('is-open');

            }

            /**
             * Closes the menu.
             */
            function closeNav() {

                $trigger
                    .removeClass('is-active');

                $nav
                    .removeClass('is-open')
                    .addClass('is-closed');

                $subnav
                    .removeClass('is-open')
                    .addClass('is-closed');

            }

            /**
             * Resets the trigger and menu (removes all classes).
             */
            function resetNav() {

                $trigger
                    .removeClass('is-active');

                $nav
                    .removeClass('is-open is-closed');

                $subnav
                    .removeClass('is-open is-closed');

            }

            /**
             * Opens a sub menu.
             *
             * @param  {Object} $target The clicked element preceding the sub
             *                          menu.
             */
            function openSubnav($target) {

                if (!$target.siblings(options.subnav).hasClass('is-open')) {

                    event.preventDefault();

                    $target.siblings(options.subnav)
                        .removeClass('is-closed')
                        .addClass('is-open');

                }

            }

            /**
             * Attaches all event handlers for this instance of the plugin.
             */
            function attachEventHandlers() {

                isReset = false;

                // Event handling for the trigger.
                //
                // The target should toggle when the trigger (or one of its
                // children) is clicked.
                //
                // When a subnav item is clicked, the subnav should be opened.
                // Otherwise the link should be followed normally.
                //
                // Clicks on any other element close the menu.
                $document.on(clickEvent, function(event) {

                    var $target;

                    $target = $(event.target);

                    // 1. The trigger (or one of its children) is clicked.
                    // 2. A subnav element is clicked.
                    // 3. Any other element is clicked.
                    if ($target.closest($trigger).length) {

                        if ($trigger.hasClass('is-active')) {

                            closeNav();

                        } else {

                            openNav();

                        }

                    } else if ($target.closest($nav).length &&
                               $target.siblings($subnav).length) {

                        openSubnav($target);

                    } else {

                        closeNav();

                    }

                });

            }

            /**
             * Detaches all event handlers for this instance of the plugin.
             */
            function detachEventHandlers() {

                isReset = true;

                $document.off(clickEvent);

            }

            // When the viewport is resized and a media query is hit where the
            // menu should be reset, the menu is closed and all styling is
            // removed.
            //
            // Events for this instance are also added or removed, depending on
            // the media queries.
            $window.on('resize' + nameSpace, function() {

                // Only trigger if media queries are provided and
                // Moderznir's .mq() method can be used.
                if (options.reset.length > 0 &&
                    typeof Modernizr === "object" &&
                    typeof Modernizr.mq === "function") {

                    // Check to see if the window really has resized as some
                    // mobile browsers trigger the resize event on scroll
                    // too.
                    if ($window.width() !== windowWidth) {

                        windowWidth = $window.width();

                        // Loop through the 'reset' queries to see if one of
                        // them has been matched to reset the menu.
                        for (var i = 0; i < options.reset.length; i++) {

                            if (Modernizr.mq(options.reset[i])) {

                                if (!isReset) {

                                    resetNav();
                                    detachEventHandlers();

                                }

                                return;

                            }

                        }

                        // If the menu has been reset, but none of the queries
                        // have been hit, reattach the event handlers.
                        if (isReset) {

                            attachEventHandlers();

                        }

                    }

                } else {

                    // If no reset queries have been specified (or Modernizr
                    // isn't used) and there are no event handlers yet, attach
                    // them.
                    if (isReset) {

                        attachEventHandlers();

                    }

                }

            }).resize();

        });

        // Return the object for chaining.
        return this;

    };

})(jQuery, window, document);
<commit_msg>Added classes to active link<commit_after>/*!
 * jQuery.togglemenu.js
 *
 * A jQuery plugin to assist with hiding and showing navigation menus.
 *
 * Leveragres Modernizr's .mq() method to reset a menu, but will ignore it if
 * Modernizr isn't used.
 *
 * The following options can be configured:
 *
 *   1. nav: the selector for the menu you want to show.
 *   2. subnav: the selector for the submenus within the menu.
 *   3. namespace: all events are namespaced for more control. leaving this
 *      blank will generate a random namespace.
 *   4. reset: an array of media queries that will reset the menu (strip all
 *      classes)
 *
 * @author  Reinier Kaper <mail@thedutchcoder.com>
 * @example

$('.js-toggle-navigation').toggleMenu({
    nav: '.nav--main',
    subnav: '.nav--sub',
    namespace: 'savemenu'
    reset: ['screen and (min-width: 40em)']
});

*/

;(function($, window, document, undefined) {

    /**
     * Add the togglemenu function to the jQuery functions.
     *
     * @param  Object options An object containing options for the plugin.
     * @return Object         Returns the jQuery object.
     */
    $.fn.togglemenu = function(options) {

        // The default options for the plugin.
        var defaults = {
            nav: 'nav > ul',
            subnav: 'ul',
            namespace: (Math.random() + 1).toString(36).substring(7),
            reset: []
        };

        // Extend the options with all the defaults and overwrite any supplied
        // options.
        options = $.extend(defaults, options);

        // Loop through each item that the plugin is attached to.
        this.each(function(index) {

            var $window,
                $document,
                $trigger,
                $nav,
                $subnav,

                nameSpace,
                windowWidth,
                clickEvent,
                isReset;

            $window = $(window);
            $document = $(document);
            $trigger = $(this);
            $nav = $(options.nav);
            $subnav = $(options.nav + ' ' + options.subnav);

            nameSpace = '.' + options.namespace;
            windowWidth = 0;
            isReset = true;

            // The click event is normalized in order to get correct body clicks
            // in certain mobile browsers.
            clickEvent = 'ontouchstart' in document.documentElement ?
                    'touchstart' + nameSpace :
                    'click' + nameSpace;

            /**
             * Opens the menu.
             */
            function openNav() {

                $trigger
                    .addClass('is-active');

                $nav
                    .addClass('is-open');

            }

            /**
             * Closes the menu.
             */
            function closeNav() {

                $trigger
                    .removeClass('is-active');

                $nav
                    .removeClass('is-open')
                    .addClass('is-closed')
                    .find('*')
                    .removeClass('is-active');

                $subnav
                    .removeClass('is-open')
                    .addClass('is-closed');

            }

            /**
             * Resets the trigger and menu (removes all classes).
             */
            function resetNav() {

                $trigger
                    .removeClass('is-active');

                $nav
                    .removeClass('is-open is-closed')
                    .find('*')
                    .removeClass('is-active');

                $subnav
                    .removeClass('is-open is-closed');

            }

            /**
             * Opens a sub menu.
             *
             * @param  {Object} $target The clicked element preceding the sub
             *                          menu.
             */
            function openSubnav($target) {

                if (!$target.siblings(options.subnav).hasClass('is-open')) {

                    event.preventDefault();

                    $target
                        .addClass('is-active')
                        .siblings(options.subnav)
                        .removeClass('is-closed')
                        .addClass('is-open');

                }

            }

            /**
             * Attaches all event handlers for this instance of the plugin.
             */
            function attachEventHandlers() {

                isReset = false;

                // Event handling for the trigger.
                //
                // The target should toggle when the trigger (or one of its
                // children) is clicked.
                //
                // When a subnav item is clicked, the subnav should be opened.
                // Otherwise the link should be followed normally.
                //
                // Clicks on any other element close the menu.
                $document.on(clickEvent, function(event) {

                    var $target;

                    $target = $(event.target);

                    // 1. The trigger (or one of its children) is clicked.
                    // 2. A subnav element is clicked.
                    // 3. Any other element is clicked.
                    if ($target.closest($trigger).length) {

                        if ($trigger.hasClass('is-active')) {

                            closeNav();

                        } else {

                            openNav();

                        }

                    } else if ($target.closest($nav).length &&
                               $target.siblings($subnav).length) {

                        openSubnav($target);

                    } else {

                        closeNav();

                    }

                });

            }

            /**
             * Detaches all event handlers for this instance of the plugin.
             */
            function detachEventHandlers() {

                isReset = true;

                $document.off(clickEvent);

            }

            // When the viewport is resized and a media query is hit where the
            // menu should be reset, the menu is closed and all styling is
            // removed.
            //
            // Events for this instance are also added or removed, depending on
            // the media queries.
            $window.on('resize' + nameSpace, function() {

                // Only trigger if media queries are provided and
                // Moderznir's .mq() method can be used.
                if (options.reset.length > 0 &&
                    typeof Modernizr === "object" &&
                    typeof Modernizr.mq === "function") {

                    // Check to see if the window really has resized as some
                    // mobile browsers trigger the resize event on scroll
                    // too.
                    if ($window.width() !== windowWidth) {

                        windowWidth = $window.width();

                        // Loop through the 'reset' queries to see if one of
                        // them has been matched to reset the menu.
                        for (var i = 0; i < options.reset.length; i++) {

                            if (Modernizr.mq(options.reset[i])) {

                                if (!isReset) {

                                    resetNav();
                                    detachEventHandlers();

                                }

                                return;

                            }

                        }

                        // If the menu has been reset, but none of the queries
                        // have been hit, reattach the event handlers.
                        if (isReset) {

                            attachEventHandlers();

                        }

                    }

                } else {

                    // If no reset queries have been specified (or Modernizr
                    // isn't used) and there are no event handlers yet, attach
                    // them.
                    if (isReset) {

                        attachEventHandlers();

                    }

                }

            }).resize();

        });

        // Return the object for chaining.
        return this;

    };

})(jQuery, window, document);
<|endoftext|>